diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/__init__.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb4339dd1cea8e0b7173af8a78a49b015abae9b2 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/__init__.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_internal_context.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_internal_context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5457fb75681ddd349965ddcfb905e9bc80275ef6 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_internal_context.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55b588fb5eddeae7be8abaa62d58ea76c442e5fe Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports_registry.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports_registry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49431c34489c704b98d25286f459009dced7e645 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_lazy_imports_registry.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_logging.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_logging.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73fd70bf0e9abf024901c5ae712796a387dac885 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_logging.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38d9076f472af447d635e2387ae00982157c2b7a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis_credential_provider.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis_credential_provider.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d968fcd0494fe7e9710d979a02c8e7bb6bfe634 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_redis_credential_provider.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_service_logger.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_service_logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90d407770feaded1867e4daae93de88b1b35d9f7 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_service_logger.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_uuid.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_uuid.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf5d1c3a3f022defb9095002a496aa8582e1a597 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_uuid.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_version.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_version.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ad5ba785fd208e9efc67198e4dcfd702ae8361a Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/_version.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/anthropic_beta_headers_manager.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/anthropic_beta_headers_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8598c3d102b4fc495c92e0ce33f0b803e89a6888 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/anthropic_beta_headers_manager.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/budget_manager.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/budget_manager.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66d8af4b8f46c82ab171d02d85d78a962dff165f Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/budget_manager.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/constants.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/constants.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..138112f6c8c017f23f2f6a900cbc747c9b18143c Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/constants.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/cost_calculator.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/cost_calculator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9c0742a7046ec02dabb772b44b6a7b18199a1a3 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/cost_calculator.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/exceptions.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f20233a65cb4e35abc4254fa12c7fbdcb2ab652 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/exceptions.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/scheduler.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b864a08ff49299401161eb88f2be4321f0b74484 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/scheduler.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/setup_wizard.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/setup_wizard.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03316cb6e7d59ed0123517cd3c40d9530fbe36d1 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/setup_wizard.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/timeout.cpython-310.pyc b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/timeout.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95c6a729cad2816dd9062bb77e0826e981281f71 Binary files /dev/null and b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/__pycache__/timeout.cpython-310.pyc differ diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85c03687e255ce4c0b3b403566d63dd21989feaf --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/__init__.py @@ -0,0 +1,73 @@ +""" +LiteLLM A2A - Wrapper for invoking A2A protocol agents. + +This module provides a thin wrapper around the official `a2a` SDK that: +- Handles httpx client creation and agent card resolution +- Adds LiteLLM logging via @client decorator +- Matches the A2A SDK interface (SendMessageRequest, SendMessageResponse, etc.) + +Example usage (standalone functions with @client decorator): + ```python + from litellm.a2a_protocol import asend_message + from a2a.types import SendMessageRequest, MessageSendParams + from uuid import uuid4 + + request = SendMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={ + "role": "user", + "parts": [{"kind": "text", "text": "Hello!"}], + "messageId": uuid4().hex, + } + ) + ) + response = await asend_message( + base_url="http://localhost:10001", + request=request, + ) + print(response.model_dump(mode='json', exclude_none=True)) + ``` + +Example usage (class-based): + ```python + from litellm.a2a_protocol import A2AClient + + client = A2AClient(base_url="http://localhost:10001") + response = await client.send_message(request) + ``` +""" + +from litellm.a2a_protocol.client import A2AClient +from litellm.a2a_protocol.exceptions import ( + A2AAgentCardError, + A2AConnectionError, + A2AError, + A2ALocalhostURLError, +) +from litellm.a2a_protocol.main import ( + aget_agent_card, + asend_message, + asend_message_streaming, + create_a2a_client, + send_message, +) +from litellm.types.agents import LiteLLMSendMessageResponse + +__all__ = [ + # Client + "A2AClient", + # Functions + "asend_message", + "send_message", + "asend_message_streaming", + "aget_agent_card", + "create_a2a_client", + # Response types + "LiteLLMSendMessageResponse", + # Exceptions + "A2AError", + "A2AConnectionError", + "A2AAgentCardError", + "A2ALocalhostURLError", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/card_resolver.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/card_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5dd3e3ba6c77c99ff43596e5bcfa13af717494 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/card_resolver.py @@ -0,0 +1,144 @@ +""" +Custom A2A Card Resolver for LiteLLM. + +Extends the A2A SDK's card resolver to support multiple well-known paths. +""" + +from typing import TYPE_CHECKING, Any, Dict, Optional + +from litellm._logging import verbose_logger +from litellm.constants import LOCALHOST_URL_PATTERNS + +if TYPE_CHECKING: + from a2a.types import AgentCard + +# Runtime imports with availability check +_A2ACardResolver: Any = None +AGENT_CARD_WELL_KNOWN_PATH: str = "/.well-known/agent-card.json" +PREV_AGENT_CARD_WELL_KNOWN_PATH: str = "/.well-known/agent.json" + +try: + from a2a.client import A2ACardResolver as _A2ACardResolver # type: ignore[no-redef] + from a2a.utils.constants import ( # type: ignore[no-redef] + AGENT_CARD_WELL_KNOWN_PATH, + PREV_AGENT_CARD_WELL_KNOWN_PATH, + ) +except ImportError: + pass + + +def is_localhost_or_internal_url(url: Optional[str]) -> bool: + """ + Check if a URL is a localhost or internal URL. + + This detects common development URLs that are accidentally left in + agent cards when deploying to production. + + Args: + url: The URL to check + + Returns: + True if the URL is localhost/internal + """ + if not url: + return False + + url_lower = url.lower() + + return any(pattern in url_lower for pattern in LOCALHOST_URL_PATTERNS) + + +def fix_agent_card_url(agent_card: "AgentCard", base_url: str) -> "AgentCard": + """ + Fix the agent card URL if it contains a localhost/internal address. + + Many A2A agents are deployed with agent cards that contain internal URLs + like "http://0.0.0.0:8001/" or "http://localhost:8000/". This function + replaces such URLs with the provided base_url. + + Args: + agent_card: The agent card to fix + base_url: The base URL to use as replacement + + Returns: + The agent card with the URL fixed if necessary + """ + card_url = getattr(agent_card, "url", None) + + if card_url and is_localhost_or_internal_url(card_url): + # Normalize base_url to ensure it ends with / + fixed_url = base_url.rstrip("/") + "/" + agent_card.url = fixed_url + + return agent_card + + +class LiteLLMA2ACardResolver(_A2ACardResolver): # type: ignore[misc] + """ + Custom A2A card resolver that supports multiple well-known paths. + + Extends the base A2ACardResolver to try both: + - /.well-known/agent-card.json (standard) + - /.well-known/agent.json (previous/alternative) + """ + + async def get_agent_card( + self, + relative_card_path: Optional[str] = None, + http_kwargs: Optional[Dict[str, Any]] = None, + ) -> "AgentCard": + """ + Fetch the agent card, trying multiple well-known paths. + + First tries the standard path, then falls back to the previous path. + + Args: + relative_card_path: Optional path to the agent card endpoint. + If None, tries both well-known paths. + http_kwargs: Optional dictionary of keyword arguments to pass to httpx.get + + Returns: + AgentCard from the A2A agent + + Raises: + A2AClientHTTPError or A2AClientJSONError if both paths fail + """ + # If a specific path is provided, use the parent implementation + if relative_card_path is not None: + return await super().get_agent_card( + relative_card_path=relative_card_path, + http_kwargs=http_kwargs, + ) + + # Try both well-known paths + paths = [ + AGENT_CARD_WELL_KNOWN_PATH, + PREV_AGENT_CARD_WELL_KNOWN_PATH, + ] + + last_error = None + for path in paths: + try: + verbose_logger.debug( + f"Attempting to fetch agent card from {self.base_url}{path}" + ) + return await super().get_agent_card( + relative_card_path=path, + http_kwargs=http_kwargs, + ) + except Exception as e: + verbose_logger.debug( + f"Failed to fetch agent card from {self.base_url}{path}: {e}" + ) + last_error = e + continue + + # If we get here, all paths failed - re-raise the last error + if last_error is not None: + raise last_error + + # This shouldn't happen, but just in case + raise Exception( + f"Failed to fetch agent card from {self.base_url}. " + f"Tried paths: {', '.join(paths)}" + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/client.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/client.py new file mode 100644 index 0000000000000000000000000000000000000000..05e21284af159173568ecf3f4e3248f9b247d605 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/client.py @@ -0,0 +1,109 @@ +""" +LiteLLM A2A Client class. + +Provides a class-based interface for A2A agent invocation. +""" + +from typing import TYPE_CHECKING, AsyncIterator, Dict, Optional + +from litellm.types.agents import LiteLLMSendMessageResponse + +if TYPE_CHECKING: + from a2a.client import A2AClient as A2AClientType + from a2a.types import ( + AgentCard, + SendMessageRequest, + SendStreamingMessageRequest, + SendStreamingMessageResponse, + ) + + +class A2AClient: + """ + LiteLLM wrapper for A2A agent invocation. + + Creates the underlying A2A client once on first use and reuses it. + + Example: + ```python + from litellm.a2a_protocol import A2AClient + from a2a.types import SendMessageRequest, MessageSendParams + from uuid import uuid4 + + client = A2AClient(base_url="http://localhost:10001") + + request = SendMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={ + "role": "user", + "parts": [{"kind": "text", "text": "Hello!"}], + "messageId": uuid4().hex, + } + ) + ) + response = await client.send_message(request) + ``` + """ + + def __init__( + self, + base_url: str, + timeout: float = 60.0, + extra_headers: Optional[Dict[str, str]] = None, + ): + """ + Initialize the A2A client wrapper. + + Args: + base_url: The base URL of the A2A agent (e.g., "http://localhost:10001") + timeout: Request timeout in seconds (default: 60.0) + extra_headers: Optional additional headers to include in requests + """ + self.base_url = base_url + self.timeout = timeout + self.extra_headers = extra_headers + self._a2a_client: Optional["A2AClientType"] = None + + async def _get_client(self) -> "A2AClientType": + """Get or create the underlying A2A client.""" + if self._a2a_client is None: + from litellm.a2a_protocol.main import create_a2a_client + + self._a2a_client = await create_a2a_client( + base_url=self.base_url, + timeout=self.timeout, + extra_headers=self.extra_headers, + ) + return self._a2a_client + + async def get_agent_card(self) -> "AgentCard": + """Fetch the agent card from the server.""" + from litellm.a2a_protocol.main import aget_agent_card + + return await aget_agent_card( + base_url=self.base_url, + timeout=self.timeout, + extra_headers=self.extra_headers, + ) + + async def send_message( + self, request: "SendMessageRequest" + ) -> LiteLLMSendMessageResponse: + """Send a message to the A2A agent.""" + from litellm.a2a_protocol.main import asend_message + + a2a_client = await self._get_client() + return await asend_message(a2a_client=a2a_client, request=request) + + async def send_message_streaming( + self, request: "SendStreamingMessageRequest" + ) -> AsyncIterator["SendStreamingMessageResponse"]: + """Send a streaming message to the A2A agent.""" + from litellm.a2a_protocol.main import asend_message_streaming + + a2a_client = await self._get_client() + async for chunk in asend_message_streaming( + a2a_client=a2a_client, request=request + ): + yield chunk diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/cost_calculator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/cost_calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..f64174f8be5fb07b08721251dcfff73157f9538c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/cost_calculator.py @@ -0,0 +1,107 @@ +""" +Cost calculator for A2A (Agent-to-Agent) calls. + +Supports dynamic cost parameters that allow platform owners +to define custom costs per agent query or per token. +""" + +from typing import TYPE_CHECKING, Any, Optional + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import ( + Logging as LitellmLoggingObject, + ) +else: + LitellmLoggingObject = Any + + +class A2ACostCalculator: + @staticmethod + def calculate_a2a_cost( + litellm_logging_obj: Optional[LitellmLoggingObject], + ) -> float: + """ + Calculate the cost of an A2A send_message call. + + Supports multiple cost parameters for platform owners: + - cost_per_query: Fixed cost per query + - input_cost_per_token + output_cost_per_token: Token-based pricing + + Priority order: + 1. response_cost - if set directly (backward compatibility) + 2. cost_per_query - fixed cost per query + 3. input_cost_per_token + output_cost_per_token - token-based cost + 4. Default to 0.0 + + Args: + litellm_logging_obj: The LiteLLM logging object containing call details + + Returns: + float: The cost of the A2A call + """ + if litellm_logging_obj is None: + return 0.0 + + model_call_details = litellm_logging_obj.model_call_details + + # Check if user set a custom response cost (backward compatibility) + response_cost = model_call_details.get("response_cost", None) + if response_cost is not None: + return float(response_cost) + + # Get litellm_params for cost parameters + litellm_params = model_call_details.get("litellm_params", {}) or {} + + # Check for cost_per_query (fixed cost per query) + if litellm_params.get("cost_per_query") is not None: + return float(litellm_params["cost_per_query"]) + + # Check for token-based pricing + input_cost_per_token = litellm_params.get("input_cost_per_token") + output_cost_per_token = litellm_params.get("output_cost_per_token") + + if input_cost_per_token is not None or output_cost_per_token is not None: + return A2ACostCalculator._calculate_token_based_cost( + model_call_details=model_call_details, + input_cost_per_token=input_cost_per_token, + output_cost_per_token=output_cost_per_token, + ) + + # Default to 0.0 for A2A calls + return 0.0 + + @staticmethod + def _calculate_token_based_cost( + model_call_details: dict, + input_cost_per_token: Optional[float], + output_cost_per_token: Optional[float], + ) -> float: + """ + Calculate cost based on token usage and per-token pricing. + + Args: + model_call_details: The model call details containing usage + input_cost_per_token: Cost per input token (can be None, defaults to 0) + output_cost_per_token: Cost per output token (can be None, defaults to 0) + + Returns: + float: The calculated cost + """ + # Get usage from model_call_details + usage = model_call_details.get("usage") + if usage is None: + return 0.0 + + # Get token counts + prompt_tokens = getattr(usage, "prompt_tokens", 0) or 0 + completion_tokens = getattr(usage, "completion_tokens", 0) or 0 + + # Calculate costs + input_cost = prompt_tokens * ( + float(input_cost_per_token) if input_cost_per_token else 0.0 + ) + output_cost = completion_tokens * ( + float(output_cost_per_token) if output_cost_per_token else 0.0 + ) + + return input_cost + output_cost diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exception_mapping_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exception_mapping_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..49dbb22b158625d78b1fd1bb379e1e6083b09043 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exception_mapping_utils.py @@ -0,0 +1,203 @@ +""" +A2A Protocol Exception Mapping Utils. + +Maps A2A SDK exceptions to LiteLLM A2A exception types. +""" + +from typing import TYPE_CHECKING, Any, Optional + +from litellm._logging import verbose_logger +from litellm.a2a_protocol.card_resolver import ( + fix_agent_card_url, + is_localhost_or_internal_url, +) +from litellm.a2a_protocol.exceptions import ( + A2AAgentCardError, + A2AConnectionError, + A2AError, + A2ALocalhostURLError, +) +from litellm.constants import CONNECTION_ERROR_PATTERNS + +if TYPE_CHECKING: + from a2a.client import A2AClient as A2AClientType + + +# Runtime import +A2A_SDK_AVAILABLE = False +try: + from a2a.client import A2AClient as _A2AClient # type: ignore[no-redef] + + A2A_SDK_AVAILABLE = True +except ImportError: + _A2AClient = None # type: ignore[assignment, misc] + + +class A2AExceptionCheckers: + """ + Helper class for checking various A2A error conditions. + """ + + @staticmethod + def is_connection_error(error_str: str) -> bool: + """ + Check if an error string indicates a connection error. + + Args: + error_str: The error string to check + + Returns: + True if the error indicates a connection issue + """ + if not isinstance(error_str, str): + return False + + error_str_lower = error_str.lower() + return any(pattern in error_str_lower for pattern in CONNECTION_ERROR_PATTERNS) + + @staticmethod + def is_localhost_url(url: Optional[str]) -> bool: + """ + Check if a URL is a localhost/internal URL. + + Args: + url: The URL to check + + Returns: + True if the URL is localhost/internal + """ + return is_localhost_or_internal_url(url) + + @staticmethod + def is_agent_card_error(error_str: str) -> bool: + """ + Check if an error string indicates an agent card error. + + Args: + error_str: The error string to check + + Returns: + True if the error is related to agent card fetching/parsing + """ + if not isinstance(error_str, str): + return False + + error_str_lower = error_str.lower() + agent_card_patterns = [ + "agent card", + "agent-card", + ".well-known", + "card not found", + "invalid agent", + ] + return any(pattern in error_str_lower for pattern in agent_card_patterns) + + +def map_a2a_exception( + original_exception: Exception, + card_url: Optional[str] = None, + api_base: Optional[str] = None, + model: Optional[str] = None, +) -> Exception: + """ + Map an A2A SDK exception to a LiteLLM A2A exception type. + + Args: + original_exception: The original exception from the A2A SDK + card_url: The URL from the agent card (if available) + api_base: The original API base URL + model: The model/agent name + + Returns: + A mapped LiteLLM A2A exception + + Raises: + A2ALocalhostURLError: If the error is a connection error to a localhost URL + A2AConnectionError: If the error is a general connection error + A2AAgentCardError: If the error is related to agent card issues + A2AError: For other A2A-related errors + """ + error_str = str(original_exception) + + # Check for localhost URL connection error (special case - retryable) + if ( + card_url + and api_base + and A2AExceptionCheckers.is_localhost_url(card_url) + and A2AExceptionCheckers.is_connection_error(error_str) + ): + raise A2ALocalhostURLError( + localhost_url=card_url, + base_url=api_base, + original_error=original_exception, + model=model, + ) + + # Check for agent card errors + if A2AExceptionCheckers.is_agent_card_error(error_str): + raise A2AAgentCardError( + message=error_str, + url=api_base, + model=model, + ) + + # Check for general connection errors + if A2AExceptionCheckers.is_connection_error(error_str): + raise A2AConnectionError( + message=error_str, + url=card_url or api_base, + model=model, + ) + + # Default: wrap in generic A2AError + raise A2AError( + message=error_str, + model=model, + ) + + +def handle_a2a_localhost_retry( + error: A2ALocalhostURLError, + agent_card: Any, + a2a_client: "A2AClientType", + is_streaming: bool = False, +) -> "A2AClientType": + """ + Handle A2ALocalhostURLError by fixing the URL and creating a new client. + + This is called when we catch an A2ALocalhostURLError and want to retry + with the corrected URL. + + Args: + error: The localhost URL error + agent_card: The agent card object to fix + a2a_client: The current A2A client + is_streaming: Whether this is a streaming request (for logging) + + Returns: + A new A2A client with the fixed URL + + Raises: + ImportError: If the A2A SDK is not installed + """ + if not A2A_SDK_AVAILABLE or _A2AClient is None: + raise ImportError( + "A2A SDK is required for localhost retry handling. " + "Install it with: pip install a2a" + ) + + request_type = "streaming " if is_streaming else "" + verbose_logger.warning( + f"A2A {request_type}request to '{error.localhost_url}' failed: {error.original_error}. " + f"Agent card contains localhost/internal URL. " + f"Retrying with base_url '{error.base_url}'." + ) + + # Fix the agent card URL + fix_agent_card_url(agent_card, error.base_url) + + # Create a new client with the fixed agent card (transport caches URL) + return _A2AClient( + httpx_client=a2a_client._transport.httpx_client, # type: ignore[union-attr] + agent_card=agent_card, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exceptions.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..546b23105be98b0b969b2b6ff2530d05a3dae592 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/exceptions.py @@ -0,0 +1,150 @@ +""" +A2A Protocol Exceptions. + +Custom exception types for A2A protocol operations, following LiteLLM's exception pattern. +""" + +from typing import Optional + +import httpx + + +class A2AError(Exception): + """ + Base exception for A2A protocol errors. + + Follows the same pattern as LiteLLM's main exceptions. + """ + + def __init__( + self, + message: str, + status_code: int = 500, + llm_provider: str = "a2a_agent", + model: Optional[str] = None, + response: Optional[httpx.Response] = None, + litellm_debug_info: Optional[str] = None, + max_retries: Optional[int] = None, + num_retries: Optional[int] = None, + ): + self.status_code = status_code + self.message = f"litellm.A2AError: {message}" + self.llm_provider = llm_provider + self.model = model + self.litellm_debug_info = litellm_debug_info + self.max_retries = max_retries + self.num_retries = num_retries + self.response = response or httpx.Response( + status_code=self.status_code, + request=httpx.Request(method="POST", url="https://litellm.ai"), + ) + super().__init__(self.message) + + def __str__(self) -> str: + _message = self.message + if self.num_retries: + _message += f" LiteLLM Retried: {self.num_retries} times" + if self.max_retries: + _message += f", LiteLLM Max Retries: {self.max_retries}" + return _message + + def __repr__(self) -> str: + return self.__str__() + + +class A2AConnectionError(A2AError): + """ + Raised when connection to an A2A agent fails. + + This typically occurs when: + - The agent is unreachable + - The agent card contains a localhost/internal URL + - Network issues prevent connection + """ + + def __init__( + self, + message: str, + url: Optional[str] = None, + model: Optional[str] = None, + response: Optional[httpx.Response] = None, + litellm_debug_info: Optional[str] = None, + max_retries: Optional[int] = None, + num_retries: Optional[int] = None, + ): + self.url = url + super().__init__( + message=message, + status_code=503, + llm_provider="a2a_agent", + model=model, + response=response, + litellm_debug_info=litellm_debug_info, + max_retries=max_retries, + num_retries=num_retries, + ) + + +class A2AAgentCardError(A2AError): + """ + Raised when there's an issue with the agent card. + + This includes: + - Failed to fetch agent card + - Invalid agent card format + - Missing required fields + """ + + def __init__( + self, + message: str, + url: Optional[str] = None, + model: Optional[str] = None, + response: Optional[httpx.Response] = None, + litellm_debug_info: Optional[str] = None, + ): + self.url = url + super().__init__( + message=message, + status_code=404, + llm_provider="a2a_agent", + model=model, + response=response, + litellm_debug_info=litellm_debug_info, + ) + + +class A2ALocalhostURLError(A2AConnectionError): + """ + Raised when an agent card contains a localhost/internal URL. + + Many A2A agents are deployed with agent cards that contain internal URLs + like "http://0.0.0.0:8001/" or "http://localhost:8000/". This error + indicates that the URL needs to be corrected and the request should be retried. + + Attributes: + localhost_url: The localhost/internal URL found in the agent card + base_url: The public base URL that should be used instead + original_error: The original connection error that was raised + """ + + def __init__( + self, + localhost_url: str, + base_url: str, + original_error: Optional[Exception] = None, + model: Optional[str] = None, + ): + self.localhost_url = localhost_url + self.base_url = base_url + self.original_error = original_error + + message = ( + f"Agent card contains localhost/internal URL '{localhost_url}'. " + f"Retrying with base URL '{base_url}'." + ) + super().__init__( + message=message, + url=localhost_url, + model=model, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/main.py new file mode 100644 index 0000000000000000000000000000000000000000..3ad5485dea1c5ee91709656cbe7ad072a47cab57 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/main.py @@ -0,0 +1,744 @@ +""" +LiteLLM A2A SDK functions. + +Provides standalone functions with @client decorator for LiteLLM logging integration. +""" + +import asyncio +import datetime +import uuid +from typing import TYPE_CHECKING, Any, AsyncIterator, Coroutine, Dict, Optional, Union + +import litellm +from litellm._logging import verbose_logger, verbose_proxy_logger +from litellm.a2a_protocol.streaming_iterator import A2AStreamingIterator +from litellm.a2a_protocol.utils import A2ARequestUtils +from litellm.constants import DEFAULT_A2A_AGENT_TIMEOUT +from litellm.litellm_core_utils.litellm_logging import Logging +from litellm.llms.custom_httpx.http_handler import ( + get_async_httpx_client, + httpxSpecialProvider, +) +from litellm.types.agents import LiteLLMSendMessageResponse +from litellm.utils import client + +if TYPE_CHECKING: + from a2a.client import A2AClient as A2AClientType + from a2a.types import AgentCard, SendMessageRequest, SendStreamingMessageRequest + +# Runtime imports with availability check +A2A_SDK_AVAILABLE = False +A2ACardResolver: Any = None +_A2AClient: Any = None + +try: + from a2a.client import A2AClient as _A2AClient # type: ignore[no-redef] + + A2A_SDK_AVAILABLE = True +except ImportError: + pass + +# Import our custom card resolver that supports multiple well-known paths +from litellm.a2a_protocol.card_resolver import LiteLLMA2ACardResolver +from litellm.a2a_protocol.exception_mapping_utils import ( + handle_a2a_localhost_retry, + map_a2a_exception, +) +from litellm.a2a_protocol.exceptions import A2ALocalhostURLError + +# Use our custom resolver instead of the default A2A SDK resolver +A2ACardResolver = LiteLLMA2ACardResolver + + +def _set_usage_on_logging_obj( + kwargs: Dict[str, Any], + prompt_tokens: int, + completion_tokens: int, +) -> None: + """ + Set usage on litellm_logging_obj for standard logging payload. + + Args: + kwargs: The kwargs dict containing litellm_logging_obj + prompt_tokens: Number of input tokens + completion_tokens: Number of output tokens + """ + litellm_logging_obj = kwargs.get("litellm_logging_obj") + if litellm_logging_obj is not None: + usage = litellm.Usage( + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + total_tokens=prompt_tokens + completion_tokens, + ) + litellm_logging_obj.model_call_details["usage"] = usage + + +def _set_agent_id_on_logging_obj( + kwargs: Dict[str, Any], + agent_id: Optional[str], +) -> None: + """ + Set agent_id on litellm_logging_obj for SpendLogs tracking. + + Args: + kwargs: The kwargs dict containing litellm_logging_obj + agent_id: The A2A agent ID + """ + if agent_id is None: + return + + litellm_logging_obj = kwargs.get("litellm_logging_obj") + if litellm_logging_obj is not None: + # Set agent_id directly on model_call_details (same pattern as custom_llm_provider) + litellm_logging_obj.model_call_details["agent_id"] = agent_id + + +def _get_a2a_model_info(a2a_client: Any, kwargs: Dict[str, Any]) -> str: + """ + Extract agent info and set model/custom_llm_provider for cost tracking. + + Sets model info on the litellm_logging_obj if available. + Returns the agent name for logging. + """ + agent_name = "unknown" + + # Try to get agent card from our stored attribute first, then fallback to SDK attribute + agent_card = getattr(a2a_client, "_litellm_agent_card", None) + if agent_card is None: + agent_card = getattr(a2a_client, "agent_card", None) + + if agent_card is not None: + agent_name = getattr(agent_card, "name", "unknown") or "unknown" + + # Build model string + model = f"a2a_agent/{agent_name}" + custom_llm_provider = "a2a_agent" + + # Set on litellm_logging_obj if available (for standard logging payload) + litellm_logging_obj = kwargs.get("litellm_logging_obj") + if litellm_logging_obj is not None: + litellm_logging_obj.model = model + litellm_logging_obj.custom_llm_provider = custom_llm_provider + litellm_logging_obj.model_call_details["model"] = model + litellm_logging_obj.model_call_details["custom_llm_provider"] = ( + custom_llm_provider + ) + + return agent_name + + +async def _send_message_via_completion_bridge( + request: "SendMessageRequest", + custom_llm_provider: str, + api_base: Optional[str], + litellm_params: Dict[str, Any], +) -> LiteLLMSendMessageResponse: + """ + Route a send_message through the LiteLLM completion bridge (e.g. LangGraph, Bedrock AgentCore). + + Requires request; api_base is optional for providers that derive endpoint from model. + """ + verbose_logger.info( + f"A2A using completion bridge: provider={custom_llm_provider}, api_base={api_base}" + ) + + from litellm.a2a_protocol.litellm_completion_bridge.handler import ( + A2ACompletionBridgeHandler, + ) + + params = ( + request.params.model_dump(mode="json") + if hasattr(request.params, "model_dump") + else dict(request.params) + ) + + response_dict = await A2ACompletionBridgeHandler.handle_non_streaming( + request_id=str(request.id), + params=params, + litellm_params=litellm_params, + api_base=api_base, + ) + + return LiteLLMSendMessageResponse.from_dict(response_dict) + + +async def _execute_a2a_send_with_retry( + a2a_client: Any, + request: Any, + agent_card: Any, + card_url: Optional[str], + api_base: Optional[str], + agent_name: Optional[str], +) -> Any: + """Send an A2A message with retry logic for localhost URL errors.""" + a2a_response = None + for _ in range(2): # max 2 attempts: original + 1 retry + try: + a2a_response = await a2a_client.send_message(request) + break # success, exit retry loop + except A2ALocalhostURLError as e: + a2a_client = handle_a2a_localhost_retry( + error=e, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=False, + ) + card_url = agent_card.url if agent_card else None + except Exception as e: + try: + map_a2a_exception(e, card_url, api_base, model=agent_name) + except A2ALocalhostURLError as localhost_err: + a2a_client = handle_a2a_localhost_retry( + error=localhost_err, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=False, + ) + card_url = agent_card.url if agent_card else None + continue + except Exception: + raise + if a2a_response is None: + raise RuntimeError( + "A2A send_message failed: no response received after retry attempts." + ) + return a2a_response + + +@client +async def asend_message( + a2a_client: Optional["A2AClientType"] = None, + request: Optional["SendMessageRequest"] = None, + api_base: Optional[str] = None, + litellm_params: Optional[Dict[str, Any]] = None, + agent_id: Optional[str] = None, + agent_extra_headers: Optional[Dict[str, str]] = None, + **kwargs: Any, +) -> LiteLLMSendMessageResponse: + """ + Async: Send a message to an A2A agent. + + Uses the @client decorator for LiteLLM logging and tracking. + If litellm_params contains custom_llm_provider, routes through the completion bridge. + + Args: + a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge) + request: SendMessageRequest from a2a.types (optional if using completion bridge with api_base) + api_base: API base URL (required for completion bridge, optional for standard A2A) + litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge + agent_id: Optional agent ID for tracking in SpendLogs + **kwargs: Additional arguments passed to the client decorator + + Returns: + LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params) + + Example (standard A2A): + ```python + from litellm.a2a_protocol import asend_message, create_a2a_client + from a2a.types import SendMessageRequest, MessageSendParams + from uuid import uuid4 + + a2a_client = await create_a2a_client(base_url="http://localhost:10001") + request = SendMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex} + ) + ) + response = await asend_message(a2a_client=a2a_client, request=request) + ``` + + Example (completion bridge with LangGraph): + ```python + from litellm.a2a_protocol import asend_message + from a2a.types import SendMessageRequest, MessageSendParams + from uuid import uuid4 + + request = SendMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex} + ) + ) + response = await asend_message( + request=request, + api_base="http://localhost:2024", + litellm_params={"custom_llm_provider": "langgraph", "model": "agent"}, + ) + ``` + """ + litellm_params = litellm_params or {} + logging_obj = kwargs.get("litellm_logging_obj") + trace_id = getattr(logging_obj, "litellm_trace_id", None) if logging_obj else None + custom_llm_provider = litellm_params.get("custom_llm_provider") + + # Route through completion bridge if custom_llm_provider is set + if custom_llm_provider: + if request is None: + raise ValueError("request is required for completion bridge") + return await _send_message_via_completion_bridge( + request=request, + custom_llm_provider=custom_llm_provider, + api_base=api_base, + litellm_params=litellm_params, + ) + + # Standard A2A client flow + if request is None: + raise ValueError("request is required") + + # Create A2A client if not provided but api_base is available + if a2a_client is None: + if api_base is None: + raise ValueError( + "Either a2a_client or api_base is required for standard A2A flow" + ) + trace_id = trace_id or str(uuid.uuid4()) + extra_headers: Dict[str, str] = {"X-LiteLLM-Trace-Id": trace_id} + if agent_id: + extra_headers["X-LiteLLM-Agent-Id"] = agent_id + # Overlay agent-level headers (agent headers take precedence over LiteLLM internal ones) + if agent_extra_headers: + extra_headers.update(agent_extra_headers) + a2a_client = await create_a2a_client( + base_url=api_base, extra_headers=extra_headers + ) + + # Type assertion: a2a_client is guaranteed to be non-None here + assert a2a_client is not None + + agent_name = _get_a2a_model_info(a2a_client, kwargs) + + verbose_logger.info(f"A2A send_message request_id={request.id}, agent={agent_name}") + + # Get agent card URL for localhost retry logic + agent_card = getattr(a2a_client, "_litellm_agent_card", None) or getattr( + a2a_client, "agent_card", None + ) + card_url = getattr(agent_card, "url", None) if agent_card else None + + context_id = trace_id or str(uuid.uuid4()) + message = request.params.message + if isinstance(message, dict): + if message.get("context_id") is None: + message["context_id"] = context_id + else: + if getattr(message, "context_id", None) is None: + message.context_id = context_id + + a2a_response = await _execute_a2a_send_with_retry( + a2a_client=a2a_client, + request=request, + agent_card=agent_card, + card_url=card_url, + api_base=api_base, + agent_name=agent_name, + ) + + verbose_logger.info(f"A2A send_message completed, request_id={request.id}") + + # Wrap in LiteLLM response type for _hidden_params support + response = LiteLLMSendMessageResponse.from_a2a_response(a2a_response) + + # Calculate token usage from request and response + response_dict = a2a_response.model_dump(mode="json", exclude_none=True) + ( + prompt_tokens, + completion_tokens, + _, + ) = A2ARequestUtils.calculate_usage_from_request_response( + request=request, + response_dict=response_dict, + ) + + # Set usage on logging obj for standard logging payload + _set_usage_on_logging_obj( + kwargs=kwargs, + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + ) + + # Set agent_id on logging obj for SpendLogs tracking + _set_agent_id_on_logging_obj(kwargs=kwargs, agent_id=agent_id) + + return response + + +@client +def send_message( + a2a_client: "A2AClientType", + request: "SendMessageRequest", + **kwargs: Any, +) -> Union[LiteLLMSendMessageResponse, Coroutine[Any, Any, LiteLLMSendMessageResponse]]: + """ + Sync: Send a message to an A2A agent. + + Uses the @client decorator for LiteLLM logging and tracking. + + Args: + a2a_client: An initialized a2a.client.A2AClient instance + request: SendMessageRequest from a2a.types + **kwargs: Additional arguments passed to the client decorator + + Returns: + LiteLLMSendMessageResponse (wraps a2a SendMessageResponse with _hidden_params) + """ + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = None + + if loop is not None: + return asend_message(a2a_client=a2a_client, request=request, **kwargs) + else: + return asyncio.run( + asend_message(a2a_client=a2a_client, request=request, **kwargs) + ) + + +def _build_streaming_logging_obj( + request: "SendStreamingMessageRequest", + agent_name: str, + agent_id: Optional[str], + litellm_params: Optional[Dict[str, Any]], + metadata: Optional[Dict[str, Any]], + proxy_server_request: Optional[Dict[str, Any]], +) -> Logging: + """Build logging object for streaming A2A requests.""" + start_time = datetime.datetime.now() + model = f"a2a_agent/{agent_name}" + + logging_obj = Logging( + model=model, + messages=[{"role": "user", "content": "streaming-request"}], + stream=False, + call_type="asend_message_streaming", + start_time=start_time, + litellm_call_id=str(request.id), + function_id=str(request.id), + ) + logging_obj.model = model + logging_obj.custom_llm_provider = "a2a_agent" + logging_obj.model_call_details["model"] = model + logging_obj.model_call_details["custom_llm_provider"] = "a2a_agent" + if agent_id: + logging_obj.model_call_details["agent_id"] = agent_id + + _litellm_params = litellm_params.copy() if litellm_params else {} + if metadata: + _litellm_params["metadata"] = metadata + if proxy_server_request: + _litellm_params["proxy_server_request"] = proxy_server_request + + logging_obj.litellm_params = _litellm_params + logging_obj.optional_params = _litellm_params + logging_obj.model_call_details["litellm_params"] = _litellm_params + logging_obj.model_call_details["metadata"] = metadata or {} + + return logging_obj + + +async def asend_message_streaming( # noqa: PLR0915 + a2a_client: Optional["A2AClientType"] = None, + request: Optional["SendStreamingMessageRequest"] = None, + api_base: Optional[str] = None, + litellm_params: Optional[Dict[str, Any]] = None, + agent_id: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, + proxy_server_request: Optional[Dict[str, Any]] = None, + agent_extra_headers: Optional[Dict[str, str]] = None, +) -> AsyncIterator[Any]: + """ + Async: Send a streaming message to an A2A agent. + + If litellm_params contains custom_llm_provider, routes through the completion bridge. + + Args: + a2a_client: An initialized a2a.client.A2AClient instance (optional if using completion bridge) + request: SendStreamingMessageRequest from a2a.types + api_base: API base URL (required for completion bridge) + litellm_params: Optional dict with custom_llm_provider, model, etc. for completion bridge + agent_id: Optional agent ID for tracking in SpendLogs + metadata: Optional metadata dict (contains user_api_key, user_id, team_id, etc.) + proxy_server_request: Optional proxy server request data + + Yields: + SendStreamingMessageResponse chunks from the agent + + Example (completion bridge with LangGraph): + ```python + from litellm.a2a_protocol import asend_message_streaming + from a2a.types import SendStreamingMessageRequest, MessageSendParams + from uuid import uuid4 + + request = SendStreamingMessageRequest( + id=str(uuid4()), + params=MessageSendParams( + message={"role": "user", "parts": [{"kind": "text", "text": "Hello!"}], "messageId": uuid4().hex} + ) + ) + async for chunk in asend_message_streaming( + request=request, + api_base="http://localhost:2024", + litellm_params={"custom_llm_provider": "langgraph", "model": "agent"}, + ): + print(chunk) + ``` + """ + litellm_params = litellm_params or {} + custom_llm_provider = litellm_params.get("custom_llm_provider") + + # Route through completion bridge if custom_llm_provider is set + if custom_llm_provider: + if request is None: + raise ValueError("request is required for completion bridge") + # api_base is optional for providers that derive endpoint from model (e.g., bedrock/agentcore) + + verbose_logger.info( + f"A2A streaming using completion bridge: provider={custom_llm_provider}" + ) + + from litellm.a2a_protocol.litellm_completion_bridge.handler import ( + A2ACompletionBridgeHandler, + ) + + # Extract params from request + params = ( + request.params.model_dump(mode="json") + if hasattr(request.params, "model_dump") + else dict(request.params) + ) + + async for chunk in A2ACompletionBridgeHandler.handle_streaming( + request_id=str(request.id), + params=params, + litellm_params=litellm_params, + api_base=api_base, + ): + yield chunk + return + + # Standard A2A client flow + if request is None: + raise ValueError("request is required") + + # Create A2A client if not provided but api_base is available + if a2a_client is None: + if api_base is None: + raise ValueError( + "Either a2a_client or api_base is required for standard A2A flow" + ) + # Mirror the non-streaming path: always include trace and agent-id headers + streaming_extra_headers: Dict[str, str] = { + "X-LiteLLM-Trace-Id": str(request.id), + } + if agent_id: + streaming_extra_headers["X-LiteLLM-Agent-Id"] = agent_id + if agent_extra_headers: + streaming_extra_headers.update(agent_extra_headers) + a2a_client = await create_a2a_client( + base_url=api_base, extra_headers=streaming_extra_headers + ) + + # Type assertion: a2a_client is guaranteed to be non-None here + assert a2a_client is not None + + verbose_logger.info(f"A2A send_message_streaming request_id={request.id}") + + # Build logging object for streaming completion callbacks + agent_card = getattr(a2a_client, "_litellm_agent_card", None) or getattr( + a2a_client, "agent_card", None + ) + card_url = getattr(agent_card, "url", None) if agent_card else None + agent_name = getattr(agent_card, "name", "unknown") if agent_card else "unknown" + + logging_obj = _build_streaming_logging_obj( + request=request, + agent_name=agent_name, + agent_id=agent_id, + litellm_params=litellm_params, + metadata=metadata, + proxy_server_request=proxy_server_request, + ) + + # Retry loop: if connection fails due to localhost URL in agent card, retry with fixed URL + # Connection errors in streaming typically occur on first chunk iteration + first_chunk = True + for attempt in range(2): # max 2 attempts: original + 1 retry + stream = a2a_client.send_message_streaming(request) + iterator = A2AStreamingIterator( + stream=stream, + request=request, + logging_obj=logging_obj, + agent_name=agent_name, + ) + + try: + first_chunk = True + async for chunk in iterator: + if first_chunk: + first_chunk = False # connection succeeded + yield chunk + return # stream completed successfully + except A2ALocalhostURLError as e: + # Only retry on first chunk, not mid-stream + if first_chunk and attempt == 0: + a2a_client = handle_a2a_localhost_retry( + error=e, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=True, + ) + card_url = agent_card.url if agent_card else None + else: + raise + except Exception as e: + # Only map exception on first chunk + if first_chunk and attempt == 0: + try: + map_a2a_exception(e, card_url, api_base, model=agent_name) + except A2ALocalhostURLError as localhost_err: + # Localhost URL error - fix and retry + a2a_client = handle_a2a_localhost_retry( + error=localhost_err, + agent_card=agent_card, + a2a_client=a2a_client, + is_streaming=True, + ) + card_url = agent_card.url if agent_card else None + continue + except Exception: + # Re-raise the mapped exception + raise + raise + + +async def create_a2a_client( + base_url: str, + timeout: float = DEFAULT_A2A_AGENT_TIMEOUT, + extra_headers: Optional[Dict[str, str]] = None, +) -> "A2AClientType": + """ + Create an A2A client for the given agent URL. + + This resolves the agent card and returns a ready-to-use A2A client. + The client can be reused for multiple requests. + + Args: + base_url: The base URL of the A2A agent (e.g., "http://localhost:10001") + timeout: Request timeout in seconds (default: ``DEFAULT_A2A_AGENT_TIMEOUT`` / env ``DEFAULT_A2A_AGENT_TIMEOUT``) + extra_headers: Optional additional headers to include in requests + + Returns: + An initialized a2a.client.A2AClient instance + + Example: + ```python + from litellm.a2a_protocol import create_a2a_client, asend_message + + # Create client once + client = await create_a2a_client(base_url="http://localhost:10001") + + # Reuse for multiple requests + response1 = await asend_message(a2a_client=client, request=request1) + response2 = await asend_message(a2a_client=client, request=request2) + ``` + """ + if not A2A_SDK_AVAILABLE: + raise ImportError( + "The 'a2a' package is required for A2A agent invocation. " + "Install it with: pip install a2a-sdk" + ) + + verbose_logger.info(f"Creating A2A client for {base_url}") + + # Use get_async_httpx_client with per-agent params so that different agents + # (with different extra_headers) get separate cached clients. The params + # dict is hashed into the cache key, keeping agent auth isolated while + # still reusing connections within the same agent. + # + # Only pass params that AsyncHTTPHandler.__init__ accepts (e.g. timeout). + # Use "disable_aiohttp_transport" key for cache-key-only data (it's + # filtered out before reaching the constructor). + _client_params: dict = {"timeout": timeout} + if extra_headers: + # Encode headers into a cache-key-only param so each unique header + # set produces a distinct cache key. + _client_params["disable_aiohttp_transport"] = str(sorted(extra_headers.items())) + _async_handler = get_async_httpx_client( + llm_provider=httpxSpecialProvider.A2AProvider, + params=_client_params, + ) + httpx_client = _async_handler.client + if extra_headers: + httpx_client.headers.update(extra_headers) + verbose_proxy_logger.debug( + f"A2A client created with extra_headers={list(extra_headers.keys())}" + ) + + # Resolve agent card + resolver = A2ACardResolver( + httpx_client=httpx_client, + base_url=base_url, + ) + agent_card = await resolver.get_agent_card() + + verbose_logger.debug( + f"Resolved agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}" + ) + + # Create A2A client + a2a_client = _A2AClient( + httpx_client=httpx_client, + agent_card=agent_card, + ) + + # Store agent_card on client for later retrieval (SDK doesn't expose it) + a2a_client._litellm_agent_card = agent_card # type: ignore[attr-defined] + + verbose_logger.info(f"A2A client created for {base_url}") + + return a2a_client + + +async def aget_agent_card( + base_url: str, + timeout: float = DEFAULT_A2A_AGENT_TIMEOUT, + extra_headers: Optional[Dict[str, str]] = None, +) -> "AgentCard": + """ + Fetch the agent card from an A2A agent. + + Args: + base_url: The base URL of the A2A agent (e.g., "http://localhost:10001") + timeout: Request timeout in seconds (default: ``DEFAULT_A2A_AGENT_TIMEOUT`` / env ``DEFAULT_A2A_AGENT_TIMEOUT``) + extra_headers: Optional additional headers to include in requests + + Returns: + AgentCard from the A2A agent + """ + if not A2A_SDK_AVAILABLE: + raise ImportError( + "The 'a2a' package is required for A2A agent invocation. " + "Install it with: pip install a2a-sdk" + ) + + verbose_logger.info(f"Fetching agent card from {base_url}") + + # Use LiteLLM's cached httpx client + http_handler = get_async_httpx_client( + llm_provider=httpxSpecialProvider.A2A, + params={"timeout": timeout}, + ) + httpx_client = http_handler.client + + resolver = A2ACardResolver( + httpx_client=httpx_client, + base_url=base_url, + ) + agent_card = await resolver.get_agent_card() + + verbose_logger.info( + f"Fetched agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}" + ) + return agent_card diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/streaming_iterator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/streaming_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ae9bcdc3cf55f59121417a602604dc1d90b7b3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/streaming_iterator.py @@ -0,0 +1,184 @@ +""" +A2A Streaming Iterator with token tracking and logging support. +""" + +import asyncio +from datetime import datetime +from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, List, Optional + +import litellm +from litellm._logging import verbose_logger +from litellm.a2a_protocol.cost_calculator import A2ACostCalculator +from litellm.a2a_protocol.utils import A2ARequestUtils +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.litellm_core_utils.thread_pool_executor import executor + +if TYPE_CHECKING: + from a2a.types import SendStreamingMessageRequest, SendStreamingMessageResponse + + +class A2AStreamingIterator: + """ + Async iterator for A2A streaming responses with token tracking. + + Collects chunks, extracts text, and logs usage on completion. + """ + + def __init__( + self, + stream: AsyncIterator["SendStreamingMessageResponse"], + request: "SendStreamingMessageRequest", + logging_obj: LiteLLMLoggingObj, + agent_name: str = "unknown", + ): + self.stream = stream + self.request = request + self.logging_obj = logging_obj + self.agent_name = agent_name + self.start_time = datetime.now() + + # Collect chunks for token counting + self.chunks: List[Any] = [] + self.collected_text_parts: List[str] = [] + self.final_chunk: Optional[Any] = None + + def __aiter__(self): + return self + + async def __anext__(self) -> "SendStreamingMessageResponse": + try: + chunk = await self.stream.__anext__() + + # Store chunk + self.chunks.append(chunk) + + # Extract text from chunk for token counting + self._collect_text_from_chunk(chunk) + + # Check if this is the final chunk (completed status) + if self._is_completed_chunk(chunk): + self.final_chunk = chunk + + return chunk + + except StopAsyncIteration: + # Stream ended - handle logging + if self.final_chunk is None and self.chunks: + self.final_chunk = self.chunks[-1] + await self._handle_stream_complete() + raise + + def _collect_text_from_chunk(self, chunk: Any) -> None: + """Extract text from a streaming chunk and add to collected parts.""" + try: + chunk_dict = ( + chunk.model_dump(mode="json", exclude_none=True) + if hasattr(chunk, "model_dump") + else {} + ) + text = A2ARequestUtils.extract_text_from_response(chunk_dict) + if text: + self.collected_text_parts.append(text) + except Exception: + verbose_logger.debug("Failed to extract text from A2A streaming chunk") + + def _is_completed_chunk(self, chunk: Any) -> bool: + """Check if chunk indicates stream completion.""" + try: + chunk_dict = ( + chunk.model_dump(mode="json", exclude_none=True) + if hasattr(chunk, "model_dump") + else {} + ) + result = chunk_dict.get("result", {}) + if isinstance(result, dict): + status = result.get("status", {}) + if isinstance(status, dict): + return status.get("state") == "completed" + except Exception: + pass + return False + + async def _handle_stream_complete(self) -> None: + """Handle logging and token counting when stream completes.""" + try: + end_time = datetime.now() + + # Calculate tokens from collected text + input_message = A2ARequestUtils.get_input_message_from_request(self.request) + input_text = A2ARequestUtils.extract_text_from_message(input_message) + prompt_tokens = A2ARequestUtils.count_tokens(input_text) + + # Use the last (most complete) text from chunks + output_text = ( + self.collected_text_parts[-1] if self.collected_text_parts else "" + ) + completion_tokens = A2ARequestUtils.count_tokens(output_text) + + total_tokens = prompt_tokens + completion_tokens + + # Create usage object + usage = litellm.Usage( + prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, + total_tokens=total_tokens, + ) + + # Set usage on logging obj + self.logging_obj.model_call_details["usage"] = usage + # Mark stream flag for downstream callbacks + self.logging_obj.model_call_details["stream"] = False + + # Calculate cost using A2ACostCalculator + response_cost = A2ACostCalculator.calculate_a2a_cost(self.logging_obj) + self.logging_obj.model_call_details["response_cost"] = response_cost + + # Build result for logging + result = self._build_logging_result(usage) + + # Call success handlers - they will build standard_logging_object + asyncio.create_task( + self.logging_obj.async_success_handler( + result=result, + start_time=self.start_time, + end_time=end_time, + cache_hit=None, + ) + ) + + executor.submit( + self.logging_obj.success_handler, + result=result, + cache_hit=None, + start_time=self.start_time, + end_time=end_time, + ) + + verbose_logger.info( + f"A2A streaming completed: prompt_tokens={prompt_tokens}, " + f"completion_tokens={completion_tokens}, total_tokens={total_tokens}, " + f"response_cost={response_cost}" + ) + + except Exception as e: + verbose_logger.debug(f"Error in A2A streaming completion handler: {e}") + + def _build_logging_result(self, usage: litellm.Usage) -> Dict[str, Any]: + """Build a result dict for logging.""" + result: Dict[str, Any] = { + "id": getattr(self.request, "id", "unknown"), + "jsonrpc": "2.0", + "usage": ( + usage.model_dump() if hasattr(usage, "model_dump") else dict(usage) + ), + } + + # Add final chunk result if available + if self.final_chunk: + try: + chunk_dict = self.final_chunk.model_dump(mode="json", exclude_none=True) + result["result"] = chunk_dict.get("result", {}) + except Exception: + pass + + return result diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1cdbde97755e9f3f0e0e75dd11c714f2f6af51a5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/a2a_protocol/utils.py @@ -0,0 +1,138 @@ +""" +Utility functions for A2A protocol. +""" + +from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union + +import litellm +from litellm._logging import verbose_logger + +if TYPE_CHECKING: + from a2a.types import SendMessageRequest, SendStreamingMessageRequest + + +class A2ARequestUtils: + """Utility class for A2A request/response processing.""" + + @staticmethod + def extract_text_from_message(message: Any) -> str: + """ + Extract text content from A2A message parts. + + Args: + message: A2A message dict or object with 'parts' containing text parts + + Returns: + Concatenated text from all text parts + """ + if message is None: + return "" + + # Handle both dict and object access + if isinstance(message, dict): + parts = message.get("parts", []) + else: + parts = getattr(message, "parts", []) or [] + + text_parts: List[str] = [] + for part in parts: + if isinstance(part, dict): + if part.get("kind") == "text": + text_parts.append(part.get("text", "")) + else: + if getattr(part, "kind", None) == "text": + text_parts.append(getattr(part, "text", "")) + + return " ".join(text_parts) + + @staticmethod + def extract_text_from_response(response_dict: Dict[str, Any]) -> str: + """ + Extract text content from A2A response result. + + Args: + response_dict: A2A response dict with 'result' containing message + + Returns: + Text from response message parts + """ + result = response_dict.get("result", {}) + if not isinstance(result, dict): + return "" + + message = result.get("message", {}) + return A2ARequestUtils.extract_text_from_message(message) + + @staticmethod + def get_input_message_from_request( + request: "Union[SendMessageRequest, SendStreamingMessageRequest]", + ) -> Any: + """ + Extract the input message from an A2A request. + + Args: + request: The A2A SendMessageRequest or SendStreamingMessageRequest + + Returns: + The message object/dict or None + """ + params = getattr(request, "params", None) + if params is None: + return None + return getattr(params, "message", None) + + @staticmethod + def count_tokens(text: str) -> int: + """ + Count tokens in text using litellm.token_counter. + + Args: + text: Text to count tokens for + + Returns: + Token count, or 0 if counting fails + """ + if not text: + return 0 + try: + return litellm.token_counter(text=text) + except Exception: + verbose_logger.debug("Failed to count tokens") + return 0 + + @staticmethod + def calculate_usage_from_request_response( + request: "Union[SendMessageRequest, SendStreamingMessageRequest]", + response_dict: Dict[str, Any], + ) -> Tuple[int, int, int]: + """ + Calculate token usage from A2A request and response. + + Args: + request: The A2A SendMessageRequest or SendStreamingMessageRequest + response_dict: The A2A response as a dict + + Returns: + Tuple of (prompt_tokens, completion_tokens, total_tokens) + """ + # Count input tokens + input_message = A2ARequestUtils.get_input_message_from_request(request) + input_text = A2ARequestUtils.extract_text_from_message(input_message) + prompt_tokens = A2ARequestUtils.count_tokens(input_text) + + # Count output tokens + output_text = A2ARequestUtils.extract_text_from_response(response_dict) + completion_tokens = A2ARequestUtils.count_tokens(output_text) + + total_tokens = prompt_tokens + completion_tokens + + return prompt_tokens, completion_tokens, total_tokens + + +# Backwards compatibility aliases +def extract_text_from_a2a_message(message: Any) -> str: + return A2ARequestUtils.extract_text_from_message(message) + + +def extract_text_from_a2a_response(response_dict: Dict[str, Any]) -> str: + return A2ARequestUtils.extract_text_from_response(response_dict) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..280d70142b14134359580268e5d8da3a629b1e5e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/__init__.py @@ -0,0 +1,7 @@ +""" +Anthropic module for LiteLLM +""" + +from .messages import acreate, create + +__all__ = ["acreate", "create"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/readme.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..01c5f1b7c31654670828f41f8c7fdbc55c244346 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/anthropic_interface/readme.md @@ -0,0 +1,116 @@ +## Use LLM API endpoints in Anthropic Interface + +Note: This is called `anthropic_interface` because `anthropic` is a known python package and was failing mypy type checking. + + +## Usage +--- + +### LiteLLM Python SDK + +#### Non-streaming example +```python showLineNumbers title="Example using LiteLLM Python SDK" +import litellm +response = await litellm.anthropic.messages.acreate( + messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}], + api_key=api_key, + model="anthropic/claude-3-haiku-20240307", + max_tokens=100, +) +``` + +Example response: +```json +{ + "content": [ + { + "text": "Hi! this is a very short joke", + "type": "text" + } + ], + "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF", + "model": "claude-3-7-sonnet-20250219", + "role": "assistant", + "stop_reason": "end_turn", + "stop_sequence": null, + "type": "message", + "usage": { + "input_tokens": 2095, + "output_tokens": 503, + "cache_creation_input_tokens": 2095, + "cache_read_input_tokens": 0 + } +} +``` + +#### Streaming example +```python showLineNumbers title="Example using LiteLLM Python SDK" +import litellm +response = await litellm.anthropic.messages.acreate( + messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}], + api_key=api_key, + model="anthropic/claude-3-haiku-20240307", + max_tokens=100, + stream=True, +) +async for chunk in response: + print(chunk) +``` + +### LiteLLM Proxy Server + + +1. Setup config.yaml + +```yaml +model_list: + - model_name: anthropic-claude + litellm_params: + model: claude-3-7-sonnet-latest +``` + +2. Start proxy + +```bash +litellm --config /path/to/config.yaml +``` + +3. Test it! + + + + +```python showLineNumbers title="Example using LiteLLM Proxy Server" +import anthropic + +# point anthropic sdk to litellm proxy +client = anthropic.Anthropic( + base_url="http://0.0.0.0:4000", + api_key="sk-1234", +) + +response = client.messages.create( + messages=[{"role": "user", "content": "Hello, can you tell me a short joke?"}], + model="anthropic/claude-3-haiku-20240307", + max_tokens=100, +) +``` + + + +```bash showLineNumbers title="Example using LiteLLM Proxy Server" +curl -L -X POST 'http://0.0.0.0:4000/v1/messages' \ +-H 'content-type: application/json' \ +-H 'x-api-key: $LITELLM_API_KEY' \ +-H 'anthropic-version: 2023-06-01' \ +-d '{ + "model": "anthropic-claude", + "messages": [ + { + "role": "user", + "content": "Hello, can you tell me a short joke?" + } + ], + "max_tokens": 100 +}' +``` \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/main.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9375e6b84ca14707abdb71fc88e9dd2ff63be6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/main.py @@ -0,0 +1,1484 @@ +# What is this? +## Main file for assistants API logic +import asyncio +import contextvars +import os +from functools import partial +from typing import Any, Coroutine, Dict, Iterable, List, Literal, Optional, Union + +import httpx +from openai import AsyncOpenAI, OpenAI +from openai.types.beta.assistant import Assistant +from openai.types.beta.assistant_deleted import AssistantDeleted + +import litellm +from litellm.types.router import GenericLiteLLMParams +from litellm.utils import ( + exception_type, + get_litellm_params, + get_llm_provider, + get_secret, + supports_httpx_timeout, +) + +from ..llms.azure.assistants import AzureAssistantsAPI +from ..llms.openai.openai import OpenAIAssistantsAPI +from ..types.llms.openai import * +from ..types.router import * +from .utils import get_optional_params_add_message + +####### ENVIRONMENT VARIABLES ################### +openai_assistants_api = OpenAIAssistantsAPI() +azure_assistants_api = AzureAssistantsAPI() + +### ASSISTANTS ### + + +async def aget_assistants( + custom_llm_provider: Literal["openai", "azure"], + client: Optional[AsyncOpenAI] = None, + **kwargs, +) -> AsyncCursorPage[Assistant]: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["aget_assistants"] = True + try: + # Use a partial function to pass your keyword arguments + func = partial(get_assistants, custom_llm_provider, client, **kwargs) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def get_assistants( + custom_llm_provider: Literal["openai", "azure"], + client: Optional[Any] = None, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + api_version: Optional[str] = None, + **kwargs, +) -> SyncCursorPage[Assistant]: + aget_assistants: Optional[bool] = kwargs.pop("aget_assistants", None) + if aget_assistants is not None and not isinstance(aget_assistants, bool): + raise Exception( + "Invalid value passed in for aget_assistants. Only bool or None allowed" + ) + optional_params = GenericLiteLLMParams( + api_key=api_key, api_base=api_base, api_version=api_version, **kwargs + ) + litellm_params_dict = get_litellm_params(**kwargs) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + response: Optional[SyncCursorPage[Assistant]] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_assistants_api.get_assistants( + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + client=client, + aget_assistants=aget_assistants, # type: ignore + ) # type: ignore + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + response = azure_assistants_api.get_assistants( + api_base=api_base, + api_key=api_key, + api_version=api_version, + azure_ad_token=azure_ad_token, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + aget_assistants=aget_assistants, # type: ignore + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'get_assistants'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + + if response is None: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'get_assistants'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + + return response + + +async def acreate_assistants( + custom_llm_provider: Literal["openai", "azure"], + client: Optional[AsyncOpenAI] = None, + **kwargs, +) -> Assistant: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["async_create_assistants"] = True + model = kwargs.pop("model", None) + try: + kwargs["client"] = client + # Use a partial function to pass your keyword arguments + func = partial(create_assistants, custom_llm_provider, model, **kwargs) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model=model, custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def create_assistants( + custom_llm_provider: Literal["openai", "azure"], + model: str, + name: Optional[str] = None, + description: Optional[str] = None, + instructions: Optional[str] = None, + tools: Optional[List[Dict[str, Any]]] = None, + tool_resources: Optional[Dict[str, Any]] = None, + metadata: Optional[Dict[str, str]] = None, + temperature: Optional[float] = None, + top_p: Optional[float] = None, + response_format: Optional[Union[str, Dict[str, str]]] = None, + client: Optional[Any] = None, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + api_version: Optional[str] = None, + **kwargs, +) -> Union[Assistant, Coroutine[Any, Any, Assistant]]: + async_create_assistants: Optional[bool] = kwargs.pop( + "async_create_assistants", None + ) + if async_create_assistants is not None and not isinstance( + async_create_assistants, bool + ): + raise ValueError( + "Invalid value passed in for async_create_assistants. Only bool or None allowed" + ) + optional_params = GenericLiteLLMParams( + api_key=api_key, api_base=api_base, api_version=api_version, **kwargs + ) + litellm_params_dict = get_litellm_params(**kwargs) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + create_assistant_data = { + "model": model, + "name": name, + "description": description, + "instructions": instructions, + "tools": tools, + "tool_resources": tool_resources, + "metadata": metadata, + "temperature": temperature, + "top_p": top_p, + "response_format": response_format, + } + + # only send params that are not None + create_assistant_data = { + k: v for k, v in create_assistant_data.items() if v is not None + } + + response: Optional[Union[Coroutine[Any, Any, Assistant], Assistant]] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_assistants_api.create_assistants( + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + create_assistant_data=create_assistant_data, + client=client, + async_create_assistants=async_create_assistants, # type: ignore + ) # type: ignore + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + if isinstance(client, OpenAI): + client = None # only pass client if it's AzureOpenAI + + response = azure_assistants_api.create_assistants( + api_base=api_base, + api_key=api_key, + azure_ad_token=azure_ad_token, + api_version=api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + async_create_assistants=async_create_assistants, + create_assistant_data=create_assistant_data, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_assistants'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + if response is None: + raise litellm.exceptions.InternalServerError( + message="No response returned from 'create_assistants'", + model=model, + llm_provider=custom_llm_provider, + ) + return response + + +async def adelete_assistant( + custom_llm_provider: Literal["openai", "azure"], + client: Optional[AsyncOpenAI] = None, + **kwargs, +) -> AssistantDeleted: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["async_delete_assistants"] = True + try: + kwargs["client"] = client + # Use a partial function to pass your keyword arguments + func = partial(delete_assistant, custom_llm_provider, **kwargs) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def delete_assistant( + custom_llm_provider: Literal["openai", "azure"], + assistant_id: str, + client: Optional[Any] = None, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + api_version: Optional[str] = None, + **kwargs, +) -> Union[AssistantDeleted, Coroutine[Any, Any, AssistantDeleted]]: + optional_params = GenericLiteLLMParams( + api_key=api_key, api_base=api_base, api_version=api_version, **kwargs + ) + + litellm_params_dict = get_litellm_params(**kwargs) + + async_delete_assistants: Optional[bool] = kwargs.pop( + "async_delete_assistants", None + ) + if async_delete_assistants is not None and not isinstance( + async_delete_assistants, bool + ): + raise ValueError( + "Invalid value passed in for async_delete_assistants. Only bool or None allowed" + ) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + response: Optional[ + Union[AssistantDeleted, Coroutine[Any, Any, AssistantDeleted]] + ] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_assistants_api.delete_assistant( + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + assistant_id=assistant_id, + client=client, + async_delete_assistants=async_delete_assistants, + ) + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + if isinstance(client, OpenAI): + client = None # only pass client if it's AzureOpenAI + + response = azure_assistants_api.delete_assistant( + assistant_id=assistant_id, + api_base=api_base, + api_key=api_key, + azure_ad_token=azure_ad_token, + api_version=api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + async_delete_assistants=async_delete_assistants, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'delete_assistant'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request( + method="delete_assistant", url="https://github.com/BerriAI/litellm" + ), + ), + ) + if response is None: + raise litellm.exceptions.InternalServerError( + message="No response returned from 'delete_assistant'", + model="n/a", + llm_provider=custom_llm_provider, + ) + return response + + +### THREADS ### + + +async def acreate_thread( + custom_llm_provider: Literal["openai", "azure"], **kwargs +) -> Thread: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["acreate_thread"] = True + try: + # Use a partial function to pass your keyword arguments + func = partial(create_thread, custom_llm_provider, **kwargs) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def create_thread( + custom_llm_provider: Literal["openai", "azure"], + messages: Optional[Iterable[OpenAICreateThreadParamsMessage]] = None, + metadata: Optional[dict] = None, + tool_resources: Optional[OpenAICreateThreadParamsToolResources] = None, + client: Optional[OpenAI] = None, + **kwargs, +) -> Thread: + """ + - get the llm provider + - if openai - route it there + - pass through relevant params + + ``` + from litellm import create_thread + + create_thread( + custom_llm_provider="openai", + ### OPTIONAL ### + messages = { + "role": "user", + "content": "Hello, what is AI?" + }, + { + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }] + ) + ``` + """ + acreate_thread = kwargs.get("acreate_thread", None) + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = get_litellm_params(**kwargs) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + api_base: Optional[str] = None + api_key: Optional[str] = None + + response: Optional[Thread] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + response = openai_assistants_api.create_thread( + messages=messages, + metadata=metadata, + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + client=client, + acreate_thread=acreate_thread, + ) + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + api_version: Optional[str] = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + if isinstance(client, OpenAI): + client = None # only pass client if it's AzureOpenAI + + response = azure_assistants_api.create_thread( + messages=messages, + metadata=metadata, + api_base=api_base, + api_key=api_key, + azure_ad_token=azure_ad_token, + api_version=api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + acreate_thread=acreate_thread, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_thread'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response # type: ignore + + +async def aget_thread( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + client: Optional[AsyncOpenAI] = None, + **kwargs, +) -> Thread: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["aget_thread"] = True + try: + # Use a partial function to pass your keyword arguments + func = partial(get_thread, custom_llm_provider, thread_id, client, **kwargs) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def get_thread( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + client=None, + **kwargs, +) -> Thread: + """Get the thread object, given a thread_id""" + aget_thread = kwargs.pop("aget_thread", None) + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = get_litellm_params(**kwargs) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + api_base: Optional[str] = None + api_key: Optional[str] = None + response: Optional[Thread] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_assistants_api.get_thread( + thread_id=thread_id, + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + client=client, + aget_thread=aget_thread, + ) + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version: Optional[str] = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + if isinstance(client, OpenAI): + client = None # only pass client if it's AzureOpenAI + + response = azure_assistants_api.get_thread( + thread_id=thread_id, + api_base=api_base, + api_key=api_key, + azure_ad_token=azure_ad_token, + api_version=api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + aget_thread=aget_thread, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'get_thread'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response # type: ignore + + +### MESSAGES ### + + +async def a_add_message( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + role: Literal["user", "assistant"], + content: str, + attachments: Optional[List[Attachment]] = None, + metadata: Optional[dict] = None, + client=None, + **kwargs, +) -> OpenAIMessage: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["a_add_message"] = True + try: + # Use a partial function to pass your keyword arguments + func = partial( + add_message, + custom_llm_provider, + thread_id, + role, + content, + attachments, + metadata, + client, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + # Call the synchronous function using run_in_executor + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def add_message( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + role: Literal["user", "assistant"], + content: str, + attachments: Optional[List[Attachment]] = None, + metadata: Optional[dict] = None, + client=None, + **kwargs, +) -> OpenAIMessage: + ### COMMON OBJECTS ### + a_add_message = kwargs.pop("a_add_message", None) + _message_data = MessageData( + role=role, content=content, attachments=attachments, metadata=metadata + ) + litellm_params_dict = get_litellm_params(**kwargs) + optional_params = GenericLiteLLMParams(**kwargs) + + message_data = get_optional_params_add_message( + role=_message_data["role"], + content=_message_data["content"], + attachments=_message_data["attachments"], + metadata=_message_data["metadata"], + custom_llm_provider=custom_llm_provider, + ) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + api_key: Optional[str] = None + api_base: Optional[str] = None + response: Optional[OpenAIMessage] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + response = openai_assistants_api.add_message( + thread_id=thread_id, + message_data=message_data, + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + client=client, + a_add_message=a_add_message, + ) + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version: Optional[str] = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + response = azure_assistants_api.add_message( + thread_id=thread_id, + message_data=message_data, + api_base=api_base, + api_key=api_key, + api_version=api_version, + azure_ad_token=azure_ad_token, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + a_add_message=a_add_message, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_thread'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + + return response # type: ignore + + +async def aget_messages( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + client: Optional[AsyncOpenAI] = None, + **kwargs, +) -> AsyncCursorPage[OpenAIMessage]: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["aget_messages"] = True + try: + # Use a partial function to pass your keyword arguments + func = partial( + get_messages, + custom_llm_provider, + thread_id, + client, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + # Call the synchronous function using run_in_executor + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def get_messages( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + client: Optional[Any] = None, + **kwargs, +) -> SyncCursorPage[OpenAIMessage]: + aget_messages = kwargs.pop("aget_messages", None) + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = get_litellm_params(**kwargs) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + response: Optional[SyncCursorPage[OpenAIMessage]] = None + api_key: Optional[str] = None + api_base: Optional[str] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + response = openai_assistants_api.get_messages( + thread_id=thread_id, + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + client=client, + aget_messages=aget_messages, + ) + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version: Optional[str] = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token: Optional[str] = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + response = azure_assistants_api.get_messages( + thread_id=thread_id, + api_base=api_base, + api_key=api_key, + api_version=api_version, + azure_ad_token=azure_ad_token, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + aget_messages=aget_messages, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'get_messages'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + + return response # type: ignore + + +### RUNS ### +def arun_thread_stream( + *, + event_handler: Optional[AssistantEventHandler] = None, + **kwargs, +) -> AsyncAssistantStreamManager[AsyncAssistantEventHandler]: + kwargs["arun_thread"] = True + return run_thread(stream=True, event_handler=event_handler, **kwargs) # type: ignore + + +async def arun_thread( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + assistant_id: str, + additional_instructions: Optional[str] = None, + instructions: Optional[str] = None, + metadata: Optional[dict] = None, + model: Optional[str] = None, + stream: Optional[bool] = None, + tools: Optional[Iterable[AssistantToolParam]] = None, + client: Optional[Any] = None, + **kwargs, +) -> Run: + loop = asyncio.get_event_loop() + ### PASS ARGS TO GET ASSISTANTS ### + kwargs["arun_thread"] = True + try: + # Use a partial function to pass your keyword arguments + func = partial( + run_thread, + custom_llm_provider, + thread_id, + assistant_id, + additional_instructions, + instructions, + metadata, + model, + stream, + tools, + client, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + + _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore + model="", custom_llm_provider=custom_llm_provider + ) # type: ignore + + # Await normally + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + # Call the synchronous function using run_in_executor + response = init_response + return response # type: ignore + except Exception as e: + raise exception_type( + model="", + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs={}, + extra_kwargs=kwargs, + ) + + +def run_thread_stream( + *, + event_handler: Optional[AssistantEventHandler] = None, + **kwargs, +) -> AssistantStreamManager[AssistantEventHandler]: + return run_thread(stream=True, event_handler=event_handler, **kwargs) # type: ignore + + +def run_thread( + custom_llm_provider: Literal["openai", "azure"], + thread_id: str, + assistant_id: str, + additional_instructions: Optional[str] = None, + instructions: Optional[str] = None, + metadata: Optional[dict] = None, + model: Optional[str] = None, + stream: Optional[bool] = None, + tools: Optional[Iterable[AssistantToolParam]] = None, + client: Optional[Any] = None, + event_handler: Optional[AssistantEventHandler] = None, # for stream=True calls + **kwargs, +) -> Run: + """Run a given thread + assistant.""" + arun_thread = kwargs.pop("arun_thread", None) + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = get_litellm_params(**kwargs) + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + response: Optional[Run] = None + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_assistants_api.run_thread( + thread_id=thread_id, + assistant_id=assistant_id, + additional_instructions=additional_instructions, + instructions=instructions, + metadata=metadata, + model=model, + stream=stream, + tools=tools, + api_base=api_base, + api_key=api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=organization, + client=client, + arun_thread=arun_thread, + event_handler=event_handler, + ) + elif custom_llm_provider == "azure": + api_base = ( + optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") + ) # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret("AZURE_OPENAI_API_KEY") + or get_secret("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + azure_ad_token = None + if extra_body is not None: + azure_ad_token = extra_body.pop("azure_ad_token", None) + else: + azure_ad_token = get_secret("AZURE_AD_TOKEN") # type: ignore + + response = azure_assistants_api.run_thread( + thread_id=thread_id, + assistant_id=assistant_id, + additional_instructions=additional_instructions, + instructions=instructions, + metadata=metadata, + model=model, + stream=stream, + tools=tools, + api_base=str(api_base) if api_base is not None else None, + api_key=str(api_key) if api_key is not None else None, + api_version=str(api_version) if api_version is not None else None, + azure_ad_token=str(azure_ad_token) if azure_ad_token is not None else None, + timeout=timeout, + max_retries=optional_params.max_retries, + client=client, + arun_thread=arun_thread, + litellm_params=litellm_params_dict, + ) # type: ignore + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'run_thread'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response # type: ignore diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f8fc6ee0af7b31a3d65703abe5be2b5ede229253 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/assistants/utils.py @@ -0,0 +1,161 @@ +from typing import Optional, Union + +import litellm + +from ..exceptions import UnsupportedParamsError +from ..types.llms.openai import * + + +def get_optional_params_add_message( + role: Optional[str], + content: Optional[ + Union[ + str, + List[ + Union[ + MessageContentTextObject, + MessageContentImageFileObject, + MessageContentImageURLObject, + ] + ], + ] + ], + attachments: Optional[List[Attachment]], + metadata: Optional[dict], + custom_llm_provider: str, + **kwargs, +): + """ + Azure doesn't support 'attachments' for creating a message + + Reference - https://learn.microsoft.com/en-us/azure/ai-services/openai/assistants-reference-messages?tabs=python#create-message + """ + passed_params = locals() + custom_llm_provider = passed_params.pop("custom_llm_provider") + special_params = passed_params.pop("kwargs") + for k, v in special_params.items(): + passed_params[k] = v + + default_params = { + "role": None, + "content": None, + "attachments": None, + "metadata": None, + } + + non_default_params = { + k: v + for k, v in passed_params.items() + if (k in default_params and v != default_params[k]) + } + optional_params = {} + + ## raise exception if non-default value passed for non-openai/azure embedding calls + def _check_valid_arg(supported_params): + if len(non_default_params.keys()) > 0: + keys = list(non_default_params.keys()) + for k in keys: + if ( + litellm.drop_params is True and k not in supported_params + ): # drop the unsupported non-default values + non_default_params.pop(k, None) + elif k not in supported_params: + raise litellm.utils.UnsupportedParamsError( + status_code=500, + message="k={}, not supported by {}. Supported params={}. To drop it from the call, set `litellm.drop_params = True`.".format( + k, custom_llm_provider, supported_params + ), + ) + return non_default_params + + if custom_llm_provider == "openai": + optional_params = non_default_params + elif custom_llm_provider == "azure": + supported_params = ( + litellm.AzureOpenAIAssistantsAPIConfig().get_supported_openai_create_message_params() + ) + _check_valid_arg(supported_params=supported_params) + optional_params = litellm.AzureOpenAIAssistantsAPIConfig().map_openai_params_create_message_params( + non_default_params=non_default_params, optional_params=optional_params + ) + for k in passed_params.keys(): + if k not in default_params.keys(): + optional_params[k] = passed_params[k] + return optional_params + + +def get_optional_params_image_gen( + n: Optional[int] = None, + quality: Optional[str] = None, + response_format: Optional[str] = None, + size: Optional[str] = None, + style: Optional[str] = None, + user: Optional[str] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +): + # retrieve all parameters passed to the function + passed_params = locals() + custom_llm_provider = passed_params.pop("custom_llm_provider") + special_params = passed_params.pop("kwargs") + for k, v in special_params.items(): + passed_params[k] = v + + default_params = { + "n": None, + "quality": None, + "response_format": None, + "size": None, + "style": None, + "user": None, + } + + non_default_params = { + k: v + for k, v in passed_params.items() + if (k in default_params and v != default_params[k]) + } + optional_params = {} + + ## raise exception if non-default value passed for non-openai/azure embedding calls + def _check_valid_arg(supported_params): + if len(non_default_params.keys()) > 0: + keys = list(non_default_params.keys()) + for k in keys: + if ( + litellm.drop_params is True and k not in supported_params + ): # drop the unsupported non-default values + non_default_params.pop(k, None) + elif k not in supported_params: + raise UnsupportedParamsError( + status_code=500, + message=f"Setting user/encoding format is not supported by {custom_llm_provider}. To drop it from the call, set `litellm.drop_params = True`.", + ) + return non_default_params + + if ( + custom_llm_provider == "openai" + or custom_llm_provider == "azure" + or custom_llm_provider in litellm.openai_compatible_providers + ): + optional_params = non_default_params + elif custom_llm_provider == "bedrock": + supported_params = ["size"] + _check_valid_arg(supported_params=supported_params) + if size is not None: + width, height = size.split("x") + optional_params["width"] = int(width) + optional_params["height"] = int(height) + elif custom_llm_provider == "vertex_ai": + supported_params = ["n"] + """ + All params here: https://console.cloud.google.com/vertex-ai/publishers/google/model-garden/imagegeneration?project=adroit-crow-413218 + """ + _check_valid_arg(supported_params=supported_params) + if n is not None: + optional_params["sampleCount"] = int(n) + + for k in passed_params.keys(): + if k not in default_params.keys(): + optional_params[k] = passed_params[k] + return optional_params diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/Readme.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1d920219830a2d9ba2722458424b964a654bd9e3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/Readme.md @@ -0,0 +1,41 @@ +# Caching on LiteLLM + +LiteLLM supports multiple caching mechanisms. This allows users to choose the most suitable caching solution for their use case. + +The following caching mechanisms are supported: + +1. **RedisCache** +2. **RedisSemanticCache** +3. **QdrantSemanticCache** +4. **InMemoryCache** +5. **DiskCache** +6. **S3Cache** +7. **AzureBlobCache** +8. **DualCache** (updates both Redis and an in-memory cache simultaneously) + +## Folder Structure + +``` +litellm/caching/ +├── base_cache.py +├── caching.py +├── caching_handler.py +├── disk_cache.py +├── dual_cache.py +├── in_memory_cache.py +├── qdrant_semantic_cache.py +├── redis_cache.py +├── redis_semantic_cache.py +├── s3_cache.py +``` + +## Documentation +- [Caching on LiteLLM Gateway](https://docs.litellm.ai/docs/proxy/caching) +- [Caching on LiteLLM Python](https://docs.litellm.ai/docs/caching/all_caches) + + + + + + + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bbe90b041219f821dbf2e201e2690c9d8b61e185 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/__init__.py @@ -0,0 +1,11 @@ +from .azure_blob_cache import AzureBlobCache +from .caching import Cache, LiteLLMCacheType +from .disk_cache import DiskCache +from .dual_cache import DualCache +from .in_memory_cache import InMemoryCache +from .qdrant_semantic_cache import QdrantSemanticCache +from .redis_cache import RedisCache +from .redis_cluster_cache import RedisClusterCache +from .redis_semantic_cache import RedisSemanticCache +from .s3_cache import S3Cache +from .gcs_cache import GCSCache diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/_internal_lru_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/_internal_lru_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..54b0fe9690ca5ef8b57c8078c12e3805d1dc55fb --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/_internal_lru_cache.py @@ -0,0 +1,30 @@ +from functools import lru_cache +from typing import Callable, Optional, TypeVar + +T = TypeVar("T") + + +def lru_cache_wrapper( + maxsize: Optional[int] = None, +) -> Callable[[Callable[..., T]], Callable[..., T]]: + """ + Wrapper for lru_cache that caches success and exceptions + """ + + def decorator(f: Callable[..., T]) -> Callable[..., T]: + @lru_cache(maxsize=maxsize) + def wrapper(*args, **kwargs): + try: + return ("success", f(*args, **kwargs)) + except Exception as e: + return ("error", e) + + def wrapped(*args, **kwargs): + result = wrapper(*args, **kwargs) + if result[0] == "error": + raise result[1] + return result[1] + + return wrapped + + return decorator diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/azure_blob_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/azure_blob_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..a2246640c30e49aa43f31dbcdb74c947de2f325d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/azure_blob_cache.py @@ -0,0 +1,107 @@ +""" +Azure Blob Cache implementation + +Has 4 methods: + - set_cache + - get_cache + - async_set_cache + - async_get_cache +""" + +import asyncio +import json +from contextlib import suppress + +from litellm._logging import print_verbose, verbose_logger + +from .base_cache import BaseCache + + +class AzureBlobCache(BaseCache): + def __init__(self, account_url, container) -> None: + from azure.storage.blob import BlobServiceClient + from azure.core.exceptions import ResourceExistsError + from azure.identity import DefaultAzureCredential + from azure.identity.aio import ( + DefaultAzureCredential as AsyncDefaultAzureCredential, + ) + from azure.storage.blob.aio import BlobServiceClient as AsyncBlobServiceClient + + self.container_client = BlobServiceClient( + account_url=account_url, + credential=DefaultAzureCredential(), + ).get_container_client(container) + self.async_container_client = AsyncBlobServiceClient( + account_url=account_url, + credential=AsyncDefaultAzureCredential(), + ).get_container_client(container) + + with suppress(ResourceExistsError): + self.container_client.create_container() + + def set_cache(self, key, value, **kwargs) -> None: + print_verbose(f"LiteLLM SET Cache - Azure Blob. Key={key}. Value={value}") + serialized_value = json.dumps(value) + try: + self.container_client.upload_blob(key, serialized_value) + except Exception as e: + # NON blocking - notify users Azure Blob is throwing an exception + print_verbose(f"LiteLLM set_cache() - Got exception from Azure Blob: {e}") + + async def async_set_cache(self, key, value, **kwargs) -> None: + print_verbose(f"LiteLLM SET Cache - Azure Blob. Key={key}. Value={value}") + serialized_value = json.dumps(value) + try: + await self.async_container_client.upload_blob( + key, serialized_value, overwrite=True + ) + except Exception as e: + # NON blocking - notify users Azure Blob is throwing an exception + print_verbose(f"LiteLLM set_cache() - Got exception from Azure Blob: {e}") + + def get_cache(self, key, **kwargs): + from azure.core.exceptions import ResourceNotFoundError + + try: + print_verbose(f"Get Azure Blob Cache: key: {key}") + as_bytes = self.container_client.download_blob(key).readall() + as_str = as_bytes.decode("utf-8") + cached_response = json.loads(as_str) + + verbose_logger.debug( + f"Got Azure Blob Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}" + ) + + return cached_response + except ResourceNotFoundError: + return None + + async def async_get_cache(self, key, **kwargs): + from azure.core.exceptions import ResourceNotFoundError + + try: + print_verbose(f"Get Azure Blob Cache: key: {key}") + blob = await self.async_container_client.download_blob(key) + as_bytes = await blob.readall() + as_str = as_bytes.decode("utf-8") + cached_response = json.loads(as_str) + verbose_logger.debug( + f"Got Azure Blob Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}" + ) + return cached_response + except ResourceNotFoundError: + return None + + def flush_cache(self) -> None: + for blob in self.container_client.walk_blobs(): + self.container_client.delete_blob(blob.name) + + async def disconnect(self) -> None: + self.container_client.close() + await self.async_container_client.close() + + async def async_set_cache_pipeline(self, cache_list, **kwargs) -> None: + tasks = [] + for val in cache_list: + tasks.append(self.async_set_cache(val[0], val[1], **kwargs)) + await asyncio.gather(*tasks) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/base_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/base_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..81f1d61bd0d4a2b9a0b63bc58fabcf7c5c2274fc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/base_cache.py @@ -0,0 +1,64 @@ +""" +Base Cache implementation. All cache implementations should inherit from this class. + +Has 4 methods: + - set_cache + - get_cache + - async_set_cache + - async_get_cache +""" + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Optional, Union + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + Span = Union[_Span, Any] +else: + Span = Any + + +class BaseCache(ABC): + def __init__(self, default_ttl: int = 60): + self.default_ttl = default_ttl + + def get_ttl(self, **kwargs) -> Optional[int]: + kwargs_ttl: Optional[int] = kwargs.get("ttl") + if kwargs_ttl is not None: + try: + return int(kwargs_ttl) + except ValueError: + return self.default_ttl + return self.default_ttl + + def set_cache(self, key, value, **kwargs): + raise NotImplementedError + + async def async_set_cache(self, key, value, **kwargs): + raise NotImplementedError + + @abstractmethod + async def async_set_cache_pipeline(self, cache_list, **kwargs): + pass + + def get_cache(self, key, **kwargs): + raise NotImplementedError + + async def async_get_cache(self, key, **kwargs): + raise NotImplementedError + + async def batch_cache_write(self, key, value, **kwargs): + raise NotImplementedError + + async def disconnect(self): + raise NotImplementedError + + async def test_connection(self) -> dict: + """ + Test the cache connection. + + Returns: + dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} + """ + raise NotImplementedError diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching.py new file mode 100644 index 0000000000000000000000000000000000000000..11733ce4cee10f5ec2b64206f6ebfe43d15b421b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching.py @@ -0,0 +1,987 @@ +# +-----------------------------------------------+ +# | | +# | Give Feedback / Get Help | +# | https://github.com/BerriAI/litellm/issues/new | +# | | +# +-----------------------------------------------+ +# +# Thank you users! We ❤️ you! - Krrish & Ishaan + +import ast +import hashlib +import json +import time +import traceback +from enum import Enum +from typing import Any, Dict, List, Optional, Tuple, Union + +from pydantic import BaseModel + +import litellm +from litellm._logging import verbose_logger +from litellm.constants import CACHED_STREAMING_CHUNK_DELAY +from litellm.litellm_core_utils.model_param_helper import ModelParamHelper +from litellm.types.caching import * +from litellm.types.utils import EmbeddingResponse, all_litellm_params + +from .azure_blob_cache import AzureBlobCache +from .base_cache import BaseCache +from .disk_cache import DiskCache +from .dual_cache import DualCache # noqa +from .gcs_cache import GCSCache +from .in_memory_cache import InMemoryCache +from .qdrant_semantic_cache import QdrantSemanticCache +from .redis_cache import RedisCache +from .redis_cluster_cache import RedisClusterCache +from .redis_semantic_cache import RedisSemanticCache +from .s3_cache import S3Cache + + +def print_verbose(print_statement): + try: + verbose_logger.debug(print_statement) + if litellm.set_verbose: + print(print_statement) # noqa + except Exception: + pass + + +class CacheMode(str, Enum): + default_on = "default_on" + default_off = "default_off" + + +#### LiteLLM.Completion / Embedding Cache #### +class Cache: + def __init__( + self, + type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL, + mode: Optional[ + CacheMode + ] = CacheMode.default_on, # when default_on cache is always on, when default_off cache is opt in + host: Optional[str] = None, + port: Optional[str] = None, + password: Optional[str] = None, + namespace: Optional[str] = None, + ttl: Optional[float] = None, + default_in_memory_ttl: Optional[float] = None, + default_in_redis_ttl: Optional[float] = None, + similarity_threshold: Optional[float] = None, + supported_call_types: Optional[List[CachingSupportedCallTypes]] = [ + "completion", + "acompletion", + "embedding", + "aembedding", + "atranscription", + "transcription", + "atext_completion", + "text_completion", + "arerank", + "rerank", + "responses", + "aresponses", + ], + # s3 Bucket, boto3 configuration + azure_account_url: Optional[str] = None, + azure_blob_container: Optional[str] = None, + s3_bucket_name: Optional[str] = None, + s3_region_name: Optional[str] = None, + s3_api_version: Optional[str] = None, + s3_use_ssl: Optional[bool] = True, + s3_verify: Optional[Union[bool, str]] = None, + s3_endpoint_url: Optional[str] = None, + s3_aws_access_key_id: Optional[str] = None, + s3_aws_secret_access_key: Optional[str] = None, + s3_aws_session_token: Optional[str] = None, + s3_config: Optional[Any] = None, + s3_path: Optional[str] = None, + gcs_bucket_name: Optional[str] = None, + gcs_path_service_account: Optional[str] = None, + gcs_path: Optional[str] = None, + redis_semantic_cache_embedding_model: str = "text-embedding-ada-002", + redis_semantic_cache_index_name: Optional[str] = None, + redis_flush_size: Optional[int] = None, + redis_startup_nodes: Optional[List] = None, + disk_cache_dir: Optional[str] = None, + qdrant_api_base: Optional[str] = None, + qdrant_api_key: Optional[str] = None, + qdrant_collection_name: Optional[str] = None, + qdrant_quantization_config: Optional[str] = None, + qdrant_semantic_cache_embedding_model: str = "text-embedding-ada-002", + qdrant_semantic_cache_vector_size: Optional[int] = None, + # GCP IAM authentication parameters + gcp_service_account: Optional[str] = None, + gcp_ssl_ca_certs: Optional[str] = None, + **kwargs, + ): + """ + Initializes the cache based on the given type. + + Args: + type (str, optional): The type of cache to initialize. Can be "local", "redis", "redis-semantic", "qdrant-semantic", "s3" or "disk". Defaults to "local". + + # Redis Cache Args + host (str, optional): The host address for the Redis cache. Required if type is "redis". + port (int, optional): The port number for the Redis cache. Required if type is "redis". + password (str, optional): The password for the Redis cache. Required if type is "redis". + namespace (str, optional): The namespace for the Redis cache. Required if type is "redis". + ttl (float, optional): The ttl for the Redis cache + redis_flush_size (int, optional): The number of keys to flush at a time. Defaults to 1000. Only used if batch redis set caching is used. + redis_startup_nodes (list, optional): The list of startup nodes for the Redis cache. Defaults to None. + + # Qdrant Cache Args + qdrant_api_base (str, optional): The url for your qdrant cluster. Required if type is "qdrant-semantic". + qdrant_api_key (str, optional): The api_key for the local or cloud qdrant cluster. + qdrant_collection_name (str, optional): The name for your qdrant collection. Required if type is "qdrant-semantic". + similarity_threshold (float, optional): The similarity threshold for semantic-caching, Required if type is "redis-semantic" or "qdrant-semantic". + + # Disk Cache Args + disk_cache_dir (str, optional): The directory for the disk cache. Defaults to None. + + # S3 Cache Args + s3_bucket_name (str, optional): The bucket name for the s3 cache. Defaults to None. + s3_region_name (str, optional): The region name for the s3 cache. Defaults to None. + s3_api_version (str, optional): The api version for the s3 cache. Defaults to None. + s3_use_ssl (bool, optional): The use ssl for the s3 cache. Defaults to True. + s3_verify (bool, optional): The verify for the s3 cache. Defaults to None. + s3_endpoint_url (str, optional): The endpoint url for the s3 cache. Defaults to None. + s3_aws_access_key_id (str, optional): The aws access key id for the s3 cache. Defaults to None. + s3_aws_secret_access_key (str, optional): The aws secret access key for the s3 cache. Defaults to None. + s3_aws_session_token (str, optional): The aws session token for the s3 cache. Defaults to None. + s3_config (dict, optional): The config for the s3 cache. Defaults to None. + + # GCS Cache Args + gcs_bucket_name (str, optional): The bucket name for the gcs cache. Defaults to None. + gcs_path_service_account (str, optional): Path to the service account json. + gcs_path (str, optional): Folder path inside the bucket to store cache files. + + # Common Cache Args + supported_call_types (list, optional): List of call types to cache for. Defaults to cache == on for all call types. + **kwargs: Additional keyword arguments for redis.Redis() cache + + Raises: + ValueError: If an invalid cache type is provided. + + Returns: + None. Cache is set as a litellm param + """ + if type == LiteLLMCacheType.REDIS: + # Check REDIS_CLUSTER_NODES env var if no explicit startup nodes + if not redis_startup_nodes: + _env_cluster_nodes = litellm.get_secret("REDIS_CLUSTER_NODES") + if _env_cluster_nodes is not None and isinstance( + _env_cluster_nodes, str + ): + redis_startup_nodes = json.loads(_env_cluster_nodes) + + if redis_startup_nodes: + # Only pass GCP parameters if they are provided + cluster_kwargs = { + "host": host, + "port": port, + "password": password, + "redis_flush_size": redis_flush_size, + "startup_nodes": redis_startup_nodes, + **kwargs, + } + if gcp_service_account is not None: + cluster_kwargs["gcp_service_account"] = gcp_service_account + if gcp_ssl_ca_certs is not None: + cluster_kwargs["gcp_ssl_ca_certs"] = gcp_ssl_ca_certs + + self.cache: BaseCache = RedisClusterCache(**cluster_kwargs) + else: + self.cache = RedisCache( + host=host, + port=port, + password=password, + redis_flush_size=redis_flush_size, + **kwargs, + ) + elif type == LiteLLMCacheType.REDIS_SEMANTIC: + self.cache = RedisSemanticCache( + host=host, + port=port, + password=password, + similarity_threshold=similarity_threshold, + embedding_model=redis_semantic_cache_embedding_model, + index_name=redis_semantic_cache_index_name, + **kwargs, + ) + elif type == LiteLLMCacheType.QDRANT_SEMANTIC: + self.cache = QdrantSemanticCache( + qdrant_api_base=qdrant_api_base, + qdrant_api_key=qdrant_api_key, + collection_name=qdrant_collection_name, + similarity_threshold=similarity_threshold, + quantization_config=qdrant_quantization_config, + embedding_model=qdrant_semantic_cache_embedding_model, + vector_size=qdrant_semantic_cache_vector_size, + ) + elif type == LiteLLMCacheType.LOCAL: + self.cache = InMemoryCache() + elif type == LiteLLMCacheType.S3: + self.cache = S3Cache( + s3_bucket_name=s3_bucket_name, + s3_region_name=s3_region_name, + s3_api_version=s3_api_version, + s3_use_ssl=s3_use_ssl, + s3_verify=s3_verify, + s3_endpoint_url=s3_endpoint_url, + s3_aws_access_key_id=s3_aws_access_key_id, + s3_aws_secret_access_key=s3_aws_secret_access_key, + s3_aws_session_token=s3_aws_session_token, + s3_config=s3_config, + s3_path=s3_path, + **kwargs, + ) + elif type == LiteLLMCacheType.GCS: + self.cache = GCSCache( + bucket_name=gcs_bucket_name, + path_service_account=gcs_path_service_account, + gcs_path=gcs_path, + ) + elif type == LiteLLMCacheType.AZURE_BLOB: + self.cache = AzureBlobCache( + account_url=azure_account_url, + container=azure_blob_container, + ) + elif type == LiteLLMCacheType.DISK: + self.cache = DiskCache(disk_cache_dir=disk_cache_dir) + if "cache" not in litellm.input_callback: + litellm.input_callback.append("cache") + if "cache" not in litellm.success_callback: + litellm.logging_callback_manager.add_litellm_success_callback("cache") + if "cache" not in litellm._async_success_callback: + litellm.logging_callback_manager.add_litellm_async_success_callback("cache") + self.supported_call_types = supported_call_types # default to ["completion", "acompletion", "embedding", "aembedding"] + self.type = type + self.namespace = namespace + self.redis_flush_size = redis_flush_size + self.ttl = ttl + self.mode: CacheMode = mode or CacheMode.default_on + + if self.type == LiteLLMCacheType.LOCAL and default_in_memory_ttl is not None: + self.ttl = default_in_memory_ttl + + if ( + self.type == LiteLLMCacheType.REDIS + or self.type == LiteLLMCacheType.REDIS_SEMANTIC + ) and default_in_redis_ttl is not None: + self.ttl = default_in_redis_ttl + + if self.namespace is not None and isinstance(self.cache, RedisCache): + self.cache.namespace = self.namespace + + def get_cache_key(self, **kwargs) -> str: + """ + Get the cache key for the given arguments. + + Args: + **kwargs: kwargs to litellm.completion() or embedding() + + Returns: + str: The cache key generated from the arguments, or None if no cache key could be generated. + """ + cache_key = "" + # verbose_logger.debug("\nGetting Cache key. Kwargs: %s", kwargs) + + preset_cache_key = self._get_preset_cache_key_from_kwargs(**kwargs) + if preset_cache_key is not None: + verbose_logger.debug("\nReturning preset cache key: %s", preset_cache_key) + return preset_cache_key + + combined_kwargs = ModelParamHelper._get_all_llm_api_params() + litellm_param_kwargs = all_litellm_params + for param in kwargs: + if param in combined_kwargs: + param_value: Optional[str] = self._get_param_value(param, kwargs) + if param_value is not None: + cache_key += f"{str(param)}: {str(param_value)}" + elif ( + param not in litellm_param_kwargs + ): # check if user passed in optional param - e.g. top_k + if ( + litellm.enable_caching_on_provider_specific_optional_params is True + ): # feature flagged for now + if kwargs[param] is None: + continue # ignore None params + param_value = kwargs[param] + cache_key += f"{str(param)}: {str(param_value)}" + + verbose_logger.debug("\nCreated cache key: %s", cache_key) + hashed_cache_key = Cache._get_hashed_cache_key(cache_key) + hashed_cache_key = self._add_namespace_to_cache_key(hashed_cache_key, **kwargs) + # Remove preset_cache_key from kwargs to avoid "got multiple values" TypeError + # when kwargs already contains preset_cache_key from upstream callers + kwargs_for_preset = {k: v for k, v in kwargs.items() if k != "preset_cache_key"} + self._set_preset_cache_key_in_kwargs( + preset_cache_key=hashed_cache_key, **kwargs_for_preset + ) + return hashed_cache_key + + def _get_param_value( + self, + param: str, + kwargs: dict, + ) -> Optional[str]: + """ + Get the value for the given param from kwargs + """ + if param == "model": + return self._get_model_param_value(kwargs) + elif param == "file": + return self._get_file_param_value(kwargs) + return kwargs[param] + + def _get_model_param_value(self, kwargs: dict) -> str: + """ + Handles getting the value for the 'model' param from kwargs + + 1. If caching groups are set, then return the caching group as the model https://docs.litellm.ai/docs/routing#caching-across-model-groups + 2. Else if a model_group is set, then return the model_group as the model. This is used for all requests sent through the litellm.Router() + 3. Else use the `model` passed in kwargs + """ + metadata: Dict = kwargs.get("metadata", {}) or {} + litellm_params: Dict = kwargs.get("litellm_params", {}) or {} + metadata_in_litellm_params: Dict = litellm_params.get("metadata", {}) or {} + model_group: Optional[str] = metadata.get( + "model_group" + ) or metadata_in_litellm_params.get("model_group") + caching_group = self._get_caching_group(metadata, model_group) + return caching_group or model_group or kwargs["model"] + + def _get_caching_group( + self, metadata: dict, model_group: Optional[str] + ) -> Optional[str]: + caching_groups: Optional[List] = metadata.get("caching_groups", []) + if caching_groups: + for group in caching_groups: + if model_group in group: + return str(group) + return None + + def _get_file_param_value(self, kwargs: dict) -> str: + """ + Handles getting the value for the 'file' param from kwargs. Used for `transcription` requests + """ + file = kwargs.get("file") + metadata = kwargs.get("metadata", {}) + litellm_params = kwargs.get("litellm_params", {}) + return ( + metadata.get("file_checksum") + or getattr(file, "name", None) + or metadata.get("file_name") + or litellm_params.get("file_name") + ) + + def _get_preset_cache_key_from_kwargs(self, **kwargs) -> Optional[str]: + """ + Get the preset cache key from kwargs["litellm_params"] + + We use _get_preset_cache_keys for two reasons + + 1. optional params like max_tokens, get transformed for bedrock -> max_new_tokens + 2. avoid doing duplicate / repeated work + """ + if kwargs: + if "litellm_params" in kwargs: + return kwargs["litellm_params"].get("preset_cache_key", None) + return None + + def _set_preset_cache_key_in_kwargs(self, preset_cache_key: str, **kwargs) -> None: + """ + Set the calculated cache key in kwargs + + This is used to avoid doing duplicate / repeated work + + Placed in kwargs["litellm_params"] + """ + if kwargs: + if "litellm_params" in kwargs: + kwargs["litellm_params"]["preset_cache_key"] = preset_cache_key + + @staticmethod + def _get_hashed_cache_key(cache_key: str) -> str: + """ + Get the hashed cache key for the given cache key. + + Use hashlib to create a sha256 hash of the cache key + + Args: + cache_key (str): The cache key to hash. + + Returns: + str: The hashed cache key. + """ + hash_object = hashlib.sha256(cache_key.encode()) + # Hexadecimal representation of the hash + hash_hex = hash_object.hexdigest() + verbose_logger.debug("Hashed cache key (SHA-256): %s", hash_hex) + return hash_hex + + def _add_namespace_to_cache_key(self, hash_hex: str, **kwargs) -> str: + """ + If a redis namespace is provided, add it to the cache key + + Args: + hash_hex (str): The hashed cache key. + **kwargs: Additional keyword arguments. + + Returns: + str: The final hashed cache key with the redis namespace. + """ + dynamic_cache_control: DynamicCacheControl = kwargs.get("cache", {}) + metadata = kwargs.get("metadata") or {} + namespace = ( + dynamic_cache_control.get("namespace") + or metadata.get("redis_namespace") + or self.namespace + ) + if namespace: + hash_hex = f"{namespace}:{hash_hex}" + verbose_logger.debug("Final hashed key: %s", hash_hex) + return hash_hex + + def generate_streaming_content(self, content): + chunk_size = 5 # Adjust the chunk size as needed + for i in range(0, len(content), chunk_size): + yield { + "choices": [ + { + "delta": { + "role": "assistant", + "content": content[i : i + chunk_size], + } + } + ] + } + time.sleep(CACHED_STREAMING_CHUNK_DELAY) + + def _get_cache_logic( + self, + cached_result: Optional[Any], + max_age: Optional[float], + ): + """ + Common get cache logic across sync + async implementations + """ + # Check if a timestamp was stored with the cached response + if ( + cached_result is not None + and isinstance(cached_result, dict) + and "timestamp" in cached_result + ): + timestamp = cached_result["timestamp"] + current_time = time.time() + + # Calculate age of the cached response + response_age = current_time - timestamp + + # Check if the cached response is older than the max-age + if max_age is not None and response_age > max_age: + return None # Cached response is too old + + # If the response is fresh, or there's no max-age requirement, return the cached response + # cached_response is in `b{} convert it to ModelResponse + cached_response = cached_result.get("response") + try: + if isinstance(cached_response, dict): + pass + else: + cached_response = json.loads( + cached_response # type: ignore + ) # Convert string to dictionary + except Exception: + cached_response = ast.literal_eval(cached_response) # type: ignore + return cached_response + return cached_result + + def get_cache(self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): + """ + Retrieves the cached result for the given arguments. + + Args: + *args: args to litellm.completion() or embedding() + **kwargs: kwargs to litellm.completion() or embedding() + + Returns: + The cached result if it exists, otherwise None. + """ + try: # never block execution + if self.should_use_cache(**kwargs) is not True: + return + messages = kwargs.get("messages", []) + if "cache_key" in kwargs: + cache_key = kwargs["cache_key"] + else: + cache_key = self.get_cache_key(**kwargs) + if cache_key is not None: + cache_control_args: DynamicCacheControl = kwargs.get("cache", {}) + max_age = ( + cache_control_args.get("s-maxage") + or cache_control_args.get("s-max-age") + or float("inf") + ) + if dynamic_cache_object is not None: + cached_result = dynamic_cache_object.get_cache( + cache_key, messages=messages + ) + else: + cached_result = self.cache.get_cache(cache_key, messages=messages) + return self._get_cache_logic( + cached_result=cached_result, max_age=max_age + ) + except Exception: + print_verbose(f"An exception occurred: {traceback.format_exc()}") + return None + + async def async_get_cache( + self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs + ): + """ + Async get cache implementation. + + Used for embedding calls in async wrapper + """ + + try: # never block execution + if self.should_use_cache(**kwargs) is not True: + return + + kwargs.get("messages", []) + if "cache_key" in kwargs: + cache_key = kwargs["cache_key"] + else: + cache_key = self.get_cache_key(**kwargs) + if cache_key is not None: + cache_control_args = kwargs.get("cache", {}) + max_age = cache_control_args.get( + "s-max-age", cache_control_args.get("s-maxage", float("inf")) + ) + if dynamic_cache_object is not None: + cached_result = await dynamic_cache_object.async_get_cache( + cache_key, **kwargs + ) + else: + cached_result = await self.cache.async_get_cache( + cache_key, **kwargs + ) + return self._get_cache_logic( + cached_result=cached_result, max_age=max_age + ) + except Exception: + print_verbose(f"An exception occurred: {traceback.format_exc()}") + return None + + def _add_cache_logic(self, result, **kwargs): + """ + Common implementation across sync + async add_cache functions + """ + try: + if "cache_key" in kwargs: + cache_key = kwargs["cache_key"] + else: + cache_key = self.get_cache_key(**kwargs) + if cache_key is not None: + if isinstance(result, BaseModel): + result = result.model_dump_json() + + ## DEFAULT TTL ## + if self.ttl is not None: + kwargs["ttl"] = self.ttl + ## Get Cache-Controls ## + _cache_kwargs = kwargs.get("cache", None) + if isinstance(_cache_kwargs, dict): + for k, v in _cache_kwargs.items(): + if k == "ttl": + kwargs["ttl"] = v + + cached_data = {"timestamp": time.time(), "response": result} + return cache_key, cached_data, kwargs + else: + raise Exception("cache key is None") + except Exception as e: + raise e + + def add_cache(self, result, **kwargs): + """ + Adds a result to the cache. + + Args: + *args: args to litellm.completion() or embedding() + **kwargs: kwargs to litellm.completion() or embedding() + + Returns: + None + """ + try: + if self.should_use_cache(**kwargs) is not True: + return + cache_key, cached_data, kwargs = self._add_cache_logic( + result=result, **kwargs + ) + self.cache.set_cache(cache_key, cached_data, **kwargs) + except Exception as e: + verbose_logger.exception(f"LiteLLM Cache: Excepton add_cache: {str(e)}") + + async def async_add_cache( + self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs + ): + """ + Async implementation of add_cache + """ + try: + if self.should_use_cache(**kwargs) is not True: + return + if self.type == "redis" and self.redis_flush_size is not None: + # high traffic - fill in results in memory and then flush + await self.batch_cache_write(result, **kwargs) + else: + cache_key, cached_data, kwargs = self._add_cache_logic( + result=result, **kwargs + ) + if dynamic_cache_object is not None: + await dynamic_cache_object.async_set_cache( + cache_key, cached_data, **kwargs + ) + else: + await self.cache.async_set_cache(cache_key, cached_data, **kwargs) + except Exception as e: + verbose_logger.exception(f"LiteLLM Cache: Excepton add_cache: {str(e)}") + + def _convert_to_cached_embedding( + self, + embedding_response: Any, + model: Optional[str], + prompt_tokens_details: Optional[dict] = None, + ) -> CachedEmbedding: + """ + Convert any embedding response into the standardized CachedEmbedding TypedDict format. + """ + try: + if isinstance(embedding_response, dict): + return { + "embedding": embedding_response.get("embedding"), + "index": embedding_response.get("index"), + "object": embedding_response.get("object"), + "model": model, + "prompt_tokens_details": prompt_tokens_details, + } + elif hasattr(embedding_response, "model_dump"): + data = embedding_response.model_dump() + return { + "embedding": data.get("embedding"), + "index": data.get("index"), + "object": data.get("object"), + "model": model, + "prompt_tokens_details": prompt_tokens_details, + } + else: + data = vars(embedding_response) + return { + "embedding": data.get("embedding"), + "index": data.get("index"), + "object": data.get("object"), + "model": model, + "prompt_tokens_details": prompt_tokens_details, + } + except KeyError as e: + raise ValueError(f"Missing expected key in embedding response: {e}") + + def _get_per_item_prompt_tokens_details( + self, + result: EmbeddingResponse, + idx_in_result_data: int, + ) -> Optional[dict]: + """ + Extract per-item prompt_tokens_details from a response for caching. + + For single-item responses (common for multimodal providers like Bedrock Titan, + Nova, Vertex AI), returns the full prompt_tokens_details. + For multi-item responses, distributes integer fields evenly across items + so that summing all per-item details reconstructs the original totals. + """ + if result.usage is None or result.usage.prompt_tokens_details is None: + return None + + details = result.usage.prompt_tokens_details + if hasattr(details, "model_dump"): + details_dict = details.model_dump(exclude_none=True) + elif isinstance(details, dict): + details_dict = {k: v for k, v in details.items() if v is not None} + else: + return None + + if not details_dict: + return None + + num_items = len(result.data) + if num_items <= 1: + return details_dict + + # Distribute integer/float fields evenly across items + per_item: dict = {} + for key, value in details_dict.items(): + if isinstance(value, int): + quotient, remainder = divmod(value, num_items) + per_item[key] = quotient + (1 if idx_in_result_data < remainder else 0) + elif isinstance(value, float): + per_item[key] = value / num_items + else: + per_item[key] = value + return per_item if per_item else None + + def add_embedding_response_to_cache( + self, + result: EmbeddingResponse, + input: str, + kwargs: dict, + idx_in_result_data: int = 0, + ) -> Tuple[str, dict, dict]: + preset_cache_key = self.get_cache_key(**{**kwargs, "input": input}) + kwargs["cache_key"] = preset_cache_key + embedding_response = result.data[idx_in_result_data] + + # Extract per-item prompt_tokens_details from response usage + prompt_tokens_details = self._get_per_item_prompt_tokens_details( + result=result, + idx_in_result_data=idx_in_result_data, + ) + + # Always convert to properly typed CachedEmbedding + model_name = result.model + embedding_dict: CachedEmbedding = self._convert_to_cached_embedding( + embedding_response, + model_name, + prompt_tokens_details=prompt_tokens_details, + ) + + cache_key, cached_data, kwargs = self._add_cache_logic( + result=embedding_dict, + **kwargs, + ) + return cache_key, cached_data, kwargs + + async def async_add_cache_pipeline( + self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs + ): + """ + Async implementation of add_cache for Embedding calls + + Does a bulk write, to prevent using too many clients + """ + try: + if self.should_use_cache(**kwargs) is not True: + return + + # set default ttl if not set + if self.ttl is not None: + kwargs["ttl"] = self.ttl + + cache_list = [] + if isinstance(kwargs["input"], list): + for idx, i in enumerate(kwargs["input"]): + ( + cache_key, + cached_data, + kwargs, + ) = self.add_embedding_response_to_cache(result, i, kwargs, idx) + cache_list.append((cache_key, cached_data)) + elif isinstance(kwargs["input"], str): + cache_key, cached_data, kwargs = self.add_embedding_response_to_cache( + result, kwargs["input"], kwargs + ) + cache_list.append((cache_key, cached_data)) + + if dynamic_cache_object is not None: + await dynamic_cache_object.async_set_cache_pipeline( + cache_list=cache_list, **kwargs + ) + else: + await self.cache.async_set_cache_pipeline( + cache_list=cache_list, **kwargs + ) + except Exception as e: + verbose_logger.exception(f"LiteLLM Cache: Excepton add_cache: {str(e)}") + + def should_use_cache(self, **kwargs): + """ + Returns true if we should use the cache for LLM API calls + + If cache is default_on then this is True + If cache is default_off then this is only true when user has opted in to use cache + """ + if self.mode == CacheMode.default_on: + return True + + # when mode == default_off -> Cache is opt in only + _cache = kwargs.get("cache", None) + verbose_logger.debug("should_use_cache: kwargs: %s; _cache: %s", kwargs, _cache) + if _cache and isinstance(_cache, dict): + if _cache.get("use-cache", False) is True: + return True + return False + + async def batch_cache_write(self, result, **kwargs): + cache_key, cached_data, kwargs = self._add_cache_logic(result=result, **kwargs) + await self.cache.batch_cache_write(cache_key, cached_data, **kwargs) + + async def ping(self): + cache_ping = getattr(self.cache, "ping") + if cache_ping: + return await cache_ping() + return None + + async def delete_cache_keys(self, keys): + cache_delete_cache_keys = getattr(self.cache, "delete_cache_keys") + if cache_delete_cache_keys: + return await cache_delete_cache_keys(keys) + return None + + async def disconnect(self): + if hasattr(self.cache, "disconnect"): + await self.cache.disconnect() + + def _supports_async(self) -> bool: + """ + Internal method to check if the cache type supports async get/set operations + + All cache types now support async operations + + """ + return True + + +def enable_cache( + type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL, + host: Optional[str] = None, + port: Optional[str] = None, + password: Optional[str] = None, + supported_call_types: Optional[List[CachingSupportedCallTypes]] = [ + "completion", + "acompletion", + "embedding", + "aembedding", + "atranscription", + "transcription", + "atext_completion", + "text_completion", + "arerank", + "rerank", + "responses", + "aresponses", + ], + **kwargs, +): + """ + Enable cache with the specified configuration. + + Args: + type (Optional[Literal["local", "redis", "s3", "disk"]]): The type of cache to enable. Defaults to "local". + host (Optional[str]): The host address of the cache server. Defaults to None. + port (Optional[str]): The port number of the cache server. Defaults to None. + password (Optional[str]): The password for the cache server. Defaults to None. + supported_call_types (Optional[List[Literal["completion", "acompletion", "embedding", "aembedding"]]]): + The supported call types for the cache. Defaults to ["completion", "acompletion", "embedding", "aembedding"]. + **kwargs: Additional keyword arguments. + + Returns: + None + + Raises: + None + """ + print_verbose("LiteLLM: Enabling Cache") + if "cache" not in litellm.input_callback: + litellm.input_callback.append("cache") + if "cache" not in litellm.success_callback: + litellm.logging_callback_manager.add_litellm_success_callback("cache") + if "cache" not in litellm._async_success_callback: + litellm.logging_callback_manager.add_litellm_async_success_callback("cache") + + if litellm.cache is None: + litellm.cache = Cache( + type=type, + host=host, + port=port, + password=password, + supported_call_types=supported_call_types, + **kwargs, + ) + print_verbose(f"LiteLLM: Cache enabled, litellm.cache={litellm.cache}") + print_verbose(f"LiteLLM Cache: {vars(litellm.cache)}") + + +def update_cache( + type: Optional[LiteLLMCacheType] = LiteLLMCacheType.LOCAL, + host: Optional[str] = None, + port: Optional[str] = None, + password: Optional[str] = None, + supported_call_types: Optional[List[CachingSupportedCallTypes]] = [ + "completion", + "acompletion", + "embedding", + "aembedding", + "atranscription", + "transcription", + "atext_completion", + "text_completion", + "arerank", + "rerank", + "responses", + "aresponses", + ], + **kwargs, +): + """ + Update the cache for LiteLLM. + + Args: + type (Optional[Literal["local", "redis", "s3", "disk"]]): The type of cache. Defaults to "local". + host (Optional[str]): The host of the cache. Defaults to None. + port (Optional[str]): The port of the cache. Defaults to None. + password (Optional[str]): The password for the cache. Defaults to None. + supported_call_types (Optional[List[Literal["completion", "acompletion", "embedding", "aembedding"]]]): + The supported call types for the cache. Defaults to ["completion", "acompletion", "embedding", "aembedding"]. + **kwargs: Additional keyword arguments for the cache. + + Returns: + None + + """ + print_verbose("LiteLLM: Updating Cache") + litellm.cache = Cache( + type=type, + host=host, + port=port, + password=password, + supported_call_types=supported_call_types, + **kwargs, + ) + print_verbose(f"LiteLLM: Cache Updated, litellm.cache={litellm.cache}") + print_verbose(f"LiteLLM Cache: {vars(litellm.cache)}") + + +def disable_cache(): + """ + Disable the cache used by LiteLLM. + + This function disables the cache used by the LiteLLM module. It removes the cache-related callbacks from the input_callback, success_callback, and _async_success_callback lists. It also sets the litellm.cache attribute to None. + + Parameters: + None + + Returns: + None + """ + from contextlib import suppress + + print_verbose("LiteLLM: Disabling Cache") + with suppress(ValueError): + litellm.input_callback.remove("cache") + litellm.success_callback.remove("cache") + litellm._async_success_callback.remove("cache") + + litellm.cache = None + print_verbose(f"LiteLLM: Cache disabled, litellm.cache={litellm.cache}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching_handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf1d911d7f16902ab5589a310ab54e24bcfa6d5 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/caching_handler.py @@ -0,0 +1,1209 @@ +""" +This contains LLMCachingHandler + +This exposes two methods: + - async_get_cache + - async_set_cache + +This file is a wrapper around caching.py + +This class is used to handle caching logic specific for LLM API requests (completion / embedding / text_completion / transcription etc) + +It utilizes the (RedisCache, s3Cache, RedisSemanticCache, QdrantSemanticCache, InMemoryCache, DiskCache) based on what the user has setup + +In each method it will call the appropriate method from caching.py +""" + +import asyncio +import datetime +import inspect +import time +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Callable, + Dict, + Generator, + List, + Optional, + Tuple, + Union, +) + +from pydantic import BaseModel + +import litellm +from litellm._logging import print_verbose, verbose_logger +from litellm.caching import InMemoryCache +from litellm.caching.caching import S3Cache +from litellm.litellm_core_utils.llm_response_utils.response_metadata import ( + update_response_metadata, +) +from litellm.litellm_core_utils.logging_utils import ( + _assemble_complete_response_from_streaming_chunks, +) +from litellm.types.caching import CachedEmbedding +from litellm.types.llms.openai import ResponsesAPIResponse +from litellm.types.rerank import RerankResponse +from litellm.types.utils import ( + CachingDetails, + CallTypes, + Embedding, + EmbeddingResponse, + ModelResponse, + TextCompletionResponse, + TranscriptionResponse, + Usage, +) + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj + from litellm.types.utils import PromptTokensDetailsWrapper +else: + LiteLLMLoggingObj = Any + + +from litellm.litellm_core_utils.core_helpers import ( + _get_parent_otel_span_from_kwargs, +) +from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper + + +class CachingHandlerResponse(BaseModel): + """ + This is the response object for the caching handler. We need to separate embedding cached responses and (completion / text_completion / transcription) cached responses + + For embeddings there can be a cache hit for some of the inputs in the list and a cache miss for others + """ + + cached_result: Optional[Any] = None + final_embedding_cached_response: Optional[EmbeddingResponse] = None + embedding_all_elements_cache_hit: bool = ( + False # this is set to True when all elements in the list have a cache hit in the embedding cache, if true return the final_embedding_cached_response no need to make an API call + ) + + +in_memory_cache_obj = InMemoryCache() + + +def _should_defer_streaming_cache_hit_callbacks(*, kwargs: Dict[str, Any]) -> bool: + """ + When stream=True, do not run success callbacks at cache-hit time. + + Cached chat/text completion replay uses CustomStreamWrapper; cached Responses + replay uses CachedResponsesAPIStreamingIterator. Both invoke logging success + handlers when the stream finishes; firing them here too would double-count + spend and callback records. + """ + return kwargs.get("stream", False) is True + + +class LLMCachingHandler: + def __init__( + self, + original_function: Callable, + request_kwargs: Dict[str, Any], + start_time: datetime.datetime, + ): + from litellm.caching import DualCache, RedisCache + + self.async_streaming_chunks: List[ModelResponse] = [] + self.sync_streaming_chunks: List[ModelResponse] = [] + self.request_kwargs = request_kwargs + self.preset_cache_key: Optional[str] = None + self.original_function = original_function + self.start_time = start_time + if litellm.cache is not None and isinstance(litellm.cache.cache, RedisCache): + self.dual_cache: Optional[DualCache] = DualCache( + redis_cache=litellm.cache.cache, + in_memory_cache=in_memory_cache_obj, + ) + else: + self.dual_cache = None + pass + + async def _async_get_cache( + self, + model: str, + original_function: Callable, + logging_obj: LiteLLMLoggingObj, + start_time: datetime.datetime, + call_type: str, + kwargs: Dict[str, Any], + args: Optional[Tuple[Any, ...]] = None, + ) -> Optional[CachingHandlerResponse]: + """ + Internal method to get from the cache. + Handles different call types (embeddings, chat/completions, text_completion, transcription) + and accordingly returns the cached response + + Args: + model: str: + original_function: Callable: + logging_obj: LiteLLMLoggingObj: + start_time: datetime.datetime: + call_type: str: + kwargs: Dict[str, Any]: + args: Optional[Tuple[Any, ...]] = None: + + + Returns: + CachingHandlerResponse: + Raises: + None + """ + # Check if caching should be performed BEFORE doing expensive operations + if ( + (kwargs.get("caching", None) is None and litellm.cache is not None) + or kwargs.get("caching", False) is True + ) and ( + kwargs.get("cache", {}).get("no-cache", False) is not True + ): # allow users to control returning cached responses from the completion function + args = args or () + final_embedding_cached_response: Optional[EmbeddingResponse] = None + embedding_all_elements_cache_hit: bool = False + cached_result: Optional[Any] = None + kwargs = kwargs.copy() + ######################################################### + # Init cache timing metrics + ######################################################### + cache_check_start_time = time.perf_counter() + cache_check_end_time: Optional[float] = None + ######################################################### + parent_otel_span = _get_parent_otel_span_from_kwargs(kwargs) + kwargs["parent_otel_span"] = parent_otel_span + + if litellm.cache is not None and self._is_call_type_supported_by_cache( + original_function=original_function + ): + verbose_logger.debug("Checking Async Cache") + cached_result = await self._retrieve_from_cache( + call_type=call_type, + kwargs=kwargs, + args=args, + ) + cache_check_end_time = time.perf_counter() + + if cached_result is not None and not isinstance(cached_result, list): + verbose_logger.debug("Cache Hit!") + cache_hit = True + end_time = datetime.datetime.now() + model, custom_llm_provider, _, _ = litellm.get_llm_provider( + model=model, + custom_llm_provider=kwargs.get("custom_llm_provider", None), + api_base=kwargs.get("api_base", None), + api_key=kwargs.get("api_key", None), + ) + cache_duration_ms = ( + cache_check_end_time - cache_check_start_time + ) * 1000 + self._update_litellm_logging_obj_environment( + logging_obj=logging_obj, + model=model, + kwargs=kwargs, + cached_result=cached_result, + is_async=True, + custom_llm_provider=custom_llm_provider, + cache_duration_ms=cache_duration_ms, + ) + + call_type = original_function.__name__ + + cached_result = self._convert_cached_result_to_model_response( + cached_result=cached_result, + call_type=call_type, + kwargs=kwargs, + logging_obj=logging_obj, + model=model, + custom_llm_provider=kwargs.get("custom_llm_provider", None), + args=args, + ) + if not _should_defer_streaming_cache_hit_callbacks(kwargs=kwargs): + # LOG SUCCESS + self._async_log_cache_hit_on_callbacks( + logging_obj=logging_obj, + cached_result=cached_result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, + ) + cache_key = ( + self.preset_cache_key + or self.request_kwargs.get("cache_key") + or litellm.cache.get_cache_key(**self.request_kwargs) + ) + if hasattr(cached_result, "_hidden_params"): + cached_result._hidden_params["cache_key"] = cache_key # type: ignore + return CachingHandlerResponse(cached_result=cached_result) + elif ( + call_type == CallTypes.aembedding.value + and cached_result is not None + and isinstance(cached_result, list) + and litellm.cache is not None + and not isinstance( + litellm.cache.cache, S3Cache + ) # s3 doesn't support bulk writing. Exclude. + ): + ( + final_embedding_cached_response, + embedding_all_elements_cache_hit, + ) = self._process_async_embedding_cached_response( + final_embedding_cached_response=final_embedding_cached_response, + cached_result=cached_result, + kwargs=kwargs, + logging_obj=logging_obj, + start_time=start_time, + model=model, + ) + return CachingHandlerResponse( + final_embedding_cached_response=final_embedding_cached_response, + embedding_all_elements_cache_hit=embedding_all_elements_cache_hit, + ) + + verbose_logger.debug(f"CACHE RESULT: {cached_result}") + return CachingHandlerResponse( + cached_result=cached_result, + final_embedding_cached_response=final_embedding_cached_response, + ) + # Caching disabled - return None to indicate no caching attempted + return None + + def _sync_get_cache( + self, + model: str, + original_function: Callable, + logging_obj: LiteLLMLoggingObj, + start_time: datetime.datetime, + call_type: str, + kwargs: Dict[str, Any], + args: Optional[Tuple[Any, ...]] = None, + ) -> CachingHandlerResponse: + cached_result: Optional[Any] = None + + # Check if caching should be performed BEFORE doing expensive kwargs copy + if litellm.cache is not None and self._is_call_type_supported_by_cache( + original_function=original_function + ): + args = args or () + # Now that we confirmed caching will happen, prepare kwargs + new_kwargs = kwargs.copy() + new_kwargs.update( + convert_args_to_kwargs( + self.original_function, + args, + ) + ) + if new_kwargs.get("metadata") is None: + new_kwargs.pop("metadata", None) + if new_kwargs.get("stream") is True and "cache_key" not in new_kwargs: + new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs) + self.request_kwargs = new_kwargs + print_verbose("Checking Sync Cache") + cached_result = litellm.cache.get_cache(**new_kwargs) + if cached_result is not None: + if "detail" in cached_result: + # implies an error occurred + pass + else: + call_type = original_function.__name__ + cached_result = self._convert_cached_result_to_model_response( + cached_result=cached_result, + call_type=call_type, + kwargs=kwargs, + logging_obj=logging_obj, + model=model, + custom_llm_provider=kwargs.get("custom_llm_provider", None), + args=args, + ) + + # LOG SUCCESS + cache_hit = True + end_time = datetime.datetime.now() + ( + model, + custom_llm_provider, + dynamic_api_key, + api_base, + ) = litellm.get_llm_provider( + model=model or "", + custom_llm_provider=kwargs.get("custom_llm_provider", None), + api_base=kwargs.get("api_base", None), + api_key=kwargs.get("api_key", None), + ) + self._update_litellm_logging_obj_environment( + logging_obj=logging_obj, + model=f"{custom_llm_provider}/{model}", + kwargs=kwargs, + cached_result=cached_result, + is_async=False, + ) + + if not _should_defer_streaming_cache_hit_callbacks(kwargs=kwargs): + logging_obj.handle_sync_success_callbacks_for_async_calls( + result=cached_result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, + ) + cache_key = ( + self.preset_cache_key + or self.request_kwargs.get("cache_key") + or litellm.cache.get_cache_key(**self.request_kwargs) + ) + if hasattr(cached_result, "_hidden_params"): + cached_result._hidden_params["cache_key"] = cache_key # type: ignore + return CachingHandlerResponse(cached_result=cached_result) + return CachingHandlerResponse(cached_result=cached_result) + + def handle_kwargs_input_list_or_str(self, kwargs: Dict[str, Any]) -> List[str]: + """ + Handles the input of kwargs['input'] being a list or a string + """ + if isinstance(kwargs["input"], str): + return [kwargs["input"]] + elif isinstance(kwargs["input"], list): + return kwargs["input"] + else: + raise ValueError("input must be a string or a list") + + def _extract_model_from_cached_results( + self, non_null_list: List[Tuple[int, CachedEmbedding]] + ) -> Optional[str]: + """ + Helper method to extract the model name from cached results. + + Args: + non_null_list: List of (idx, cr) tuples where cr is the cached result dict + + Returns: + Optional[str]: The model name if found, None otherwise + """ + for _, cr in non_null_list: + if isinstance(cr, dict) and cr.get("model"): + return cr["model"] + return None + + def _process_async_embedding_cached_response( + self, + final_embedding_cached_response: Optional[EmbeddingResponse], + cached_result: List[Optional[CachedEmbedding]], + kwargs: Dict[str, Any], + logging_obj: LiteLLMLoggingObj, + start_time: datetime.datetime, + model: str, + ) -> Tuple[Optional[EmbeddingResponse], bool]: + """ + Returns the final embedding cached response and a boolean indicating if all elements in the list have a cache hit + + For embedding responses, there can be a cache hit for some of the inputs in the list and a cache miss for others + This function processes the cached embedding responses and returns the final embedding cached response and a boolean indicating if all elements in the list have a cache hit + + Args: + final_embedding_cached_response: Optional[EmbeddingResponse]: + cached_result: List[Optional[Dict[str, Any]]]: + kwargs: Dict[str, Any]: + logging_obj: LiteLLMLoggingObj: + start_time: datetime.datetime: + model: str: + + Returns: + Tuple[Optional[EmbeddingResponse], bool]: + Returns the final embedding cached response and a boolean indicating if all elements in the list have a cache hit + + + """ + embedding_all_elements_cache_hit: bool = False + remaining_list = [] + non_null_list = [] + kwargs_input_as_list = self.handle_kwargs_input_list_or_str(kwargs) + for idx, cr in enumerate(cached_result): + if cr is None: + remaining_list.append(kwargs_input_as_list[idx]) + else: + non_null_list.append((idx, cr)) + kwargs["input"] = remaining_list + if len(non_null_list) > 0: + # Use the model from the first non-null cached result, fallback to kwargs if not present + model_name = self._extract_model_from_cached_results(non_null_list) + if not model_name: + model_name = kwargs.get("model") + final_embedding_cached_response = EmbeddingResponse( + model=model_name, + data=[None] * len(kwargs_input_as_list), + ) + final_embedding_cached_response._hidden_params["cache_hit"] = True + + prompt_tokens = 0 + aggregated_details: Optional[dict] = None + for val in non_null_list: + idx, cr = val # (idx, cr) tuple + if cr is not None: + embedding_data = cr.get("embedding") + if embedding_data is not None: + final_embedding_cached_response.data[idx] = Embedding( + embedding=embedding_data, + index=idx, + object="embedding", + ) + if isinstance(kwargs_input_as_list[idx], str): + from litellm.utils import token_counter + + prompt_tokens += token_counter( + text=kwargs_input_as_list[idx], count_response_tokens=True + ) + # Aggregate prompt_tokens_details from cached items + item_details = cr.get("prompt_tokens_details") + if item_details: + if aggregated_details is None: + aggregated_details = {} + for key, value in item_details.items(): + if isinstance(value, (int, float)): + aggregated_details[key] = ( + aggregated_details.get(key, 0) + value + ) + else: + aggregated_details[key] = value + + ## USAGE + prompt_tokens_details: Optional["PromptTokensDetailsWrapper"] = None + if aggregated_details: + from litellm.types.utils import PromptTokensDetailsWrapper + + try: + prompt_tokens_details = PromptTokensDetailsWrapper( + **aggregated_details + ) + except Exception: + prompt_tokens_details = None + usage = Usage( + prompt_tokens=prompt_tokens, + completion_tokens=0, + total_tokens=prompt_tokens, + prompt_tokens_details=prompt_tokens_details, + ) + final_embedding_cached_response.usage = usage + if len(remaining_list) == 0: + # LOG SUCCESS + cache_hit = True + embedding_all_elements_cache_hit = True + end_time = datetime.datetime.now() + ( + model, + custom_llm_provider, + dynamic_api_key, + api_base, + ) = litellm.get_llm_provider( + model=model, + custom_llm_provider=kwargs.get("custom_llm_provider", None), + api_base=kwargs.get("api_base", None), + api_key=kwargs.get("api_key", None), + ) + + self._update_litellm_logging_obj_environment( + logging_obj=logging_obj, + model=model, + kwargs=kwargs, + cached_result=final_embedding_cached_response, + is_async=True, + is_embedding=True, + ) + self._async_log_cache_hit_on_callbacks( + logging_obj=logging_obj, + cached_result=final_embedding_cached_response, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, + ) + return final_embedding_cached_response, embedding_all_elements_cache_hit + return final_embedding_cached_response, embedding_all_elements_cache_hit + + def combine_usage(self, usage1: Usage, usage2: Usage) -> Usage: + return Usage( + prompt_tokens=usage1.prompt_tokens + usage2.prompt_tokens, + completion_tokens=usage1.completion_tokens + usage2.completion_tokens, + total_tokens=usage1.total_tokens + usage2.total_tokens, + prompt_tokens_details=self._merge_prompt_tokens_details( + usage1.prompt_tokens_details, + usage2.prompt_tokens_details, + ), + ) + + def _merge_prompt_tokens_details( + self, + details1: Optional["PromptTokensDetailsWrapper"], + details2: Optional["PromptTokensDetailsWrapper"], + ) -> Optional["PromptTokensDetailsWrapper"]: + """Merge two PromptTokensDetailsWrapper objects by summing numeric fields.""" + if details1 is None and details2 is None: + return None + if details1 is None: + return details2 + if details2 is None: + return details1 + + dict1 = ( + details1.model_dump(exclude_none=True) + if hasattr(details1, "model_dump") + else {} + ) + dict2 = ( + details2.model_dump(exclude_none=True) + if hasattr(details2, "model_dump") + else {} + ) + + merged: dict = {} + for key in set(dict1.keys()) | set(dict2.keys()): + v1 = dict1.get(key, 0) + v2 = dict2.get(key, 0) + if isinstance(v1, (int, float)) and isinstance(v2, (int, float)): + merged[key] = v1 + v2 + elif isinstance(v1, dict) and isinstance(v2, dict): + # Recursively merge nested dicts (e.g. cache_creation_token_details) + nested: dict = {} + for nk in set(v1.keys()) | set(v2.keys()): + nv1 = v1.get(nk, 0) + nv2 = v2.get(nk, 0) + if isinstance(nv1, (int, float)) and isinstance(nv2, (int, float)): + nested[nk] = nv1 + nv2 + elif nv1: + nested[nk] = nv1 + else: + nested[nk] = nv2 + merged[key] = nested + elif v1: + merged[key] = v1 + else: + merged[key] = v2 + + if not merged: + return None + + from litellm.types.utils import PromptTokensDetailsWrapper + + try: + return PromptTokensDetailsWrapper(**merged) + except Exception: + return None + + def _combine_cached_embedding_response_with_api_result( + self, + _caching_handler_response: CachingHandlerResponse, + embedding_response: EmbeddingResponse, + start_time: datetime.datetime, + end_time: datetime.datetime, + ) -> EmbeddingResponse: + """ + Combines the cached embedding response with the API EmbeddingResponse + + For caching there can be a cache hit for some of the inputs in the list and a cache miss for others + This function combines the cached embedding response with the API EmbeddingResponse + + Args: + caching_handler_response: CachingHandlerResponse: + embedding_response: EmbeddingResponse: + + Returns: + EmbeddingResponse: + """ + if _caching_handler_response.final_embedding_cached_response is None: + return embedding_response + + idx = 0 + final_data_list = [] + for item in _caching_handler_response.final_embedding_cached_response.data: + if item is None and embedding_response.data is not None: + final_data_list.append(embedding_response.data[idx]) + idx += 1 + else: + final_data_list.append(item) + + _caching_handler_response.final_embedding_cached_response.data = final_data_list + _caching_handler_response.final_embedding_cached_response._hidden_params[ + "cache_hit" + ] = True + _caching_handler_response.final_embedding_cached_response._response_ms = ( + end_time - start_time + ).total_seconds() * 1000 + + ## USAGE + if ( + _caching_handler_response.final_embedding_cached_response.usage is not None + and embedding_response.usage is not None + ): + _caching_handler_response.final_embedding_cached_response.usage = self.combine_usage( + usage1=_caching_handler_response.final_embedding_cached_response.usage, + usage2=embedding_response.usage, + ) + + return _caching_handler_response.final_embedding_cached_response + + def _async_log_cache_hit_on_callbacks( + self, + logging_obj: LiteLLMLoggingObj, + cached_result: Any, + start_time: datetime.datetime, + end_time: datetime.datetime, + cache_hit: bool, + ): + """ + Helper function to log the success of a cached result on callbacks + + Args: + logging_obj (LiteLLMLoggingObj): The logging object. + cached_result: The cached result. + start_time (datetime): The start time of the operation. + end_time (datetime): The end time of the operation. + cache_hit (bool): Whether it was a cache hit. + """ + from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER + + GLOBAL_LOGGING_WORKER.ensure_initialized_and_enqueue( + async_coroutine=logging_obj.async_success_handler( + result=cached_result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, + ) + ) + + logging_obj.handle_sync_success_callbacks_for_async_calls( + result=cached_result, + start_time=start_time, + end_time=end_time, + cache_hit=cache_hit, + ) + + async def _retrieve_from_cache( + self, call_type: str, kwargs: Dict[str, Any], args: Tuple[Any, ...] + ) -> Optional[Any]: + """ + Internal method to + - get cache key + - check what type of cache is used - Redis, RedisSemantic, Qdrant, S3 + - async get cache value + - return the cached value + + Args: + call_type: str: + kwargs: Dict[str, Any]: + args: Optional[Tuple[Any, ...]] = None: + + Returns: + Optional[Any]: + Raises: + None + """ + if litellm.cache is None: + return None + + new_kwargs = kwargs.copy() + new_kwargs.update( + convert_args_to_kwargs( + self.original_function, + args, + ) + ) + if new_kwargs.get("metadata") is None: + new_kwargs.pop("metadata", None) + if new_kwargs.get("stream") is True and "cache_key" not in new_kwargs: + new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs) + self.request_kwargs = new_kwargs + cached_result: Optional[Any] = None + if call_type == CallTypes.aembedding.value: + if isinstance(new_kwargs["input"], str): + new_kwargs["input"] = [new_kwargs["input"]] + elif not isinstance(new_kwargs["input"], list): + raise ValueError("input must be a string or a list") + tasks = [] + for idx, i in enumerate(new_kwargs["input"]): + preset_cache_key = litellm.cache.get_cache_key( + **{**new_kwargs, "input": i} + ) + tasks.append( + litellm.cache.async_get_cache( + cache_key=preset_cache_key, + dynamic_cache_object=self.dual_cache, + ) + ) + cached_result = await asyncio.gather(*tasks) + ## check if cached result is None ## + if cached_result is not None and isinstance(cached_result, list): + # set cached_result to None if all elements are None + if all(result is None for result in cached_result): + cached_result = None + else: + request_kwargs = new_kwargs.copy() + request_cache_key = request_kwargs.pop("cache_key", None) + if litellm.cache._supports_async() is True: + ## check if dual cache is supported ## + self.preset_cache_key = ( + request_cache_key or litellm.cache.get_cache_key(**request_kwargs) + ) + cached_result = await litellm.cache.async_get_cache( + dynamic_cache_object=self.dual_cache, + cache_key=self.preset_cache_key, + **request_kwargs, + ) + else: # fallback for caches that don't support async + self.preset_cache_key = ( + request_cache_key or litellm.cache.get_cache_key(**request_kwargs) + ) + cached_result = litellm.cache.get_cache( + dynamic_cache_object=self.dual_cache, + cache_key=self.preset_cache_key, + **request_kwargs, + ) + return cached_result + + def _convert_cached_result_to_model_response( + self, + cached_result: Any, + call_type: str, + kwargs: Dict[str, Any], + logging_obj: LiteLLMLoggingObj, + model: str, + args: Tuple[Any, ...], + custom_llm_provider: Optional[str] = None, + ) -> Optional[ + Union[ + ModelResponse, + TextCompletionResponse, + EmbeddingResponse, + RerankResponse, + TranscriptionResponse, + CustomStreamWrapper, + ] + ]: + """ + Internal method to process the cached result + + Checks the call type and converts the cached result to the appropriate model response object + example if call type is text_completion -> returns TextCompletionResponse object + + Args: + cached_result: Any: + call_type: str: + kwargs: Dict[str, Any]: + logging_obj: LiteLLMLoggingObj: + model: str: + custom_llm_provider: Optional[str] = None: + args: Optional[Tuple[Any, ...]] = None: + + Returns: + Optional[Any]: + """ + from litellm.utils import convert_to_model_response_object + + if ( + call_type == CallTypes.acompletion.value + or call_type == CallTypes.completion.value + ) and isinstance(cached_result, dict): + if kwargs.get("stream", False) is True: + cached_result = self._convert_cached_stream_response( + cached_result=cached_result, + call_type=call_type, + logging_obj=logging_obj, + model=model, + ) + else: + cached_result = convert_to_model_response_object( + response_object=cached_result, + model_response_object=ModelResponse(), + ) + if ( + call_type == CallTypes.atext_completion.value + or call_type == CallTypes.text_completion.value + ) and isinstance(cached_result, dict): + if kwargs.get("stream", False) is True: + cached_result = self._convert_cached_stream_response( + cached_result=cached_result, + call_type=call_type, + logging_obj=logging_obj, + model=model, + ) + else: + cached_result = TextCompletionResponse(**cached_result) + elif ( + call_type == CallTypes.aembedding.value + or call_type == CallTypes.embedding.value + ) and isinstance(cached_result, dict): + cached_result = convert_to_model_response_object( + response_object=cached_result, + model_response_object=EmbeddingResponse(), + response_type="embedding", + ) + + elif ( + call_type == CallTypes.arerank.value or call_type == CallTypes.rerank.value + ) and isinstance(cached_result, dict): + cached_result = convert_to_model_response_object( + response_object=cached_result, + model_response_object=None, + response_type="rerank", + ) + elif ( + call_type == CallTypes.atranscription.value + or call_type == CallTypes.transcription.value + ) and isinstance(cached_result, dict): + hidden_params = { + "model": "whisper-1", + "custom_llm_provider": custom_llm_provider, + "cache_hit": True, + } + cached_result = convert_to_model_response_object( + response_object=cached_result, + model_response_object=TranscriptionResponse(), + response_type="audio_transcription", + hidden_params=hidden_params, + ) + elif (call_type == "aresponses" or call_type == "responses") and isinstance( + cached_result, dict + ): + from litellm.responses.streaming_iterator import ( + CachedResponsesAPIStreamingIterator, + ) + + response_obj = ResponsesAPIResponse(**cached_result) + if ( + hasattr(response_obj, "_hidden_params") + and response_obj._hidden_params is not None + and isinstance(response_obj._hidden_params, dict) + ): + response_obj._hidden_params["cache_hit"] = True + + if kwargs.get("stream", False) is True: + cached_result = CachedResponsesAPIStreamingIterator( + response=response_obj, + logging_obj=logging_obj, + request_data=kwargs, + call_type=call_type, + ) + else: + cached_result = response_obj + + if ( + hasattr(cached_result, "_hidden_params") + and cached_result._hidden_params is not None + and isinstance(cached_result._hidden_params, dict) + ): + cached_result._hidden_params["cache_hit"] = True + + ######################################################### + # Add final timing metrics to the cached result + ######################################################### + update_response_metadata( + result=cached_result, + logging_obj=logging_obj, + model=model, + kwargs=kwargs, + start_time=self.start_time, + end_time=datetime.datetime.now(), + ) + return cached_result + + def _convert_cached_stream_response( + self, + cached_result: Any, + call_type: str, + logging_obj: LiteLLMLoggingObj, + model: str, + ) -> CustomStreamWrapper: + from litellm.utils import ( + CustomStreamWrapper, + convert_to_streaming_response, + convert_to_streaming_response_async, + ) + + _stream_cached_result: Union[AsyncGenerator, Generator] + if ( + call_type == CallTypes.acompletion.value + or call_type == CallTypes.atext_completion.value + ): + _stream_cached_result = convert_to_streaming_response_async( + response_object=cached_result, + ) + else: + _stream_cached_result = convert_to_streaming_response( + response_object=cached_result, + ) + return CustomStreamWrapper( + completion_stream=_stream_cached_result, + model=model, + custom_llm_provider="cached_response", + logging_obj=logging_obj, + ) + + async def async_set_cache( + self, + result: Any, + original_function: Callable, + kwargs: Dict[str, Any], + args: Optional[Tuple[Any, ...]] = None, + ): + """ + Internal method to check the type of the result & cache used and adds the result to the cache accordingly + + Args: + result: Any: + original_function: Callable: + kwargs: Dict[str, Any]: + args: Optional[Tuple[Any, ...]] = None: + + Returns: + None + Raises: + None + """ + from litellm.litellm_core_utils.core_helpers import ( + _get_parent_otel_span_from_kwargs, + ) + + if litellm.cache is None: + return + + new_kwargs = kwargs.copy() + new_kwargs.update( + convert_args_to_kwargs( + original_function, + args, + ) + ) + parent_otel_span = _get_parent_otel_span_from_kwargs(new_kwargs) + new_kwargs["parent_otel_span"] = parent_otel_span + # [OPTIONAL] ADD TO CACHE + if self._should_store_result_in_cache( + original_function=original_function, kwargs=new_kwargs + ): + if ( + isinstance(result, litellm.ModelResponse) + or isinstance(result, litellm.EmbeddingResponse) + or isinstance(result, TranscriptionResponse) + or isinstance(result, RerankResponse) + or isinstance(result, ResponsesAPIResponse) + ): + if ( + isinstance(result, EmbeddingResponse) + and litellm.cache is not None + and not isinstance( + litellm.cache.cache, S3Cache + ) # s3 doesn't support bulk writing. Exclude. + ): + asyncio.create_task( + litellm.cache.async_add_cache_pipeline( + result, dynamic_cache_object=self.dual_cache, **new_kwargs + ) + ) + else: + asyncio.create_task( + litellm.cache.async_add_cache( + result.model_dump_json(), + dynamic_cache_object=self.dual_cache, + **new_kwargs, + ) + ) + else: + asyncio.create_task(litellm.cache.async_add_cache(result, **new_kwargs)) + + def sync_set_cache( + self, + result: Any, + kwargs: Dict[str, Any], + args: Optional[Tuple[Any, ...]] = None, + ): + """ + Sync internal method to add the result to the cache + """ + + new_kwargs = kwargs.copy() + new_kwargs.update( + convert_args_to_kwargs( + self.original_function, + args, + ) + ) + if litellm.cache is None: + return + + if self._should_store_result_in_cache( + original_function=self.original_function, kwargs=new_kwargs + ): + litellm.cache.add_cache(result, **new_kwargs) + + return + + def _should_store_result_in_cache( + self, original_function: Callable, kwargs: Dict[str, Any] + ) -> bool: + """ + Helper function to determine if the result should be stored in the cache. + + Returns: + bool: True if the result should be stored in the cache, False otherwise. + """ + return ( + (litellm.cache is not None) + and litellm.cache.supported_call_types is not None + and (str(original_function.__name__) in litellm.cache.supported_call_types) + and (kwargs.get("cache", {}).get("no-store", False) is not True) + ) + + def _is_call_type_supported_by_cache( + self, + original_function: Callable, + ) -> bool: + """ + Helper function to determine if the call type is supported by the cache. + + call types are acompletion, aembedding, atext_completion, atranscription, arerank + + Defined on `litellm.types.utils.CallTypes` + + Returns: + bool: True if the call type is supported by the cache, False otherwise. + """ + if ( + litellm.cache is not None + and litellm.cache.supported_call_types is not None + and str(original_function.__name__) in litellm.cache.supported_call_types + ): + return True + return False + + async def _add_streaming_response_to_cache(self, processed_chunk: ModelResponse): + """ + Internal method to add the streaming response to the cache + + + - If 'streaming_chunk' has a 'finish_reason' then assemble a litellm.ModelResponse object + - Else append the chunk to self.async_streaming_chunks + + """ + + complete_streaming_response: Optional[ + Union[ModelResponse, TextCompletionResponse] + ] = _assemble_complete_response_from_streaming_chunks( + result=processed_chunk, + start_time=self.start_time, + end_time=datetime.datetime.now(), + request_kwargs=self.request_kwargs, + streaming_chunks=self.async_streaming_chunks, + is_async=True, + ) + # if a complete_streaming_response is assembled, add it to the cache + if complete_streaming_response is not None: + await self.async_set_cache( + result=complete_streaming_response, + original_function=self.original_function, + kwargs=self.request_kwargs, + ) + + def _sync_add_streaming_response_to_cache(self, processed_chunk: ModelResponse): + """ + Sync internal method to add the streaming response to the cache + """ + complete_streaming_response: Optional[ + Union[ModelResponse, TextCompletionResponse] + ] = _assemble_complete_response_from_streaming_chunks( + result=processed_chunk, + start_time=self.start_time, + end_time=datetime.datetime.now(), + request_kwargs=self.request_kwargs, + streaming_chunks=self.sync_streaming_chunks, + is_async=False, + ) + + # if a complete_streaming_response is assembled, add it to the cache + if complete_streaming_response is not None: + self.sync_set_cache( + result=complete_streaming_response, + kwargs=self.request_kwargs, + ) + + def _update_litellm_logging_obj_environment( + self, + logging_obj: LiteLLMLoggingObj, + model: str, + kwargs: Dict[str, Any], + cached_result: Any, + is_async: bool, + is_embedding: bool = False, + custom_llm_provider: Optional[str] = None, + cache_duration_ms: Optional[float] = None, + ): + """ + Helper function to update the LiteLLMLoggingObj environment variables. + + Args: + logging_obj (LiteLLMLoggingObj): The logging object to update. + model (str): The model being used. + kwargs (Dict[str, Any]): The keyword arguments from the original function call. + cached_result (Any): The cached result to log. + is_async (bool): Whether the call is asynchronous or not. + is_embedding (bool): Whether the call is for embeddings or not. + custom_llm_provider (Optional[str]): The custom llm provider being used. + + Returns: + None + """ + litellm_params = { + "logger_fn": kwargs.get("logger_fn", None), + "acompletion": is_async, + "api_base": kwargs.get("api_base", ""), + "metadata": kwargs.get("metadata", {}), + "model_info": kwargs.get("model_info", {}), + "proxy_server_request": kwargs.get("proxy_server_request", None), + "stream_response": kwargs.get("stream_response", {}), + "custom_llm_provider": custom_llm_provider, + } + + if litellm.cache is not None: + litellm_params["preset_cache_key"] = ( + litellm.cache._get_preset_cache_key_from_kwargs(**kwargs) + ) + else: + litellm_params["preset_cache_key"] = None + + logging_obj.update_environment_variables( + model=model, + user=kwargs.get("user", None), + optional_params={}, + litellm_params=litellm_params, + input=( + kwargs.get("messages", "") + if not is_embedding + else kwargs.get("input", "") + ), + api_key=kwargs.get("api_key", None), + original_response=str(cached_result), + additional_args=None, + stream=kwargs.get("stream", False), + custom_llm_provider=custom_llm_provider, + ) + + logging_obj.caching_details = CachingDetails( + cache_hit=True, + cache_duration_ms=cache_duration_ms, + ) + + +def convert_args_to_kwargs( + original_function: Callable, + args: Optional[Tuple[Any, ...]] = None, +) -> Dict[str, Any]: + # Get the signature of the original function + signature = inspect.signature(original_function) + + # Get parameter names in the order they appear in the original function + param_names = list(signature.parameters.keys()) + + # Create a mapping of positional arguments to parameter names + args_to_kwargs = {} + if args: + for index, arg in enumerate(args): + if index < len(param_names): + param_name = param_names[index] + args_to_kwargs[param_name] = arg + + return args_to_kwargs diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/disk_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/disk_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e32c29b3bc66c990b27b7a74ca8dd296dc3911a2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/disk_cache.py @@ -0,0 +1,93 @@ +import json +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base_cache import BaseCache + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + Span = Union[_Span, Any] +else: + Span = Any + + +class DiskCache(BaseCache): + def __init__(self, disk_cache_dir: Optional[str] = None): + try: + import diskcache as dc + except ModuleNotFoundError as e: + raise ModuleNotFoundError( + "Please install litellm with `litellm[caching]` to use disk caching." + ) from e + + # if users don't provider one, use the default litellm cache + if disk_cache_dir is None: + self.disk_cache = dc.Cache(".litellm_cache") + else: + self.disk_cache = dc.Cache(disk_cache_dir) + + def set_cache(self, key, value, **kwargs): + if "ttl" in kwargs: + self.disk_cache.set(key, value, expire=kwargs["ttl"]) + else: + self.disk_cache.set(key, value) + + async def async_set_cache(self, key, value, **kwargs): + self.set_cache(key=key, value=value, **kwargs) + + async def async_set_cache_pipeline(self, cache_list, **kwargs): + for cache_key, cache_value in cache_list: + if "ttl" in kwargs: + self.set_cache(key=cache_key, value=cache_value, ttl=kwargs["ttl"]) + else: + self.set_cache(key=cache_key, value=cache_value) + + def get_cache(self, key, **kwargs): + original_cached_response = self.disk_cache.get(key) + if original_cached_response: + try: + cached_response = json.loads(original_cached_response) # type: ignore + except Exception: + cached_response = original_cached_response + return cached_response + return None + + def batch_get_cache(self, keys: list, **kwargs): + return_val = [] + for k in keys: + val = self.get_cache(key=k, **kwargs) + return_val.append(val) + return return_val + + def increment_cache(self, key, value: int, **kwargs) -> int: + # get the value + init_value = self.get_cache(key=key) or 0 + value = init_value + value # type: ignore + self.set_cache(key, value, **kwargs) + return value + + async def async_get_cache(self, key, **kwargs): + return self.get_cache(key=key, **kwargs) + + async def async_batch_get_cache(self, keys: list, **kwargs): + return_val = [] + for k in keys: + val = self.get_cache(key=k, **kwargs) + return_val.append(val) + return return_val + + async def async_increment(self, key, value: int, **kwargs) -> int: + # get the value + init_value = await self.async_get_cache(key=key) or 0 + value = init_value + value # type: ignore + await self.async_set_cache(key, value, **kwargs) + return value + + def flush_cache(self): + self.disk_cache.clear() + + async def disconnect(self): + pass + + def delete_cache(self, key): + self.disk_cache.pop(key) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/dual_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/dual_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..8060a65b78d4ac07af9850cbb4111fe97311d634 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/dual_cache.py @@ -0,0 +1,539 @@ +""" +Dual Cache implementation - Class to update both Redis and an in-memory cache simultaneously. + +Has 4 primary methods: + - set_cache + - get_cache + - async_set_cache + - async_get_cache +""" + +import asyncio +import time +import traceback +from concurrent.futures import ThreadPoolExecutor +from threading import Lock +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union + +if TYPE_CHECKING: + from litellm.types.caching import RedisPipelineIncrementOperation + +import litellm +from litellm._logging import print_verbose, verbose_logger +from litellm.constants import DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE + +from .base_cache import BaseCache +from .in_memory_cache import InMemoryCache +from .redis_cache import RedisCache + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + Span = Union[_Span, Any] +else: + Span = Any + +from collections import OrderedDict + + +class LimitedSizeOrderedDict(OrderedDict): + def __init__(self, *args, max_size=100, **kwargs): + super().__init__(*args, **kwargs) + self.max_size = max_size + + def __setitem__(self, key, value): + # If inserting a new key exceeds max size, remove the oldest item + if len(self) >= self.max_size: + self.popitem(last=False) + super().__setitem__(key, value) + + +class DualCache(BaseCache): + """ + DualCache is a cache implementation that updates both Redis and an in-memory cache simultaneously. + When data is updated or inserted, it is written to both the in-memory cache + Redis. + This ensures that even if Redis hasn't been updated yet, the in-memory cache reflects the most recent data. + """ + + def __init__( + self, + in_memory_cache: Optional[InMemoryCache] = None, + redis_cache: Optional[RedisCache] = None, + default_in_memory_ttl: Optional[float] = None, + default_redis_ttl: Optional[float] = None, + default_redis_batch_cache_expiry: Optional[float] = None, + default_max_redis_batch_cache_size: int = DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE, + ) -> None: + super().__init__() + # If in_memory_cache is not provided, use the default InMemoryCache + self.in_memory_cache = in_memory_cache or InMemoryCache() + # If redis_cache is not provided, use the default RedisCache + self.redis_cache = redis_cache + self.last_redis_batch_access_time = LimitedSizeOrderedDict( + max_size=default_max_redis_batch_cache_size + ) + self._last_redis_batch_access_time_lock = Lock() + self.redis_batch_cache_expiry = ( + default_redis_batch_cache_expiry + or litellm.default_redis_batch_cache_expiry + or 10 + ) + self.default_in_memory_ttl = ( + default_in_memory_ttl or litellm.default_in_memory_ttl + ) + self.default_redis_ttl = default_redis_ttl or litellm.default_redis_ttl + + def update_cache_ttl( + self, default_in_memory_ttl: Optional[float], default_redis_ttl: Optional[float] + ): + if default_in_memory_ttl is not None: + self.default_in_memory_ttl = default_in_memory_ttl + + if default_redis_ttl is not None: + self.default_redis_ttl = default_redis_ttl + + def attach_redis_cache( + self, + redis_cache: Optional[RedisCache] = None, + *, + default_redis_ttl: Optional[float] = None, + ) -> None: + """ + Attach a Redis backend if this DualCache does not already have one. + + No-op when ``redis_cache`` is None or when Redis was already set (constructor + or a prior attach). Use this for lazy wiring after a shared Redis client exists. + Does not backfill in-memory-only keys to Redis. + """ + if redis_cache is None or self.redis_cache is not None: + return + self.redis_cache = redis_cache + if default_redis_ttl is not None: + self.default_redis_ttl = default_redis_ttl + + def set_cache(self, key, value, local_only: bool = False, **kwargs): + # Update both Redis and in-memory cache + try: + if self.in_memory_cache is not None: + if "ttl" not in kwargs and self.default_in_memory_ttl is not None: + kwargs["ttl"] = self.default_in_memory_ttl + + self.in_memory_cache.set_cache(key, value, **kwargs) + + if self.redis_cache is not None and local_only is False: + self.redis_cache.set_cache(key, value, **kwargs) + except Exception as e: + print_verbose(e) + + def increment_cache( + self, key, value: int, local_only: bool = False, **kwargs + ) -> int: + """ + Key - the key in cache + + Value - int - the value you want to increment by + + Returns - int - the incremented value + """ + try: + result: int = value + if self.in_memory_cache is not None: + result = self.in_memory_cache.increment_cache(key, value, **kwargs) + + if self.redis_cache is not None and local_only is False: + result = self.redis_cache.increment_cache(key, value, **kwargs) + + return result + except Exception as e: + verbose_logger.error(f"LiteLLM Cache: Excepton async add_cache: {str(e)}") + raise e + + def get_cache( + self, + key, + parent_otel_span: Optional[Span] = None, + local_only: bool = False, + **kwargs, + ): + # Try to fetch from in-memory cache first + try: + result = None + if self.in_memory_cache is not None: + in_memory_result = self.in_memory_cache.get_cache(key, **kwargs) + + if in_memory_result is not None: + result = in_memory_result + + if result is None and self.redis_cache is not None and local_only is False: + # If not found in in-memory cache, try fetching from Redis + redis_result = self.redis_cache.get_cache( + key, parent_otel_span=parent_otel_span + ) + + if redis_result is not None: + # Update in-memory cache with the value from Redis + self.in_memory_cache.set_cache(key, redis_result, **kwargs) + + result = redis_result + + print_verbose(f"get cache: cache result: {result}") + return result + except Exception: + verbose_logger.error(traceback.format_exc()) + + def batch_get_cache( + self, + keys: list, + parent_otel_span: Optional[Span] = None, + local_only: bool = False, + **kwargs, + ): + received_args = locals() + received_args.pop("self") + + def run_in_new_loop(): + """Run the coroutine in a new event loop within this thread.""" + new_loop = asyncio.new_event_loop() + try: + asyncio.set_event_loop(new_loop) + return new_loop.run_until_complete( + self.async_batch_get_cache(**received_args) + ) + finally: + new_loop.close() + asyncio.set_event_loop(None) + + try: + # First, try to get the current event loop + _ = asyncio.get_running_loop() + # If we're already in an event loop, run in a separate thread + # to avoid nested event loop issues + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(run_in_new_loop) + return future.result() + + except RuntimeError: + # No running event loop, we can safely run in this thread + return run_in_new_loop() + + async def async_get_cache( + self, + key, + parent_otel_span: Optional[Span] = None, + local_only: bool = False, + **kwargs, + ): + # Try to fetch from in-memory cache first + try: + print_verbose( + f"async get cache: cache key: {key}; local_only: {local_only}" + ) + result = None + if self.in_memory_cache is not None: + in_memory_result = await self.in_memory_cache.async_get_cache( + key, **kwargs + ) + + print_verbose(f"in_memory_result: {in_memory_result}") + if in_memory_result is not None: + result = in_memory_result + + if result is None and self.redis_cache is not None and local_only is False: + # If not found in in-memory cache, try fetching from Redis + redis_result = await self.redis_cache.async_get_cache( + key, parent_otel_span=parent_otel_span + ) + + if redis_result is not None: + # Update in-memory cache with the value from Redis + await self.in_memory_cache.async_set_cache( + key, redis_result, **kwargs + ) + + result = redis_result + + print_verbose(f"get cache: cache result: {result}") + return result + except Exception: + verbose_logger.error(traceback.format_exc()) + + def _reserve_redis_batch_keys( + self, + current_time: float, + keys: List[str], + result: List[Any], + ) -> Tuple[List[str], Dict[str, Optional[float]]]: + """ + Atomically choose keys to fetch from Redis and reserve their access time. + This prevents check-then-act races under concurrent async callers. + """ + sublist_keys: List[str] = [] + previous_access_times: Dict[str, Optional[float]] = {} + + with self._last_redis_batch_access_time_lock: + for key, value in zip(keys, result): + if value is not None: + continue + + if ( + key not in self.last_redis_batch_access_time + or current_time - self.last_redis_batch_access_time[key] + >= self.redis_batch_cache_expiry + ): + sublist_keys.append(key) + previous_access_times[key] = self.last_redis_batch_access_time.get( + key + ) + self.last_redis_batch_access_time[key] = current_time + + return sublist_keys, previous_access_times + + def _rollback_redis_batch_key_reservations( + self, previous_access_times: Dict[str, Optional[float]] + ) -> None: + with self._last_redis_batch_access_time_lock: + for key, previous_time in previous_access_times.items(): + if previous_time is None: + self.last_redis_batch_access_time.pop(key, None) + else: + self.last_redis_batch_access_time[key] = previous_time + + async def async_batch_get_cache( + self, + keys: list, + parent_otel_span: Optional[Span] = None, + local_only: bool = False, + **kwargs, + ): + try: + result = [None] * len(keys) + if self.in_memory_cache is not None: + in_memory_result = await self.in_memory_cache.async_batch_get_cache( + keys, **kwargs + ) + + if in_memory_result is not None: + result = in_memory_result + + if None in result and self.redis_cache is not None and local_only is False: + """ + - for the none values in the result + - check the redis cache + """ + current_time = time.time() + sublist_keys, previous_access_times = self._reserve_redis_batch_keys( + current_time, keys, result + ) + + # Only hit Redis if enough time has passed since last access. + if len(sublist_keys) > 0: + try: + # If not found in in-memory cache, try fetching from Redis + redis_result = await self.redis_cache.async_batch_get_cache( + sublist_keys, parent_otel_span=parent_otel_span + ) + except Exception: + # Do not throttle subsequent callers if the Redis read fails. + self._rollback_redis_batch_key_reservations( + previous_access_times + ) + raise + + # Short-circuit if redis_result is None or contains only None values + if redis_result is None or all( + v is None for v in redis_result.values() + ): + return result + + # Pre-compute key-to-index mapping for O(1) lookup + key_to_index = {key: i for i, key in enumerate(keys)} + + # Update both result and in-memory cache in a single loop + for key, value in redis_result.items(): + result[key_to_index[key]] = value + + if value is not None and self.in_memory_cache is not None: + await self.in_memory_cache.async_set_cache( + key, value, **kwargs + ) + + return result + except Exception: + verbose_logger.error(traceback.format_exc()) + + async def async_set_cache(self, key, value, local_only: bool = False, **kwargs): + print_verbose( + f"async set cache: cache key: {key}; local_only: {local_only}; value: {value}" + ) + try: + if self.in_memory_cache is not None: + if "ttl" not in kwargs and self.default_in_memory_ttl is not None: + kwargs["ttl"] = self.default_in_memory_ttl + await self.in_memory_cache.async_set_cache(key, value, **kwargs) + + if self.redis_cache is not None and local_only is False: + await self.redis_cache.async_set_cache(key, value, **kwargs) + except Exception as e: + verbose_logger.exception( + f"LiteLLM Cache: Excepton async add_cache: {str(e)}" + ) + + # async_batch_set_cache + async def async_set_cache_pipeline( + self, cache_list: list, local_only: bool = False, **kwargs + ): + """ + Batch write values to the cache + """ + print_verbose( + f"async batch set cache: cache keys: {cache_list}; local_only: {local_only}" + ) + try: + if self.in_memory_cache is not None: + if "ttl" not in kwargs and self.default_in_memory_ttl is not None: + kwargs["ttl"] = self.default_in_memory_ttl + await self.in_memory_cache.async_set_cache_pipeline( + cache_list=cache_list, **kwargs + ) + + if self.redis_cache is not None and local_only is False: + await self.redis_cache.async_set_cache_pipeline( + cache_list=cache_list, ttl=kwargs.pop("ttl", None), **kwargs + ) + except Exception as e: + verbose_logger.exception( + f"LiteLLM Cache: Excepton async add_cache: {str(e)}" + ) + + async def async_increment_cache( + self, + key, + value: float, + parent_otel_span: Optional[Span] = None, + local_only: bool = False, + refresh_ttl: bool = False, + **kwargs, + ) -> Optional[float]: + """ + Key - the key in cache + + Value - float - the value you want to increment by + + Refresh_ttl - bool - if True, resets the Redis TTL on every write. + Default False preserves window-style semantics. + + Returns - the incremented value, or None if no cache backend is + available (in_memory_cache is None and Redis failed/is absent). + """ + result: Optional[float] = None + try: + if self.in_memory_cache is not None: + result = await self.in_memory_cache.async_increment( + key, value, **kwargs + ) + + if self.redis_cache is not None and local_only is False: + result = await self.redis_cache.async_increment( + key, + value, + parent_otel_span=parent_otel_span, + ttl=kwargs.get("ttl", None), + refresh_ttl=refresh_ttl, + ) + + return result + except Exception as e: + verbose_logger.warning( + "Redis async_increment_cache failed, falling back to in-memory result: %s", + e, + ) + return result + + async def async_increment_cache_pipeline( + self, + increment_list: List["RedisPipelineIncrementOperation"], + local_only: bool = False, + parent_otel_span: Optional[Span] = None, + **kwargs, + ) -> Optional[List[float]]: + result: Optional[List[float]] = None + try: + if self.in_memory_cache is not None: + result = await self.in_memory_cache.async_increment_pipeline( + increment_list=increment_list, + parent_otel_span=parent_otel_span, + ) + + if self.redis_cache is not None and local_only is False: + result = await self.redis_cache.async_increment_pipeline( + increment_list=increment_list, + parent_otel_span=parent_otel_span, + ) + + return result + except Exception as e: + verbose_logger.warning( + "Redis async_increment_cache_pipeline failed, falling back to in-memory result: %s", + e, + ) + return result + + async def async_set_cache_sadd( + self, key, value: List, local_only: bool = False, **kwargs + ) -> None: + """ + Add value to a set + + Key - the key in cache + + Value - str - the value you want to add to the set + + Returns - None + """ + try: + if self.in_memory_cache is not None: + _ = await self.in_memory_cache.async_set_cache_sadd( + key, value, ttl=kwargs.get("ttl", None) + ) + + if self.redis_cache is not None and local_only is False: + _ = await self.redis_cache.async_set_cache_sadd( + key, value, ttl=kwargs.get("ttl", None) + ) + + return None + except Exception as e: + raise e # don't log, if exception is raised + + def flush_cache(self): + if self.in_memory_cache is not None: + self.in_memory_cache.flush_cache() + if self.redis_cache is not None: + self.redis_cache.flush_cache() + + def delete_cache(self, key): + """ + Delete a key from the cache + """ + if self.in_memory_cache is not None: + self.in_memory_cache.delete_cache(key) + if self.redis_cache is not None: + self.redis_cache.delete_cache(key) + + async def async_delete_cache(self, key: str): + """ + Delete a key from the cache + """ + if self.in_memory_cache is not None: + self.in_memory_cache.delete_cache(key) + if self.redis_cache is not None: + await self.redis_cache.async_delete_cache(key) + + async def async_get_ttl(self, key: str) -> Optional[int]: + """ + Get the remaining TTL of a key in in-memory cache or redis + """ + ttl = await self.in_memory_cache.async_get_ttl(key) + if ttl is None and self.redis_cache is not None: + ttl = await self.redis_cache.async_get_ttl(key) + return ttl diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/gcs_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/gcs_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..3327e094bc2fced2e088330aa5d3f5ab5b25d21f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/gcs_cache.py @@ -0,0 +1,114 @@ +"""GCS Cache implementation +Supports syncing responses to Google Cloud Storage Buckets using HTTP requests. +""" + +import json +import asyncio +from typing import Optional + +from litellm._logging import print_verbose, verbose_logger +from litellm.integrations.gcs_bucket.gcs_bucket_base import GCSBucketBase +from litellm.llms.custom_httpx.http_handler import ( + get_async_httpx_client, + _get_httpx_client, + httpxSpecialProvider, +) +from .base_cache import BaseCache + + +class GCSCache(BaseCache): + def __init__( + self, + bucket_name: Optional[str] = None, + path_service_account: Optional[str] = None, + gcs_path: Optional[str] = None, + ) -> None: + super().__init__() + self.bucket_name = bucket_name or GCSBucketBase(bucket_name=None).BUCKET_NAME + self.path_service_account = ( + path_service_account + or GCSBucketBase(bucket_name=None).path_service_account_json + ) + self.key_prefix = gcs_path.rstrip("/") + "/" if gcs_path else "" + # create httpx clients + self.async_client = get_async_httpx_client( + llm_provider=httpxSpecialProvider.LoggingCallback + ) + self.sync_client = _get_httpx_client() + + def _construct_headers(self) -> dict: + base = GCSBucketBase(bucket_name=self.bucket_name) + base.path_service_account_json = self.path_service_account + base.BUCKET_NAME = self.bucket_name + return base.sync_construct_request_headers() + + def set_cache(self, key, value, **kwargs): + try: + print_verbose(f"LiteLLM SET Cache - GCS. Key={key}. Value={value}") + headers = self._construct_headers() + object_name = self.key_prefix + key + bucket_name = self.bucket_name + url = f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}" + data = json.dumps(value) + self.sync_client.post(url=url, data=data, headers=headers) + except Exception as e: + print_verbose(f"GCS Caching: set_cache() - Got exception from GCS: {e}") + + async def async_set_cache(self, key, value, **kwargs): + try: + headers = self._construct_headers() + object_name = self.key_prefix + key + bucket_name = self.bucket_name + url = f"https://storage.googleapis.com/upload/storage/v1/b/{bucket_name}/o?uploadType=media&name={object_name}" + data = json.dumps(value) + await self.async_client.post(url=url, data=data, headers=headers) + except Exception as e: + print_verbose( + f"GCS Caching: async_set_cache() - Got exception from GCS: {e}" + ) + + def get_cache(self, key, **kwargs): + try: + headers = self._construct_headers() + object_name = self.key_prefix + key + bucket_name = self.bucket_name + url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media" + response = self.sync_client.get(url=url, headers=headers) + if response.status_code == 200: + cached_response = json.loads(response.text) + verbose_logger.debug( + f"Got GCS Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}" + ) + return cached_response + return None + except Exception as e: + verbose_logger.error( + f"GCS Caching: get_cache() - Got exception from GCS: {e}" + ) + + async def async_get_cache(self, key, **kwargs): + try: + headers = self._construct_headers() + object_name = self.key_prefix + key + bucket_name = self.bucket_name + url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name}?alt=media" + response = await self.async_client.get(url=url, headers=headers) + if response.status_code == 200: + return json.loads(response.text) + return None + except Exception as e: + verbose_logger.error( + f"GCS Caching: async_get_cache() - Got exception from GCS: {e}" + ) + + def flush_cache(self): + pass + + async def disconnect(self): + pass + + async def async_set_cache_pipeline(self, cache_list, **kwargs): + tasks = [] + for val in cache_list: + tasks.append(self.async_set_cache(val[0], val[1], **kwargs)) + await asyncio.gather(*tasks) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/in_memory_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/in_memory_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..ba446dd4f608280ed64274d2ffdefae2f2d23a6a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/in_memory_cache.py @@ -0,0 +1,289 @@ +""" +In-Memory Cache implementation + +Has 4 methods: + - set_cache + - get_cache + - async_set_cache + - async_get_cache +""" + +import json +import sys +import time +import heapq +from typing import TYPE_CHECKING, Any, List, Optional + +if TYPE_CHECKING: + from litellm.types.caching import RedisPipelineIncrementOperation + +from pydantic import BaseModel + +from litellm.constants import MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB + +from .base_cache import BaseCache + + +class InMemoryCache(BaseCache): + def __init__( + self, + max_size_in_memory: Optional[int] = 200, + default_ttl: Optional[ + int + ] = 600, # default ttl is 10 minutes. At maximum litellm rate limiting logic requires objects to be in memory for 1 minute + max_size_per_item: Optional[int] = 1024, # 1MB = 1024KB + ): + """ + max_size_in_memory [int]: Maximum number of items in cache. done to prevent memory leaks. Use 200 items as a default + """ + self.max_size_in_memory = ( + max_size_in_memory if max_size_in_memory is not None else 200 + ) # set an upper bound of 200 items in-memory + self.default_ttl = default_ttl or 600 + self.max_size_per_item = ( + max_size_per_item or MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB + ) # 1MB = 1024KB + + # in-memory cache + self.cache_dict: dict = {} + self.ttl_dict: dict = {} + self.expiration_heap: list[tuple[float, str]] = [] + + def check_value_size(self, value: Any): + """ + Check if value size exceeds max_size_per_item (1MB) + Returns True if value size is acceptable, False otherwise + """ + try: + # Fast path for common primitive types that are typically small + if ( + isinstance(value, (bool, int, float, str)) + and len(str(value)) + < self.max_size_per_item * MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB + ): # Conservative estimate + return True + + # Direct size check for bytes objects + if isinstance(value, bytes): + return sys.getsizeof(value) / 1024 <= self.max_size_per_item + + # Handle special types without full conversion when possible + if hasattr(value, "__sizeof__"): # Use __sizeof__ if available + size = value.__sizeof__() / 1024 + return size <= self.max_size_per_item + + # Fallback for complex types + if isinstance(value, BaseModel) and hasattr( + value, "model_dump" + ): # Pydantic v2 + value = value.model_dump() + elif hasattr(value, "isoformat"): # datetime objects + return True # datetime strings are always small + + # Only convert to JSON if absolutely necessary + if not isinstance(value, (str, bytes)): + value = json.dumps(value, default=str) + + return sys.getsizeof(value) / 1024 <= self.max_size_per_item + + except Exception: + return False + + def _is_key_expired(self, key: str) -> bool: + """ + Check if a specific key is expired + """ + return key in self.ttl_dict and time.time() > self.ttl_dict[key] + + def _remove_key(self, key: str) -> None: + """ + Remove a key from both cache_dict and ttl_dict + """ + self.cache_dict.pop(key, None) + self.ttl_dict.pop(key, None) + + def evict_cache(self): + """ + Eviction policy: + 1. First, remove expired items from ttl_dict and cache_dict + 2. If cache is still at or above max_size_in_memory, evict items with earliest expiration times + + + This guarantees the following: + - 1. When item ttl not set: At minimum each item will remain in memory for the default ttl + - 2. When ttl is set: the item will remain in memory for at least that amount of time, unless cache size requires eviction + - 3. the size of in-memory cache is bounded + + """ + current_time = time.time() + + # Step 1: Remove expired or outdated items + while self.expiration_heap: + expiration_time, key = self.expiration_heap[0] + + # Case 1: Heap entry is outdated + if expiration_time != self.ttl_dict.get(key): + heapq.heappop(self.expiration_heap) + # Case 2: Entry is valid but expired + elif expiration_time <= current_time: + heapq.heappop(self.expiration_heap) + self._remove_key(key) + else: + # Case 3: Entry is valid and not expired + break + + # Step 2: Evict if cache is still full + while len(self.cache_dict) >= self.max_size_in_memory: + expiration_time, key = heapq.heappop(self.expiration_heap) + # Skip if key was removed or updated + if self.ttl_dict.get(key) == expiration_time: + self._remove_key(key) + + # de-reference the removed item + # https://www.geeksforgeeks.org/diagnosing-and-fixing-memory-leaks-in-python/ + # One of the most common causes of memory leaks in Python is the retention of objects that are no longer being used. + # This can occur when an object is referenced by another object, but the reference is never removed. + + def allow_ttl_override(self, key: str) -> bool: + """ + Check if ttl is set for a key + """ + ttl_time = self.ttl_dict.get(key) + if ttl_time is None: # if ttl is not set, allow override + return True + elif float(ttl_time) < time.time(): # if ttl is expired, allow override + return True + else: + return False + + def set_cache(self, key, value, **kwargs): + # Handle the edge case where max_size_in_memory is 0 + if self.max_size_in_memory == 0: + return # Don't cache anything if max size is 0 + + # Always prune expired/outdated heap roots before inserting. + # This keeps expiration_heap bounded even when the live cache stays + # below max_size_in_memory and keys are reinserted after TTL expiry. + self.evict_cache() + if not self.check_value_size(value): + return + + self.cache_dict[key] = value + if self.allow_ttl_override(key): # if ttl is not set, set it to default ttl + if "ttl" in kwargs and kwargs["ttl"] is not None: + self.ttl_dict[key] = time.time() + float(kwargs["ttl"]) + heapq.heappush(self.expiration_heap, (self.ttl_dict[key], key)) + else: + self.ttl_dict[key] = time.time() + self.default_ttl + heapq.heappush(self.expiration_heap, (self.ttl_dict[key], key)) + + async def async_set_cache(self, key, value, **kwargs): + self.set_cache(key=key, value=value, **kwargs) + + async def async_set_cache_pipeline(self, cache_list, ttl=None, **kwargs): + for cache_key, cache_value in cache_list: + if ttl is not None: + self.set_cache(key=cache_key, value=cache_value, ttl=ttl) + else: + self.set_cache(key=cache_key, value=cache_value) + + async def async_set_cache_sadd(self, key, value: List, ttl: Optional[float]): + """ + Add value to set + """ + # get the value + init_value = self.get_cache(key=key) or set() + for val in value: + init_value.add(val) + self.set_cache(key, init_value, ttl=ttl) + return value + + def evict_element_if_expired(self, key: str) -> bool: + """ + Returns True if the element is expired and removed from the cache + + Returns False if the element is not expired + """ + if self._is_key_expired(key): + self._remove_key(key) + return True + return False + + def get_cache(self, key, **kwargs): + if key in self.cache_dict: + if self.evict_element_if_expired(key): + return None + original_cached_response = self.cache_dict[key] + try: + cached_response = json.loads(original_cached_response) + except Exception: + cached_response = original_cached_response + return cached_response + return None + + def batch_get_cache(self, keys: list, **kwargs): + return_val = [] + for k in keys: + val = self.get_cache(key=k, **kwargs) + return_val.append(val) + return return_val + + def increment_cache(self, key, value: int, **kwargs) -> int: + # get the value + init_value = self.get_cache(key=key) or 0 + value = init_value + value + self.set_cache(key, value, **kwargs) + return value + + async def async_get_cache(self, key, **kwargs): + return self.get_cache(key=key, **kwargs) + + async def async_batch_get_cache(self, keys: list, **kwargs): + return_val = [] + for k in keys: + val = self.get_cache(key=k, **kwargs) + return_val.append(val) + return return_val + + async def async_increment(self, key, value: float, **kwargs) -> float: + # get the value + init_value = await self.async_get_cache(key=key) or 0 + value = init_value + value + await self.async_set_cache(key, value, **kwargs) + return value + + async def async_increment_pipeline( + self, increment_list: List["RedisPipelineIncrementOperation"], **kwargs + ) -> Optional[List[float]]: + results = [] + for increment in increment_list: + result = await self.async_increment( + increment["key"], increment["increment_value"], **kwargs + ) + results.append(result) + return results + + def flush_cache(self): + self.cache_dict.clear() + self.ttl_dict.clear() + self.expiration_heap.clear() + + async def disconnect(self): + pass + + def delete_cache(self, key): + self._remove_key(key) + + async def async_get_ttl(self, key: str) -> Optional[int]: + """ + Get the remaining TTL of a key in in-memory cache + """ + return self.ttl_dict.get(key, None) + + async def async_get_oldest_n_keys(self, n: int) -> List[str]: + """ + Get the oldest n keys in the cache + """ + # sorted ttl dict by ttl + sorted_ttl_dict = sorted(self.ttl_dict.items(), key=lambda x: x[1]) + return [key for key, _ in sorted_ttl_dict[:n]] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/llm_caching_handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/llm_caching_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..c2274713bb90da6e1e78dda9ed37f72307ade724 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/llm_caching_handler.py @@ -0,0 +1,50 @@ +""" +Add the event loop to the cache key, to prevent event loop closed errors. +""" + +import asyncio + +from .in_memory_cache import InMemoryCache + + +class LLMClientCache(InMemoryCache): + """Cache for LLM HTTP clients (OpenAI, Azure, httpx, etc.). + + IMPORTANT: This cache intentionally does NOT close clients on eviction. + Evicted clients may still be in use by in-flight requests. Closing them + eagerly causes ``RuntimeError: Cannot send a request, as the client has + been closed.`` errors in production after the TTL (1 hour) expires. + + Clients that are no longer referenced will be garbage-collected normally. + For explicit shutdown cleanup, use ``close_litellm_async_clients()``. + """ + + def update_cache_key_with_event_loop(self, key): + """ + Add the event loop to the cache key, to prevent event loop closed errors. + If none, use the key as is. + """ + try: + event_loop = asyncio.get_running_loop() + stringified_event_loop = str(id(event_loop)) + return f"{key}-{stringified_event_loop}" + except RuntimeError: # handle no current running event loop + return key + + def set_cache(self, key, value, **kwargs): + key = self.update_cache_key_with_event_loop(key) + return super().set_cache(key, value, **kwargs) + + async def async_set_cache(self, key, value, **kwargs): + key = self.update_cache_key_with_event_loop(key) + return await super().async_set_cache(key, value, **kwargs) + + def get_cache(self, key, **kwargs): + key = self.update_cache_key_with_event_loop(key) + + return super().get_cache(key, **kwargs) + + async def async_get_cache(self, key, **kwargs): + key = self.update_cache_key_with_event_loop(key) + + return await super().async_get_cache(key, **kwargs) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/qdrant_semantic_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/qdrant_semantic_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..cb521efca054d45503a765226c2fcc9055f8097b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/qdrant_semantic_cache.py @@ -0,0 +1,498 @@ +""" +Qdrant Semantic Cache implementation + +Has 4 methods: + - set_cache + - get_cache + - async_set_cache + - async_get_cache +""" + +import ast +import asyncio +import json +import os +from typing import Any, Dict, cast + +import litellm +from litellm._logging import print_verbose +from litellm.constants import QDRANT_SCALAR_QUANTILE, QDRANT_VECTOR_SIZE +from litellm.litellm_core_utils.prompt_templates.common_utils import ( + get_str_from_messages, +) +from litellm.types.utils import EmbeddingResponse + +from .base_cache import BaseCache + + +class QdrantSemanticCache(BaseCache): + CACHE_KEY_FIELD_NAME = "litellm_cache_key" + + def __init__( # noqa: PLR0915 + self, + qdrant_api_base=None, + qdrant_api_key=None, + collection_name=None, + similarity_threshold=None, + quantization_config=None, + embedding_model="text-embedding-ada-002", + host_type=None, + vector_size=None, + ): + from litellm.llms.custom_httpx.http_handler import ( + _get_httpx_client, + get_async_httpx_client, + httpxSpecialProvider, + ) + from litellm.secret_managers.main import get_secret_str + + if collection_name is None: + raise Exception("collection_name must be provided, passed None") + + self.collection_name = collection_name + print_verbose( + f"qdrant semantic-cache initializing COLLECTION - {self.collection_name}" + ) + + if similarity_threshold is None: + raise Exception("similarity_threshold must be provided, passed None") + self.similarity_threshold = similarity_threshold + self.embedding_model = embedding_model + self.vector_size = ( + vector_size if vector_size is not None else QDRANT_VECTOR_SIZE + ) + headers = {} + + # check if defined as os.environ/ variable + if qdrant_api_base: + if isinstance(qdrant_api_base, str) and qdrant_api_base.startswith( + "os.environ/" + ): + qdrant_api_base = get_secret_str(qdrant_api_base) + if qdrant_api_key: + if isinstance(qdrant_api_key, str) and qdrant_api_key.startswith( + "os.environ/" + ): + qdrant_api_key = get_secret_str(qdrant_api_key) + + qdrant_api_base = ( + qdrant_api_base or os.getenv("QDRANT_URL") or os.getenv("QDRANT_API_BASE") + ) + qdrant_api_key = qdrant_api_key or os.getenv("QDRANT_API_KEY") + headers = {"Content-Type": "application/json"} + if qdrant_api_key: + headers["api-key"] = qdrant_api_key + + if qdrant_api_base is None: + raise ValueError("Qdrant url must be provided") + + self.qdrant_api_base = qdrant_api_base + self.qdrant_api_key = qdrant_api_key + print_verbose(f"qdrant semantic-cache qdrant_api_base: {self.qdrant_api_base}") + + self.headers = headers + + self.sync_client = _get_httpx_client() + self.async_client = get_async_httpx_client( + llm_provider=httpxSpecialProvider.Caching + ) + + if quantization_config is None: + print_verbose( + "Quantization config is not provided. Default binary quantization will be used." + ) + collection_exists = self.sync_client.get( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}/exists", + headers=self.headers, + ) + if collection_exists.status_code != 200: + raise ValueError( + f"Error from qdrant checking if /collections exist {collection_exists.text}" + ) + + if collection_exists.json()["result"]["exists"]: + collection_details = self.sync_client.get( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}", + headers=self.headers, + ) + self.collection_info = collection_details.json() + print_verbose( + f"Collection already exists.\nCollection details:{self.collection_info}" + ) + self._ensure_cache_key_payload_index() + else: + quantization_params: Dict[str, Any] + if quantization_config is None or quantization_config == "binary": + quantization_params = { + "binary": { + "always_ram": False, + } + } + elif quantization_config == "scalar": + quantization_params = { + "scalar": { + "type": "int8", + "quantile": QDRANT_SCALAR_QUANTILE, + "always_ram": False, + } + } + elif quantization_config == "product": + quantization_params = { + "product": {"compression": "x16", "always_ram": False} + } + else: + raise Exception( + "Quantization config must be one of 'scalar', 'binary' or 'product'" + ) + + new_collection_status = self.sync_client.put( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}", + json={ + "vectors": {"size": self.vector_size, "distance": "Cosine"}, + "quantization_config": quantization_params, + }, + headers=self.headers, + ) + if new_collection_status.json()["result"]: + collection_details = self.sync_client.get( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}", + headers=self.headers, + ) + self.collection_info = collection_details.json() + print_verbose( + f"New collection created.\nCollection details:{self.collection_info}" + ) + self._ensure_cache_key_payload_index() + else: + raise Exception("Error while creating new collection") + + def _get_cache_logic(self, cached_response: Any): + if cached_response is None: + return cached_response + try: + cached_response = json.loads( + cached_response + ) # Convert string to dictionary + except Exception: + cached_response = ast.literal_eval(cached_response) + return cached_response + + def _get_qdrant_cache_key_filter(self, key: str) -> dict: + return { + "must": [ + { + "key": self.CACHE_KEY_FIELD_NAME, + "match": {"value": str(key)}, + } + ] + } + + def _add_cache_key_filter_to_search_data(self, data: dict, key: str) -> None: + data["filter"] = self._get_qdrant_cache_key_filter(key) + + def _ensure_cache_key_payload_index(self) -> None: + try: + response = self.sync_client.put( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}/index", + headers=self.headers, + json={ + "field_name": self.CACHE_KEY_FIELD_NAME, + "field_schema": "keyword", + }, + ) + if response.status_code not in (200, 201): + print_verbose( + "Qdrant semantic-cache could not create cache-key payload index: " + f"{response.text}" + ) + except Exception as exc: + print_verbose( + "Qdrant semantic-cache could not create cache-key payload index: " + f"{str(exc)}" + ) + + def _payload_matches_cache_key(self, payload: dict, key: str) -> bool: + # Pre-isolation points stored only prompt + response with no cache-key + # payload field. Reassigning them to a caller's key would risk + # cross-scope hits, so they're treated as misses and re-populated on + # the next set_cache. + cached_key = payload.get(self.CACHE_KEY_FIELD_NAME) + return cached_key is not None and str(cached_key) == str(key) + + async def _get_async_embedding(self, prompt: str, **kwargs) -> Any: + llm_model_list = None + llm_router = None + + try: + from litellm.proxy.proxy_server import ( + llm_model_list as proxy_llm_model_list, + llm_router as proxy_llm_router, + ) + + llm_model_list = proxy_llm_model_list + llm_router = proxy_llm_router + except ImportError: + pass + + router_model_names = ( + [m["model_name"] for m in llm_model_list] + if llm_model_list is not None + else [] + ) + if llm_router is not None and self.embedding_model in router_model_names: + user_api_key = kwargs.get("metadata", {}).get("user_api_key", "") + return await llm_router.aembedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + metadata={ + "user_api_key": user_api_key, + "semantic-cache-embedding": True, + "trace_id": kwargs.get("metadata", {}).get("trace_id", None), + }, + ) + + return await litellm.aembedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + ) + + def set_cache(self, key, value, **kwargs): + print_verbose(f"qdrant semantic-cache set_cache, kwargs: {kwargs}") + from litellm._uuid import uuid + + # get the prompt + messages = kwargs["messages"] + prompt = get_str_from_messages(messages) + + # create an embedding for prompt + embedding_response = cast( + EmbeddingResponse, + litellm.embedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + ), + ) + + # get the embedding + embedding = embedding_response["data"][0]["embedding"] + + value = str(value) + assert isinstance(value, str) + + data = { + "points": [ + { + "id": str(uuid.uuid4()), + "vector": embedding, + "payload": { + self.CACHE_KEY_FIELD_NAME: str(key), + "text": prompt, + "response": value, + }, + }, + ] + } + self.sync_client.put( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points", + headers=self.headers, + json=data, + ) + return + + def get_cache(self, key, **kwargs): + print_verbose(f"sync qdrant semantic-cache get_cache, kwargs: {kwargs}") + + # get the messages + messages = kwargs["messages"] + prompt = get_str_from_messages(messages) + + # convert to embedding + embedding_response = cast( + EmbeddingResponse, + litellm.embedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + ), + ) + + # get the embedding + embedding = embedding_response["data"][0]["embedding"] + + data = { + "vector": embedding, + "params": { + "quantization": { + "ignore": False, + "rescore": True, + "oversampling": 3.0, + } + }, + "limit": 1, + "with_payload": True, + } + self._add_cache_key_filter_to_search_data(data=data, key=key) + + search_response = self.sync_client.post( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points/search", + headers=self.headers, + json=data, + ) + results = search_response.json()["result"] + + if results is None: + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + if isinstance(results, list): + if len(results) == 0: + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + similarity = results[0]["score"] + payload = results[0]["payload"] + if not self._payload_matches_cache_key(payload=payload, key=key): + print_verbose("Qdrant semantic-cache hit did not match cache key scope") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + cached_prompt = payload["text"] + + # check similarity, if more than self.similarity_threshold, return results + print_verbose( + f"semantic cache: similarity threshold: {self.similarity_threshold}, similarity: {similarity}, prompt: {prompt}, closest_cached_prompt: {cached_prompt}" + ) + + # update kwargs["metadata"] with similarity, don't rewrite the original metadata + kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity + + if similarity >= self.similarity_threshold: + # cache hit ! + cached_value = payload["response"] + print_verbose( + f"got a cache hit, similarity: {similarity}, Current prompt: {prompt}, cached_prompt: {cached_prompt}" + ) + return self._get_cache_logic(cached_response=cached_value) + else: + # cache miss ! + return None + pass + + async def async_set_cache(self, key, value, **kwargs): + from litellm._uuid import uuid + + print_verbose(f"async qdrant semantic-cache set_cache, kwargs: {kwargs}") + + # get the prompt + messages = kwargs["messages"] + prompt = get_str_from_messages(messages) + embedding_response = await self._get_async_embedding(prompt, **kwargs) + + # get the embedding + embedding = embedding_response["data"][0]["embedding"] + + value = str(value) + assert isinstance(value, str) + + data = { + "points": [ + { + "id": str(uuid.uuid4()), + "vector": embedding, + "payload": { + self.CACHE_KEY_FIELD_NAME: str(key), + "text": prompt, + "response": value, + }, + }, + ] + } + + await self.async_client.put( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points", + headers=self.headers, + json=data, + ) + return + + async def async_get_cache(self, key, **kwargs): + print_verbose(f"async qdrant semantic-cache get_cache, kwargs: {kwargs}") + + # get the messages + messages = kwargs["messages"] + prompt = get_str_from_messages(messages) + + embedding_response = await self._get_async_embedding(prompt, **kwargs) + + # get the embedding + embedding = embedding_response["data"][0]["embedding"] + + data = { + "vector": embedding, + "params": { + "quantization": { + "ignore": False, + "rescore": True, + "oversampling": 3.0, + } + }, + "limit": 1, + "with_payload": True, + } + self._add_cache_key_filter_to_search_data(data=data, key=key) + + search_response = await self.async_client.post( + url=f"{self.qdrant_api_base}/collections/{self.collection_name}/points/search", + headers=self.headers, + json=data, + ) + + results = search_response.json()["result"] + + if results is None: + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + if isinstance(results, list): + if len(results) == 0: + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + similarity = results[0]["score"] + payload = results[0]["payload"] + if not self._payload_matches_cache_key(payload=payload, key=key): + print_verbose("Qdrant semantic-cache hit did not match cache key scope") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + cached_prompt = payload["text"] + + # check similarity, if more than self.similarity_threshold, return results + print_verbose( + f"semantic cache: similarity threshold: {self.similarity_threshold}, similarity: {similarity}, prompt: {prompt}, closest_cached_prompt: {cached_prompt}" + ) + + # update kwargs["metadata"] with similarity, don't rewrite the original metadata + kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity + + if similarity >= self.similarity_threshold: + # cache hit ! + cached_value = payload["response"] + print_verbose( + f"got a cache hit, similarity: {similarity}, Current prompt: {prompt}, cached_prompt: {cached_prompt}" + ) + return self._get_cache_logic(cached_response=cached_value) + else: + # cache miss ! + return None + pass + + async def _collection_info(self): + return self.collection_info + + async def async_set_cache_pipeline(self, cache_list, **kwargs): + tasks = [] + for val in cache_list: + tasks.append(self.async_set_cache(val[0], val[1], **kwargs)) + await asyncio.gather(*tasks) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9ce475d30256273b929c6f51df2e070d38423d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cache.py @@ -0,0 +1,1710 @@ +""" +Redis Cache implementation + +Has 4 primary methods: + - set_cache + - get_cache + - async_set_cache + - async_get_cache +""" + +import ast +import asyncio +import functools +import hashlib +import inspect +import json +import time +from datetime import timedelta +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast + +import litellm +from litellm._logging import print_verbose, verbose_logger +from litellm.constants import ( + DEFAULT_REDIS_MAJOR_VERSION, + REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD, + REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT, +) +from litellm.litellm_core_utils.core_helpers import _get_parent_otel_span_from_kwargs +from litellm.litellm_core_utils.coroutine_checker import coroutine_checker +from litellm.types.caching import ( + RedisPipelineIncrementOperation, + RedisPipelineLpopOperation, + RedisPipelineRpushOperation, +) +from litellm.types.services import ServiceTypes + +from .base_cache import BaseCache + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + from redis.asyncio import Redis, RedisCluster + from redis.asyncio.client import Pipeline + from redis.asyncio.cluster import ClusterPipeline + + pipeline = Pipeline + cluster_pipeline = ClusterPipeline + async_redis_client = Redis + async_redis_cluster_client = RedisCluster + Span = Union[_Span, Any] +else: + pipeline = Any + cluster_pipeline = Any + async_redis_client = Any + async_redis_cluster_client = Any + Span = Any + + +def _get_call_stack_info(num_frames: int = 2) -> str: + """ + Get the function names from the previous 1-2 functions in the call stack. + + Args: + num_frames: Number of previous frames to include (default: 2) + + Returns: + A string with format "current_function <- caller_function [<- grandparent_function]" + """ + try: + current_frame = inspect.currentframe() + if current_frame is None: + return "unknown" + + # Skip this function and the immediate caller (which sets call_type) + f_back = current_frame.f_back + if f_back is None: + return "unknown" + frame = f_back.f_back + if frame is None: + return "unknown" + function_names = [] + + for _ in range(num_frames): + if frame is None: + break + func_name = frame.f_code.co_name + function_names.append(func_name) + frame = frame.f_back + + if not function_names: + return "unknown" + + return " <- ".join(function_names) + except Exception: + return "unknown" + + +class RedisCircuitBreaker: + """ + Tracks Redis health for a RedisCache instance. + + States: + CLOSED - normal, Redis is called + OPEN - Redis is down, raise immediately (no network call) + HALF_OPEN - recovery probe: allow one request through + + Transitions: + CLOSED -> OPEN after failure_threshold consecutive failures + OPEN -> HALF_OPEN after recovery_timeout seconds + HALF_OPEN -> CLOSED on success + HALF_OPEN -> OPEN on failure (resets timer) + """ + + CLOSED = "closed" + OPEN = "open" + HALF_OPEN = "half_open" + + def __init__(self, failure_threshold: int, recovery_timeout: int) -> None: + self.failure_threshold = failure_threshold + self.recovery_timeout = recovery_timeout + self._failure_count = 0 + self._opened_at: Optional[float] = None + self._state = self.CLOSED + + def is_open(self) -> bool: + """Returns True if Redis calls should be skipped.""" + if self._state == self.HALF_OPEN: + # Probe already in flight — fast-fail all concurrent requests. + # Only the one call that caused the OPEN→HALF_OPEN transition + # (which returned False) is the designated probe. + return True + if self._state == self.OPEN: + if time.time() - (self._opened_at or 0) > self.recovery_timeout: + self._state = self.HALF_OPEN + return False # this caller is the designated probe + return True + return False + + def record_failure(self) -> None: + self._failure_count += 1 + self._opened_at = time.time() + if self._failure_count >= self.failure_threshold: + if self._state != self.OPEN: + verbose_logger.warning( + "Redis circuit breaker OPENED after %d consecutive failures — " + "fast-failing Redis calls for %ds", + self._failure_count, + self.recovery_timeout, + ) + self._state = self.OPEN + + def record_success(self) -> None: + if self._state == self.HALF_OPEN: + verbose_logger.info("Redis circuit breaker CLOSED — Redis recovered") + self._failure_count = 0 + self._state = self.CLOSED + + +def _redis_circuit_breaker_guard(method): # type: ignore + """ + Decorator for RedisCache async methods. + Checks the circuit breaker before each call; records success/failure after. + Does not apply to ping/disconnect/test_connection (health/teardown must always run). + """ + + @functools.wraps(method) + async def wrapper(self, *args, **kwargs): # type: ignore + if self._circuit_breaker.is_open(): + raise Exception( + f"Redis circuit breaker is open — skipping {method.__name__}" + ) + try: + result = await method(self, *args, **kwargs) + self._circuit_breaker.record_success() + return result + except Exception: + self._circuit_breaker.record_failure() + raise + + return wrapper + + +class RedisCache(BaseCache): + # if users don't provider one, use the default litellm cache + + def __init__( + self, + host=None, + port=None, + password=None, + redis_flush_size: Optional[int] = 100, + namespace: Optional[str] = None, + startup_nodes: Optional[List] = None, # for redis-cluster + socket_timeout: Optional[float] = 5.0, # default 5 second timeout + **kwargs, + ): + from litellm._service_logger import ServiceLogging + + from .._redis import get_redis_client, get_redis_connection_pool + + redis_kwargs = {} + if host is not None: + redis_kwargs["host"] = host + if port is not None: + redis_kwargs["port"] = port + if password is not None: + redis_kwargs["password"] = password + if startup_nodes is not None: + redis_kwargs["startup_nodes"] = startup_nodes + if socket_timeout is not None: + redis_kwargs["socket_timeout"] = socket_timeout + + ### HEALTH MONITORING OBJECT ### + if kwargs.get("service_logger_obj", None) is not None and isinstance( + kwargs["service_logger_obj"], ServiceLogging + ): + self.service_logger_obj = kwargs.pop("service_logger_obj") + else: + self.service_logger_obj = ServiceLogging() + + redis_kwargs.update(kwargs) + self.redis_client = get_redis_client(**redis_kwargs) + self.redis_async_client: Optional[ + Union[async_redis_client, async_redis_cluster_client] + ] = None + self.redis_kwargs = redis_kwargs + self.async_redis_conn_pool = get_redis_connection_pool(**redis_kwargs) + + # redis namespaces + self.namespace = namespace + # for high traffic, we store the redis results in memory and then batch write to redis + self.redis_batch_writing_buffer: list = [] + if redis_flush_size is None: + self.redis_flush_size: int = 100 + else: + self.redis_flush_size = redis_flush_size + self.redis_version = "Unknown" + try: + if not coroutine_checker.is_async_callable(self.redis_client): + self.redis_version = self.redis_client.info()["redis_version"] # type: ignore + except Exception: + pass + + self._circuit_breaker = RedisCircuitBreaker( + failure_threshold=REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD, + recovery_timeout=REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT, + ) + + self._setup_health_pings() + + if litellm.default_redis_ttl is not None: + super().__init__(default_ttl=int(litellm.default_redis_ttl)) + else: + super().__init__() # defaults to 60s + + def _setup_health_pings(self): + """Setup async and sync health pings for Redis.""" + # ASYNC HEALTH PING + try: + _ = asyncio.get_running_loop().create_task(self.ping()) + except Exception as e: + if "no running event loop" in str(e): + verbose_logger.debug( + "Ignoring async redis ping. No running event loop." + ) + else: + verbose_logger.error( + "Error connecting to Async Redis client - {}".format(str(e)), + extra={"error": str(e)}, + ) + self._handle_async_ping_error(e) + + # SYNC HEALTH PING + try: + if hasattr(self.redis_client, "ping"): + self.redis_client.ping() # type: ignore + except Exception as e: + verbose_logger.error( + "Error connecting to Sync Redis client", extra={"error": str(e)} + ) + self._handle_sync_ping_error(e) + + def _handle_async_ping_error(self, e: Exception): + """Handle async ping error with service failure hook.""" + try: + loop = asyncio.get_running_loop() + start_time = time.time() + end_time = start_time + loop.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=end_time - start_time, + error=e, + call_type="redis_async_ping", + ) + ) + except Exception: + pass + + def _handle_sync_ping_error(self, e: Exception): + """Handle sync ping error with service failure hook.""" + try: + loop = asyncio.get_running_loop() + start_time = time.time() + end_time = start_time + loop.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=end_time - start_time, + error=e, + call_type="redis_sync_ping", + ) + ) + except Exception: + pass + + def _get_async_client_cache_key(self) -> str: + """ + Generate a cache key for the async Redis client based on connection parameters. + This ensures different Redis configurations use different cached clients. + """ + # Create a stable representation of redis_kwargs for hashing + # Sort keys to ensure consistent hash regardless of parameter order + sorted_kwargs = sorted(self.redis_kwargs.items()) + kwargs_str = json.dumps(sorted_kwargs, sort_keys=True) + kwargs_hash = hashlib.sha256(kwargs_str.encode()).hexdigest()[:16] + return f"async-redis-client-{kwargs_hash}" + + def init_async_client( + self, + ) -> Union[async_redis_client, async_redis_cluster_client]: + from litellm import in_memory_llm_clients_cache + + from .._redis import get_redis_async_client, get_redis_connection_pool + + cache_key = self._get_async_client_cache_key() + cached_client = in_memory_llm_clients_cache.get_cache(key=cache_key) + if cached_client is not None: + redis_async_client = cast( + Union[async_redis_client, async_redis_cluster_client], cached_client + ) + else: + # Create new connection pool and client for current event loop + self.async_redis_conn_pool = get_redis_connection_pool(**self.redis_kwargs) + redis_async_client = get_redis_async_client( + connection_pool=self.async_redis_conn_pool, **self.redis_kwargs + ) + in_memory_llm_clients_cache.set_cache( + key=cache_key, value=redis_async_client + ) + + self.redis_async_client = redis_async_client # type: ignore + return redis_async_client + + def check_and_fix_namespace(self, key: str) -> str: + """ + Make sure each key starts with the given namespace + """ + if self.namespace is not None and not key.startswith(self.namespace): + key = self.namespace + ":" + key + + return key + + def _parse_redis_major_version(self) -> int: + """ + Parse Redis version to extract the major version number. + + Handles multiple version formats: + - Strings: "7.0.0", "6", "7.0.0-rc1", " 7.0.0 " + - Floats: 7.0 (e.g., from AWS ElastiCache Valkey) + - Integers: 7 + - Malformed: "latest", "", "Unknown" (defaults to DEFAULT_REDIS_MAJOR_VERSION) + + Returns: + int: The major version number (defaults to DEFAULT_REDIS_MAJOR_VERSION if unparseable) + """ + if self.redis_version == "Unknown": + return DEFAULT_REDIS_MAJOR_VERSION + + try: + version_str = str(self.redis_version).strip() + # Handle cases where there's no dot (e.g., "7" or 7) + if "." in version_str: + major_version = int(version_str.split(".")[0]) + else: + # Direct integer or single-digit string + major_version = int(float(version_str)) + return major_version + except (ValueError, AttributeError): + # Fallback for unparseable versions (e.g., "v7.0.0", "latest") + return DEFAULT_REDIS_MAJOR_VERSION + + def set_cache(self, key, value, **kwargs): + ttl = self.get_ttl(**kwargs) + print_verbose( + f"Set Redis Cache: key: {key}\nValue {value}\nttl={ttl}, redis_version={self.redis_version}" + ) + key = self.check_and_fix_namespace(key=key) + try: + start_time = time.time() + self.redis_client.set(name=key, value=str(value), ex=ttl) + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"set_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + print_verbose( + f"litellm.caching.caching: set() - Got exception from REDIS : {str(e)}" + ) + + def increment_cache( + self, key, value: int, ttl: Optional[float] = None, **kwargs + ) -> int: + _redis_client = self.redis_client + start_time = time.time() + set_ttl = self.get_ttl(ttl=ttl) + try: + start_time = time.time() + result: int = _redis_client.incr(name=key, amount=value) # type: ignore + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"increment_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + + if set_ttl is not None: + # check if key already has ttl, if not -> set ttl + start_time = time.time() + current_ttl = _redis_client.ttl(key) + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"increment_cache_ttl <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + if current_ttl == -1: + # Key has no expiration + start_time = time.time() + _redis_client.expire(key, set_ttl) # type: ignore + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"increment_cache_expire <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + return result + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + verbose_logger.error( + "LiteLLM Redis Caching: increment_cache() - Got exception from REDIS %s, Writing value=%s", + str(e), + value, + ) + raise e + + @_redis_circuit_breaker_guard + async def async_scan_iter(self, pattern: str, count: int = 100) -> list: + start_time = time.time() + try: + keys = [] + _redis_client = self.init_async_client() + if not hasattr(_redis_client, "scan_iter"): + verbose_logger.debug( + "Redis client does not support scan_iter, potentially using Redis Cluster. Returning empty list." + ) + return [] + + async for key in _redis_client.scan_iter(match=pattern + "*", count=count): # type: ignore + keys.append(key) + if len(keys) >= count: + break + + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_scan_iter <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + ) # DO NOT SLOW DOWN CALL B/C OF THIS + return keys + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_scan_iter <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + ) + raise e + + def async_register_script(self, script: str) -> Any: + """ + Register a Lua script with Redis asynchronously. + Works with both standalone Redis and Redis Cluster. + + Args: + script (str): The Lua script to register + + Returns: + Any: A script object that can be called with keys and args + """ + try: + _redis_client = self.init_async_client() + # For standalone Redis + if hasattr(_redis_client, "register_script"): + return _redis_client.register_script(script) # type: ignore + # For Redis Cluster + elif hasattr(_redis_client, "script_load"): + # Load the script and get its SHA + script_sha = _redis_client.script_load(script) # type: ignore + + # Return a callable that uses evalsha + async def script_callable(keys: List[str], args: List[Any]) -> Any: + return _redis_client.evalsha(script_sha, len(keys), *keys, *args) # type: ignore + + return script_callable + except Exception as e: + verbose_logger.error(f"Error registering Redis script: {str(e)}") + raise e + + @_redis_circuit_breaker_guard + async def async_set_cache(self, key, value, **kwargs): + from redis.asyncio import Redis + + if key is None: + verbose_logger.debug( + "LiteLLM Redis Caching: async set() skipped — key is None, value=%r", + value, + ) + return None + + start_time = time.time() + try: + _redis_client: Redis = self.init_async_client() # type: ignore + except Exception as e: + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + call_type=f"async_set_cache <- {_get_call_stack_info()}", + ) + ) + verbose_logger.error( + "LiteLLM Redis Caching: async set() - Got exception from REDIS %s, key=%r, value=%r", + str(e), + key, + value, + ) + raise e + + key = self.check_and_fix_namespace(key=key) + ttl = self.get_ttl(**kwargs) + nx = kwargs.get("nx", False) + print_verbose(f"Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={ttl}") + + try: + if not hasattr(_redis_client, "set"): + raise Exception("Redis client cannot set cache. Attribute not found.") + result = await _redis_client.set( + name=key, + value=json.dumps(value), + nx=nx, + ex=ttl, + ) + print_verbose( + f"Successfully Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={ttl}" + ) + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_set_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + event_metadata={"key": key}, + ) + ) + return result + except Exception as e: + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_set_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + event_metadata={"key": key}, + ) + ) + verbose_logger.error( + "LiteLLM Redis Caching: async set() - Got exception from REDIS %s, Writing value=%s", + str(e), + value, + ) + + async def _pipeline_helper( + self, + pipe: Union[pipeline, cluster_pipeline], + cache_list: List[Tuple[Any, Any]], + ttl: Optional[float], + ) -> List: + """ + Helper function for executing a pipeline of set operations on Redis + """ + ttl = self.get_ttl(ttl=ttl) + # Iterate through each key-value pair in the cache_list and set them in the pipeline. + for cache_key, cache_value in cache_list: + cache_key = self.check_and_fix_namespace(key=cache_key) + print_verbose( + f"Set ASYNC Redis Cache PIPELINE: key: {cache_key}\nValue {cache_value}\nttl={ttl}" + ) + json_cache_value = json.dumps(cache_value) + # Set the value with a TTL if it's provided. + _td: Optional[timedelta] = None + if ttl is not None: + _td = timedelta(seconds=ttl) + pipe.set( # type: ignore + name=cache_key, + value=json_cache_value, + ex=_td, + ) + # Execute the pipeline and return the results. + results = await pipe.execute() + return results + + @_redis_circuit_breaker_guard + async def async_set_cache_pipeline( + self, cache_list: List[Tuple[Any, Any]], ttl: Optional[float] = None, **kwargs + ): + """ + Use Redis Pipelines for bulk write operations + """ + # don't waste a network request if there's nothing to set + if len(cache_list) == 0: + return + + _redis_client = self.init_async_client() + start_time = time.time() + + print_verbose( + f"Set Async Redis Cache: key list: {cache_list}\nttl={ttl}, redis_version={self.redis_version}" + ) + cache_value: Any = None + try: + async with _redis_client.pipeline(transaction=False) as pipe: + results = await self._pipeline_helper(pipe, cache_list, ttl) + + print_verbose(f"pipeline results: {results}") + # Optionally, you could process 'results' to make sure that all set operations were successful. + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_set_cache_pipeline <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + ) + ) + return None + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_set_cache_pipeline <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + ) + ) + + verbose_logger.error( + "LiteLLM Redis Caching: async set_cache_pipeline() - Got exception from REDIS %s, Writing value=%s", + str(e), + cache_value, + ) + + async def _set_cache_sadd_helper( + self, + redis_client: async_redis_client, + key: str, + value: List, + ttl: Optional[float], + ) -> None: + """Helper function for async_set_cache_sadd. Separated for testing.""" + ttl = self.get_ttl(ttl=ttl) + try: + await redis_client.sadd(key, *value) # type: ignore + if ttl is not None: + _td = timedelta(seconds=ttl) + await redis_client.expire(key, _td) + except Exception: + raise + + @_redis_circuit_breaker_guard + async def async_set_cache_sadd( + self, key, value: List, ttl: Optional[float], **kwargs + ): + from redis.asyncio import Redis + + start_time = time.time() + try: + _redis_client: Redis = self.init_async_client() # type: ignore + except Exception as e: + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + call_type=f"async_set_cache_sadd <- {_get_call_stack_info()}", + ) + ) + # NON blocking - notify users Redis is throwing an exception + verbose_logger.error( + "LiteLLM Redis Caching: async set() - Got exception from REDIS %s, Writing value=%s", + str(e), + value, + ) + raise e + + key = self.check_and_fix_namespace(key=key) + print_verbose(f"Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={ttl}") + try: + await self._set_cache_sadd_helper( + redis_client=_redis_client, key=key, value=value, ttl=ttl + ) + print_verbose( + f"Successfully Set ASYNC Redis Cache SADD: key: {key}\nValue {value}\nttl={ttl}" + ) + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_set_cache_sadd <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + ) + ) + except Exception as e: + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_set_cache_sadd <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + ) + ) + # NON blocking - notify users Redis is throwing an exception + verbose_logger.error( + "LiteLLM Redis Caching: async set_cache_sadd() - Got exception from REDIS %s, Writing value=%s", + str(e), + value, + ) + + @_redis_circuit_breaker_guard + async def batch_cache_write(self, key, value, **kwargs): + print_verbose( + f"in batch cache writing for redis buffer size={len(self.redis_batch_writing_buffer)}", + ) + key = self.check_and_fix_namespace(key=key) + self.redis_batch_writing_buffer.append((key, value)) + if len(self.redis_batch_writing_buffer) >= self.redis_flush_size: + await self.flush_cache_buffer() # logging done in here + + @_redis_circuit_breaker_guard + async def async_increment( + self, + key, + value: float, + ttl: Optional[int] = None, + parent_otel_span: Optional[Span] = None, + refresh_ttl: bool = False, + ) -> float: + from redis.asyncio import Redis + + _redis_client: Redis = self.init_async_client() # type: ignore + start_time = time.time() + _used_ttl = self.get_ttl(ttl=ttl) + key = self.check_and_fix_namespace(key=key) + try: + result = await _redis_client.incrbyfloat(name=key, amount=value) + if _used_ttl is not None: + if refresh_ttl: + await _redis_client.expire(key, _used_ttl) + else: + current_ttl = await _redis_client.ttl(key) + if current_ttl == -1: + await _redis_client.expire(key, _used_ttl) + + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_increment <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + ) + ) + return result + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_increment <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + ) + ) + verbose_logger.error( + "LiteLLM Redis Caching: async async_increment() - Got exception from REDIS %s, Writing value=%s", + str(e), + value, + ) + raise e + + async def flush_cache_buffer(self): + print_verbose( + f"flushing to redis....reached size of buffer {len(self.redis_batch_writing_buffer)}" + ) + await self.async_set_cache_pipeline(self.redis_batch_writing_buffer) + self.redis_batch_writing_buffer = [] + + def _get_cache_logic(self, cached_response: Any): + """ + Common 'get_cache_logic' across sync + async redis client implementations + """ + if cached_response is None: + return cached_response + # cached_response is in `b{} convert it to ModelResponse + cached_response = cached_response.decode("utf-8") # Convert bytes to string + try: + cached_response = json.loads( + cached_response + ) # Convert string to dictionary + except Exception: + cached_response = ast.literal_eval(cached_response) + return cached_response + + def get_cache(self, key, parent_otel_span: Optional[Span] = None, **kwargs): + try: + key = self.check_and_fix_namespace(key=key) + print_verbose(f"Get Redis Cache: key: {key}") + start_time = time.time() + cached_response = self.redis_client.get(key) + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"get_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + ) + print_verbose( + f"Got Redis Cache: key: {key}, cached_response {cached_response}" + ) + return self._get_cache_logic(cached_response=cached_response) + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + verbose_logger.error( + "litellm.caching.caching: get() - Got exception from REDIS: ", e + ) + + def _run_redis_mget_operation(self, keys: List[str]) -> List[Any]: + """ + Wrapper to call `mget` on the redis client + + We use a wrapper so RedisCluster can override this method + """ + return self.redis_client.mget(keys=keys) # type: ignore + + async def _async_run_redis_mget_operation(self, keys: List[str]) -> List[Any]: + """ + Wrapper to call `mget` on the redis client + + We use a wrapper so RedisCluster can override this method + """ + async_redis_client = self.init_async_client() + return await async_redis_client.mget(keys=keys) # type: ignore + + def batch_get_cache( + self, + key_list: Union[List[str], List[Optional[str]]], + parent_otel_span: Optional[Span] = None, + ) -> dict: + """ + Use Redis for bulk read operations + + Args: + key_list: List of keys to get from Redis + parent_otel_span: Optional parent OpenTelemetry span + + Returns: + dict: A dictionary mapping keys to their cached values + """ + key_value_dict = {} + _key_list = [key for key in key_list if key is not None] + + try: + _keys = [] + for cache_key in _key_list: + cache_key = self.check_and_fix_namespace(key=cache_key or "") + _keys.append(cache_key) + start_time = time.time() + results: List = self._run_redis_mget_operation(keys=_keys) + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"batch_get_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + ) + + # Associate the results back with their keys. + # 'results' is a list of values corresponding to the order of keys in '_key_list'. + key_value_dict = dict(zip(_key_list, results)) + + decoded_results = {} + for k, v in key_value_dict.items(): + if isinstance(k, bytes): + k = k.decode("utf-8") + v = self._get_cache_logic(v) + decoded_results[k] = v + + return decoded_results + except Exception as e: + verbose_logger.error(f"Error occurred in batch get cache - {str(e)}") + return key_value_dict + + @_redis_circuit_breaker_guard + async def async_get_cache( + self, key, parent_otel_span: Optional[Span] = None, **kwargs + ): + from redis.asyncio import Redis + + _redis_client: Redis = self.init_async_client() # type: ignore + key = self.check_and_fix_namespace(key=key) + start_time = time.time() + + try: + print_verbose(f"Get Async Redis Cache: key: {key}") + cached_response = await _redis_client.get(key) + print_verbose( + f"Got Async Redis Cache: key: {key}, cached_response {cached_response}" + ) + response = self._get_cache_logic(cached_response=cached_response) + + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_get_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + event_metadata={"key": key}, + ) + ) + return response + except Exception as e: + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_get_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + event_metadata={"key": key}, + ) + ) + print_verbose( + f"litellm.caching.caching: async get() - Got exception from REDIS: {str(e)}" + ) + + @_redis_circuit_breaker_guard + async def async_batch_get_cache( + self, + key_list: Union[List[str], List[Optional[str]]], + parent_otel_span: Optional[Span] = None, + ) -> dict: + """ + Use Redis for bulk read operations + + Args: + key_list: List of keys to get from Redis + parent_otel_span: Optional parent OpenTelemetry span + + Returns: + dict: A dictionary mapping keys to their cached values + + `.mget` does not support None keys. This will filter out None keys. + """ + # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `mget` + key_value_dict = {} + start_time = time.time() + _key_list = [key for key in key_list if key is not None] + try: + _keys = [] + for cache_key in _key_list: + cache_key = self.check_and_fix_namespace(key=cache_key) + _keys.append(cache_key) + results = await self._async_run_redis_mget_operation(keys=_keys) + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_batch_get_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + ) + ) + + # Associate the results back with their keys. + # 'results' is a list of values corresponding to the order of keys in 'key_list'. + key_value_dict = dict(zip(_key_list, results)) + + decoded_results = {} + for k, v in key_value_dict.items(): + if isinstance(k, bytes): + k = k.decode("utf-8") + v = self._get_cache_logic(v) + decoded_results[k] = v + + return decoded_results + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_batch_get_cache <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=parent_otel_span, + ) + ) + verbose_logger.error(f"Error occurred in async batch get cache - {str(e)}") + return key_value_dict + + def sync_ping(self) -> bool: + """ + Tests if the sync redis client is correctly setup. + """ + print_verbose("Pinging Sync Redis Cache") + start_time = time.time() + try: + response: bool = self.redis_client.ping() # type: ignore + print_verbose(f"Redis Cache PING: {response}") + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"sync_ping <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + ) + return response + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + self.service_logger_obj.service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"sync_ping <- {_get_call_stack_info()}", + ) + verbose_logger.error( + f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}" + ) + raise e + + async def ping(self) -> bool: + # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `ping` + _redis_client: Any = self.init_async_client() + start_time = time.time() + print_verbose("Pinging Async Redis Cache") + try: + response = await _redis_client.ping() + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_ping <- {_get_call_stack_info()}", + ) + ) + return response + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_ping <- {_get_call_stack_info()}", + ) + ) + verbose_logger.error( + f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}" + ) + raise e + + @_redis_circuit_breaker_guard + async def delete_cache_keys(self, keys): + # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `delete` + _redis_client: Any = self.init_async_client() + # keys is a list, unpack it so it gets passed as individual elements to delete + await _redis_client.delete(*keys) + + def client_list(self) -> List: + client_list: List = self.redis_client.client_list() # type: ignore + return client_list + + def info(self): + info = self.redis_client.info() + return info + + def flush_cache(self): + self.redis_client.flushall() + + def flushall(self): + self.redis_client.flushall() + + async def disconnect(self): + await self.async_redis_conn_pool.disconnect(inuse_connections=True) + try: + self.redis_client.close() + except Exception as e: + verbose_logger.debug("Error closing sync Redis client: %s", e) + + async def test_connection(self) -> dict: + """ + Test the Redis connection by creating a new client and pinging it. + + This creates a fresh connection without using cached clients or connection pools + to ensure the credentials are actually valid. + + Returns: + dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} + """ + try: + import redis.asyncio as redis_async + + # Create a fresh Redis client with current settings + redis_client = redis_async.Redis(**self.redis_kwargs) + + # Test the connection + ping_result = await redis_client.ping() # type: ignore[misc] + + # Close the connection + await redis_client.aclose() # type: ignore[attr-defined] + + if ping_result: + return { + "status": "success", + "message": "Redis connection test successful", + } + else: + return {"status": "failed", "message": "Redis ping returned False"} + except Exception as e: + verbose_logger.error(f"Redis connection test failed: {str(e)}") + return { + "status": "failed", + "message": f"Redis connection failed: {str(e)}", + "error": str(e), + } + + @_redis_circuit_breaker_guard + async def async_delete_cache(self, key: str): + # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `delete` + _redis_client: Any = self.init_async_client() + # keys is str + return await _redis_client.delete(key) + + def delete_cache(self, key): + self.redis_client.delete(key) + + async def _pipeline_increment_helper( + self, + pipe: pipeline, + increment_list: List[RedisPipelineIncrementOperation], + ) -> Optional[List[float]]: + """Helper function for pipeline increment operations""" + # Iterate through each increment operation and add commands to pipeline + for increment_op in increment_list: + cache_key = self.check_and_fix_namespace(key=increment_op["key"]) + print_verbose( + f"Increment ASYNC Redis Cache PIPELINE: key: {cache_key}\nValue {increment_op['increment_value']}\nttl={increment_op['ttl']}" + ) + pipe.incrbyfloat(cache_key, increment_op["increment_value"]) + if increment_op["ttl"] is not None: + _td = timedelta(seconds=increment_op["ttl"]) + pipe.expire(cache_key, _td) + # Execute the pipeline and return results + results = await pipe.execute() + # only return float values + verbose_logger.debug( + f"Increment ASYNC Redis Cache PIPELINE: results: {results}" + ) + return [r for r in results if isinstance(r, float)] + + @_redis_circuit_breaker_guard + async def async_increment_pipeline( + self, increment_list: List[RedisPipelineIncrementOperation], **kwargs + ) -> Optional[List[float]]: + """ + Use Redis Pipelines for bulk increment operations + Args: + increment_list: List of RedisPipelineIncrementOperation dicts containing: + - key: str + - increment_value: float + - ttl_seconds: int + """ + # don't waste a network request if there's nothing to increment + if len(increment_list) == 0: + return None + + from redis.asyncio import Redis + + _redis_client: Redis = self.init_async_client() # type: ignore + start_time = time.time() + + print_verbose( + f"Increment Async Redis Cache Pipeline: increment list: {increment_list}" + ) + + try: + async with _redis_client.pipeline(transaction=False) as pipe: + results = await self._pipeline_increment_helper(pipe, increment_list) + + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_increment_pipeline <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + ) + ) + return results + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_increment_pipeline <- {_get_call_stack_info()}", + start_time=start_time, + end_time=end_time, + parent_otel_span=_get_parent_otel_span_from_kwargs(kwargs), + ) + ) + verbose_logger.error( + "LiteLLM Redis Caching: async increment_pipeline() - Got exception from REDIS %s", + str(e), + ) + raise e + + @_redis_circuit_breaker_guard + async def async_get_ttl(self, key: str) -> Optional[int]: + """ + Get the remaining TTL of a key in Redis + + Args: + key (str): The key to get TTL for + + Returns: + Optional[int]: The remaining TTL in seconds, or None if key doesn't exist + + Redis ref: https://redis.io/docs/latest/commands/ttl/ + """ + try: + # typed as Any, redis python lib has incomplete type stubs for RedisCluster and does not include `ttl` + _redis_client: Any = self.init_async_client() + ttl = await _redis_client.ttl(key) + if ttl <= -1: # -1 means the key does not exist, -2 key does not exist + return None + return ttl + except Exception as e: + verbose_logger.debug(f"Redis TTL Error: {e}") + return None + + @_redis_circuit_breaker_guard + async def async_rpush( + self, + key: str, + values: List[Any], + parent_otel_span: Optional[Span] = None, + **kwargs, + ) -> int: + """ + Append one or multiple values to a list stored at key + + Args: + key: The Redis key of the list + values: One or more values to append to the list + parent_otel_span: Optional parent OpenTelemetry span + + Returns: + int: The length of the list after the push operation + """ + _redis_client: Any = self.init_async_client() + start_time = time.time() + try: + response = await _redis_client.rpush(key, *values) + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_rpush <- {_get_call_stack_info()}", + ) + ) + return response + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_rpush <- {_get_call_stack_info()}", + ) + ) + verbose_logger.error( + f"LiteLLM Redis Cache RPUSH: - Got exception from REDIS : {str(e)}" + ) + raise e + + async def _pipeline_rpush_helper( + self, + pipe: pipeline, + rpush_list: List[RedisPipelineRpushOperation], + ) -> List[int]: + """Helper function for pipeline rpush operations""" + for rpush_op in rpush_list: + pipe.rpush(rpush_op["key"], *rpush_op["values"]) + results = await pipe.execute() + # Preserve positional correspondence — raise on per-command errors + for r in results: + if isinstance(r, Exception): + raise r + return results + + @_redis_circuit_breaker_guard + async def async_rpush_pipeline( + self, + rpush_list: List[RedisPipelineRpushOperation], + ) -> List[int]: + """ + Use Redis Pipelines for bulk RPUSH operations + + Args: + rpush_list: List of RedisPipelineRpushOperation dicts containing: + - key: str + - values: List[Any] + + Returns: + List[int]: List lengths after each push + """ + if len(rpush_list) == 0: + return [] + + _redis_client: Any = self.init_async_client() + start_time = time.time() + + try: + async with _redis_client.pipeline(transaction=False) as pipe: + results = await self._pipeline_rpush_helper(pipe, rpush_list) + + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_rpush_pipeline <- {_get_call_stack_info()}", + ) + ) + return results + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_rpush_pipeline <- {_get_call_stack_info()}", + ) + ) + verbose_logger.error( + "LiteLLM Redis Caching: async_rpush_pipeline() - Got exception from REDIS %s", + str(e), + ) + raise e + + async def handle_lpop_count_for_older_redis_versions( + self, pipe: pipeline, key: str, count: int + ) -> List[bytes]: + result: List[bytes] = [] + for _ in range(count): + pipe.lpop(key) + results = await pipe.execute() + + # Filter out None values and decode bytes + for r in results: + if r is not None: + result.append(r) + + return result + + @_redis_circuit_breaker_guard + async def async_lpop( + self, + key: str, + count: Optional[int] = None, + parent_otel_span: Optional[Span] = None, + **kwargs, + ) -> Union[Any, List[Any]]: + _redis_client: Any = self.init_async_client() + start_time = time.time() + print_verbose(f"LPOP from Redis list: key: {key}, count: {count}") + try: + major_version = self._parse_redis_major_version() + + if count is not None and major_version < 7: + # For Redis < 7.0, use pipeline to execute multiple LPOP commands + async with _redis_client.pipeline(transaction=False) as pipe: + result = await self.handle_lpop_count_for_older_redis_versions( + pipe, key, count + ) + else: + # For Redis >= 7.0 or when count is None, use native LPOP with count + result = await _redis_client.lpop(key, count) + + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_lpop <- {_get_call_stack_info()}", + ) + ) + + # Handle result parsing if needed + if isinstance(result, bytes): + try: + return result.decode("utf-8") + except Exception: + return result + elif isinstance(result, list) and all( + isinstance(item, bytes) for item in result + ): + try: + return [item.decode("utf-8") for item in result] + except Exception: + return result + return result + except Exception as e: + # NON blocking - notify users Redis is throwing an exception + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_lpop <- {_get_call_stack_info()}", + ) + ) + verbose_logger.error( + f"LiteLLM Redis Cache LPOP: - Got exception from REDIS : {str(e)}" + ) + raise e + + async def _pipeline_lpop_helper( + self, + pipe: pipeline, + lpop_list: List[RedisPipelineLpopOperation], + ) -> List[Optional[List[str]]]: + """Helper function for pipeline lpop operations. + + For Redis >= 7, queues one LPOP(key, count) per operation. + For Redis < 7, queues `count` individual LPOP(key) commands per operation. + """ + major_version = self._parse_redis_major_version() + + if major_version >= 7: + for lpop_op in lpop_list: + pipe.lpop(lpop_op["key"], lpop_op["count"]) + raw_results = await pipe.execute() + else: + # For Redis < 7, LPOP doesn't support count param. + # Issue `count` individual LPOP commands per key, all in one pipeline. + counts: List[int] = [] + for lpop_op in lpop_list: + count = lpop_op["count"] or 1 + counts.append(count) + for _ in range(count): + pipe.lpop(lpop_op["key"]) + flat_results = await pipe.execute() + + # Re-group the flat results back into per-key lists + raw_results = [] + offset = 0 + for count in counts: + key_results = [ + r for r in flat_results[offset : offset + count] if r is not None + ] + raw_results.append(key_results if key_results else None) + offset += count + + # Raise on per-command errors (matches _pipeline_rpush_helper behavior) + for r in raw_results: + if isinstance(r, Exception): + raise r + + # Decode bytes -> str for each result set + decoded_results: List[Optional[List[str]]] = [] + for r in raw_results: + if r is None: + decoded_results.append(None) + elif isinstance(r, list): + try: + decoded_results.append( + [ + item.decode("utf-8") if isinstance(item, bytes) else item + for item in r + if item is not None + ] + or None + ) + except Exception: + decoded_results.append(r) # type: ignore + else: + decoded_results.append(None) + return decoded_results + + @_redis_circuit_breaker_guard + async def async_lpop_pipeline( + self, + lpop_list: List[RedisPipelineLpopOperation], + ) -> List[Optional[List[str]]]: + """ + Use Redis Pipelines for bulk LPOP operations + + Args: + lpop_list: List of RedisPipelineLpopOperation dicts containing: + - key: str + - count: Optional[int] + + Returns: + List[Optional[List[str]]]: Decoded results per key, None if key was empty + """ + if len(lpop_list) == 0: + return [] + + _redis_client: Any = self.init_async_client() + start_time = time.time() + + try: + async with _redis_client.pipeline(transaction=False) as pipe: + results = await self._pipeline_lpop_helper(pipe, lpop_list) + + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_success_hook( + service=ServiceTypes.REDIS, + duration=_duration, + call_type=f"async_lpop_pipeline <- {_get_call_stack_info()}", + ) + ) + return results + except Exception as e: + ## LOGGING ## + end_time = time.time() + _duration = end_time - start_time + asyncio.create_task( + self.service_logger_obj.async_service_failure_hook( + service=ServiceTypes.REDIS, + duration=_duration, + error=e, + call_type=f"async_lpop_pipeline <- {_get_call_stack_info()}", + ) + ) + verbose_logger.error( + "LiteLLM Redis Caching: async_lpop_pipeline() - Got exception from REDIS %s", + str(e), + ) + raise e diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cluster_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cluster_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..b0f5754f58e34c71756331ab60d7c899f1362b25 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_cluster_cache.py @@ -0,0 +1,109 @@ +""" +Redis Cluster Cache implementation + +Key differences: +- RedisClient NEEDs to be re-used across requests, adds 3000ms latency if it's re-created +""" + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from litellm.caching.redis_cache import RedisCache + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + from redis.asyncio import Redis, RedisCluster + from redis.asyncio.client import Pipeline + + pipeline = Pipeline + async_redis_client = Redis + Span = Union[_Span, Any] +else: + pipeline = Any + async_redis_client = Any + Span = Any + + +class RedisClusterCache(RedisCache): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.redis_async_redis_cluster_client: Optional[RedisCluster] = None + self.redis_sync_redis_cluster_client: Optional[RedisCluster] = None + + def init_async_client(self): + from redis.asyncio import RedisCluster + + from .._redis import get_redis_async_client + + if self.redis_async_redis_cluster_client: + return self.redis_async_redis_cluster_client + + _redis_client = get_redis_async_client( + connection_pool=self.async_redis_conn_pool, **self.redis_kwargs + ) + if isinstance(_redis_client, RedisCluster): + self.redis_async_redis_cluster_client = _redis_client + + return _redis_client + + def _run_redis_mget_operation(self, keys: List[str]) -> List[Any]: + """ + Overrides `_run_redis_mget_operation` in redis_cache.py + """ + return self.redis_client.mget_nonatomic(keys=keys) # type: ignore + + async def _async_run_redis_mget_operation(self, keys: List[str]) -> List[Any]: + """ + Overrides `_async_run_redis_mget_operation` in redis_cache.py + """ + async_redis_cluster_client = self.init_async_client() + return await async_redis_cluster_client.mget_nonatomic(keys=keys) # type: ignore + + async def test_connection(self) -> dict: + """ + Test the Redis Cluster connection. + + Returns: + dict: {"status": "success" | "failed", "message": str, "error": Optional[str]} + """ + try: + import redis.asyncio as redis_async + from redis.cluster import ClusterNode + + # Create ClusterNode objects from startup_nodes + cluster_kwargs = self.redis_kwargs.copy() + startup_nodes = cluster_kwargs.pop("startup_nodes", []) + + new_startup_nodes: List[ClusterNode] = [] + for item in startup_nodes: + new_startup_nodes.append(ClusterNode(**item)) + + # Create a fresh Redis Cluster client with current settings + redis_client = redis_async.RedisCluster( + startup_nodes=new_startup_nodes, **cluster_kwargs # type: ignore + ) + + # Test the connection + ping_result = await redis_client.ping() # type: ignore[attr-defined, misc] + + # Close the connection + await redis_client.aclose() # type: ignore[attr-defined] + + if ping_result: + return { + "status": "success", + "message": "Redis Cluster connection test successful", + } + else: + return { + "status": "failed", + "message": "Redis Cluster ping returned False", + } + except Exception as e: + from litellm._logging import verbose_logger + + verbose_logger.error(f"Redis Cluster connection test failed: {str(e)}") + return { + "status": "failed", + "message": f"Redis Cluster connection failed: {str(e)}", + "error": str(e), + } diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_semantic_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_semantic_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..da9e7b1e5871dd1c202c8148152d17e7080aa089 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/redis_semantic_cache.py @@ -0,0 +1,556 @@ +""" +Redis Semantic Cache implementation for LiteLLM + +The RedisSemanticCache provides semantic caching functionality using Redis as a backend. +This cache stores responses based on the semantic similarity of prompts rather than +exact matching, allowing for more flexible caching of LLM responses. + +This implementation uses RedisVL's SemanticCache to find semantically similar prompts +and their cached responses. +""" + +import ast +import asyncio +import json +import os +from typing import Any, Dict, List, Optional, Tuple, cast + +import litellm +from litellm._logging import print_verbose +from litellm.litellm_core_utils.prompt_templates.common_utils import ( + get_str_from_messages, +) +from litellm.types.utils import EmbeddingResponse + +from .base_cache import BaseCache + + +class RedisSemanticCache(BaseCache): + """ + Redis-backed semantic cache for LLM responses. + + This cache uses vector similarity to find semantically similar prompts that have been + previously sent to the LLM, allowing for cache hits even when prompts are not identical + but carry similar meaning. + """ + + DEFAULT_REDIS_INDEX_NAME: str = "litellm_semantic_cache_index" + CACHE_KEY_FIELD_NAME: str = "litellm_cache_key" + + def __init__( + self, + host: Optional[str] = None, + port: Optional[str] = None, + password: Optional[str] = None, + redis_url: Optional[str] = None, + similarity_threshold: Optional[float] = None, + embedding_model: str = "text-embedding-ada-002", + index_name: Optional[str] = None, + **kwargs, + ): + """ + Initialize the Redis Semantic Cache. + + Args: + host: Redis host address + port: Redis port + password: Redis password + redis_url: Full Redis URL (alternative to separate host/port/password) + similarity_threshold: Threshold for semantic similarity (0.0 to 1.0) + where 1.0 requires exact matches and 0.0 accepts any match + embedding_model: Model to use for generating embeddings + index_name: Name for the Redis index + ttl: Default time-to-live for cache entries in seconds + **kwargs: Additional arguments passed to the Redis client + + Raises: + Exception: If similarity_threshold is not provided or required Redis + connection information is missing + """ + from redisvl.extensions.llmcache import SemanticCache # type: ignore[import-not-found, import-untyped] + from redisvl.utils.vectorize import CustomTextVectorizer # type: ignore[import-not-found, import-untyped] + + if index_name is None: + index_name = self.DEFAULT_REDIS_INDEX_NAME + + print_verbose(f"Redis semantic-cache initializing index - {index_name}") + + # Validate similarity threshold + if similarity_threshold is None: + raise ValueError("similarity_threshold must be provided, passed None") + + # Store configuration + self.similarity_threshold = similarity_threshold + + # Convert similarity threshold [0,1] to distance threshold [0,2] + # For cosine distance: 0 = most similar, 2 = least similar + # While similarity: 1 = most similar, 0 = least similar + self.distance_threshold = 1 - similarity_threshold + self.embedding_model = embedding_model + + # Set up Redis connection + if redis_url is None: + try: + # Attempt to use provided parameters or fallback to environment variables + host = host or os.environ["REDIS_HOST"] + port = port or os.environ["REDIS_PORT"] + password = password or os.environ["REDIS_PASSWORD"] + except KeyError as e: + # Raise a more informative exception if any of the required keys are missing + missing_var = e.args[0] + raise ValueError( + f"Missing required Redis configuration: {missing_var}. " + f"Provide {missing_var} or redis_url." + ) from e + + redis_url = f"redis://:{password}@{host}:{port}" + + print_verbose(f"Redis semantic-cache redis_url: {redis_url}") + + # Initialize the Redis vectorizer and cache + cache_vectorizer = CustomTextVectorizer(self._get_embedding) + + self.llmcache = self._init_semantic_cache( + semantic_cache_cls=SemanticCache, + index_name=index_name, + redis_url=redis_url, + cache_vectorizer=cache_vectorizer, + ) + + @classmethod + def _cache_key_filterable_field(cls) -> Dict[str, str]: + return { + "name": cls.CACHE_KEY_FIELD_NAME, + "type": "tag", + } + + def _init_semantic_cache( + self, + semantic_cache_cls: Any, + index_name: str, + redis_url: str, + cache_vectorizer: Any, + ) -> Any: + def _is_schema_mismatch(exc: ValueError) -> bool: + error_message = str(exc).lower() + return any( + phrase in error_message + for phrase in ("schema does not match", "index schema") + ) + + try: + return semantic_cache_cls( + name=index_name, + redis_url=redis_url, + vectorizer=cache_vectorizer, + distance_threshold=self.distance_threshold, + filterable_fields=[self._cache_key_filterable_field()], + overwrite=False, + ) + except ValueError as exc: + if not _is_schema_mismatch(exc): + raise + + isolated_index_name = f"{index_name}_isolated" + print_verbose( + "Redis semantic-cache existing index schema is not isolated; " + f"using isolated index - {isolated_index_name}" + ) + try: + return semantic_cache_cls( + name=isolated_index_name, + redis_url=redis_url, + vectorizer=cache_vectorizer, + distance_threshold=self.distance_threshold, + filterable_fields=[self._cache_key_filterable_field()], + overwrite=False, + ) + except ValueError as isolated_exc: + if not _is_schema_mismatch(isolated_exc): + raise + + print_verbose( + "Redis semantic-cache isolated index schema is stale; " + f"recreating isolated index - {isolated_index_name}" + ) + return semantic_cache_cls( + name=isolated_index_name, + redis_url=redis_url, + vectorizer=cache_vectorizer, + distance_threshold=self.distance_threshold, + filterable_fields=[self._cache_key_filterable_field()], + overwrite=True, + ) + + def _get_cache_filters(self, key: str) -> Dict[str, str]: + return {self.CACHE_KEY_FIELD_NAME: str(key)} + + def _get_cache_key_filter_expression(self, key: str) -> Any: + from redisvl.query.filter import Tag # type: ignore[import-not-found, import-untyped] + + return Tag(self.CACHE_KEY_FIELD_NAME) == str(key) + + def _cache_hit_matches_key(self, cache_hit: Dict[str, Any], key: str) -> bool: + # Pre-isolation entries with no ``litellm_cache_key`` field cannot be + # safely reassigned to a caller's scope and are treated as misses. + cached_key = cache_hit.get(self.CACHE_KEY_FIELD_NAME) + if isinstance(cached_key, bytes): + cached_key = cached_key.decode("utf-8") + return cached_key is not None and str(cached_key) == str(key) + + def _get_ttl(self, **kwargs) -> Optional[int]: + """ + Get the TTL (time-to-live) value for cache entries. + + Args: + **kwargs: Keyword arguments that may contain a custom TTL + + Returns: + Optional[int]: The TTL value in seconds, or None if no TTL should be applied + """ + ttl = kwargs.get("ttl") + if ttl is not None: + ttl = int(ttl) + return ttl + + def _get_embedding(self, prompt: str) -> List[float]: + """ + Generate an embedding vector for the given prompt using the configured embedding model. + + Args: + prompt: The text to generate an embedding for + + Returns: + List[float]: The embedding vector + """ + # Create an embedding from prompt + embedding_response = cast( + EmbeddingResponse, + litellm.embedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + ), + ) + embedding = embedding_response["data"][0]["embedding"] + return embedding + + def _get_cache_logic(self, cached_response: Any) -> Any: + """ + Process the cached response to prepare it for use. + + Args: + cached_response: The raw cached response + + Returns: + The processed cache response, or None if input was None + """ + if cached_response is None: + return cached_response + + # Convert bytes to string if needed + if isinstance(cached_response, bytes): + cached_response = cached_response.decode("utf-8") + + # Convert string representation to Python object + try: + cached_response = json.loads(cached_response) + except json.JSONDecodeError: + try: + cached_response = ast.literal_eval(cached_response) + except (ValueError, SyntaxError) as e: + print_verbose(f"Error parsing cached response: {str(e)}") + return None + + return cached_response + + def set_cache(self, key: str, value: Any, **kwargs) -> None: + """ + Store a value in the semantic cache. + + Args: + key: The cache key used to isolate semantic cache entries + value: The response value to cache + **kwargs: Additional arguments including 'messages' for the prompt + and optional 'ttl' for time-to-live + """ + print_verbose(f"Redis semantic-cache set_cache, kwargs: {kwargs}") + + value_str: Optional[str] = None + try: + # Extract the prompt from messages + messages = kwargs.get("messages", []) + if not messages: + print_verbose("No messages provided for semantic caching") + return + + prompt = get_str_from_messages(messages) + value_str = str(value) + + store_kwargs: Dict[str, Any] = { + "filters": self._get_cache_filters(key), + } + + # Get TTL and store in Redis semantic cache + ttl = self._get_ttl(**kwargs) + if ttl is not None: + store_kwargs["ttl"] = int(ttl) + self.llmcache.store(prompt, value_str, **store_kwargs) + except Exception as e: + print_verbose( + f"Error setting {value_str or value} in the Redis semantic cache: {str(e)}" + ) + + def get_cache(self, key: str, **kwargs) -> Any: + """ + Retrieve a semantically similar cached response. + + Args: + key: The cache key used to isolate semantic cache entries + **kwargs: Additional arguments including 'messages' for the prompt + + Returns: + The cached response if a semantically similar prompt is found, else None + """ + print_verbose(f"Redis semantic-cache get_cache, kwargs: {kwargs}") + + try: + # Extract the prompt from messages + messages = kwargs.get("messages", []) + if not messages: + print_verbose("No messages provided for semantic cache lookup") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + prompt = get_str_from_messages(messages) + # Check the cache for semantically similar prompts in this exact + # LiteLLM cache-key scope. + check_kwargs: Dict[str, Any] = { + "prompt": prompt, + "filter_expression": self._get_cache_key_filter_expression(key), + } + results = self.llmcache.check(**check_kwargs) + + # Return None if no similar prompts found + if not results: + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + # Process the best matching result + cache_hit = results[0] + if not self._cache_hit_matches_key(cache_hit=cache_hit, key=key): + print_verbose("Redis semantic-cache hit did not match cache key scope") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + vector_distance = float(cache_hit["vector_distance"]) + + # Convert vector distance back to similarity score + # For cosine distance: 0 = most similar, 2 = least similar + # While similarity: 1 = most similar, 0 = least similar + similarity = 1 - vector_distance + + cached_prompt = cache_hit["prompt"] + cached_response = cache_hit["response"] + + # update kwargs["metadata"] with similarity, don't rewrite the original metadata + kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity + + print_verbose( + f"Cache hit: similarity threshold: {self.similarity_threshold}, " + f"actual similarity: {similarity}, " + f"current prompt: {prompt}, " + f"cached prompt: {cached_prompt}" + ) + + return self._get_cache_logic(cached_response=cached_response) + except Exception as e: + print_verbose(f"Error retrieving from Redis semantic cache: {str(e)}") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + + async def _get_async_embedding(self, prompt: str, **kwargs) -> List[float]: + """ + Asynchronously generate an embedding for the given prompt. + + Args: + prompt: The text to generate an embedding for + **kwargs: Additional arguments that may contain metadata + + Returns: + List[float]: The embedding vector + """ + from litellm.proxy.proxy_server import llm_model_list, llm_router + + # Route the embedding request through the proxy if appropriate + router_model_names = ( + [m["model_name"] for m in llm_model_list] + if llm_model_list is not None + else [] + ) + + try: + if llm_router is not None and self.embedding_model in router_model_names: + # Use the router for embedding generation + user_api_key = kwargs.get("metadata", {}).get("user_api_key", "") + embedding_response = await llm_router.aembedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + metadata={ + "user_api_key": user_api_key, + "semantic-cache-embedding": True, + "trace_id": kwargs.get("metadata", {}).get("trace_id", None), + }, + ) + else: + # Generate embedding directly + embedding_response = await litellm.aembedding( + model=self.embedding_model, + input=prompt, + cache={"no-store": True, "no-cache": True}, + ) + + # Extract and return the embedding vector + return embedding_response["data"][0]["embedding"] + except Exception as e: + print_verbose(f"Error generating async embedding: {str(e)}") + raise ValueError(f"Failed to generate embedding: {str(e)}") from e + + async def async_set_cache(self, key: str, value: Any, **kwargs) -> None: + """ + Asynchronously store a value in the semantic cache. + + Args: + key: The cache key used to isolate semantic cache entries + value: The response value to cache + **kwargs: Additional arguments including 'messages' for the prompt + and optional 'ttl' for time-to-live + """ + print_verbose(f"Async Redis semantic-cache set_cache, kwargs: {kwargs}") + + try: + # Extract the prompt from messages + messages = kwargs.get("messages", []) + if not messages: + print_verbose("No messages provided for semantic caching") + return + + prompt = get_str_from_messages(messages) + value_str = str(value) + + # Generate embedding for the value (response) to cache + prompt_embedding = await self._get_async_embedding(prompt, **kwargs) + + store_kwargs: Dict[str, Any] = { + "vector": prompt_embedding, + "filters": self._get_cache_filters(key), + } + + # Get TTL and store in Redis semantic cache + ttl = self._get_ttl(**kwargs) + if ttl is not None: + store_kwargs["ttl"] = ttl + await self.llmcache.astore( + prompt, + value_str, + **store_kwargs, + ) + except Exception as e: + print_verbose(f"Error in async_set_cache: {str(e)}") + + async def async_get_cache(self, key: str, **kwargs) -> Any: + """ + Asynchronously retrieve a semantically similar cached response. + + Args: + key: The cache key used to isolate semantic cache entries + **kwargs: Additional arguments including 'messages' for the prompt + + Returns: + The cached response if a semantically similar prompt is found, else None + """ + print_verbose(f"Async Redis semantic-cache get_cache, kwargs: {kwargs}") + + try: + # Extract the prompt from messages + messages = kwargs.get("messages", []) + if not messages: + print_verbose("No messages provided for semantic cache lookup") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + prompt = get_str_from_messages(messages) + + # Generate embedding for the prompt + prompt_embedding = await self._get_async_embedding(prompt, **kwargs) + + # Check the cache for semantically similar prompts in this exact + # LiteLLM cache-key scope. + check_kwargs: Dict[str, Any] = { + "prompt": prompt, + "vector": prompt_embedding, + "filter_expression": self._get_cache_key_filter_expression(key), + } + results = await self.llmcache.acheck(**check_kwargs) + + # handle results / cache hit + if not results: + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + + cache_hit = results[0] + if not self._cache_hit_matches_key(cache_hit=cache_hit, key=key): + print_verbose("Redis semantic-cache hit did not match cache key scope") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + return None + vector_distance = float(cache_hit["vector_distance"]) + + # Convert vector distance back to similarity + # For cosine distance: 0 = most similar, 2 = least similar + # While similarity: 1 = most similar, 0 = least similar + similarity = 1 - vector_distance + + cached_prompt = cache_hit["prompt"] + cached_response = cache_hit["response"] + + # update kwargs["metadata"] with similarity, don't rewrite the original metadata + kwargs.setdefault("metadata", {})["semantic-similarity"] = similarity + + print_verbose( + f"Cache hit: similarity threshold: {self.similarity_threshold}, " + f"actual similarity: {similarity}, " + f"current prompt: {prompt}, " + f"cached prompt: {cached_prompt}" + ) + + return self._get_cache_logic(cached_response=cached_response) + except Exception as e: + print_verbose(f"Error in async_get_cache: {str(e)}") + kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 + + async def _index_info(self) -> Dict[str, Any]: + """ + Get information about the Redis index. + + Returns: + Dict[str, Any]: Information about the Redis index + """ + aindex = await self.llmcache._get_async_index() + return await aindex.info() + + async def async_set_cache_pipeline( + self, cache_list: List[Tuple[str, Any]], **kwargs + ) -> None: + """ + Asynchronously store multiple values in the semantic cache. + + Args: + cache_list: List of (key, value) tuples to cache + **kwargs: Additional arguments + """ + try: + tasks = [] + for val in cache_list: + tasks.append(self.async_set_cache(val[0], val[1], **kwargs)) + await asyncio.gather(*tasks) + except Exception as e: + print_verbose(f"Error in async_set_cache_pipeline: {str(e)}") diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/s3_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/s3_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e26fbe8981c76140477ab56d141c63bf24db241a --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/caching/s3_cache.py @@ -0,0 +1,193 @@ +""" +S3 Cache implementation + +Has 4 methods: + - set_cache + - get_cache + - async_set_cache (uses run_in_executor) + - async_get_cache (uses run_in_executor) +""" + +import ast +import asyncio +import json +from functools import partial +from typing import Optional +from datetime import datetime, timezone, timedelta + +from litellm._logging import print_verbose, verbose_logger + +from .base_cache import BaseCache + + +class S3Cache(BaseCache): + def __init__( + self, + s3_bucket_name, + s3_region_name=None, + s3_api_version=None, + s3_use_ssl: Optional[bool] = True, + s3_verify=None, + s3_endpoint_url=None, + s3_aws_access_key_id=None, + s3_aws_secret_access_key=None, + s3_aws_session_token=None, + s3_config=None, + s3_path=None, + **kwargs, + ): + import boto3 + + self.bucket_name = s3_bucket_name + self.key_prefix = s3_path.rstrip("/") + "/" if s3_path else "" + # Create an S3 client with custom endpoint URL + + self.s3_client = boto3.client( + "s3", + region_name=s3_region_name, + endpoint_url=s3_endpoint_url, + api_version=s3_api_version, + use_ssl=s3_use_ssl, + verify=s3_verify, + aws_access_key_id=s3_aws_access_key_id, + aws_secret_access_key=s3_aws_secret_access_key, + aws_session_token=s3_aws_session_token, + config=s3_config, + **kwargs, + ) + + def _to_s3_key(self, key: str) -> str: + """Convert cache key to S3 key""" + return self.key_prefix + key.replace(":", "/") + + def set_cache(self, key, value, **kwargs): + try: + print_verbose(f"LiteLLM SET Cache - S3. Key={key}. Value={value}") + ttl = kwargs.get("ttl", None) + # Convert value to JSON before storing in S3 + serialized_value = json.dumps(value) + key = self._to_s3_key(key) + + if ttl is not None: + cache_control = f"immutable, max-age={ttl}, s-maxage={ttl}" + + # Calculate expiration time + expiration_time = datetime.now(timezone.utc) + timedelta(seconds=ttl) + # Upload the data to S3 with the calculated expiration time + self.s3_client.put_object( + Bucket=self.bucket_name, + Key=key, + Body=serialized_value, + Expires=expiration_time, + CacheControl=cache_control, + ContentType="application/json", + ContentLanguage="en", + ContentDisposition=f'inline; filename="{key}.json"', + ) + else: + cache_control = "immutable, max-age=31536000, s-maxage=31536000" + # Upload the data to S3 without specifying Expires + self.s3_client.put_object( + Bucket=self.bucket_name, + Key=key, + Body=serialized_value, + CacheControl=cache_control, + ContentType="application/json", + ContentLanguage="en", + ContentDisposition=f'inline; filename="{key}.json"', + ) + except Exception as e: + print_verbose(f"S3 Caching: set_cache() - Got exception from S3: {e}") + + async def async_set_cache(self, key, value, **kwargs): + """ + Asynchronously set cache using run_in_executor to avoid blocking the event loop. + Compatible with Python 3.8+. + """ + try: + verbose_logger.debug(f"Set ASYNC S3 Cache: Key={key}. Value={value}") + loop = asyncio.get_event_loop() + func = partial(self.set_cache, key, value, **kwargs) + await loop.run_in_executor(None, func) + except Exception as e: + verbose_logger.error( + f"S3 Caching: async_set_cache() - Got exception from S3: {e}" + ) + + def get_cache(self, key, **kwargs): + import botocore + + try: + key = self._to_s3_key(key) + + print_verbose(f"Get S3 Cache: key: {key}") + # Download the data from S3 + cached_response = self.s3_client.get_object( + Bucket=self.bucket_name, Key=key + ) + + if cached_response is not None: + if "Expires" in cached_response: + expires_time = cached_response["Expires"] + current_time = datetime.now(expires_time.tzinfo) + + if current_time > expires_time: + return None + + # cached_response is in `b{} convert it to ModelResponse + cached_response = ( + cached_response["Body"].read().decode("utf-8") + ) # Convert bytes to string + try: + cached_response = json.loads( + cached_response + ) # Convert string to dictionary + except Exception: + cached_response = ast.literal_eval(cached_response) + if not isinstance(cached_response, dict): + cached_response = dict(cached_response) + verbose_logger.debug( + f"Got S3 Cache: key: {key}, cached_response {cached_response}. Type Response {type(cached_response)}" + ) + + return cached_response + except botocore.exceptions.ClientError as e: # type: ignore + if e.response["Error"]["Code"] == "NoSuchKey": + verbose_logger.debug( + f"S3 Cache: The specified key '{key}' does not exist in the S3 bucket." + ) + return None + + except Exception as e: + verbose_logger.error( + f"S3 Caching: get_cache() - Got exception from S3: {e}" + ) + + async def async_get_cache(self, key, **kwargs): + """ + Asynchronously get cache using run_in_executor to avoid blocking the event loop. + Compatible with Python 3.8+. + """ + try: + verbose_logger.debug(f"Get ASYNC S3 Cache: key: {key}") + loop = asyncio.get_event_loop() + func = partial(self.get_cache, key, **kwargs) + result = await loop.run_in_executor(None, func) + return result + except Exception as e: + verbose_logger.error( + f"S3 Caching: async_get_cache() - Got exception from S3: {e}" + ) + return None + + def flush_cache(self): + pass + + async def disconnect(self): + pass + + async def async_set_cache_pipeline(self, cache_list, **kwargs): + tasks = [] + for val in cache_list: + tasks.append(self.async_set_cache(val[0], val[1], **kwargs)) + await asyncio.gather(*tasks) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/README.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55b9c35dc5b26281be58fcbb52d0b5cf1c28ca38 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/README.md @@ -0,0 +1,4 @@ +Logic specific for `litellm.completion`. + +Includes: +- Bridge for transforming completion requests to responses api requests \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..eeb3e1cf600a4008a1f3c3de3ba3a04e7e31124c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/completion_extras/__init__.py @@ -0,0 +1,3 @@ +from .litellm_responses_transformation import responses_api_bridge + +__all__ = ["responses_api_bridge"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..11c5eaf84ef5eb8e271f72fcebcb1ef0a32c5470 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/__init__.py @@ -0,0 +1,3 @@ +from litellm.compression.compress import compress + +__all__ = ["compress"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/compress.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/compress.py new file mode 100644 index 0000000000000000000000000000000000000000..45795c9ca15d40b732b81b9722f7476b555050cd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/compress.py @@ -0,0 +1,513 @@ +""" +Main compress() function — normalizes input messages, orchestrates BM25/embedding +scoring, message stubbing, and retrieval tool injection. +""" + +from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast + +from litellm.caching.dual_cache import DualCache +from litellm.compression.message_stubbing import ( + extract_key, + stub_message, + truncate_message, +) +from litellm.compression.retrieval_tool import build_retrieval_tool +from litellm.compression.scoring.bm25 import bm25_score_messages +from litellm.litellm_core_utils.token_counter import token_counter +from litellm.types.compression import CompressedResult +from litellm.types.utils import CallTypes + +# CallTypes that produce Anthropic-shaped messages (structured content blocks). +# Everything else is treated as OpenAI chat-completions shape. +_ANTHROPIC_CALL_TYPES = frozenset({CallTypes.anthropic_messages.value}) +# CallTypes that are valid targets for compression. Compression operates on +# message-shaped inputs, so we only accept call types whose payload is a list +# of role/content messages. +_SUPPORTED_CALL_TYPES = frozenset( + { + CallTypes.completion.value, + CallTypes.acompletion.value, + CallTypes.anthropic_messages.value, + } +) + + +def _normalize_call_type(call_type: Union[CallTypes, str]) -> str: + """Return the string value for a ``CallTypes`` enum or a raw string.""" + if isinstance(call_type, CallTypes): + return call_type.value + return call_type + + +def _is_anthropic_call_type(call_type: str) -> bool: + return call_type in _ANTHROPIC_CALL_TYPES + + +def _build_retrieval_tools(keys: List[str], call_type: str) -> List[dict]: + """ + Build retrieval tool definitions in the target request schema. + + - Chat-completions call types: keep OpenAI function-tool schema. + - Anthropic messages call type: remap to Anthropic's custom tool schema. + """ + if not keys: + return [] + + openai_tools = [build_retrieval_tool(keys)] + if not _is_anthropic_call_type(call_type): + return openai_tools + + # Lazy import to avoid introducing provider transformation imports during + # module import for non-Anthropic call paths. + from litellm.llms.anthropic.chat.transformation import AnthropicConfig + + anthropic_tools, _mcp_servers = AnthropicConfig()._map_tools(openai_tools) + return cast(List[dict], anthropic_tools) + + +def _content_to_text(content: Any) -> str: + """ + Convert OpenAI/Anthropic message content blocks to plain text. + + Text extraction policy: + - Include text-bearing fields only (`text` blocks + string values). + - For `tool_result`, expand into nested `content` items. + - Ignore non-textual blocks (images/documents/tool metadata/thinking metadata). + + Implemented iteratively (stack-based) to avoid unbounded recursion. + """ + parts: List[str] = [] + stack: List[Any] = [content] + while stack: + item = stack.pop() + if isinstance(item, str): + parts.append(item) + elif isinstance(item, list): + # Push list items in reverse order so they are processed left-to-right. + for element in reversed(item): + stack.append(element) + elif isinstance(item, dict): + item_type = item.get("type") + if item_type == "text": + parts.append(str(item.get("text", ""))) + elif item_type == "tool_result": + stack.append(item.get("content", "")) + return " ".join(parts) + + +def _normalize_messages_for_compression( + messages: List[dict], + call_type: str, +) -> Tuple[List[dict], List[dict]]: + """ + Normalize each original message to a text-surrogate content for scoring. + + Returns: + (normalized_messages, original_messages_copy) + """ + if call_type not in _SUPPORTED_CALL_TYPES: + raise ValueError( + f"Unsupported call_type={call_type!r} for compression. " + f"Expected one of: {sorted(_SUPPORTED_CALL_TYPES)}." + ) + + original_messages: List[Dict[str, Any]] = [dict(m) for m in messages] + + normalized_messages: List[dict] = [] + for msg in original_messages: + normalized_messages.append( + { + **msg, + "content": _content_to_text(msg.get("content", "")), + } + ) + return normalized_messages, original_messages + + +def _extract_last_user_message(messages: List[dict]) -> str: + """Return the text content of the last user message.""" + for msg in reversed(messages): + if msg.get("role") == "user": + return _content_to_text(msg.get("content", "")) + return "" + + +def _extract_tool_use_ids(content: Any) -> List[str]: + if not isinstance(content, list): + return [] + tool_use_ids: List[str] = [] + for part in content: + if not isinstance(part, dict): + continue + if part.get("type") != "tool_use": + continue + tool_use_id = part.get("id") + if isinstance(tool_use_id, str) and tool_use_id: + tool_use_ids.append(tool_use_id) + return tool_use_ids + + +def _extract_tool_result_ids(content: Any) -> Set[str]: + if not isinstance(content, list): + return set() + tool_result_ids: Set[str] = set() + for part in content: + if not isinstance(part, dict): + continue + if part.get("type") != "tool_result": + continue + tool_use_id = part.get("tool_use_id") + if isinstance(tool_use_id, str) and tool_use_id: + tool_result_ids.add(tool_use_id) + return tool_result_ids + + +def _extract_anthropic_tool_exchange_spans( + messages: List[dict], +) -> Tuple[List[Set[int]], Optional[str]]: + """ + Return atomic 2-message spans for Anthropic tool exchanges. + + Each assistant message containing `tool_use` must be immediately followed by a + user message containing matching `tool_result` blocks for all tool_use ids. + """ + spans: List[Set[int]] = [] + i = 0 + while i < len(messages): + current = messages[i] + if current.get("role") != "assistant": + i += 1 + continue + + tool_use_ids = _extract_tool_use_ids(current.get("content")) + if not tool_use_ids: + i += 1 + continue + + if i + 1 >= len(messages): + return [], "invalid_anthropic_tool_sequence" + + next_msg = messages[i + 1] + if next_msg.get("role") != "user": + return [], "invalid_anthropic_tool_sequence" + + tool_result_ids = _extract_tool_result_ids(next_msg.get("content")) + if not tool_result_ids: + return [], "invalid_anthropic_tool_sequence" + + for tool_use_id in tool_use_ids: + if tool_use_id not in tool_result_ids: + return [], "invalid_anthropic_tool_sequence" + + spans.append({i, i + 1}) + i += 2 + + return spans, None + + +def _get_protected_indices(messages: List[dict]) -> List[int]: + """ + Return indices of messages that must never be compressed: + - All system messages + - The last user message + - The last assistant message + """ + protected: List[int] = [] + + last_user_idx = None + last_assistant_idx = None + + for i, msg in enumerate(messages): + role = msg.get("role", "") + if role == "system": + protected.append(i) + elif role == "user": + last_user_idx = i + elif role == "assistant": + last_assistant_idx = i + + if last_user_idx is not None: + protected.append(last_user_idx) + if last_assistant_idx is not None: + protected.append(last_assistant_idx) + + return protected + + +def _combine_scores( + bm25_scores: List[float], + emb_scores: List[float], + bm25_weight: float = 0.4, +) -> List[float]: + """Weighted average of BM25 and embedding scores, with min-max normalization.""" + + def _normalize(scores: List[float]) -> List[float]: + min_s = min(scores) if scores else 0.0 + max_s = max(scores) if scores else 0.0 + rng = max_s - min_s + if rng == 0: + return [0.0] * len(scores) + return [(s - min_s) / rng for s in scores] + + norm_bm25 = _normalize(bm25_scores) + norm_emb = _normalize(emb_scores) + emb_weight = 1.0 - bm25_weight + + return [bm25_weight * b + emb_weight * e for b, e in zip(norm_bm25, norm_emb)] + + +def _select_kept_indices_for_budget( + normalized_messages: List[dict], + original_messages: List[dict], + combined_scores: List[float], + compression_target: int, + model: str, + initial_kept_indices: Set[int], + tool_exchange_spans: List[Set[int]], +) -> Tuple[Set[int], Dict[int, dict]]: + kept_indices = set(initial_kept_indices) + current_tokens = 0 + for i in kept_indices: + current_tokens += token_counter( + model=model, + text=cast(str, normalized_messages[i].get("content", "") or ""), + ) + + # Fill token budget from highest-scoring units. + # A unit is either: + # 1) a single message index, or + # 2) an Anthropic tool-exchange span that must be kept/dropped atomically. + truncated_overrides: Dict[int, dict] = {} # idx -> truncated message dict + span_id_by_index: Dict[int, int] = {} + for span_id, span in enumerate(tool_exchange_spans): + for idx in span: + span_id_by_index[idx] = span_id + + # Build single-message candidate units (non-span messages). + candidate_units: List[Tuple[float, Tuple[int, ...], bool]] = [] + for idx in range(len(normalized_messages)): + if idx in span_id_by_index or idx in kept_indices: + continue + candidate_units.append((combined_scores[idx], (idx,), True)) + + # Build span candidate units (atomic keep/drop for tool exchanges). + for span in tool_exchange_spans: + span_indices = tuple(sorted(span)) + if any(idx in kept_indices for idx in span_indices): + continue + span_score = max(combined_scores[idx] for idx in span_indices) + candidate_units.append((span_score, span_indices, False)) + + # Sort by descending relevance score. + candidate_units.sort(key=lambda item: item[0], reverse=True) + + for _score, indices, can_truncate in candidate_units: + if any(idx in kept_indices for idx in indices): + continue + msg_tokens = 0 + for idx in indices: + msg_tokens += token_counter( + model=model, + text=cast(str, normalized_messages[idx].get("content", "") or ""), + ) + remaining = compression_target - current_tokens + + if remaining <= 0: + break # budget exhausted + + if current_tokens + msg_tokens <= compression_target: + # Fits entirely + kept_indices.update(indices) + current_tokens += msg_tokens + elif can_truncate and len(indices) == 1 and remaining >= 100: + # Too large to fit whole single message, but we have budget — truncate it. + idx = indices[0] + truncated = truncate_message(original_messages[idx], remaining) + truncated_tokens = token_counter( + model=model, + text=truncated.get("content", "") or "", + ) + truncated_overrides[idx] = truncated + kept_indices.add(idx) + current_tokens += truncated_tokens + + return kept_indices, truncated_overrides + + +def _get_dropped_tool_span_indices( + kept_indices: Set[int], tool_exchange_spans: List[Set[int]] +) -> Set[int]: + dropped_tool_span_indices: Set[int] = set() + for span in tool_exchange_spans: + if not any(idx in kept_indices for idx in span): + dropped_tool_span_indices.update(span) + return dropped_tool_span_indices + + +def compress( + messages: List[dict], + model: str, + call_type: Union[CallTypes, str] = CallTypes.completion, + compression_trigger: int = 200_000, + compression_target: Optional[int] = None, + embedding_model: Optional[str] = None, + embedding_model_params: Optional[Dict[str, Any]] = None, + compression_cache: Optional[DualCache] = None, +) -> CompressedResult: + """ + Compress a list of messages by replacing low-relevance content with stubs. + + Messages below ``compression_trigger`` tokens pass through unchanged. + Messages above are scored with BM25 (and optionally embeddings), ranked, + and the lowest-relevance messages are replaced with stubs. Originals are + cached and a retrieval tool is injected so the model can recover dropped + content on demand. + + Parameters: + messages: The conversation messages to (potentially) compress. + model: The LLM model name — used for token counting. + call_type: The LiteLLM call type whose message schema these messages + follow. Supported values: + - ``CallTypes.completion`` / ``CallTypes.acompletion`` — OpenAI + chat-completions shape (default) + - ``CallTypes.anthropic_messages`` — Anthropic Messages shape + (structured content blocks + atomic tool exchanges) + compression_trigger: Only compress if input exceeds this token count. + compression_target: Target token count after compression. + Defaults to ``compression_trigger // 2``. + embedding_model: If provided, use BM25 + embeddings for scoring. + If ``None``, BM25 only. + embedding_model_params: Optional kwargs forwarded to + ``litellm.embedding()`` when ``embedding_model`` is set. + compression_cache: Passed through to ``litellm.embedding()`` for + cross-turn caching of embedding vectors. + + Returns: + A ``CompressedResult`` dict containing compressed messages, token + counts, a cache of original content, and the retrieval tool definition. + """ + call_type_str = _normalize_call_type(call_type) + normalized_messages, original_messages = _normalize_messages_for_compression( + messages=messages, + call_type=call_type_str, + ) + + if compression_target is None: + compression_target = compression_trigger * 7 // 10 + + original_tokens = token_counter( + model=model, + messages=cast(List[Any], original_messages), + ) + + # Pass through if below trigger + if original_tokens <= compression_trigger: + return CompressedResult( + messages=original_messages, + original_tokens=original_tokens, + compressed_tokens=original_tokens, + compression_ratio=0.0, + cache={}, + tools=[], + compression_skipped_reason="below_trigger", + ) + + # Extract query for relevance scoring + query = _extract_last_user_message(normalized_messages) + + # Score each message + bm25_scores = bm25_score_messages(query, normalized_messages) + + if embedding_model: + from litellm.compression.scoring.embedding_scorer import ( + embedding_score_messages, + ) + + emb_scores = embedding_score_messages( + query, + normalized_messages, + model=embedding_model, + cache=compression_cache, + embedding_model_params=embedding_model_params, + ) + combined_scores = _combine_scores(bm25_scores, emb_scores, bm25_weight=0.4) + else: + combined_scores = bm25_scores + + # Protected messages are never compressed + protected_indices = _get_protected_indices(normalized_messages) + kept_indices: Set[int] = set(protected_indices) + + tool_exchange_spans: List[Set[int]] = [] + if _is_anthropic_call_type(call_type_str): + tool_exchange_spans, tool_sequence_error = ( + _extract_anthropic_tool_exchange_spans(original_messages) + ) + if tool_sequence_error is not None: + return CompressedResult( + messages=original_messages, + original_tokens=original_tokens, + compressed_tokens=original_tokens, + compression_ratio=0.0, + cache={}, + tools=[], + compression_skipped_reason=tool_sequence_error, + ) + + for span in tool_exchange_spans: + # If any message in the span is protected, keep the whole span. + if any(idx in kept_indices for idx in span): + kept_indices.update(span) + + kept_indices, truncated_overrides = _select_kept_indices_for_budget( + normalized_messages=normalized_messages, + original_messages=original_messages, + combined_scores=combined_scores, + compression_target=compression_target, + model=model, + initial_kept_indices=kept_indices, + tool_exchange_spans=tool_exchange_spans, + ) + + # Build compressed messages and cache + compressed_messages: List[dict] = [] + cache: Dict[str, str] = {} + used_keys: Set[str] = set() + dropped_tool_span_indices = _get_dropped_tool_span_indices( + kept_indices=kept_indices, tool_exchange_spans=tool_exchange_spans + ) + + for i, msg in enumerate(original_messages): + if i in dropped_tool_span_indices: + continue + if i in kept_indices: + # Use the truncated version if we made one, otherwise the original + compressed_messages.append(truncated_overrides.get(i, msg)) + else: + key = extract_key( + normalized_messages[i], fallback_index=i, used_keys=used_keys + ) + content = _content_to_text(msg.get("content", "")) + cache[key] = content + compressed_messages.append(stub_message(msg, key)) + + # Build retrieval tool in the target request schema + tools = _build_retrieval_tools(list(cache.keys()), call_type=call_type_str) + + compressed_tokens = token_counter( + model=model, + messages=cast(List[Any], compressed_messages), + ) + + return CompressedResult( + messages=compressed_messages, + original_tokens=original_tokens, + compressed_tokens=compressed_tokens, + compression_ratio=( + round(1 - (compressed_tokens / original_tokens), 4) + if original_tokens > 0 + else 0.0 + ), + cache=cache, + tools=tools, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/content_detection.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/content_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..0655a42daf589d02196b390398a6eec2307de03b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/content_detection.py @@ -0,0 +1,45 @@ +""" +Auto-detect content type per message: code, JSON, or text. +""" + +import json +import re + + +_CODE_KEYWORDS = re.compile( + r"\b(?:def |function |class |import |from |require\(|#include|fn |func |const |let |var |public |private |static )\b" +) + + +def detect_content_type(content: str) -> str: + """ + Detect whether content is code, JSON, or plain text. + + Returns one of: "code", "json", "text" + """ + stripped = content.strip() + if not stripped: + return "text" + + # Check JSON + if stripped[0] in ("{", "["): + try: + json.loads(stripped) + return "json" + except (json.JSONDecodeError, ValueError): + pass + + # Check code indicators + # Sample first 5000 chars for performance + sample = stripped[:5000] + keyword_matches = len(_CODE_KEYWORDS.findall(sample)) + lines = sample.split("\n") + indented_lines = sum( + 1 for line in lines if line.startswith((" ", "\t")) and line.strip() + ) + + # If we see multiple code keywords or significant indentation, it's likely code + if keyword_matches >= 3 or (indented_lines > len(lines) * 0.3 and len(lines) > 5): + return "code" + + return "text" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/message_stubbing.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/message_stubbing.py new file mode 100644 index 0000000000000000000000000000000000000000..2330f1bbc9efd95dab5c3c2c96523e997a1a82f8 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/message_stubbing.py @@ -0,0 +1,120 @@ +""" +Replace messages with compact stubs and extract human-readable keys. +""" + +import re +from typing import Set + +from litellm.compression.content_detection import detect_content_type + +# Patterns for extracting file paths from content +_FILE_PATH_PATTERNS = [ + re.compile(r"^#\s*(\S+\.\w+)", re.MULTILINE), # # filename.py + re.compile(r"^//\s*(\S+\.\w+)", re.MULTILINE), # // filename.js + re.compile(r"^File:\s*(\S+)", re.MULTILINE), # File: path/to/file + re.compile(r"^---\s*(\S+\.\w+)", re.MULTILINE), # --- filename.ext + re.compile(r"`(\S+\.\w{1,5})`"), # `filename.ext` in backticks +] + + +def extract_key(message: dict, fallback_index: int, used_keys: Set[str]) -> str: + """ + Extract a human-readable key for the message. + + Looks for file path patterns in the content. Falls back to message_{index}. + Handles duplicates by appending _2, _3, etc. + """ + content = message.get("content", "") + if isinstance(content, list): + content = " ".join( + p.get("text", "") if isinstance(p, dict) else str(p) for p in content + ) + + key = None + for pattern in _FILE_PATH_PATTERNS: + match = pattern.search(content[:2000]) # Only search the beginning + if match: + # Use just the filename, not full path + path = match.group(1) + key = path.split("/")[-1] + break + + if key is None: + key = f"message_{fallback_index}" + + # Handle duplicates + base_key = key + counter = 2 + while key in used_keys: + key = f"{base_key}_{counter}" + counter += 1 + + used_keys.add(key) + return key + + +def stub_message(message: dict, key: str) -> dict: + """ + Replace message content with a compact stub. + + Returns a new message dict with the same role but content replaced + with a short description referencing the retrieval tool. + """ + content = message.get("content", "") + if isinstance(content, list): + content = " ".join( + p.get("text", "") if isinstance(p, dict) else str(p) for p in content + ) + + line_count = content.count("\n") + 1 + content_type = detect_content_type(content) + + stub_content = ( + f"[Compressed: {key} — {line_count} lines, {content_type}. " + f"Use litellm_content_retrieve tool to get full content.]" + ) + + return {**message, "content": stub_content} + + +def truncate_message(message: dict, max_tokens: int) -> dict: + """ + Truncate a message's content to approximately max_tokens by keeping + the first 70% and last 30% of lines with a separator in between. + + Uses line-based splitting to preserve code structure (function + boundaries, indentation) rather than word-based splitting which + mangles code. + + Used when a message is too large to fit entirely in the budget but + too relevant to fully stub out. + """ + content = message.get("content", "") + if isinstance(content, list): + content = " ".join( + p.get("text", "") if isinstance(p, dict) else str(p) for p in content + ) + + # Rough conversion: 1 token ≈ 3 characters + target_chars = max(100, max_tokens * 3) + + if len(content) <= target_chars: + return {**message, "content": content} + + lines = content.split("\n") + + # Estimate target line count from character budget + avg_line_len = max(1, len(content) // max(1, len(lines))) + target_lines = max(2, target_chars // avg_line_len) + + if len(lines) <= target_lines: + return {**message, "content": content} + + first_count = (target_lines * 7) // 10 + last_count = target_lines - first_count + truncated = ( + "\n".join(lines[:first_count]) + + "\n...[truncated for context window]...\n" + + "\n".join(lines[-last_count:]) + ) + return {**message, "content": truncated} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/retrieval_tool.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/retrieval_tool.py new file mode 100644 index 0000000000000000000000000000000000000000..1ee24784a6370e4738ed3e0f30e9b8fb2abbd49f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/compression/retrieval_tool.py @@ -0,0 +1,35 @@ +""" +Build the litellm_content_retrieve tool definition for the LLM. +""" + +from typing import List + + +def build_retrieval_tool(available_keys: List[str]) -> dict: + """ + Return an OpenAI-format tool definition that lets the model + retrieve the full content of a compressed message. + """ + return { + "type": "function", + "function": { + "name": "litellm_content_retrieve", + "description": ( + "Retrieve the full content of a file or message that was " + "compressed to save tokens. Use this when you need the complete " + "content to answer accurately. Available keys: " + + ", ".join(available_keys) + ), + "parameters": { + "type": "object", + "properties": { + "key": { + "type": "string", + "description": "The identifier of the content to retrieve", + "enum": available_keys, + } + }, + "required": ["key"], + }, + }, + } diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/Readme.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..4fbd624369c00ae16c566947674555f78773b667 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/Readme.md @@ -0,0 +1,6 @@ +# LiteLLM MCP Client + +LiteLLM MCP Client is a client that allows you to use MCP tools with LiteLLM. + + + diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7110d5375e46f2f017b3844e3bf04c02b2e598b1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/__init__.py @@ -0,0 +1,3 @@ +from .tools import call_openai_tool, load_mcp_tools + +__all__ = ["load_mcp_tools", "call_openai_tool"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/client.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/client.py new file mode 100644 index 0000000000000000000000000000000000000000..e703a3956b9fab2335400ab3542ce556c40b67ba --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/client.py @@ -0,0 +1,752 @@ +""" +LiteLLM Proxy uses this MCP Client to connnect to other MCP servers. +""" + +import asyncio +import base64 +from typing import ( + Any, + Awaitable, + Callable, + Dict, + Generator, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +import httpx +from mcp import ClientSession, ReadResourceResult, Resource, StdioServerParameters +from mcp.client.sse import sse_client +from mcp.client.stdio import stdio_client + +streamable_http_client: Optional[Any] = None +try: + import mcp.client.streamable_http as streamable_http_module # type: ignore + + streamable_http_client = getattr( + streamable_http_module, "streamable_http_client", None + ) +except ImportError: + pass +from mcp.types import CallToolRequestParams as MCPCallToolRequestParams +from mcp.types import CallToolResult as MCPCallToolResult +from mcp.types import ( + GetPromptRequestParams, + GetPromptResult, + Prompt, + ResourceTemplate, + TextContent, +) +from mcp.types import Tool as MCPTool +from pydantic import AnyUrl + +from litellm._logging import verbose_logger +from litellm.constants import MCP_CLIENT_TIMEOUT +from litellm.llms.custom_httpx.http_handler import get_ssl_configuration +from litellm.types.llms.custom_http import VerifyTypes +from litellm.types.mcp import ( + MCPAuth, + MCPAuthType, + MCPStdioConfig, + MCPTransport, + MCPTransportType, +) + + +def to_basic_auth(auth_value: str) -> str: + """Convert auth value to Basic Auth format.""" + return base64.b64encode(auth_value.encode("utf-8")).decode() + + +TSessionResult = TypeVar("TSessionResult") + + +class MCPSigV4Auth(httpx.Auth): + """ + httpx Auth class that signs each request with AWS SigV4. + + This is used for MCP servers that require AWS SigV4 authentication, + such as AWS Bedrock AgentCore MCP servers. httpx calls auth_flow() + for every outgoing request, enabling per-request signature computation. + """ + + requires_request_body = True + + def __init__( + self, + aws_access_key_id: Optional[str] = None, + aws_secret_access_key: Optional[str] = None, + aws_session_token: Optional[str] = None, + aws_region_name: Optional[str] = None, + aws_service_name: Optional[str] = None, + aws_role_name: Optional[str] = None, + aws_session_name: Optional[str] = None, + ): + try: + from botocore.credentials import Credentials + except ImportError: + raise ImportError( + "Missing botocore to use AWS SigV4 authentication. " + "Run 'pip install boto3'." + ) + + self.service_name = aws_service_name or "bedrock-agentcore" + self.region_name = aws_region_name or "us-east-1" + + # Note: os.environ/ prefixed values are already resolved by + # ProxyConfig._check_for_os_environ_vars() at config load time. + # Values arrive here as plain strings. + if aws_role_name: + self.credentials = self._assume_role( + aws_role_name=aws_role_name, + aws_session_name=aws_session_name, + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + aws_session_token=aws_session_token, + aws_region_name=self.region_name, + ) + elif aws_access_key_id and aws_secret_access_key: + self.credentials = Credentials( + access_key=aws_access_key_id, + secret_key=aws_secret_access_key, + token=aws_session_token, + ) + else: + # Fall back to default boto3 credential chain + import botocore.session + + session = botocore.session.get_session() + self.credentials = session.get_credentials() + if self.credentials is None: + raise ValueError( + "No AWS credentials found. Provide aws_access_key_id and " + "aws_secret_access_key, or configure default credentials " + "(env vars, ~/.aws/credentials, instance profile)." + ) + + @staticmethod + def _assume_role( + aws_role_name: str, + aws_session_name: Optional[str], + aws_access_key_id: Optional[str], + aws_secret_access_key: Optional[str], + aws_session_token: Optional[str], + aws_region_name: str, + ): + """Call STS AssumeRole and return temporary credentials.""" + import boto3 + from botocore.credentials import Credentials + + session_name = ( + aws_session_name or f"litellm-mcp-{int(__import__('time').time())}" + ) + + sts_kwargs: dict = {"region_name": aws_region_name} + if aws_access_key_id and aws_secret_access_key: + sts_kwargs["aws_access_key_id"] = aws_access_key_id + sts_kwargs["aws_secret_access_key"] = aws_secret_access_key + if aws_session_token: + sts_kwargs["aws_session_token"] = aws_session_token + + sts_client = boto3.client("sts", **sts_kwargs) + sts_response = sts_client.assume_role( + RoleArn=aws_role_name, + RoleSessionName=session_name, + ) + + sts_creds = sts_response["Credentials"] + return Credentials( + access_key=sts_creds["AccessKeyId"], + secret_key=sts_creds["SecretAccessKey"], + token=sts_creds["SessionToken"], + ) + + def auth_flow( + self, request: httpx.Request + ) -> Generator[httpx.Request, httpx.Response, None]: + from botocore.auth import SigV4Auth + from botocore.awsrequest import AWSRequest + + # Build AWSRequest from the httpx Request. + # Pass all request headers so the canonical SigV4 signature covers them. + aws_request = AWSRequest( + method=request.method, + url=str(request.url), + data=request.content, + headers=dict(request.headers), + ) + + # Sign the request — SigV4Auth.add_auth() adds Authorization, + # X-Amz-Date, and X-Amz-Security-Token (if session token present). + # Host header is derived automatically from the URL. + sigv4 = SigV4Auth(self.credentials, self.service_name, self.region_name) + sigv4.add_auth(aws_request) + + # Copy SigV4 headers back to the httpx request + for header_name, header_value in aws_request.headers.items(): + request.headers[header_name] = header_value + + yield request + + +class MCPClient: + """ + MCP Client supporting: + SSE and HTTP transports + Authentication via Bearer token, Basic Auth, or API Key + Tool calling with error handling and result parsing + """ + + def __init__( + self, + server_url: str = "", + transport_type: MCPTransportType = MCPTransport.http, + auth_type: MCPAuthType = None, + auth_value: Optional[Union[str, Dict[str, str]]] = None, + timeout: Optional[float] = None, + stdio_config: Optional[MCPStdioConfig] = None, + extra_headers: Optional[Dict[str, str]] = None, + ssl_verify: Optional[VerifyTypes] = None, + aws_auth: Optional[httpx.Auth] = None, + ): + self.server_url: str = server_url + self.transport_type: MCPTransport = transport_type + self.auth_type: MCPAuthType = auth_type + self.timeout: float = timeout if timeout is not None else MCP_CLIENT_TIMEOUT + self._mcp_auth_value: Optional[Union[str, Dict[str, str]]] = None + self.stdio_config: Optional[MCPStdioConfig] = stdio_config + self.extra_headers: Optional[Dict[str, str]] = extra_headers + self.ssl_verify: Optional[VerifyTypes] = ssl_verify + self._aws_auth: Optional[httpx.Auth] = aws_auth + self._last_initialize_instructions: Optional[str] = None + # handle the basic auth value if provided + if auth_value: + self.update_auth_value(auth_value) + + def _create_transport_context( + self, + ) -> Tuple[Any, Optional[httpx.AsyncClient]]: + """ + Create the appropriate transport context based on transport type. + + Returns: + Tuple of (transport_context, http_client). + http_client is only set for HTTP transport and needs cleanup. + """ + http_client: Optional[httpx.AsyncClient] = None + + if self.transport_type == MCPTransport.stdio: + if not self.stdio_config: + raise ValueError("stdio_config is required for stdio transport") + server_params = StdioServerParameters( + command=self.stdio_config.get("command", ""), + args=self.stdio_config.get("args", []), + env=self.stdio_config.get("env", {}), + ) + return stdio_client(server_params), None + + if self.transport_type == MCPTransport.sse: + headers = self._get_auth_headers() + httpx_client_factory = self._create_httpx_client_factory() + return ( + sse_client( + url=self.server_url, + timeout=self.timeout, + headers=headers, + httpx_client_factory=httpx_client_factory, + ), + None, + ) + + # HTTP transport (default) + if streamable_http_client is None: + raise ImportError( + "streamable_http_client is not available. " + "Please install mcp with HTTP support." + ) + + headers = self._get_auth_headers() + httpx_client_factory = self._create_httpx_client_factory() + verbose_logger.debug("litellm headers for streamable_http_client: %s", headers) + http_client = httpx_client_factory( + headers=headers, + timeout=httpx.Timeout(self.timeout), + ) + transport_ctx = streamable_http_client( + url=self.server_url, + http_client=http_client, + ) + return transport_ctx, http_client + + async def _execute_session_operation( + self, + transport_ctx: Any, + operation: Callable[[ClientSession], Awaitable[TSessionResult]], + ) -> TSessionResult: + """ + Execute an operation within a transport and session context. + + Handles entering/exiting contexts and running the operation. + """ + transport = await transport_ctx.__aenter__() + try: + read_stream, write_stream = transport[0], transport[1] + session_ctx = ClientSession(read_stream, write_stream) + session = await session_ctx.__aenter__() + try: + init_result = await session.initialize() + self._last_initialize_instructions = None + if init_result is not None: + ins = getattr(init_result, "instructions", None) + if isinstance(ins, str) and ins.strip(): + self._last_initialize_instructions = ins.strip() + return await operation(session) + finally: + try: + await session_ctx.__aexit__(None, None, None) + except BaseException as e: + verbose_logger.debug(f"Error during session context exit: {e}") + finally: + try: + await transport_ctx.__aexit__(None, None, None) + except BaseException as e: + verbose_logger.debug(f"Error during transport context exit: {e}") + + async def run_with_session( + self, operation: Callable[[ClientSession], Awaitable[TSessionResult]] + ) -> TSessionResult: + """Open a session, run the provided coroutine, and clean up.""" + http_client: Optional[httpx.AsyncClient] = None + try: + self._last_initialize_instructions = None + transport_ctx, http_client = self._create_transport_context() + return await self._execute_session_operation(transport_ctx, operation) + except Exception: + verbose_logger.warning( + "MCP client run_with_session failed for %s", self.server_url or "stdio" + ) + raise + finally: + if http_client is not None: + try: + await http_client.aclose() + except BaseException as e: + verbose_logger.debug(f"Error during http_client cleanup: {e}") + + def update_auth_value(self, mcp_auth_value: Union[str, Dict[str, str]]): + """ + Set the authentication header for the MCP client. + """ + if isinstance(mcp_auth_value, dict): + self._mcp_auth_value = mcp_auth_value + else: + if self.auth_type == MCPAuth.basic: + # Assuming mcp_auth_value is in format "username:password", convert it when updating + mcp_auth_value = to_basic_auth(mcp_auth_value) + self._mcp_auth_value = mcp_auth_value + + def _get_auth_headers(self) -> dict: + """Generate authentication headers based on auth type.""" + headers = {} + + if self._mcp_auth_value: + if isinstance(self._mcp_auth_value, str): + if self.auth_type == MCPAuth.bearer_token: + headers["Authorization"] = f"Bearer {self._mcp_auth_value}" + elif self.auth_type == MCPAuth.basic: + headers["Authorization"] = f"Basic {self._mcp_auth_value}" + elif self.auth_type == MCPAuth.api_key: + headers["X-API-Key"] = self._mcp_auth_value + elif self.auth_type == MCPAuth.authorization: + headers["Authorization"] = self._mcp_auth_value + elif self.auth_type == MCPAuth.oauth2: + headers["Authorization"] = f"Bearer {self._mcp_auth_value}" + elif self.auth_type == MCPAuth.token: + headers["Authorization"] = f"token {self._mcp_auth_value}" + elif isinstance(self._mcp_auth_value, dict): + headers.update(self._mcp_auth_value) + # Note: aws_sigv4 auth is not handled here — SigV4 requires per-request + # signing (including the body hash), so it uses httpx.Auth flow instead + # of static headers. See MCPSigV4Auth and _create_httpx_client_factory(). + + # update the headers with the extra headers + if self.extra_headers: + headers.update(self.extra_headers) + + return headers + + def _create_httpx_client_factory(self) -> Callable[..., httpx.AsyncClient]: + """ + Create a custom httpx client factory that uses LiteLLM's SSL configuration. + + This factory follows the same CA bundle path logic as http_handler.py: + 1. Check ssl_verify parameter (can be SSLContext, bool, or path to CA bundle) + 2. Check SSL_VERIFY environment variable + 3. Check SSL_CERT_FILE environment variable + 4. Fall back to certifi CA bundle + """ + + def factory( + *, + headers: Optional[Dict[str, str]] = None, + timeout: Optional[httpx.Timeout] = None, + auth: Optional[httpx.Auth] = None, + ) -> httpx.AsyncClient: + """Create an httpx.AsyncClient with LiteLLM's SSL configuration.""" + # Get unified SSL configuration using the same logic as http_handler.py + ssl_config = get_ssl_configuration(self.ssl_verify) + + verbose_logger.debug( + f"MCP client using SSL configuration: {type(ssl_config).__name__}" + ) + + # Use SigV4 auth if configured and no explicit auth provided. + # The MCP SDK's sse_client and streamable_http_client call this + # factory without passing auth=, so self._aws_auth is used. + # For non-SigV4 clients, self._aws_auth is None — no behavior change. + effective_auth = auth if auth is not None else self._aws_auth + + return httpx.AsyncClient( + headers=headers, + timeout=timeout, + auth=effective_auth, + verify=ssl_config, + follow_redirects=True, + ) + + return factory + + async def list_tools(self) -> List[MCPTool]: + """List available tools from the server.""" + verbose_logger.debug( + f"MCP client listing tools from {self.server_url or 'stdio'}" + ) + + async def _list_tools_operation(session: ClientSession): + return await session.list_tools() + + try: + result = await self.run_with_session(_list_tools_operation) + tool_count = len(result.tools) + tool_names = [tool.name for tool in result.tools] + verbose_logger.info( + f"MCP client listed {tool_count} tools from {self.server_url or 'stdio'}: {tool_names}" + ) + return result.tools + except asyncio.CancelledError: + verbose_logger.warning("MCP client list_tools was cancelled") + raise + except Exception as e: + error_type = type(e).__name__ + verbose_logger.exception( + f"MCP client list_tools failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream during list_tools - " + "the MCP server may have crashed, disconnected, or timed out" + ) + + # Return empty list instead of raising to allow graceful degradation + return [] + + async def call_tool( + self, + call_tool_request_params: MCPCallToolRequestParams, + host_progress_callback: Optional[Callable] = None, + ) -> MCPCallToolResult: + """ + Call an MCP Tool. + """ + verbose_logger.info( + f"MCP client calling tool '{call_tool_request_params.name}' with arguments: {call_tool_request_params.arguments}" + ) + + async def on_progress( + progress: float, total: float | None, message: str | None + ): + percentage = (progress / total * 100) if total else 0 + verbose_logger.info( + f"MCP Tool '{call_tool_request_params.name}' progress: " + f"{progress}/{total} ({percentage:.0f}%) - {message or ''}" + ) + + # Forward to Host if callback provided + if host_progress_callback: + try: + await host_progress_callback(progress, total) + except Exception as e: + verbose_logger.warning(f"Failed to forward to Host: {e}") + + async def _call_tool_operation(session: ClientSession): + verbose_logger.debug("MCP client sending tool call to session") + return await session.call_tool( + name=call_tool_request_params.name, + arguments=call_tool_request_params.arguments, + progress_callback=on_progress, + ) + + try: + tool_result = await self.run_with_session(_call_tool_operation) + verbose_logger.info( + f"MCP client tool call '{call_tool_request_params.name}' completed successfully" + ) + return tool_result + except asyncio.CancelledError: + verbose_logger.warning("MCP client tool call was cancelled") + raise + except Exception as e: + import traceback + + error_trace = traceback.format_exc() + verbose_logger.debug(f"MCP client tool call traceback:\n{error_trace}") + + # Log detailed error information + error_type = type(e).__name__ + verbose_logger.error( + f"MCP client call_tool failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Tool: {call_tool_request_params.name}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream - " + "the MCP server may have crashed, disconnected, or timed out." + ) + + # Return a default error result instead of raising + return MCPCallToolResult( + content=[ + TextContent(type="text", text=f"{error_type}: {str(e)}") + ], # Empty content for error case + isError=True, + ) + + async def list_prompts(self) -> List[Prompt]: + """List available prompts from the server.""" + verbose_logger.debug( + f"MCP client listing tools from {self.server_url or 'stdio'}" + ) + + async def _list_prompts_operation(session: ClientSession): + return await session.list_prompts() + + try: + result = await self.run_with_session(_list_prompts_operation) + prompt_count = len(result.prompts) + prompt_names = [prompt.name for prompt in result.prompts] + verbose_logger.info( + f"MCP client listed {prompt_count} tools from {self.server_url or 'stdio'}: {prompt_names}" + ) + return result.prompts + except asyncio.CancelledError: + verbose_logger.warning("MCP client list_prompts was cancelled") + raise + except Exception as e: + error_type = type(e).__name__ + verbose_logger.error( + f"MCP client list_prompts failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream during list_tools - " + "the MCP server may have crashed, disconnected, or timed out" + ) + + # Return empty list instead of raising to allow graceful degradation + return [] + + async def get_prompt( + self, get_prompt_request_params: GetPromptRequestParams + ) -> GetPromptResult: + """Fetch a prompt definition from the MCP server.""" + verbose_logger.info( + f"MCP client fetching prompt '{get_prompt_request_params.name}' with arguments: {get_prompt_request_params.arguments}" + ) + + async def _get_prompt_operation(session: ClientSession): + verbose_logger.debug("MCP client sending get_prompt request to session") + return await session.get_prompt( + name=get_prompt_request_params.name, + arguments=get_prompt_request_params.arguments, + ) + + try: + get_prompt_result = await self.run_with_session(_get_prompt_operation) + verbose_logger.info( + f"MCP client get_prompt '{get_prompt_request_params.name}' completed successfully" + ) + return get_prompt_result + except asyncio.CancelledError: + verbose_logger.warning("MCP client get_prompt was cancelled") + raise + except Exception as e: + import traceback + + error_trace = traceback.format_exc() + verbose_logger.debug(f"MCP client get_prompt traceback:\n{error_trace}") + + # Log detailed error information + error_type = type(e).__name__ + verbose_logger.error( + f"MCP client get_prompt failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Prompt: {get_prompt_request_params.name}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream during get_prompt - " + "the MCP server may have crashed, disconnected, or timed out." + ) + + raise + + async def list_resources(self) -> list[Resource]: + """List available resources from the server.""" + verbose_logger.debug( + f"MCP client listing resources from {self.server_url or 'stdio'}" + ) + + async def _list_resources_operation(session: ClientSession): + return await session.list_resources() + + try: + result = await self.run_with_session(_list_resources_operation) + resource_count = len(result.resources) + resource_names = [resource.name for resource in result.resources] + verbose_logger.info( + f"MCP client listed {resource_count} resources from {self.server_url or 'stdio'}: {resource_names}" + ) + return result.resources + except asyncio.CancelledError: + verbose_logger.warning("MCP client list_resources was cancelled") + raise + except Exception as e: + error_type = type(e).__name__ + verbose_logger.error( + f"MCP client list_resources failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream during list_resources - " + "the MCP server may have crashed, disconnected, or timed out" + ) + + # Return empty list instead of raising to allow graceful degradation + return [] + + async def list_resource_templates(self) -> list[ResourceTemplate]: + """List available resource templates from the server.""" + verbose_logger.debug( + f"MCP client listing resource templates from {self.server_url or 'stdio'}" + ) + + async def _list_resource_templates_operation(session: ClientSession): + return await session.list_resource_templates() + + try: + result = await self.run_with_session(_list_resource_templates_operation) + resource_template_count = len(result.resourceTemplates) + resource_template_names = [ + resourceTemplate.name for resourceTemplate in result.resourceTemplates + ] + verbose_logger.info( + f"MCP client listed {resource_template_count} resource templates from {self.server_url or 'stdio'}: {resource_template_names}" + ) + return result.resourceTemplates + except asyncio.CancelledError: + verbose_logger.warning("MCP client list_resource_templates was cancelled") + raise + except Exception as e: + error_type = type(e).__name__ + verbose_logger.error( + f"MCP client list_resource_templates failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream during list_resource_templates - " + "the MCP server may have crashed, disconnected, or timed out" + ) + + # Return empty list instead of raising to allow graceful degradation + return [] + + async def read_resource(self, url: AnyUrl) -> ReadResourceResult: + """Fetch resource contents from the MCP server.""" + verbose_logger.info(f"MCP client fetching resource '{url}'") + + async def _read_resource_operation(session: ClientSession): + verbose_logger.debug("MCP client sending read_resource request to session") + return await session.read_resource(url) + + try: + read_resource_result = await self.run_with_session(_read_resource_operation) + verbose_logger.info( + f"MCP client read_resource '{url}' completed successfully" + ) + return read_resource_result + except asyncio.CancelledError: + verbose_logger.warning("MCP client read_resource was cancelled") + raise + except Exception as e: + import traceback + + error_trace = traceback.format_exc() + verbose_logger.debug(f"MCP client read_resource traceback:\n{error_trace}") + + # Log detailed error information + error_type = type(e).__name__ + verbose_logger.error( + f"MCP client read_resource failed - " + f"Error Type: {error_type}, " + f"Error: {str(e)}, " + f"Url: {url}, " + f"Server: {self.server_url or 'stdio'}, " + f"Transport: {self.transport_type}" + ) + + # Check if it's a stream/connection error + if "BrokenResourceError" in error_type or "Broken" in error_type: + verbose_logger.error( + "MCP client detected broken connection/stream during read_resource - " + "the MCP server may have crashed, disconnected, or timed out." + ) + + raise diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/tools.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/tools.py new file mode 100644 index 0000000000000000000000000000000000000000..bd42f7e7111618d097bc6d058af2bece8443663b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/experimental_mcp_client/tools.py @@ -0,0 +1,159 @@ +import json +from typing import Dict, List, Literal, Union + +from mcp import ClientSession +from mcp.types import CallToolRequestParams as MCPCallToolRequestParams +from mcp.types import CallToolResult as MCPCallToolResult +from mcp.types import Tool as MCPTool +from openai.types.chat import ChatCompletionToolParam +from openai.types.responses.function_tool_param import FunctionToolParam +from openai.types.shared_params.function_definition import FunctionDefinition + +from litellm.types.utils import ChatCompletionMessageToolCall + + +######################################################## +# List MCP Tool functions +######################################################## +def transform_mcp_tool_to_openai_tool(mcp_tool: MCPTool) -> ChatCompletionToolParam: + """Convert an MCP tool to an OpenAI tool.""" + normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema) + + return ChatCompletionToolParam( + type="function", + function=FunctionDefinition( + name=mcp_tool.name, + description=mcp_tool.description or "", + parameters=normalized_parameters, + strict=False, + ), + ) + + +def _normalize_mcp_input_schema(input_schema: dict) -> dict: + """ + Normalize MCP input schema to ensure it's valid for OpenAI function calling. + + OpenAI requires that function parameters have: + - type: 'object' + - properties: dict (can be empty) + - additionalProperties: false (recommended) + """ + if not input_schema: + return {"type": "object", "properties": {}, "additionalProperties": False} + + # Make a copy to avoid modifying the original + normalized_schema = dict(input_schema) + + # Ensure type is 'object' + if "type" not in normalized_schema: + normalized_schema["type"] = "object" + + # Ensure properties exists (can be empty) + if "properties" not in normalized_schema: + normalized_schema["properties"] = {} + + # Add additionalProperties if not present (recommended by OpenAI) + if "additionalProperties" not in normalized_schema: + normalized_schema["additionalProperties"] = False + + return normalized_schema + + +def transform_mcp_tool_to_openai_responses_api_tool( + mcp_tool: MCPTool, +) -> FunctionToolParam: + """Convert an MCP tool to an OpenAI Responses API tool.""" + normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema) + + return FunctionToolParam( + name=mcp_tool.name, + parameters=normalized_parameters, + strict=False, + type="function", + description=mcp_tool.description or "", + ) + + +async def load_mcp_tools( + session: ClientSession, format: Literal["mcp", "openai"] = "mcp" +) -> Union[List[MCPTool], List[ChatCompletionToolParam]]: + """ + Load all available MCP tools + + Args: + session: The MCP session to use + format: The format to convert the tools to + By default, the tools are returned in MCP format. + + If format is set to "openai", the tools are converted to OpenAI API compatible tools. + """ + tools = await session.list_tools() + if format == "openai": + return [ + transform_mcp_tool_to_openai_tool(mcp_tool=tool) for tool in tools.tools + ] + return tools.tools + + +######################################################## +# Call MCP Tool functions +######################################################## + + +async def call_mcp_tool( + session: ClientSession, + call_tool_request_params: MCPCallToolRequestParams, +) -> MCPCallToolResult: + """Call an MCP tool.""" + tool_result = await session.call_tool( + name=call_tool_request_params.name, + arguments=call_tool_request_params.arguments, + ) + return tool_result + + +def _get_function_arguments(function: FunctionDefinition) -> dict: + """Helper to safely get and parse function arguments.""" + arguments = function.get("arguments", {}) + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) + except json.JSONDecodeError: + arguments = {} + return arguments if isinstance(arguments, dict) else {} + + +def transform_openai_tool_call_request_to_mcp_tool_call_request( + openai_tool: Union[ChatCompletionMessageToolCall, Dict], +) -> MCPCallToolRequestParams: + """Convert an OpenAI ChatCompletionMessageToolCall to an MCP CallToolRequestParams.""" + function = openai_tool["function"] + return MCPCallToolRequestParams( + name=function["name"], + arguments=_get_function_arguments(function), + ) + + +async def call_openai_tool( + session: ClientSession, + openai_tool: ChatCompletionMessageToolCall, +) -> MCPCallToolResult: + """ + Call an OpenAI tool using MCP client. + + Args: + session: The MCP session to use + openai_tool: The OpenAI tool to call. You can get this from the `choices[0].message.tool_calls[0]` of the response from the OpenAI API. + Returns: + The result of the MCP tool call. + """ + mcp_tool_call_request_params = ( + transform_openai_tool_call_request_to_mcp_tool_call_request( + openai_tool=openai_tool, + ) + ) + return await call_mcp_tool( + session=session, + call_tool_request_params=mcp_tool_call_request_params, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/files/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/files/main.py new file mode 100644 index 0000000000000000000000000000000000000000..669d50dde4141434a658b4f3254be201ce6134fc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/files/main.py @@ -0,0 +1,1132 @@ +""" +Main File for Files API implementation + +https://platform.openai.com/docs/api-reference/files + +""" + +import asyncio +import contextvars +import time +import uuid as uuid_module +from functools import partial +from types import MappingProxyType +from typing import Any, Coroutine, Dict, Literal, Optional, Union, cast + +import httpx + +# Type aliases for provider parameters +FileCreateProvider = Literal[ + "openai", + "azure", + "gemini", + "vertex_ai", + "bedrock", + "hosted_vllm", + "manus", + "anthropic", +] +FileRetrieveProvider = Literal[ + "openai", "azure", "gemini", "vertex_ai", "hosted_vllm", "manus", "anthropic" +] +FileDeleteProvider = Literal["openai", "azure", "gemini", "manus", "anthropic"] +FileListProvider = Literal["openai", "azure", "manus", "anthropic"] +import litellm +from litellm import get_secret_str +from litellm.files.streaming import FileContentStreamingResponse +from litellm.files.types import FileContentProvider, FileContentStreamingResult +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.azure.common_utils import get_azure_credentials +from litellm.llms.azure.files.handler import AzureOpenAIFilesAPI +from litellm.llms.bedrock.files.handler import BedrockFilesHandler +from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.llms.openai.common_utils import get_openai_credentials +from litellm.llms.openai.openai import FileDeleted, FileObject, OpenAIFilesAPI +from litellm.llms.vertex_ai.files.handler import VertexAIFilesHandler +from litellm.types.llms.openai import ( + CreateFileRequest, + FileContentRequest, + FileExpiresAfter, + FileTypes, + HttpxBinaryResponseContent, + OpenAIFileObject, +) +from litellm.types.router import * +from litellm.types.utils import ( + OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS, + LlmProviders, +) +from litellm.utils import ( + ProviderConfigManager, + client, + get_litellm_params, + supports_httpx_timeout, +) + +base_llm_http_handler = BaseLLMHTTPHandler() + +####### ENVIRONMENT VARIABLES ################### + + +def _should_sdk_support_streaming( + custom_llm_provider: Optional[Union[FileContentProvider, str]], +) -> bool: + """ + Return whether file content streaming is supported for the provider. + """ + return custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS + + +openai_files_instance = OpenAIFilesAPI() +azure_files_instance = AzureOpenAIFilesAPI() +vertex_ai_files_instance = VertexAIFilesHandler() +bedrock_files_instance = BedrockFilesHandler() +################################################# + + +def _add_trusted_model_credentials_to_litellm_params( + litellm_params_dict: Dict[str, Any], kwargs: Dict[str, Any] +) -> None: + trusted_model_credentials = kwargs.get("_litellm_internal_model_credentials") + if isinstance(trusted_model_credentials, type(MappingProxyType({}))): + litellm_params_dict["_litellm_internal_model_credentials"] = ( + trusted_model_credentials + ) + + +@client +async def acreate_file( + file: FileTypes, + purpose: Literal["assistants", "batch", "fine-tune", "messages"], + expires_after: Optional[FileExpiresAfter] = None, + custom_llm_provider: FileCreateProvider = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> OpenAIFileObject: + """ + Async: Files are used to upload documents that can be used with features like Assistants, Fine-tuning, and Batch API. + + LiteLLM Equivalent of POST: POST https://api.openai.com/v1/files + """ + try: + loop = asyncio.get_event_loop() + kwargs["acreate_file"] = True + + call_args = { + "file": file, + "purpose": purpose, + "expires_after": expires_after, + "custom_llm_provider": custom_llm_provider, + "extra_headers": extra_headers, + "extra_body": extra_body, + **kwargs, + } + + # Use a partial function to pass your keyword arguments + func = partial(create_file, **call_args) + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + + return response + except Exception as e: + raise e + + +@client +def create_file( + file: FileTypes, + purpose: Literal["assistants", "batch", "fine-tune", "messages"], + expires_after: Optional[FileExpiresAfter] = None, + custom_llm_provider: Optional[FileCreateProvider] = None, + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> Union[OpenAIFileObject, Coroutine[Any, Any, OpenAIFileObject]]: + """ + Files are used to upload documents that can be used with features like Assistants, Fine-tuning, and Batch API. + + LiteLLM Equivalent of POST: POST https://api.openai.com/v1/files + + Specify either provider_list or custom_llm_provider. + """ + try: + _is_async = kwargs.pop("acreate_file", False) is True + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = dict(**kwargs) + logging_obj = cast( + Optional[LiteLLMLoggingObj], kwargs.get("litellm_logging_obj") + ) + if logging_obj is None: + raise ValueError("logging_obj is required") + client = kwargs.get("client") + + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(cast(str, custom_llm_provider)) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + if expires_after is not None: + _create_file_request = CreateFileRequest( + file=file, + purpose=purpose, + expires_after=expires_after, + extra_headers=extra_headers, + extra_body=extra_body, + ) + else: + _create_file_request = CreateFileRequest( + file=file, + purpose=purpose, + extra_headers=extra_headers, + extra_body=extra_body, + ) + + provider_config = ProviderConfigManager.get_provider_files_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + if provider_config is not None: + response = base_llm_http_handler.create_file( + provider_config=provider_config, + litellm_params=litellm_params_dict, + create_file_data=_create_file_request, + headers=extra_headers or {}, + api_base=optional_params.api_base, + api_key=optional_params.api_key, + logging_obj=logging_obj, + _is_async=_is_async, + client=( + client + if client is not None + and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) + else None + ), + timeout=timeout, + ) + elif custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS: + openai_creds = get_openai_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + organization=optional_params.organization, + ) + response = openai_files_instance.create_file( + _is_async=_is_async, + api_base=openai_creds.api_base, + api_key=openai_creds.api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=openai_creds.organization, + create_file_data=_create_file_request, + ) + elif custom_llm_provider == "azure": + azure_creds = get_azure_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + api_version=optional_params.api_version, + ) + response = azure_files_instance.create_file( + _is_async=_is_async, + api_base=azure_creds.api_base, + api_key=azure_creds.api_key, + api_version=azure_creds.api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + create_file_data=_create_file_request, + litellm_params=litellm_params_dict, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_file'. Only ['openai', 'azure', 'vertex_ai', 'manus', 'anthropic'] are supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_file", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + raise e + + +@client +async def afile_retrieve( + file_id: str, + custom_llm_provider: FileRetrieveProvider = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> OpenAIFileObject: + """ + Async: Get file contents + + LiteLLM Equivalent of GET https://api.openai.com/v1/files + """ + try: + loop = asyncio.get_event_loop() + kwargs["is_async"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + file_retrieve, + file_id, + custom_llm_provider, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + + return OpenAIFileObject(**response.model_dump()) + except Exception as e: + raise e + + +@client +def file_retrieve( + file_id: str, + custom_llm_provider: FileRetrieveProvider = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> FileObject: + """ + Returns the contents of the specified file. + + LiteLLM Equivalent of POST: POST https://api.openai.com/v1/files + """ + try: + optional_params = GenericLiteLLMParams(**kwargs) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + _is_async = kwargs.pop("is_async", False) is True + + if custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS: + openai_creds = get_openai_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + organization=optional_params.organization, + ) + response = openai_files_instance.retrieve_file( + file_id=file_id, + _is_async=_is_async, + api_base=openai_creds.api_base, + api_key=openai_creds.api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=openai_creds.organization, + ) + elif custom_llm_provider == "azure": + azure_creds = get_azure_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + api_version=optional_params.api_version, + ) + response = azure_files_instance.retrieve_file( + _is_async=_is_async, + api_base=azure_creds.api_base, + api_key=azure_creds.api_key, + api_version=azure_creds.api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + file_id=file_id, + ) + else: + # Try using provider config pattern (for Manus, Bedrock, etc.) + provider_config = ProviderConfigManager.get_provider_files_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + if provider_config is not None: + litellm_params_dict = get_litellm_params(**kwargs) + _add_trusted_model_credentials_to_litellm_params( + litellm_params_dict=litellm_params_dict, + kwargs=kwargs, + ) + litellm_params_dict["api_key"] = optional_params.api_key + litellm_params_dict["api_base"] = optional_params.api_base + + logging_obj = kwargs.get("litellm_logging_obj") + if logging_obj is None: + from litellm.litellm_core_utils.litellm_logging import ( + Logging as LiteLLMLoggingObj, + ) + + logging_obj = LiteLLMLoggingObj( + model="", + messages=[], + stream=False, + call_type="afile_retrieve" if _is_async else "file_retrieve", + start_time=time.time(), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), + function_id=str(kwargs.get("id") or ""), + ) + + client = kwargs.get("client") + response = base_llm_http_handler.retrieve_file( + file_id=file_id, + provider_config=provider_config, + litellm_params=litellm_params_dict, + headers=extra_headers or {}, + logging_obj=logging_obj, + _is_async=_is_async, + client=( + client + if client is not None + and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) + else None + ), + timeout=timeout, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'file_retrieve'. Only 'openai', 'azure', 'manus', and 'anthropic' are supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + + return cast(FileObject, response) + except Exception as e: + raise e + + +# Delete file +@client +async def afile_delete( + file_id: str, + custom_llm_provider: FileDeleteProvider = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> Coroutine[Any, Any, FileObject]: + """ + Async: Delete file + + LiteLLM Equivalent of DELETE https://api.openai.com/v1/files + """ + try: + loop = asyncio.get_event_loop() + model = kwargs.pop("model", None) + kwargs["is_async"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + file_delete, + file_id, + model, + custom_llm_provider, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + + return cast(FileDeleted, response) # type: ignore + except Exception as e: + raise e + + +@client +def file_delete( + file_id: str, + model: Optional[str] = None, + custom_llm_provider: Union[FileDeleteProvider, str] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> FileDeleted: + """ + Delete file + + LiteLLM Equivalent of DELETE https://api.openai.com/v1/files + """ + try: + try: + if model is not None: + _, custom_llm_provider, _, _ = get_llm_provider( + model, custom_llm_provider + ) + except Exception: + pass + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = get_litellm_params(**kwargs) + _add_trusted_model_credentials_to_litellm_params( + litellm_params_dict=litellm_params_dict, + kwargs=kwargs, + ) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + client = kwargs.get("client") + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + _is_async = kwargs.pop("is_async", False) is True + if custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS: + openai_creds = get_openai_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + organization=optional_params.organization, + ) + response = openai_files_instance.delete_file( + file_id=file_id, + _is_async=_is_async, + api_base=openai_creds.api_base, + api_key=openai_creds.api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=openai_creds.organization, + ) + elif custom_llm_provider == "azure": + azure_creds = get_azure_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + api_version=optional_params.api_version, + ) + response = azure_files_instance.delete_file( + _is_async=_is_async, + api_base=azure_creds.api_base, + api_key=azure_creds.api_key, + api_version=azure_creds.api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + file_id=file_id, + client=client, + litellm_params=litellm_params_dict, + ) + else: + # Try using provider config pattern (for Manus, Bedrock, etc.) + provider_config = ProviderConfigManager.get_provider_files_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + if provider_config is not None: + litellm_params_dict["api_key"] = optional_params.api_key + litellm_params_dict["api_base"] = optional_params.api_base + + logging_obj = kwargs.get("litellm_logging_obj") + if logging_obj is None: + from litellm.litellm_core_utils.litellm_logging import ( + Logging as LiteLLMLoggingObj, + ) + + logging_obj = LiteLLMLoggingObj( + model="", + messages=[], + stream=False, + call_type="afile_delete" if _is_async else "file_delete", + start_time=time.time(), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), + function_id=str(kwargs.get("id") or ""), + ) + + response = base_llm_http_handler.delete_file( + file_id=file_id, + provider_config=provider_config, + litellm_params=litellm_params_dict, + headers=extra_headers or {}, + logging_obj=logging_obj, + _is_async=_is_async, + client=( + client + if client is not None + and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) + else None + ), + timeout=timeout, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'file_delete'. Only 'openai', 'azure', 'gemini', 'manus', and 'anthropic' are supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return cast(FileDeleted, response) + except Exception as e: + raise e + + +# List files +@client +async def afile_list( + custom_llm_provider: FileListProvider = "openai", + purpose: Optional[str] = None, + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +): + """ + Async: List files + + LiteLLM Equivalent of GET https://api.openai.com/v1/files + """ + try: + loop = asyncio.get_event_loop() + kwargs["is_async"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + file_list, + custom_llm_provider, + purpose, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + + return response + except Exception as e: + raise e + + +@client +def file_list( + custom_llm_provider: FileListProvider = "openai", + purpose: Optional[str] = None, + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +): + """ + List files + + LiteLLM Equivalent of GET https://api.openai.com/v1/files + """ + try: + optional_params = GenericLiteLLMParams(**kwargs) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + _is_async = kwargs.pop("is_async", False) is True + + # Check if provider has a custom files config (e.g., Manus, Bedrock, Vertex AI) + provider_config = ProviderConfigManager.get_provider_files_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + if provider_config is not None: + litellm_params_dict = get_litellm_params(**kwargs) + litellm_params_dict["api_key"] = optional_params.api_key + litellm_params_dict["api_base"] = optional_params.api_base + + logging_obj = kwargs.get("litellm_logging_obj") + if logging_obj is None: + from litellm.litellm_core_utils.litellm_logging import ( + Logging as LiteLLMLoggingObj, + ) + + logging_obj = LiteLLMLoggingObj( + model="", + messages=[], + stream=False, + call_type="afile_list" if _is_async else "file_list", + start_time=time.time(), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), + function_id=str(kwargs.get("id", "")), + ) + + client = kwargs.get("client") + response = base_llm_http_handler.list_files( + purpose=purpose, + provider_config=provider_config, + litellm_params=litellm_params_dict, + headers=extra_headers or {}, + logging_obj=logging_obj, + _is_async=_is_async, + client=( + client + if client is not None + and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) + else None + ), + timeout=timeout, + ) + return response + elif custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS: + openai_creds = get_openai_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + organization=optional_params.organization, + ) + response = openai_files_instance.list_files( + purpose=purpose, + _is_async=_is_async, + api_base=openai_creds.api_base, + api_key=openai_creds.api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=openai_creds.organization, + ) + elif custom_llm_provider == "azure": + azure_creds = get_azure_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + api_version=optional_params.api_version, + ) + response = azure_files_instance.list_files( + _is_async=_is_async, + api_base=azure_creds.api_base, + api_key=azure_creds.api_key, + api_version=azure_creds.api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + purpose=purpose, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'file_list'. Only 'openai', 'azure', 'manus', and 'anthropic' are supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="file_list", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + raise e + + +@client +async def afile_content( + file_id: str, + custom_llm_provider: FileContentProvider = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + chunk_size: int = 1024 * 1024, + stream: bool = False, + **kwargs, +) -> Union[HttpxBinaryResponseContent, FileContentStreamingResult]: + """ + Async: Get file contents + + LiteLLM Equivalent of GET https://api.openai.com/v1/files + """ + try: + loop = asyncio.get_event_loop() + kwargs["afile_content"] = True + model = kwargs.pop("model", None) + + # Use a partial function to pass your keyword arguments + func = partial( + file_content, + file_id=file_id, + model=model, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + chunk_size=chunk_size, + stream=stream, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + + return response + except Exception as e: + raise e + + +@client +def file_content( + file_id: str, + model: Optional[str] = None, + custom_llm_provider: Optional[Union[FileContentProvider, str]] = None, + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + chunk_size: int = 1024 * 1024, + stream: bool = False, + **kwargs, +) -> Union[ + HttpxBinaryResponseContent, + FileContentStreamingResult, + Coroutine[Any, Any, HttpxBinaryResponseContent], + Coroutine[Any, Any, FileContentStreamingResult], +]: + """ + Returns the contents of the specified file. + + LiteLLM Equivalent of POST: POST https://api.openai.com/v1/files + """ + try: + optional_params = GenericLiteLLMParams(**kwargs) + litellm_params_dict = get_litellm_params(**kwargs) + _add_trusted_model_credentials_to_litellm_params( + litellm_params_dict=litellm_params_dict, + kwargs=kwargs, + ) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + client = kwargs.get("client") + # set timeout for 10 minutes by default + + try: + if model is not None: + _, custom_llm_provider, _, _ = get_llm_provider( + model, custom_llm_provider + ) + except Exception: + pass + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(cast(str, custom_llm_provider)) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + _file_content_request = FileContentRequest( + file_id=file_id, + extra_headers=extra_headers, + extra_body=extra_body, + ) + + _is_async = kwargs.pop("afile_content", False) is True + + if stream and _should_sdk_support_streaming(custom_llm_provider): + return file_content_streaming( + file_id=file_id, + model=model, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + chunk_size=chunk_size, + optional_params=optional_params, + timeout=timeout, + logging_obj=cast( + Optional[LiteLLMLoggingObj], kwargs.get("litellm_logging_obj") + ), + _is_async=_is_async, + client=client, + ) + + # Check if provider has a custom files config (e.g., Anthropic, Manus) + provider_config = ProviderConfigManager.get_provider_files_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + if provider_config is not None: + litellm_params_dict["api_key"] = optional_params.api_key + litellm_params_dict["api_base"] = optional_params.api_base + + logging_obj = kwargs.get("litellm_logging_obj") + if logging_obj is None: + logging_obj = LiteLLMLoggingObj( + model="", + messages=[], + stream=False, + call_type="afile_content" if _is_async else "file_content", + start_time=time.time(), + litellm_call_id=kwargs.get( + "litellm_call_id", str(uuid_module.uuid4()) + ), + function_id=str(kwargs.get("id") or ""), + ) + + response = base_llm_http_handler.retrieve_file_content( + file_content_request=_file_content_request, + provider_config=provider_config, + litellm_params=litellm_params_dict, + headers=extra_headers or {}, + logging_obj=logging_obj, + _is_async=_is_async, + client=( + client + if client is not None + and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) + else None + ), + timeout=timeout, + ) + return response + + if custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS: + openai_creds = get_openai_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + organization=optional_params.organization, + ) + response = openai_files_instance.file_content( + _is_async=_is_async, + file_content_request=_file_content_request, + api_base=openai_creds.api_base, + api_key=openai_creds.api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=openai_creds.organization, + ) + elif custom_llm_provider == "azure": + azure_creds = get_azure_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + api_version=optional_params.api_version, + ) + response = azure_files_instance.file_content( + _is_async=_is_async, + api_base=azure_creds.api_base, + api_key=azure_creds.api_key, + api_version=azure_creds.api_version, + timeout=timeout, + max_retries=optional_params.max_retries, + file_content_request=_file_content_request, + client=client, + litellm_params=litellm_params_dict, + ) + elif custom_llm_provider == "vertex_ai": + api_base = optional_params.api_base or "" + vertex_ai_project = ( + optional_params.vertex_project + or litellm.vertex_project + or get_secret_str("VERTEXAI_PROJECT") + ) + vertex_ai_location = ( + optional_params.vertex_location + or litellm.vertex_location + or get_secret_str("VERTEXAI_LOCATION") + ) + vertex_credentials = optional_params.vertex_credentials or get_secret_str( + "VERTEXAI_CREDENTIALS" + ) + + response = vertex_ai_files_instance.file_content( + _is_async=_is_async, + file_content_request=_file_content_request, + api_base=api_base, + vertex_credentials=vertex_credentials, + vertex_project=vertex_ai_project, + vertex_location=vertex_ai_location, + timeout=timeout, + max_retries=optional_params.max_retries, + litellm_params=litellm_params_dict, + ) + elif custom_llm_provider == "bedrock": + response = bedrock_files_instance.file_content( + _is_async=_is_async, + file_content_request=_file_content_request, + api_base=optional_params.api_base, + optional_params=litellm_params_dict, + timeout=timeout, + max_retries=optional_params.max_retries, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'file_content'. Supported providers are 'openai', 'azure', 'vertex_ai', 'bedrock', 'manus', 'anthropic'.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + raise e + + +def file_content_streaming( + *, + file_id: str, + model: Optional[str], + custom_llm_provider: Optional[Union[FileContentProvider, str]], + extra_headers: Optional[Dict[str, str]], + extra_body: Optional[Dict[str, str]], + chunk_size: int, + optional_params: GenericLiteLLMParams, + timeout: Union[float, httpx.Timeout], + logging_obj: Optional[LiteLLMLoggingObj], + _is_async: bool, + client: Optional[Any], +) -> Union[FileContentStreamingResult, Coroutine[Any, Any, FileContentStreamingResult]]: + if logging_obj is not None: + logging_obj.model = model or "" + logging_obj.model_call_details["model"] = model or "" + logging_obj.model_call_details["custom_llm_provider"] = custom_llm_provider + + litellm_params = logging_obj.model_call_details.get("litellm_params", {}) or {} + if optional_params.api_base is not None: + litellm_params["api_base"] = optional_params.api_base + logging_obj.model_call_details["litellm_params"] = litellm_params + + def _wrap_streaming_result( + response: FileContentStreamingResult, + ) -> FileContentStreamingResult: + return FileContentStreamingResult( + stream_iterator=FileContentStreamingResponse( + stream_iterator=response.stream_iterator, + file_id=file_id, + model=model, + custom_llm_provider=custom_llm_provider, + logging_obj=logging_obj, + ), + headers=response.headers, + ) + + response: Union[ + FileContentStreamingResult, Coroutine[Any, Any, FileContentStreamingResult] + ] = FileContentStreamingResult(stream_iterator=iter(()), headers={}) + if custom_llm_provider in OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS: + openai_creds = get_openai_credentials( + api_base=optional_params.api_base, + api_key=optional_params.api_key, + organization=optional_params.organization, + ) + response = openai_files_instance.file_content_streaming( + _is_async=_is_async, + file_content_request=FileContentRequest( + file_id=file_id, + extra_headers=extra_headers, + extra_body=extra_body, + ), + api_base=openai_creds.api_base, + api_key=openai_creds.api_key, + timeout=timeout, + max_retries=optional_params.max_retries, + organization=openai_creds.organization, + chunk_size=chunk_size, + client=client, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for streaming 'file_content'. Supported providers are {}.".format( + custom_llm_provider, + sorted(OPENAI_COMPATIBLE_BATCH_AND_FILES_PROVIDERS), + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + + if asyncio.iscoroutine(response): + + async def _await_and_wrap() -> FileContentStreamingResult: + return _wrap_streaming_result(await response) + + return _await_and_wrap() + + return _wrap_streaming_result(response) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/files/types.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/files/types.py new file mode 100644 index 0000000000000000000000000000000000000000..688bc86f0cfb0a4a5f84f93f0c680bc5d6e943fe --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/files/types.py @@ -0,0 +1,11 @@ +from typing import AsyncIterator, Dict, Iterator, Literal, NamedTuple, Union + + +FileContentProvider = Literal[ + "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic", "manus" +] + + +class FileContentStreamingResult(NamedTuple): + stream_iterator: Union[Iterator[bytes], AsyncIterator[bytes]] + headers: Dict[str, str] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/fine_tuning/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/fine_tuning/main.py new file mode 100644 index 0000000000000000000000000000000000000000..08373cda782a4058671650f9fe8a3f8ee1621888 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/fine_tuning/main.py @@ -0,0 +1,826 @@ +""" +Main File for Fine Tuning API implementation + +https://platform.openai.com/docs/api-reference/fine-tuning + +- fine_tuning.jobs.create() +- fine_tuning.jobs.list() +- client.fine_tuning.jobs.list_events() +""" + +import asyncio +import contextvars +import os +from functools import partial +from typing import Any, Coroutine, Dict, Literal, Optional, Union + +import httpx + +import litellm +from litellm._logging import verbose_logger +from litellm.llms.azure.fine_tuning.handler import AzureOpenAIFineTuningAPI +from litellm.llms.openai.fine_tuning.handler import OpenAIFineTuningAPI +from litellm.llms.vertex_ai.fine_tuning.handler import VertexFineTuningAPI +from litellm.secret_managers.main import get_secret_str +from litellm.types.llms.openai import FineTuningJobCreate, Hyperparameters +from litellm.types.router import * +from litellm.types.utils import LiteLLMFineTuningJob +from litellm.utils import client, supports_httpx_timeout + +####### ENVIRONMENT VARIABLES ################### +openai_fine_tuning_apis_instance = OpenAIFineTuningAPI() +azure_fine_tuning_apis_instance = AzureOpenAIFineTuningAPI() +vertex_fine_tuning_apis_instance = VertexFineTuningAPI() +################################################# + + +def _prepare_azure_extra_body( + extra_body: Optional[Dict[str, Any]], + kwargs: Dict[str, Any], + azure_specific_hyperparams: Dict[str, Any], +) -> Dict[str, Any]: + """ + Prepare extra_body for Azure fine-tuning API by combining Azure-specific parameters. + + Azure fine-tuning API accepts additional parameters beyond the standard OpenAI spec: + - trainingType: Type of training (e.g., 1 for supervised fine-tuning) + - prompt_loss_weight: Weight for prompt loss in training + + These parameters must be passed in the extra_body field when calling the Azure OpenAI SDK. + + Args: + extra_body: Optional existing extra_body dict + kwargs: Request kwargs that may contain Azure-specific parameters + azure_specific_hyperparams: Dict of Azure-specific hyperparameters already extracted + + Returns: + Dict containing all Azure-specific parameters to be passed in extra_body + """ + if extra_body is None: + extra_body = {} + + # Azure-specific root-level parameters + azure_specific_params = ["trainingType"] + for param in azure_specific_params: + if param in kwargs: + extra_body[param] = kwargs[param] + + # Add Azure-specific hyperparameters + if azure_specific_hyperparams: + extra_body.update(azure_specific_hyperparams) + + return extra_body + + +@client +async def acreate_fine_tuning_job( + model: str, + training_file: str, + hyperparameters: Optional[dict] = {}, + suffix: Optional[str] = None, + validation_file: Optional[str] = None, + integrations: Optional[List[str]] = None, + seed: Optional[int] = None, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> LiteLLMFineTuningJob: + """ + Async: Creates and executes a batch from an uploaded file of request + + """ + verbose_logger.debug( + "inside acreate_fine_tuning_job model=%s and kwargs=%s", model, kwargs + ) + try: + loop = asyncio.get_event_loop() + kwargs["acreate_fine_tuning_job"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + create_fine_tuning_job, + model, + training_file, + hyperparameters, + suffix, + validation_file, + integrations, + seed, + custom_llm_provider, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + return response + except Exception as e: + raise e + + +def _build_fine_tuning_job_data( + model, training_file, hyperparameters, suffix, validation_file, integrations, seed +): + return FineTuningJobCreate( + model=model, + training_file=training_file, + hyperparameters=hyperparameters, + suffix=suffix, + validation_file=validation_file, + integrations=integrations, + seed=seed, + ) + + +def _resolve_fine_tuning_timeout( + timeout: Any, + custom_llm_provider: str, +) -> Union[float, httpx.Timeout]: + """Normalise a raw timeout value to a float (seconds) or httpx.Timeout for fine-tuning calls.""" + timeout = timeout or 600.0 + if isinstance(timeout, httpx.Timeout): + if not supports_httpx_timeout(custom_llm_provider): + return float(timeout.read or 600) + return timeout + return float(timeout) + + +@client +def create_fine_tuning_job( + model: str, + training_file: str, + hyperparameters: Optional[dict] = {}, + suffix: Optional[str] = None, + validation_file: Optional[str] = None, + integrations: Optional[List[str]] = None, + seed: Optional[int] = None, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: + """ + Creates a fine-tuning job which begins the process of creating a new model from a given dataset. + + Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete + + """ + try: + _is_async = kwargs.pop("acreate_fine_tuning_job", False) is True + optional_params = GenericLiteLLMParams(**kwargs) + + # handle hyperparameters + hyperparameters = hyperparameters or {} # original hyperparameters + + # For Azure, extract Azure-specific hyperparameters before creating OpenAI-spec hyperparameters + azure_specific_hyperparams = {} + if custom_llm_provider == "azure": + azure_hyperparameter_keys = ["prompt_loss_weight"] + for key in azure_hyperparameter_keys: + if key in hyperparameters: + azure_specific_hyperparams[key] = hyperparameters.pop(key) + + _oai_hyperparameters: Hyperparameters = Hyperparameters( + **hyperparameters + ) # Typed Hyperparameters for OpenAI Spec + timeout = _resolve_fine_tuning_timeout( + optional_params.timeout or kwargs.get("request_timeout", 600), + custom_llm_provider, + ) + + # OpenAI + if custom_llm_provider == "openai": + # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + api_base = ( + optional_params.api_base + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + create_fine_tuning_job_data_dict = _build_fine_tuning_job_data( + model, + training_file, + _oai_hyperparameters, + suffix, + validation_file, + integrations, + seed, + ).model_dump(exclude_none=True) + + response = openai_fine_tuning_apis_instance.create_fine_tuning_job( + api_base=api_base, + api_key=api_key, + api_version=optional_params.api_version, + organization=organization, + create_fine_tuning_job_data=create_fine_tuning_job_data_dict, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + client=kwargs.get( + "client", None + ), # note, when we add this to `GenericLiteLLMParams` it impacts a lot of other tests + linting + ) + # Azure OpenAI + elif custom_llm_provider == "azure": + api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret_str("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret_str("AZURE_OPENAI_API_KEY") + or get_secret_str("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + if extra_body is not None: + extra_body.pop("azure_ad_token", None) + else: + get_secret_str("AZURE_AD_TOKEN") # type: ignore + + # Prepare Azure-specific parameters for extra_body + extra_body = _prepare_azure_extra_body( + extra_body, kwargs, azure_specific_hyperparams + ) + + create_fine_tuning_job_data_dict = _build_fine_tuning_job_data( + model, + training_file, + _oai_hyperparameters, + suffix, + validation_file, + integrations, + seed, + ).model_dump(exclude_none=True) + + # Add extra_body if it has Azure-specific parameters + if extra_body: + create_fine_tuning_job_data_dict["extra_body"] = extra_body + + response = azure_fine_tuning_apis_instance.create_fine_tuning_job( + api_base=api_base, + api_key=api_key, + api_version=api_version, + create_fine_tuning_job_data=create_fine_tuning_job_data_dict, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + organization=optional_params.organization, + ) + elif custom_llm_provider == "vertex_ai": + api_base = optional_params.api_base or "" + vertex_ai_project = ( + optional_params.vertex_project + or litellm.vertex_project + or get_secret_str("VERTEXAI_PROJECT") + ) + vertex_ai_location = ( + optional_params.vertex_location + or litellm.vertex_location + or get_secret_str("VERTEXAI_LOCATION") + ) + vertex_credentials = optional_params.vertex_credentials or get_secret_str( + "VERTEXAI_CREDENTIALS" + ) + response = vertex_fine_tuning_apis_instance.create_fine_tuning_job( + _is_async=_is_async, + create_fine_tuning_job_data=_build_fine_tuning_job_data( + model, + training_file, + _oai_hyperparameters, + suffix, + validation_file, + integrations, + seed, + ), + vertex_credentials=vertex_credentials, + vertex_project=vertex_ai_project, + vertex_location=vertex_ai_location, + timeout=timeout, + api_base=api_base, + kwargs=kwargs, + original_hyperparameters=hyperparameters, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_batch'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + verbose_logger.error("got exception in create_fine_tuning_job=%s", str(e)) + raise e + + +@client +async def acancel_fine_tuning_job( + fine_tuning_job_id: str, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> LiteLLMFineTuningJob: + """ + Async: Immediately cancel a fine-tune job. + """ + try: + loop = asyncio.get_event_loop() + kwargs["acancel_fine_tuning_job"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + cancel_fine_tuning_job, + fine_tuning_job_id, + custom_llm_provider, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + return response + except Exception as e: + raise e + + +@client +def cancel_fine_tuning_job( + fine_tuning_job_id: str, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: + """ + Immediately cancel a fine-tune job. + + Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete + + """ + try: + optional_params = GenericLiteLLMParams(**kwargs) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + _is_async = kwargs.pop("acancel_fine_tuning_job", False) is True + + # OpenAI + if custom_llm_provider == "openai": + # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + api_base = ( + optional_params.api_base + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_fine_tuning_apis_instance.cancel_fine_tuning_job( + api_base=api_base, + api_key=api_key, + api_version=optional_params.api_version, + organization=organization, + fine_tuning_job_id=fine_tuning_job_id, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + client=kwargs.get("client", None), + ) + # Azure OpenAI + elif custom_llm_provider == "azure": + api_base = optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret_str("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret_str("AZURE_OPENAI_API_KEY") + or get_secret_str("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + if extra_body is not None: + extra_body.pop("azure_ad_token", None) + else: + get_secret_str("AZURE_AD_TOKEN") # type: ignore + + response = azure_fine_tuning_apis_instance.cancel_fine_tuning_job( + api_base=api_base, + api_key=api_key, + api_version=api_version, + fine_tuning_job_id=fine_tuning_job_id, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + organization=optional_params.organization, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_batch'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + raise e + + +async def alist_fine_tuning_jobs( + after: Optional[str] = None, + limit: Optional[int] = None, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +): + """ + Async: List your organization's fine-tuning jobs + """ + try: + loop = asyncio.get_event_loop() + kwargs["alist_fine_tuning_jobs"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + list_fine_tuning_jobs, + after, + limit, + custom_llm_provider, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + return response + except Exception as e: + raise e + + +def list_fine_tuning_jobs( + after: Optional[str] = None, + limit: Optional[int] = None, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +): + """ + List your organization's fine-tuning jobs + + Params: + + - after: Optional[str] = None, Identifier for the last job from the previous pagination request. + - limit: Optional[int] = None, Number of fine-tuning jobs to retrieve. Defaults to 20 + """ + try: + optional_params = GenericLiteLLMParams(**kwargs) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + _is_async = kwargs.pop("alist_fine_tuning_jobs", False) is True + + # OpenAI + if custom_llm_provider == "openai": + # for deepinfra/perplexity/anyscale/groq we check in get_llm_provider and pass in the api base from there + api_base = ( + optional_params.api_base + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 + ) + # set API KEY + api_key = ( + optional_params.api_key + or litellm.api_key # for deepinfra/perplexity/anyscale we check in get_llm_provider and pass in the api key from there + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_fine_tuning_apis_instance.list_fine_tuning_jobs( + api_base=api_base, + api_key=api_key, + api_version=optional_params.api_version, + organization=organization, + after=after, + limit=limit, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + client=kwargs.get("client", None), + ) + # Azure OpenAI + elif custom_llm_provider == "azure": + api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret_str("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret_str("AZURE_OPENAI_API_KEY") + or get_secret_str("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + if extra_body is not None: + extra_body.pop("azure_ad_token", None) + else: + get_secret("AZURE_AD_TOKEN") # type: ignore + + response = azure_fine_tuning_apis_instance.list_fine_tuning_jobs( + api_base=api_base, + api_key=api_key, + api_version=api_version, + after=after, + limit=limit, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + organization=optional_params.organization, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'create_batch'. Only 'openai' is supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + raise e + + +@client +async def aretrieve_fine_tuning_job( + fine_tuning_job_id: str, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> LiteLLMFineTuningJob: + """ + Async: Get info about a fine-tuning job. + """ + try: + loop = asyncio.get_event_loop() + kwargs["aretrieve_fine_tuning_job"] = True + + # Use a partial function to pass your keyword arguments + func = partial( + retrieve_fine_tuning_job, + fine_tuning_job_id, + custom_llm_provider, + extra_headers, + extra_body, + **kwargs, + ) + + # Add the context to the function + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response # type: ignore + return response + except Exception as e: + raise e + + +@client +def retrieve_fine_tuning_job( + fine_tuning_job_id: str, + custom_llm_provider: Literal["openai", "azure", "vertex_ai"] = "openai", + extra_headers: Optional[Dict[str, str]] = None, + extra_body: Optional[Dict[str, str]] = None, + **kwargs, +) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: + """ + Get info about a fine-tuning job. + """ + try: + optional_params = GenericLiteLLMParams(**kwargs) + ### TIMEOUT LOGIC ### + timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 + # set timeout for 10 minutes by default + + if ( + timeout is not None + and isinstance(timeout, httpx.Timeout) + and supports_httpx_timeout(custom_llm_provider) is False + ): + read_timeout = timeout.read or 600 + timeout = read_timeout # default 10 min timeout + elif timeout is not None and not isinstance(timeout, httpx.Timeout): + timeout = float(timeout) # type: ignore + elif timeout is None: + timeout = 600.0 + + _is_async = kwargs.pop("aretrieve_fine_tuning_job", False) is True + + # OpenAI + if custom_llm_provider == "openai": + api_base = ( + optional_params.api_base + or litellm.api_base + or os.getenv("OPENAI_BASE_URL") + or os.getenv("OPENAI_API_BASE") + or "https://api.openai.com/v1" + ) + organization = ( + optional_params.organization + or litellm.organization + or os.getenv("OPENAI_ORGANIZATION", None) + or None + ) + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.openai_key + or os.getenv("OPENAI_API_KEY") + ) + + response = openai_fine_tuning_apis_instance.retrieve_fine_tuning_job( + api_base=api_base, + api_key=api_key, + api_version=optional_params.api_version, + organization=organization, + fine_tuning_job_id=fine_tuning_job_id, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + client=kwargs.get("client", None), + ) + # Azure OpenAI + elif custom_llm_provider == "azure": + api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") # type: ignore + + api_version = ( + optional_params.api_version + or litellm.api_version + or get_secret_str("AZURE_API_VERSION") + ) # type: ignore + + api_key = ( + optional_params.api_key + or litellm.api_key + or litellm.azure_key + or get_secret_str("AZURE_OPENAI_API_KEY") + or get_secret_str("AZURE_API_KEY") + ) # type: ignore + + extra_body = optional_params.get("extra_body", {}) + if extra_body is not None: + extra_body.pop("azure_ad_token", None) + else: + get_secret_str("AZURE_AD_TOKEN") # type: ignore + + response = azure_fine_tuning_apis_instance.retrieve_fine_tuning_job( + api_base=api_base, + api_key=api_key, + api_version=api_version, + fine_tuning_job_id=fine_tuning_job_id, + timeout=timeout, + max_retries=optional_params.max_retries, + _is_async=_is_async, + organization=optional_params.organization, + ) + else: + raise litellm.exceptions.BadRequestError( + message="LiteLLM doesn't support {} for 'retrieve_fine_tuning_job'. Only 'openai' and 'azure' are supported.".format( + custom_llm_provider + ), + model="n/a", + llm_provider=custom_llm_provider, + response=httpx.Response( + status_code=400, + content="Unsupported provider", + request=httpx.Request(method="retrieve_fine_tuning_job", url="https://github.com/BerriAI/litellm"), # type: ignore + ), + ) + return response + except Exception as e: + raise e diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/Readme.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2c18292652d7d0d0ae0b28f29bee2b142cf3a454 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/Readme.md @@ -0,0 +1,123 @@ +# LiteLLM Google GenAI Interface + +Interface to interact with Google GenAI Functions in the native Google interface format. + +## Overview + +This module provides a native interface to Google's Generative AI API, allowing you to use Google's content generation capabilities with both streaming and non-streaming modes, in both synchronous and asynchronous contexts. + +## Available Functions + +### Non-Streaming Functions + +- `generate_content()` - Synchronous content generation +- `agenerate_content()` - Asynchronous content generation + +### Streaming Functions + +- `generate_content_stream()` - Synchronous streaming content generation +- `agenerate_content_stream()` - Asynchronous streaming content generation + +## Usage Examples + +### Basic Non-Streaming Usage + +```python +from litellm.google_genai import generate_content, agenerate_content +from google.genai.types import ContentDict, PartDict + +# Synchronous usage +contents = ContentDict( + parts=[ + PartDict(text="Hello, can you tell me a short joke?") + ], +) + +response = generate_content( + contents=contents, + model="gemini-pro", # or your preferred model + # Add other model-specific parameters as needed +) + +print(response) +``` + +### Async Non-Streaming Usage + +```python +import asyncio +from litellm.google_genai import agenerate_content +from google.genai.types import ContentDict, PartDict + +async def main(): + contents = ContentDict( + parts=[ + PartDict(text="Hello, can you tell me a short joke?") + ], + ) + + response = await agenerate_content( + contents=contents, + model="gemini-pro", + # Add other model-specific parameters as needed + ) + + print(response) + +# Run the async function +asyncio.run(main()) +``` + +### Streaming Usage + +```python +from litellm.google_genai import generate_content_stream +from google.genai.types import ContentDict, PartDict + +# Synchronous streaming +contents = ContentDict( + parts=[ + PartDict(text="Tell me a story about space exploration") + ], +) + +for chunk in generate_content_stream( + contents=contents, + model="gemini-pro", +): + print(f"Chunk: {chunk}") +``` + +### Async Streaming Usage + +```python +import asyncio +from litellm.google_genai import agenerate_content_stream +from google.genai.types import ContentDict, PartDict + +async def main(): + contents = ContentDict( + parts=[ + PartDict(text="Tell me a story about space exploration") + ], + ) + + async for chunk in agenerate_content_stream( + contents=contents, + model="gemini-pro", + ): + print(f"Async chunk: {chunk}") + +asyncio.run(main()) +``` + + +## Testing + +This module includes comprehensive tests covering: +- Sync and async non-streaming requests +- Sync and async streaming requests +- Response validation +- Error handling scenarios + +See `tests/unified_google_tests/base_google_test.py` for test implementation examples. \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca7b547c440772c8d4d289cd90c289146b0cff59 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/__init__.py @@ -0,0 +1,19 @@ +""" +This allows using Google GenAI model in their native interface. + +This module provides generate_content functionality for Google GenAI models. +""" + +from .main import ( + agenerate_content, + agenerate_content_stream, + generate_content, + generate_content_stream, +) + +__all__ = [ + "generate_content", + "agenerate_content", + "generate_content_stream", + "agenerate_content_stream", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/main.py new file mode 100644 index 0000000000000000000000000000000000000000..bdbb483dcf61d9aaffceef718834b776b74b5ef6 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/main.py @@ -0,0 +1,549 @@ +import asyncio +import contextvars +from functools import partial +from typing import TYPE_CHECKING, Any, ClassVar, Dict, Iterator, Optional, Union + +import httpx +from pydantic import BaseModel, ConfigDict + +import litellm +from litellm.constants import request_timeout + +# Import the adapter for fallback to completion format +from litellm.google_genai.adapters.handler import GenerateContentToCompletionHandler +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.google_genai.transformation import ( + BaseGoogleGenAIGenerateContentConfig, +) +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.types.router import GenericLiteLLMParams +from litellm.utils import ProviderConfigManager, client + +if TYPE_CHECKING: + from litellm.types.google_genai.main import ( + GenerateContentConfigDict, + GenerateContentContentListUnionDict, + GenerateContentResponse, + ToolConfigDict, + ) +else: + GenerateContentConfigDict = Any + GenerateContentContentListUnionDict = Any + GenerateContentResponse = Any + ToolConfigDict = Any + + +####### ENVIRONMENT VARIABLES ################### +# Initialize any necessary instances or variables here +base_llm_http_handler = BaseLLMHTTPHandler() +################################################# + + +class GenerateContentSetupResult(BaseModel): + """Internal Type - Result of setting up a generate content call""" + + model_config: ClassVar[ConfigDict] = ConfigDict(arbitrary_types_allowed=True) + + model: str + request_body: Dict[str, Any] + custom_llm_provider: str + generate_content_provider_config: Optional[BaseGoogleGenAIGenerateContentConfig] + generate_content_config_dict: Dict[str, Any] + litellm_params: GenericLiteLLMParams + litellm_logging_obj: LiteLLMLoggingObj + litellm_call_id: Optional[str] + + +class GenerateContentHelper: + """Helper class for Google GenAI generate content operations""" + + @staticmethod + def mock_generate_content_response( + mock_response: str = "This is a mock response from Google GenAI generate_content.", + ) -> Dict[str, Any]: + """Mock response for generate_content for testing purposes""" + return { + "text": mock_response, + "candidates": [ + { + "content": {"parts": [{"text": mock_response}], "role": "model"}, + "finishReason": "STOP", + "index": 0, + "safetyRatings": [], + } + ], + "usageMetadata": { + "promptTokenCount": 10, + "candidatesTokenCount": 20, + "totalTokenCount": 30, + }, + } + + @staticmethod + def setup_generate_content_call( + model: str, + contents: GenerateContentContentListUnionDict, + config: Optional[GenerateContentConfigDict] = None, + custom_llm_provider: Optional[str] = None, + tools: Optional[ToolConfigDict] = None, + **kwargs, + ) -> GenerateContentSetupResult: + """ + Common setup logic for generate_content calls + + Args: + model: The model name + contents: The content to generate from + config: Optional configuration + custom_llm_provider: Optional custom LLM provider + tools: Optional tools + **kwargs: Additional keyword arguments + + Returns: + GenerateContentSetupResult containing all setup information + """ + litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get( + "litellm_logging_obj" + ) + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + + # get llm provider logic + litellm_params = GenericLiteLLMParams(**kwargs) + + ## MOCK RESPONSE LOGIC (only for non-streaming) + if ( + not kwargs.get("stream", False) + and litellm_params.mock_response + and isinstance(litellm_params.mock_response, str) + ): + raise ValueError("Mock response should be handled by caller") + + ( + model, + custom_llm_provider, + dynamic_api_key, + dynamic_api_base, + ) = litellm.get_llm_provider( + model=model, + custom_llm_provider=custom_llm_provider, + api_base=litellm_params.api_base, + api_key=litellm_params.api_key, + ) + + if litellm_params.custom_llm_provider is None: + litellm_params.custom_llm_provider = custom_llm_provider + + # get provider config + generate_content_provider_config: Optional[ + BaseGoogleGenAIGenerateContentConfig + ] = ProviderConfigManager.get_provider_google_genai_generate_content_config( + model=model, + provider=litellm.LlmProviders(custom_llm_provider), + ) + + if generate_content_provider_config is None: + # Use adapter to transform to completion format when provider config is None + # Signal that we should use the adapter by returning special result + if litellm_logging_obj is None: + raise ValueError("litellm_logging_obj is required, but got None") + return GenerateContentSetupResult( + model=model, + custom_llm_provider=custom_llm_provider, + request_body={}, # Will be handled by adapter + generate_content_provider_config=None, # type: ignore + generate_content_config_dict=dict(config or {}), + litellm_params=litellm_params, + litellm_logging_obj=litellm_logging_obj, + litellm_call_id=litellm_call_id, + ) + + ######################################################################################### + # Construct request body + ######################################################################################### + # Create Google Optional Params Config + generate_content_config_dict = ( + generate_content_provider_config.map_generate_content_optional_params( + generate_content_config_dict=config or {}, + model=model, + ) + ) + # Extract systemInstruction from kwargs to pass to transform + system_instruction = kwargs.get("systemInstruction") or kwargs.get( + "system_instruction" + ) + request_body = ( + generate_content_provider_config.transform_generate_content_request( + model=model, + contents=contents, + tools=tools, + generate_content_config_dict=generate_content_config_dict, + system_instruction=system_instruction, + ) + ) + + # Pre Call logging + if litellm_logging_obj is None: + raise ValueError("litellm_logging_obj is required, but got None") + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=model, + optional_params=dict(generate_content_config_dict), + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + return GenerateContentSetupResult( + model=model, + custom_llm_provider=custom_llm_provider, + request_body=request_body, + generate_content_provider_config=generate_content_provider_config, + generate_content_config_dict=generate_content_config_dict, + litellm_params=litellm_params, + litellm_logging_obj=litellm_logging_obj, + litellm_call_id=litellm_call_id, + ) + + +@client +async def agenerate_content( + model: str, + contents: GenerateContentContentListUnionDict, + config: Optional[GenerateContentConfigDict] = None, + tools: Optional[ToolConfigDict] = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Any: + """ + Async: Generate content using Google GenAI + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["agenerate_content"] = True + + # Handle generationConfig parameter from kwargs for backward compatibility + if "generationConfig" in kwargs and config is None: + config = kwargs.pop("generationConfig") + # get custom llm provider so we can use this for mapping exceptions + if custom_llm_provider is None: + _, custom_llm_provider, _, _ = litellm.get_llm_provider( + model=model, + custom_llm_provider=custom_llm_provider, + ) + + func = partial( + generate_content, + model=model, + contents=contents, + config=config, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + tools=tools, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + + return response + except Exception as e: + raise litellm.exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def generate_content( + model: str, + contents: GenerateContentContentListUnionDict, + config: Optional[GenerateContentConfigDict] = None, + tools: Optional[ToolConfigDict] = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Any: + """ + Generate content using Google GenAI + """ + local_vars = locals() + try: + _is_async = kwargs.pop("agenerate_content", False) + + # Handle generationConfig parameter from kwargs for backward compatibility + if "generationConfig" in kwargs and config is None: + config = kwargs.pop("generationConfig") + # Check for mock response first + litellm_params = GenericLiteLLMParams(**kwargs) + if litellm_params.mock_response and isinstance( + litellm_params.mock_response, str + ): + return GenerateContentHelper.mock_generate_content_response( + mock_response=litellm_params.mock_response + ) + + # Setup the call + setup_result = GenerateContentHelper.setup_generate_content_call( + model=model, + contents=contents, + config=config, + custom_llm_provider=custom_llm_provider, + tools=tools, + **kwargs, + ) + + # Extract systemInstruction from kwargs to pass to handler + system_instruction = kwargs.get("systemInstruction") or kwargs.get( + "system_instruction" + ) + + # Check if we should use the adapter (when provider config is None) + if setup_result.generate_content_provider_config is None: + # Use the adapter to convert to completion format + return GenerateContentToCompletionHandler.generate_content_handler( + model=model, + contents=contents, # type: ignore + config=setup_result.generate_content_config_dict, + tools=tools, + _is_async=_is_async, + litellm_params=setup_result.litellm_params, + extra_headers=extra_headers, + **kwargs, + ) + + # Call the standard handler + response = base_llm_http_handler.generate_content_handler( + model=setup_result.model, + contents=contents, + tools=tools, + generate_content_provider_config=setup_result.generate_content_provider_config, + generate_content_config_dict=setup_result.generate_content_config_dict, + custom_llm_provider=setup_result.custom_llm_provider, + litellm_params=setup_result.litellm_params, + logging_obj=setup_result.litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + litellm_metadata=kwargs.get("litellm_metadata", {}), + system_instruction=system_instruction, + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def agenerate_content_stream( + model: str, + contents: GenerateContentContentListUnionDict, + config: Optional[GenerateContentConfigDict] = None, + tools: Optional[ToolConfigDict] = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Any: + """ + Async: Generate content using Google GenAI with streaming response + """ + local_vars = locals() + try: + kwargs["agenerate_content_stream"] = True + + # Handle generationConfig parameter from kwargs for backward compatibility + if "generationConfig" in kwargs and config is None: + config = kwargs.pop("generationConfig") + # get custom llm provider so we can use this for mapping exceptions + if custom_llm_provider is None: + _, custom_llm_provider, _, _ = litellm.get_llm_provider( + model=model, api_base=local_vars.get("base_url", None) + ) + + # Setup the call + setup_result = GenerateContentHelper.setup_generate_content_call( + model=model, + contents=contents, + config=config, + custom_llm_provider=custom_llm_provider, + tools=tools, + **kwargs, + ) + + # Extract systemInstruction from kwargs to pass to handler + system_instruction = kwargs.get("systemInstruction") or kwargs.get( + "system_instruction" + ) + + # Check if we should use the adapter (when provider config is None) + if setup_result.generate_content_provider_config is None: + if "stream" in kwargs: + kwargs.pop("stream", None) + + # Use the adapter to convert to completion format + return ( + await GenerateContentToCompletionHandler.async_generate_content_handler( + model=model, + contents=contents, # type: ignore + config=setup_result.generate_content_config_dict, + litellm_params=setup_result.litellm_params, + tools=tools, + stream=True, + extra_headers=extra_headers, + **kwargs, + ) + ) + + # Call the handler with async enabled and streaming + # Return the coroutine directly for the router to handle + return await base_llm_http_handler.generate_content_handler( + model=setup_result.model, + contents=contents, + generate_content_provider_config=setup_result.generate_content_provider_config, + generate_content_config_dict=setup_result.generate_content_config_dict, + tools=tools, + custom_llm_provider=setup_result.custom_llm_provider, + litellm_params=setup_result.litellm_params, + logging_obj=setup_result.litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + _is_async=True, + client=kwargs.get("client"), + stream=True, + litellm_metadata=kwargs.get("litellm_metadata", {}), + system_instruction=system_instruction, + ) + + except Exception as e: + raise litellm.exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def generate_content_stream( + model: str, + contents: GenerateContentContentListUnionDict, + config: Optional[GenerateContentConfigDict] = None, + tools: Optional[ToolConfigDict] = None, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Iterator[Any]: + """ + Generate content using Google GenAI with streaming response + """ + local_vars = locals() + try: + # Remove any async-related flags since this is the sync function + _is_async = kwargs.pop("agenerate_content_stream", False) + + # Handle generationConfig parameter from kwargs for backward compatibility + if "generationConfig" in kwargs and config is None: + config = kwargs.pop("generationConfig") + # Setup the call + setup_result = GenerateContentHelper.setup_generate_content_call( + model=model, + contents=contents, + config=config, + custom_llm_provider=custom_llm_provider, + tools=tools, + **kwargs, + ) + + # Check if we should use the adapter (when provider config is None) + if setup_result.generate_content_provider_config is None: + if "stream" in kwargs: + kwargs.pop("stream", None) + + # Use the adapter to convert to completion format + return GenerateContentToCompletionHandler.generate_content_handler( + model=model, + contents=contents, # type: ignore + config=setup_result.generate_content_config_dict, + _is_async=_is_async, + litellm_params=setup_result.litellm_params, + stream=True, + extra_headers=extra_headers, + **kwargs, + ) + + # Call the handler with streaming enabled (sync version) + return base_llm_http_handler.generate_content_handler( + model=setup_result.model, + contents=contents, + generate_content_provider_config=setup_result.generate_content_provider_config, + generate_content_config_dict=setup_result.generate_content_config_dict, + tools=tools, + custom_llm_provider=setup_result.custom_llm_provider, + litellm_params=setup_result.litellm_params, + logging_obj=setup_result.litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + stream=True, + litellm_metadata=kwargs.get("litellm_metadata", {}), + ) + + except Exception as e: + raise litellm.exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/streaming_iterator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/streaming_iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..3e97b4807798fbade988691ec6c28bb66350aa5e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/google_genai/streaming_iterator.py @@ -0,0 +1,165 @@ +import asyncio +from datetime import datetime +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.proxy.pass_through_endpoints.success_handler import ( + PassThroughEndpointLogging, +) +from litellm.types.passthrough_endpoints.pass_through_endpoints import EndpointType + +if TYPE_CHECKING: + from litellm.llms.base_llm.google_genai.transformation import ( + BaseGoogleGenAIGenerateContentConfig, + ) +else: + BaseGoogleGenAIGenerateContentConfig = Any + +GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ = PassThroughEndpointLogging() + + +class BaseGoogleGenAIGenerateContentStreamingIterator: + """ + Base class for Google GenAI Generate Content streaming iterators that provides common logic + for streaming response handling and logging. + """ + + def __init__( + self, + litellm_logging_obj: LiteLLMLoggingObj, + request_body: dict, + model: str, + hidden_params: Optional[Dict[str, Any]] = None, + ): + self.litellm_logging_obj = litellm_logging_obj + self.request_body = request_body + self.start_time = datetime.now() + self.collected_chunks: List[bytes] = [] + self.model = model + self._hidden_params: Dict[str, Any] = hidden_params or {} + + async def _handle_async_streaming_logging( + self, + ): + """Handle the logging after all chunks have been collected.""" + from litellm.proxy.pass_through_endpoints.streaming_handler import ( + PassThroughStreamingHandler, + ) + + end_time = datetime.now() + asyncio.create_task( + PassThroughStreamingHandler._route_streaming_logging_to_handler( + litellm_logging_obj=self.litellm_logging_obj, + passthrough_success_handler_obj=GLOBAL_PASS_THROUGH_SUCCESS_HANDLER_OBJ, + url_route="/v1/generateContent", + request_body=self.request_body or {}, + endpoint_type=EndpointType.VERTEX_AI, + start_time=self.start_time, + raw_bytes=self.collected_chunks, + end_time=end_time, + model=self.model, + ) + ) + + +class GoogleGenAIGenerateContentStreamingIterator( + BaseGoogleGenAIGenerateContentStreamingIterator +): + """ + Streaming iterator specifically for Google GenAI generate content API. + """ + + def __init__( + self, + response, + model: str, + logging_obj: LiteLLMLoggingObj, + generate_content_provider_config: BaseGoogleGenAIGenerateContentConfig, + litellm_metadata: dict, + custom_llm_provider: str, + request_body: Optional[dict] = None, + hidden_params: Optional[Dict[str, Any]] = None, + ): + super().__init__( + litellm_logging_obj=logging_obj, + request_body=request_body or {}, + model=model, + hidden_params=hidden_params, + ) + self.response = response + self.model = model + self.generate_content_provider_config = generate_content_provider_config + self.litellm_metadata = litellm_metadata + self.custom_llm_provider = custom_llm_provider + # Store the iterator once to avoid multiple stream consumption + self.stream_iterator = response.iter_bytes() + + def __iter__(self): + return self + + def __next__(self): + try: + # Get the next chunk from the stored iterator + chunk = next(self.stream_iterator) + self.collected_chunks.append(chunk) + # Just yield raw bytes + return chunk + except StopIteration: + raise StopIteration + + def __aiter__(self): + return self + + async def __anext__(self): + # This should not be used for sync responses + # If you need async iteration, use AsyncGoogleGenAIGenerateContentStreamingIterator + raise NotImplementedError( + "Use AsyncGoogleGenAIGenerateContentStreamingIterator for async iteration" + ) + + +class AsyncGoogleGenAIGenerateContentStreamingIterator( + BaseGoogleGenAIGenerateContentStreamingIterator +): + """ + Async streaming iterator specifically for Google GenAI generate content API. + """ + + def __init__( + self, + response, + model: str, + logging_obj: LiteLLMLoggingObj, + generate_content_provider_config: BaseGoogleGenAIGenerateContentConfig, + litellm_metadata: dict, + custom_llm_provider: str, + request_body: Optional[dict] = None, + hidden_params: Optional[Dict[str, Any]] = None, + ): + super().__init__( + litellm_logging_obj=logging_obj, + request_body=request_body or {}, + model=model, + hidden_params=hidden_params, + ) + self.response = response + self.model = model + self.generate_content_provider_config = generate_content_provider_config + self.litellm_metadata = litellm_metadata + self.custom_llm_provider = custom_llm_provider + # Store the async iterator once to avoid multiple stream consumption + self.stream_iterator = response.aiter_bytes() + + def __aiter__(self): + return self + + async def __anext__(self): + try: + # Get the next chunk from the stored async iterator + chunk = await self.stream_iterator.__anext__() + self.collected_chunks.append(chunk) + # Just yield raw bytes + return chunk + except StopAsyncIteration: + await self._handle_async_streaming_logging() + raise StopAsyncIteration diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/ocr/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/ocr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e97497b2db7c3873f440319b37dbed130f5cd39e --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/ocr/__init__.py @@ -0,0 +1,5 @@ +"""OCR module for LiteLLM.""" + +from .main import aocr, ocr + +__all__ = ["ocr", "aocr"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/ocr/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/ocr/main.py new file mode 100644 index 0000000000000000000000000000000000000000..b27082c361a0e59d0de987542bc4f970d3b65d4d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/ocr/main.py @@ -0,0 +1,461 @@ +""" +Main OCR function for LiteLLM. +""" + +import asyncio +import base64 +import contextvars +import mimetypes +import os +import re +from functools import partial +from io import IOBase +from typing import Any, Coroutine, Dict, Optional, Union + +import httpx + +import litellm +from litellm._logging import verbose_logger +from litellm.constants import request_timeout +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.ocr.transformation import BaseOCRConfig, OCRResponse +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.types.router import GenericLiteLLMParams +from litellm.utils import ProviderConfigManager, client + +####### ENVIRONMENT VARIABLES ################### +base_llm_http_handler = BaseLLMHTTPHandler() +################################################# + + +@client +async def aocr( + model: str, + document: Dict[str, Any], + api_key: Optional[str] = None, + api_base: Optional[str] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + **kwargs, +) -> OCRResponse: + """ + Async OCR function. + + Args: + model: Model name (e.g., "mistral/mistral-ocr-latest") + document: Document to process in Mistral format: + {"type": "document_url", "document_url": "https://..."} for PDFs/docs, + {"type": "image_url", "image_url": "https://..."} for images, or + {"type": "file", "file": } for local files + api_key: Optional API key + api_base: Optional API base URL + timeout: Optional timeout + custom_llm_provider: Optional custom LLM provider + extra_headers: Optional extra headers + **kwargs: Additional parameters (e.g., include_image_base64, pages, image_limit) + + Returns: + OCRResponse in Mistral OCR format with pages, model, usage_info, etc. + + Example: + ```python + import litellm + + # OCR with PDF + response = await litellm.aocr( + model="mistral/mistral-ocr-latest", + document={ + "type": "document_url", + "document_url": "https://arxiv.org/pdf/2201.04234" + }, + include_image_base64=True + ) + + # OCR with image + response = await litellm.aocr( + model="mistral/mistral-ocr-latest", + document={ + "type": "image_url", + "image_url": "https://example.com/image.png" + } + ) + + # OCR with base64 encoded PDF + response = await litellm.aocr( + model="mistral/mistral-ocr-latest", + document={ + "type": "document_url", + "document_url": f"data:application/pdf;base64,{base64_pdf}" + } + ) + + # OCR with local file + response = await litellm.aocr( + model="mistral/mistral-ocr-latest", + document={"type": "file", "file": "/path/to/document.pdf"} + ) + ``` + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["aocr"] = True + + # Get custom llm provider + if custom_llm_provider is None: + _, custom_llm_provider, _, _ = litellm.get_llm_provider( + model=model, api_base=api_base + ) + + func = partial( + ocr, + model=model, + document=document, + api_key=api_key, + api_base=api_base, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + + if response is None: + raise ValueError( + f"Got an unexpected None response from the OCR API: {response}" + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def ocr( + model: str, + document: Dict[str, Any], + api_key: Optional[str] = None, + api_base: Optional[str] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + **kwargs, +) -> Union[OCRResponse, Coroutine[Any, Any, OCRResponse]]: + """ + Synchronous OCR function. + + Args: + model: Model name (e.g., "mistral/mistral-ocr-latest") + document: Document to process in Mistral format: + {"type": "document_url", "document_url": "https://..."} for PDFs/docs, + {"type": "image_url", "image_url": "https://..."} for images, or + {"type": "file", "file": } for local files + api_key: Optional API key + api_base: Optional API base URL + timeout: Optional timeout + custom_llm_provider: Optional custom LLM provider + extra_headers: Optional extra headers + **kwargs: Additional parameters (e.g., include_image_base64, pages, image_limit) + + Returns: + OCRResponse in Mistral OCR format with pages, model, usage_info, etc. + + Example: + ```python + import litellm + + # OCR with PDF + response = litellm.ocr( + model="mistral/mistral-ocr-latest", + document={ + "type": "document_url", + "document_url": "https://arxiv.org/pdf/2201.04234" + }, + include_image_base64=True + ) + + # OCR with image + response = litellm.ocr( + model="mistral/mistral-ocr-latest", + document={ + "type": "image_url", + "image_url": "https://example.com/image.png" + } + ) + + # OCR with base64 encoded PDF + response = litellm.ocr( + model="mistral/mistral-ocr-latest", + document={ + "type": "document_url", + "document_url": f"data:application/pdf;base64,{base64_pdf}" + } + ) + + # OCR with local file + response = litellm.ocr( + model="mistral/mistral-ocr-latest", + document={"type": "file", "file": "/path/to/document.pdf"} + ) + + # Access pages + for page in response.pages: + print(f"Page {page.index}: {page.markdown}") + ``` + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.pop("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("aocr", False) is True + + # Validate document parameter format + if not isinstance(document, dict): + raise ValueError( + f"document must be a dict with 'type' and URL/file field, got {type(document)}" + ) + + doc_type = document.get("type") + + # Handle file type: convert to document_url/image_url with base64 data URI + if doc_type == "file": + document = convert_file_document_to_url_document(document) + doc_type = document.get("type") + + if doc_type not in ["document_url", "image_url"]: + raise ValueError( + f"Invalid document type: {doc_type}. " + "Must be 'document_url', 'image_url', or 'file'" + ) + + ( + model, + custom_llm_provider, + dynamic_api_key, + dynamic_api_base, + ) = litellm.get_llm_provider( + model=model, + custom_llm_provider=custom_llm_provider, + api_base=api_base, + api_key=api_key, + ) + + # Update with dynamic values if available + if dynamic_api_key: + api_key = dynamic_api_key + if dynamic_api_base: + api_base = dynamic_api_base + + # Get provider config + ocr_provider_config: Optional[BaseOCRConfig] = ( + ProviderConfigManager.get_provider_ocr_config( + model=model, + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if ocr_provider_config is None: + raise ValueError( + f"OCR is not supported for provider: {custom_llm_provider}" + ) + + verbose_logger.debug( + f"OCR call - model: {model}, provider: {custom_llm_provider}" + ) + + # Get litellm params using GenericLiteLLMParams (same as responses API) + litellm_params = GenericLiteLLMParams(**kwargs) + + # Extract OCR-specific parameters from kwargs + supported_params = ocr_provider_config.get_supported_ocr_params(model=model) + non_default_params = {} + for param in supported_params: + if param in kwargs: + non_default_params[param] = kwargs.pop(param) + + # Map parameters to provider-specific format + optional_params = ocr_provider_config.map_ocr_params( + non_default_params=non_default_params, + optional_params={}, + model=model, + ) + + verbose_logger.debug(f"OCR optional_params after mapping: {optional_params}") + + # Pre Call logging + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=model, + optional_params=optional_params, + litellm_params={ + "litellm_call_id": litellm_call_id, + "api_base": api_base, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Call the handler - pass document dict directly + response = base_llm_http_handler.ocr( + model=model, + document=document, # Pass the entire document dict + optional_params=optional_params, + timeout=timeout or request_timeout, + logging_obj=litellm_logging_obj, + api_key=api_key, + api_base=api_base, + custom_llm_provider=custom_llm_provider, + aocr=_is_async, + headers=extra_headers, + provider_config=ocr_provider_config, + litellm_params=dict(litellm_params), + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=model, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +################################################# +# Public utilities — used by the SDK and the proxy +################################################# + +_MIME_PATTERN = re.compile(r"^[\w.+-]+/[\w.+-]+$") + +_MIME_TYPE_MAP = { + ".pdf": "application/pdf", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".gif": "image/gif", + ".webp": "image/webp", + ".tiff": "image/tiff", + ".tif": "image/tiff", + ".bmp": "image/bmp", +} + + +def get_mime_type(file_path: str) -> str: + """ + Determine MIME type from file path extension. + + Falls back to mimetypes.guess_type, then to 'application/octet-stream'. + """ + ext = os.path.splitext(file_path)[1].lower() + mime = _MIME_TYPE_MAP.get(ext) + if mime: + return mime + guessed, _ = mimetypes.guess_type(file_path) + return guessed or "application/octet-stream" + + +def convert_file_document_to_url_document(document: Dict[str, Any]) -> Dict[str, str]: + """ + Convert a file-type document dict to a document_url-type document dict + with an inline base64 data URI. + + Accepts document dicts like: + {"type": "file", "file": Path("/path/to/doc.pdf")} # pathlib.Path + {"type": "file", "file": } # file-like object (BinaryIO) + {"type": "file", "file": b"raw bytes"} # raw bytes + + Bare ``str`` paths are not accepted — pass a ``pathlib.Path`` or + ``open(path, "rb")`` instead. See the str check below for the rationale. + + Returns: + {"type": "document_url", "document_url": "data:;base64,"} + or {"type": "image_url", "image_url": "data:;base64,"} + """ + file_input = document.get("file") + if file_input is None: + raise ValueError( + "document with type='file' must include a 'file' field containing " + "a pathlib.Path, file-like object, or bytes" + ) + + file_bytes: bytes + mime_type: str = "application/octet-stream" + file_name: Optional[str] = None + + if isinstance(file_input, str): + # Bare strings are rejected here. The OCR ``document`` accepts a + # ``{"type": "file", "file": }`` shape, and when this helper + # runs in a proxy request handler ```` is attacker-controlled. + # Opening it as a path is an arbitrary local file read on the proxy + # host, which is then base64-encoded and forwarded to the OCR + # provider — an exfiltration primitive. + raise ValueError( + "OCR file input does not accept bare str values. Pass bytes, " + "a pathlib.Path, or a file-like object. To OCR a local file " + "from a path, call open(path, 'rb') yourself." + ) + if isinstance(file_input, os.PathLike): + # os.PathLike (pathlib.Path and custom __fspath__ classes) is a + # Python-level type that HTTP form values can't fabricate. + file_path = str(file_input) + if not os.path.isfile(file_path): + raise FileNotFoundError(f"File not found: {file_path}") + mime_type = get_mime_type(file_path) + file_name = os.path.basename(file_path) + with open(file_path, "rb") as f: + file_bytes = f.read() + elif isinstance(file_input, bytes): + file_bytes = file_input + elif isinstance(file_input, IOBase) or hasattr(file_input, "read"): + if hasattr(file_input, "name"): + file_name = getattr(file_input, "name", None) + if file_name: + mime_type = get_mime_type(file_name) + file_bytes = file_input.read() + if isinstance(file_bytes, str): + file_bytes = file_bytes.encode("utf-8") + else: + raise ValueError( + f"Unsupported file input type: {type(file_input)}. " + "Expected pathlib.Path, bytes, or a file-like object." + ) + + if not file_bytes: + raise ValueError("File is empty or could not be read") + + if "mime_type" in document: + mime_type = document["mime_type"] + + if not _MIME_PATTERN.match(mime_type): + raise ValueError(f"Invalid MIME type: {mime_type}") + + base64_data = base64.b64encode(file_bytes).decode("utf-8") + data_uri = f"data:{mime_type};base64,{base64_data}" + + if mime_type.startswith("image/"): + verbose_logger.debug( + f"OCR file input: Converted file to image_url data URI " + f"(mime={mime_type}, size={len(file_bytes)} bytes, name={file_name})" + ) + return {"type": "image_url", "image_url": data_uri} + else: + verbose_logger.debug( + f"OCR file input: Converted file to document_url data URI " + f"(mime={mime_type}, size={len(file_bytes)} bytes, name={file_name})" + ) + return {"type": "document_url", "document_url": data_uri} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/README.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5a6449c43b79b03d89c5057f580f8bdd079999cc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/README.md @@ -0,0 +1,118 @@ +This makes it easier to pass through requests to the LLM APIs. + +E.g. Route to VLLM's `/classify` endpoint: + + +## SDK (Basic) + +```python +import litellm + + +response = litellm.llm_passthrough_route( + model="hosted_vllm/papluca/xlm-roberta-base-language-detection", + method="POST", + endpoint="classify", + api_base="http://localhost:8090", + api_key=None, + json={ + "model": "swapped-for-litellm-model", + "input": "Hello, world!", + } +) + +print(response) +``` + +## SDK (Router) + +```python +import asyncio +from litellm import Router + +router = Router( + model_list=[ + { + "model_name": "roberta-base-language-detection", + "litellm_params": { + "model": "hosted_vllm/papluca/xlm-roberta-base-language-detection", + "api_base": "http://localhost:8090", + } + } + ] +) + +request_data = { + "model": "roberta-base-language-detection", + "method": "POST", + "endpoint": "classify", + "api_base": "http://localhost:8090", + "api_key": None, + "json": { + "model": "roberta-base-language-detection", + "input": "Hello, world!", + } +} + +async def main(): + response = await router.allm_passthrough_route(**request_data) + print(response) + +if __name__ == "__main__": + asyncio.run(main()) +``` + +## PROXY + +1. Setup config.yaml + +```yaml +model_list: + - model_name: roberta-base-language-detection + litellm_params: + model: hosted_vllm/papluca/xlm-roberta-base-language-detection + api_base: http://localhost:8090 +``` + +2. Run the proxy + +```bash +litellm proxy --config config.yaml + +# RUNNING on http://localhost:4000 +``` + +3. Use the proxy + +```bash +curl -X POST http://localhost:4000/vllm/classify \ +-H "Content-Type: application/json" \ +-H "Authorization: Bearer " \ +-d '{"model": "roberta-base-language-detection", "input": "Hello, world!"}' \ +``` + +# How to add a provider for passthrough + +See [VLLMModelInfo](https://github.com/BerriAI/litellm/blob/main/litellm/llms/vllm/common_utils.py) for an example. + +1. Inherit from BaseModelInfo + +```python +from litellm.llms.base_llm.base_utils import BaseLLMModelInfo + +class VLLMModelInfo(BaseLLMModelInfo): + pass +``` + +2. Register the provider in the ProviderConfigManager.get_provider_model_info + +```python +from litellm.utils import ProviderConfigManager +from litellm.types.utils import LlmProviders + +provider_config = ProviderConfigManager.get_provider_model_info( + model="my-test-model", provider=LlmProviders.VLLM +) + +print(provider_config) +``` \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bfd13e7a74e36c460aadb3b62f686f48283c38db --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/__init__.py @@ -0,0 +1,8 @@ +from .main import allm_passthrough_route, llm_passthrough_route +from .utils import BasePassthroughUtils + +__all__ = [ + "allm_passthrough_route", + "llm_passthrough_route", + "BasePassthroughUtils", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/main.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c9aea6f64b72b911705e1307990b6550ff7cd2 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/main.py @@ -0,0 +1,465 @@ +""" +This module is used to pass through requests to the LLM APIs. +""" + +import asyncio +import contextvars +from functools import partial +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Coroutine, + Generator, + List, + Optional, + Union, + cast, +) + +import httpx +from httpx._types import CookieTypes, QueryParamTypes, RequestFiles + +import litellm +from litellm._logging import verbose_logger +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider +from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.passthrough.utils import CommonUtils +from litellm.utils import client + +base_llm_http_handler = BaseLLMHTTPHandler() +from .utils import BasePassthroughUtils + +if TYPE_CHECKING: + from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj + from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig + + +@client +async def allm_passthrough_route( + *, + method: str, + endpoint: str, + model: str, + custom_llm_provider: Optional[str] = None, + api_base: Optional[str] = None, + api_key: Optional[str] = None, + request_query_params: Optional[dict] = None, + request_headers: Optional[dict] = None, + content: Optional[Any] = None, + data: Optional[dict] = None, + files: Optional[RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[QueryParamTypes] = None, + cookies: Optional[CookieTypes] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + **kwargs, +) -> Union[httpx.Response, AsyncGenerator[Any, Any]]: + """ + Async: Reranks a list of documents based on their relevance to the query + """ + try: + loop = asyncio.get_event_loop() + kwargs["allm_passthrough_route"] = True + + model, custom_llm_provider, api_key, api_base = get_llm_provider( + model=model, + custom_llm_provider=custom_llm_provider, + api_base=api_base, + api_key=api_key, + ) + + from litellm.types.utils import LlmProviders + from litellm.utils import ProviderConfigManager + + provider_config = cast( + Optional["BasePassthroughConfig"], kwargs.get("provider_config") + ) or ProviderConfigManager.get_provider_passthrough_config( + provider=LlmProviders(custom_llm_provider), + model=model, + ) + + if provider_config is None: + raise Exception(f"Provider {custom_llm_provider} not found") + + func = partial( + llm_passthrough_route, + method=method, + endpoint=endpoint, + model=model, + custom_llm_provider=custom_llm_provider, + api_base=api_base, + api_key=api_key, + request_query_params=request_query_params, + request_headers=request_headers, + content=content, + data=data, + files=files, + json=json, + params=params, + cookies=cookies, + client=client, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + # Since allm_passthrough_route=True, we always get a coroutine from _async_passthrough_request + if asyncio.iscoroutine(init_response): + response = await init_response + + # Only call raise_for_status if it's a Response object (not a generator) + if isinstance(response, httpx.Response): + response.raise_for_status() + + return response + else: + # This shouldn't happen when allm_passthrough_route=True, but handle it for type safety + raise Exception("Expected coroutine from async passthrough route") + + except httpx.HTTPStatusError as e: + # For HTTP errors, re-raise as-is to preserve the original error details + # The caller (e.g., proxy layer) can handle conversion to appropriate response format + raise e + except Exception as e: + # For other exceptions, use provider-specific error handling + from litellm.types.utils import LlmProviders + from litellm.utils import ProviderConfigManager + + # Get the provider using the same logic as llm_passthrough_route + _, resolved_custom_llm_provider, _, _ = get_llm_provider( + model=model, + custom_llm_provider=custom_llm_provider, + api_base=api_base, + api_key=api_key, + ) + + # Get provider config if available + provider_config = None + if resolved_custom_llm_provider: + try: + provider_config = cast( + Optional["BasePassthroughConfig"], kwargs.get("provider_config") + ) or ProviderConfigManager.get_provider_passthrough_config( + provider=LlmProviders(resolved_custom_llm_provider), + model=model, + ) + except Exception: + # If we can't get provider config, pass None + pass + + if provider_config is None: + # If no provider config available, raise the original exception + raise e + + raise base_llm_http_handler._handle_error( + e=e, + provider_config=provider_config, + ) + + +@client +def llm_passthrough_route( + *, + method: str, + endpoint: str, + model: str, + custom_llm_provider: Optional[str] = None, + api_base: Optional[str] = None, + api_key: Optional[str] = None, + request_query_params: Optional[dict] = None, + request_headers: Optional[dict] = None, + allm_passthrough_route: bool = False, + content: Optional[Any] = None, + data: Optional[dict] = None, + files: Optional[RequestFiles] = None, + json: Optional[Any] = None, + params: Optional[QueryParamTypes] = None, + cookies: Optional[CookieTypes] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + **kwargs, +) -> Union[ + httpx.Response, + Coroutine[Any, Any, httpx.Response], + Coroutine[Any, Any, Union[httpx.Response, AsyncGenerator[Any, Any]]], + Generator[Any, Any, Any], + AsyncGenerator[Any, Any], +]: + """ + Pass through requests to the LLM APIs. + + Step 1. Build the request + Step 2. Send the request + Step 3. Return the response + """ + from litellm.litellm_core_utils.get_litellm_params import get_litellm_params + from litellm.types.utils import LlmProviders + from litellm.utils import ProviderConfigManager + + _is_async = allm_passthrough_route + + if client is None: + if _is_async: + client = litellm.module_level_aclient + else: + client = litellm.module_level_client + + litellm_logging_obj = cast("LiteLLMLoggingObj", kwargs.get("litellm_logging_obj")) + + model, custom_llm_provider, api_key, api_base = get_llm_provider( + model=model, + custom_llm_provider=custom_llm_provider, + api_base=api_base, + api_key=api_key, + ) + + litellm_params_dict = get_litellm_params(**kwargs) + + # Add model_id to litellm_params if present in kwargs (for Bedrock Application Inference Profiles) + if "model_id" in kwargs: + litellm_params_dict["model_id"] = kwargs["model_id"] + + litellm_logging_obj.update_environment_variables( + model=model, + litellm_params=litellm_params_dict, + optional_params={}, + endpoint=endpoint, + custom_llm_provider=custom_llm_provider, + request_data=data if data else json, + ) + + provider_config = cast( + Optional["BasePassthroughConfig"], kwargs.get("provider_config") + ) or ProviderConfigManager.get_provider_passthrough_config( + provider=LlmProviders(custom_llm_provider), + model=model, + ) + if provider_config is None: + raise Exception(f"Provider {custom_llm_provider} not found") + + updated_url, base_target_url = provider_config.get_complete_url( + api_base=api_base, + api_key=api_key, + model=model, + endpoint=endpoint, + request_query_params=request_query_params, + litellm_params=litellm_params_dict, + ) + + # [TODO: Refactor to bedrockpassthroughconfig] need to encode the id of application-inference-profile for bedrock + if custom_llm_provider == "bedrock" and "application-inference-profile" in endpoint: + encoded_url_str = CommonUtils.encode_bedrock_runtime_modelid_arn( + str(updated_url) + ) + updated_url = httpx.URL(encoded_url_str) + + # Add or update query parameters + provider_api_key = provider_config.get_api_key(api_key) + + auth_headers = provider_config.validate_environment( + headers={}, + model=model, + messages=[], + optional_params={}, + litellm_params=litellm_params_dict, + api_key=provider_api_key, + api_base=base_target_url, + ) + + headers = BasePassthroughUtils.forward_headers_from_request( + request_headers=request_headers or {}, + headers=auth_headers, + forward_headers=False, + ) + + headers, signed_json_body = provider_config.sign_request( + headers=headers, + litellm_params=litellm_params_dict, + request_data=data if data else json, + api_base=str(updated_url), + model=model, + ) + + ## SWAP MODEL IN JSON BODY [TODO: REFACTOR TO A provider_config.transform_request method] + if json and isinstance(json, dict) and "model" in json: + json["model"] = model + + request = client.client.build_request( + method=method, + url=updated_url, + content=signed_json_body if signed_json_body is not None else content, + data=data if (signed_json_body is None and content is None) else None, + files=files, + json=json if (signed_json_body is None and content is None) else None, + params=params, + headers=headers, + cookies=cookies, + ) + + ## IS STREAMING REQUEST + is_streaming_request = provider_config.is_streaming_request( + endpoint=endpoint, + request_data=data or json or {}, + ) + + # Update logging object with streaming status + litellm_logging_obj.stream = is_streaming_request + + ## LOGGING PRE-CALL + request_data = data if data else json + litellm_logging_obj.pre_call( + input=request_data, + api_key=provider_api_key, + additional_args={ + "complete_input_dict": request_data, + "api_base": str(updated_url), + "headers": headers, + }, + ) + + try: + if _is_async: + # Return the coroutine to be awaited by the caller + return _async_passthrough_request( + client=client, + request=request, + is_streaming_request=is_streaming_request, + litellm_logging_obj=litellm_logging_obj, + provider_config=provider_config, + ) + else: + # Sync path - client.client.send returns Response directly + response: httpx.Response = client.client.send(request=request, stream=is_streaming_request) # type: ignore + response.raise_for_status() + + if ( + hasattr(response, "iter_bytes") and is_streaming_request + ): # yield the chunk, so we can store it in the logging object + return _sync_streaming(response, litellm_logging_obj, provider_config) + else: + # For non-streaming responses, yield the entire response + return response + except Exception as e: + if provider_config is None: + raise e + raise base_llm_http_handler._handle_error( + e=e, + provider_config=provider_config, + ) + + +async def _async_passthrough_request( + client: Union[HTTPHandler, AsyncHTTPHandler], + request: httpx.Request, + is_streaming_request: bool, + litellm_logging_obj: "LiteLLMLoggingObj", + provider_config: "BasePassthroughConfig", +) -> Union[httpx.Response, AsyncGenerator[Any, Any]]: + """ + Handle async passthrough requests. + Uses async client to send request and properly handles streaming. + """ + # client.client.send returns a coroutine for async clients + response_result = client.client.send(request=request, stream=is_streaming_request) + + # Check if it's a coroutine and await it + if asyncio.iscoroutine(response_result): + if is_streaming_request: + # Pass the coroutine to _async_streaming which will await it + return _async_streaming( + response=response_result, + litellm_logging_obj=litellm_logging_obj, + provider_config=provider_config, + ) + else: + response = await response_result + await response.aread() + response.raise_for_status() + return response + else: + # Fallback for sync-like behavior (shouldn't happen in async path) + raise Exception("Expected coroutine from async client") + + +def _sync_streaming( + response: httpx.Response, + litellm_logging_obj: "LiteLLMLoggingObj", + provider_config: "BasePassthroughConfig", +): + from litellm.utils import executor + + raw_bytes: List[bytes] = [] + flush_scheduled = False + try: + for chunk in response.iter_bytes(): # type: ignore + raw_bytes.append(chunk) + yield chunk + finally: + if not flush_scheduled and raw_bytes: + flush_scheduled = True + try: + executor.submit( + litellm_logging_obj.flush_passthrough_collected_chunks, + raw_bytes=raw_bytes, + provider_config=provider_config, + ) + except Exception as e: + verbose_logger.exception( + "Failed to schedule passthrough spend-tracking flush " + "in _sync_streaming; %d buffered chunks dropped: %s", + len(raw_bytes), + e, + ) + + +async def _async_streaming( + response: Coroutine[Any, Any, httpx.Response], + litellm_logging_obj: "LiteLLMLoggingObj", + provider_config: "BasePassthroughConfig", +): + iter_response = await response + + try: + iter_response.raise_for_status() + except Exception: + try: + await iter_response.aclose() + except Exception: + pass + raise + + raw_bytes: List[bytes] = [] + flush_scheduled = False + try: + async for chunk in iter_response.aiter_bytes(): # type: ignore + raw_bytes.append(chunk) + yield chunk + except Exception: + try: + await iter_response.aclose() + except Exception: + pass + raise + finally: + # GeneratorExit (raised on client disconnect) is not caught by + # `except Exception`; the finally block ensures partial usage + # still gets flushed for spend tracking. See LIT-2642. + if not flush_scheduled and raw_bytes: + flush_scheduled = True + try: + asyncio.create_task( + litellm_logging_obj.async_flush_passthrough_collected_chunks( + raw_bytes=raw_bytes, + provider_config=provider_config, + ) + ) + except Exception as e: + verbose_logger.exception( + "Failed to schedule passthrough spend-tracking flush " + "in _async_streaming; %d buffered chunks dropped: %s", + len(raw_bytes), + e, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d39a0dda15203b509e731502ae266a5cafbd5b29 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/passthrough/utils.py @@ -0,0 +1,149 @@ +from typing import Dict, List, Mapping, Optional, Union +from urllib.parse import parse_qs + +import httpx + +from litellm._logging import verbose_logger +from litellm.constants import PASS_THROUGH_HEADER_PREFIX + +# Headers that must not be overwritten via the x-pass- forwarding mechanism. +# Includes standard credential/auth headers and protocol-level headers that +# affect routing or message framing. +_PASS_THROUGH_PROTECTED_HEADERS: frozenset = frozenset( + { + "authorization", + "api-key", + "x-api-key", + "x-goog-api-key", + "host", + "content-length", + } +) + +# Header name prefix used to block AWS SigV4 signing headers from being overridden. +_PASS_THROUGH_PROTECTED_HEADER_PREFIXES: tuple = ("x-amz-",) + + +class BasePassthroughUtils: + @staticmethod + def get_merged_query_parameters( + existing_url: httpx.URL, + request_query_params: Mapping[str, Union[str, list]], + default_query_params: Optional[Dict[str, Union[str, list]]] = None, + ) -> Dict[str, Union[str, List[str]]]: + # Get the existing query params from the target URL + existing_query_string = existing_url.query.decode("utf-8") + existing_query_params = parse_qs(existing_query_string) + + # parse_qs returns a dict where each value is a list, so let's flatten it + updated_existing_query_params = { + k: v[0] if len(v) == 1 else v for k, v in existing_query_params.items() + } + + # Start with default query params (lowest priority) + merged_params = {} + if default_query_params: + merged_params.update(default_query_params) + + # Override with existing URL query params (medium priority) + merged_params.update(updated_existing_query_params) + + # Override with request query params (highest priority - client can override anything) + merged_params.update(request_query_params) + + return merged_params + + @staticmethod + def forward_headers_from_request( + request_headers: dict, + headers: dict, + forward_headers: Optional[bool] = False, + ): + """ + Helper to forward headers from original request. + + Also handles 'x-pass-' prefixed headers which are always forwarded + with the prefix stripped, regardless of forward_headers setting. + e.g., 'x-pass-anthropic-beta: value' becomes 'anthropic-beta: value' + """ + if forward_headers is True: + # Header We Should NOT forward + request_headers.pop("content-length", None) + request_headers.pop("host", None) + + # Combine request headers with custom headers + headers = {**request_headers, **headers} + + # Process x-pass- prefixed headers (strip prefix and forward) + # Credential and protocol-level headers are excluded from this mechanism. + for header_name, header_value in request_headers.items(): + if header_name.lower().startswith(PASS_THROUGH_HEADER_PREFIX): + # Strip the 'x-pass-' prefix and normalize to lowercase + actual_header_name = header_name[ + len(PASS_THROUGH_HEADER_PREFIX) : + ].lower() + if actual_header_name in _PASS_THROUGH_PROTECTED_HEADERS or any( + actual_header_name.startswith(p) + for p in _PASS_THROUGH_PROTECTED_HEADER_PREFIXES + ): + verbose_logger.debug( + "x-pass- header %s maps to a protected header name; skipping", + header_name, + ) + continue + headers[actual_header_name] = header_value + + return headers + + +class CommonUtils: + @staticmethod + def encode_bedrock_runtime_modelid_arn(endpoint: str) -> str: + """ + Encodes any "/" found in the modelId of an AWS Bedrock Runtime Endpoint when arns are passed in. + - modelID value can be an ARN which contains slashes that SHOULD NOT be treated as path separators. + e.g endpoint: /model//invoke + containing arns with slashes need to be encoded from + arn:aws:bedrock:ap-southeast-1:123456789012:application-inference-profile/abdefg12334 => + arn:aws:bedrock:ap-southeast-1:123456789012:application-inference-profile%2Fabdefg12334 + so that it is treated as one part of the path. + Otherwise, the encoded endpoint will return 500 error when passed to Bedrock endpoint. + + See the apis in https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html + for more details on the regex patterns of modelId which we use in the regex logic below. + + Args: + endpoint (str): The original endpoint string which may contain ARNs that contain slashes. + + Returns: + str: The endpoint with properly encoded ARN slashes + """ + import re + + # Early exit: if no ARN detected, return unchanged + if "arn:aws:" not in endpoint: + return endpoint + + # Handle all patterns in one go - more efficient and cleaner + patterns = [ + # Custom model with 2 slashes (order matters - do this first) + (r"(custom-model)/([a-z0-9.-]+)/([a-z0-9]+)", r"\1%2F\2%2F\3"), + # All other resource types with 1 slash + (r"(:application-inference-profile)/", r"\1%2F"), + (r"(:inference-profile)/", r"\1%2F"), + (r"(:foundation-model)/", r"\1%2F"), + (r"(:imported-model)/", r"\1%2F"), + (r"(:provisioned-model)/", r"\1%2F"), + (r"(:prompt)/", r"\1%2F"), + (r"(:endpoint)/", r"\1%2F"), + (r"(:prompt-router)/", r"\1%2F"), + (r"(:default-prompt-router)/", r"\1%2F"), + ] + + for pattern, replacement in patterns: + # Check if pattern exists before applying regex (early exit optimization) + if re.search(pattern, endpoint): + endpoint = re.sub(pattern, replacement, endpoint) + break # Exit after first match since each ARN has only one resource type + + return endpoint diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/proxy_auth/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/proxy_auth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27624a94fb9d60f0b0670a0179f6eadd2c174c17 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/proxy_auth/__init__.py @@ -0,0 +1,30 @@ +""" +Proxy Authentication module for LiteLLM SDK. + +This module provides OAuth2/JWT token management for authenticating +with LiteLLM Proxy or any OAuth2-protected endpoint. + +Usage: + from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler + + litellm.proxy_auth = ProxyAuthHandler( + credential=AzureADCredential(), + scope="api://my-proxy/.default" + ) +""" + +from .credentials import ( + AccessToken, + TokenCredential, + AzureADCredential, + GenericOAuth2Credential, + ProxyAuthHandler, +) + +__all__ = [ + "AccessToken", + "TokenCredential", + "AzureADCredential", + "GenericOAuth2Credential", + "ProxyAuthHandler", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/proxy_auth/credentials.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/proxy_auth/credentials.py new file mode 100644 index 0000000000000000000000000000000000000000..103b0088d80979d60072718827637ee3ecec9bc1 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/proxy_auth/credentials.py @@ -0,0 +1,240 @@ +""" +Credential providers for proxy authentication. + +This module provides a provider-agnostic interface for obtaining OAuth2/JWT tokens. +It follows the same TokenCredential protocol used by Azure SDK. +""" + +import time +from dataclasses import dataclass +from typing import Any, Optional, Protocol, runtime_checkable + + +@dataclass +class AccessToken: + """ + Represents an OAuth2 access token with expiration. + + This matches the structure used by azure.core.credentials.AccessToken. + + Attributes: + token: The access token string (typically a JWT). + expires_on: Unix timestamp when the token expires. + """ + + token: str + expires_on: int + + +@runtime_checkable +class TokenCredential(Protocol): + """ + Protocol for credential providers. + + This matches the azure.core.credentials.TokenCredential interface, + allowing any Azure SDK credential to be used directly. + + Any class implementing get_token(scope) -> AccessToken can be used. + """ + + def get_token(self, scope: str) -> AccessToken: + """ + Get an access token for the specified scope. + + Args: + scope: The OAuth2 scope to request (e.g., "api://my-app/.default") + + Returns: + AccessToken with the token string and expiration timestamp. + """ + ... + + +class AzureADCredential: + """ + Wrapper for Azure Identity credentials. + + This wraps any azure-identity credential (DefaultAzureCredential, + ClientSecretCredential, ManagedIdentityCredential, etc.) and converts + the token to our AccessToken format. + + If no credential is provided, it will use DefaultAzureCredential + which tries multiple authentication methods automatically. + + Example: + # Use default credential chain (env vars, managed identity, CLI, etc.) + cred = AzureADCredential() + + # Or provide a specific credential + from azure.identity import ClientSecretCredential + azure_cred = ClientSecretCredential(tenant_id, client_id, client_secret) + cred = AzureADCredential(credential=azure_cred) + """ + + def __init__(self, credential: Optional[Any] = None): + """ + Initialize with an optional Azure credential. + + Args: + credential: An azure-identity credential object. If None, + DefaultAzureCredential will be used on first token request. + """ + self._credential: Any = credential + self._initialized = credential is not None + + def get_token(self, scope: str) -> AccessToken: + """ + Get an access token from Azure AD. + + Args: + scope: The OAuth2 scope (e.g., "api://my-app/.default") + + Returns: + AccessToken with the JWT and expiration. + + Raises: + ImportError: If azure-identity is not installed. + """ + if not self._initialized: + try: + from azure.identity import DefaultAzureCredential + + self._credential = DefaultAzureCredential() + self._initialized = True + except ImportError: + raise ImportError( + "azure-identity is required for AzureADCredential. " + "Install it with: pip install azure-identity" + ) + + result = self._credential.get_token(scope) + return AccessToken(token=result.token, expires_on=result.expires_on) + + +class GenericOAuth2Credential: + """ + Generic OAuth2 client credentials flow. + + This works with any OAuth2 provider (Okta, Auth0, Keycloak, etc.) + that supports the client_credentials grant type. + + Example: + cred = GenericOAuth2Credential( + client_id="my-client-id", + client_secret="my-client-secret", + token_url="https://my-idp.com/oauth2/token" + ) + """ + + def __init__(self, client_id: str, client_secret: str, token_url: str): + """ + Initialize OAuth2 client credentials. + + Args: + client_id: OAuth2 client ID + client_secret: OAuth2 client secret + token_url: Token endpoint URL (e.g., "https://idp.com/oauth2/token") + """ + self.client_id = client_id + self.client_secret = client_secret + self.token_url = token_url + self._cached_token: Optional[AccessToken] = None + + def get_token(self, scope: str) -> AccessToken: + """ + Get an access token using OAuth2 client credentials flow. + + Tokens are cached and reused until they expire (with 60s buffer). + + Args: + scope: The OAuth2 scope to request + + Returns: + AccessToken with the token and expiration. + """ + # Return cached token if still valid (with 60s buffer) + if self._cached_token and self._cached_token.expires_on > time.time() + 60: + return self._cached_token + + import httpx + + response = httpx.post( + self.token_url, + data={ + "grant_type": "client_credentials", + "client_id": self.client_id, + "client_secret": self.client_secret, + "scope": scope, + }, + ) + response.raise_for_status() + data = response.json() + + self._cached_token = AccessToken( + token=data["access_token"], + expires_on=int(time.time()) + data.get("expires_in", 3600), + ) + return self._cached_token + + +class ProxyAuthHandler: + """ + Manages OAuth2/JWT token lifecycle for proxy authentication. + + This handler: + - Obtains tokens from the configured credential provider + - Caches tokens to avoid unnecessary requests + - Automatically refreshes tokens before they expire (60s buffer) + - Generates Authorization headers for HTTP requests + + Set this as litellm.proxy_auth to automatically inject auth headers + into all requests to your LiteLLM Proxy. + + Example: + import litellm + from litellm.proxy_auth import AzureADCredential, ProxyAuthHandler + + litellm.proxy_auth = ProxyAuthHandler( + credential=AzureADCredential(), + scope="api://my-litellm-proxy/.default" + ) + litellm.api_base = "https://my-proxy.example.com" + + # Auth headers are now automatically injected + response = litellm.completion(model="gpt-4", messages=[...]) + """ + + def __init__(self, credential: TokenCredential, scope: str): + """ + Initialize the proxy auth handler. + + Args: + credential: A TokenCredential implementation (AzureADCredential, + GenericOAuth2Credential, or any custom implementation) + scope: The OAuth2 scope to request tokens for + """ + self.credential = credential + self.scope = scope + self._cached_token: Optional[AccessToken] = None + + def get_token(self) -> AccessToken: + """ + Get a valid access token, refreshing if necessary. + + Returns: + AccessToken that is valid for at least 60 more seconds. + """ + # Refresh if no token or token expires within 60 seconds + if not self._cached_token or self._cached_token.expires_on <= time.time() + 60: + self._cached_token = self.credential.get_token(self.scope) + return self._cached_token + + def get_auth_headers(self) -> dict: + """ + Get HTTP headers for authentication. + + Returns: + Dict with Authorization header containing Bearer token. + """ + token = self.get_token() + return {"Authorization": f"Bearer {token.token}"} diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/realtime_api/README.md b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/realtime_api/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6b467c056a60f6f49a806887df0cd8213b81d71f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/realtime_api/README.md @@ -0,0 +1 @@ +Abstraction / Routing logic for OpenAI's `/v1/realtime` endpoint. \ No newline at end of file diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/realtime_api/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/realtime_api/main.py new file mode 100644 index 0000000000000000000000000000000000000000..842e5ea4859f822de16ca7d6b2ab92a6438a7280 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/realtime_api/main.py @@ -0,0 +1,539 @@ +"""Abstraction function for OpenAI's realtime API""" + +import os +from typing import Any, Dict, Optional, cast + +import litellm +from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, request_timeout +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider +from litellm.llms.base_llm.realtime.transformation import BaseRealtimeConfig +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.secret_managers.main import get_secret_str +from litellm.types.realtime import ( + RealtimeClientSecretRequest, + RealtimeExpiresAfter, + RealtimeQueryParams, + RealtimeSessionConfig, +) +from litellm.types.router import GenericLiteLLMParams +from litellm.types.utils import LlmProviders +from litellm.utils import ProviderConfigManager + +from ..litellm_core_utils.get_litellm_params import get_litellm_params +from ..litellm_core_utils.litellm_logging import Logging as LiteLLMLogging +from ..llms.azure.realtime.handler import AzureOpenAIRealtime +from ..llms.bedrock.realtime.handler import BedrockRealtime +from ..llms.custom_httpx.http_handler import get_shared_realtime_ssl_context +from ..llms.openai.realtime.handler import OpenAIRealtime +from ..llms.vertex_ai.realtime.transformation import VertexAIRealtimeConfig +from ..llms.vertex_ai.vertex_llm_base import VertexBase +from ..llms.xai.realtime.handler import XAIRealtime +from ..utils import client as wrapper_client + +azure_realtime = AzureOpenAIRealtime() +openai_realtime = OpenAIRealtime() +bedrock_realtime = BedrockRealtime() +xai_realtime = XAIRealtime() +vertex_llm_base = VertexBase() +base_llm_http_handler = BaseLLMHTTPHandler() + + +def _build_litellm_metadata(kwargs: dict) -> dict: + """Build the litellm_metadata dict for guardrail checking (internal only, not forwarded to provider).""" + metadata: dict = {**(kwargs.get("litellm_metadata") or {})} + guardrails = ( + (kwargs.get("metadata") or {}).get("guardrails") + or kwargs.get("guardrails") + or [] + ) + if guardrails: + metadata["guardrails"] = guardrails + return metadata + + +def _get_realtime_http_provider_config( + custom_llm_provider: str, + dynamic_api_base: Optional[str], + dynamic_api_key: Optional[str], + litellm_params: GenericLiteLLMParams, +) -> tuple[Any, str, str]: + """ + Return (provider_config, resolved_api_base, resolved_api_key) for the + realtime HTTP endpoints (client_secrets / realtime_calls). + + Uses ProviderConfigManager so each provider keeps its credential-resolution + and URL-construction logic in its own transformation class. + """ + from litellm.llms.base_llm.realtime.http_transformation import ( + BaseRealtimeHTTPConfig, + ) + + provider_config: Optional[BaseRealtimeHTTPConfig] = None + if custom_llm_provider in LlmProviders._member_map_.values(): + provider_config = ProviderConfigManager.get_provider_realtime_http_config( + model="", + provider=LlmProviders(custom_llm_provider), + ) + + raw_api_base = dynamic_api_base or litellm_params.api_base + raw_api_key = dynamic_api_key or litellm_params.api_key + + if provider_config is not None: + resolved_api_base = provider_config.get_api_base(api_base=raw_api_base) + resolved_api_key = provider_config.get_api_key(api_key=raw_api_key) + else: + # Fallback for providers without a dedicated HTTP config (treated as OpenAI-compatible). + resolved_api_base = raw_api_base or litellm.api_base or "https://api.openai.com" + resolved_api_key = ( + raw_api_key + or litellm.api_key + or litellm.openai_key + or get_secret_str("OPENAI_API_KEY") + or "" + ) + + return provider_config, resolved_api_base.rstrip("/"), resolved_api_key + + +@wrapper_client +async def acreate_realtime_client_secret( + model: Optional[str] = None, + session: Optional[Dict[str, Any]] = None, + expires_after: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, +): + req = RealtimeClientSecretRequest( + model=model, + session=RealtimeSessionConfig(**session) if session else None, + expires_after=RealtimeExpiresAfter(**expires_after) if expires_after else None, + ) + model_name = ( + (req.session.model if req.session is not None else None) + or req.model + or "gpt-4o-realtime-preview" + ) + litellm_logging_obj: LiteLLMLogging = kwargs.get("litellm_logging_obj") # type: ignore + litellm_params = GenericLiteLLMParams(**kwargs) + + ( + model_name, + custom_llm_provider, + dynamic_api_key, + dynamic_api_base, + ) = get_llm_provider( + model=model_name, + api_base=litellm_params.api_base, + api_key=litellm_params.api_key, + ) + ( + provider_config, + resolved_api_base, + resolved_api_key, + ) = _get_realtime_http_provider_config( + custom_llm_provider=custom_llm_provider, + dynamic_api_base=dynamic_api_base, + dynamic_api_key=dynamic_api_key, + litellm_params=litellm_params, + ) + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=model_name, + optional_params={"expires_after": expires_after, "session": session}, + litellm_params={"api_base": resolved_api_base}, + custom_llm_provider=custom_llm_provider, + ) + request_data = req.model_dump(exclude_none=True, exclude={"model"}) + return await base_llm_http_handler.async_realtime_client_secret_handler( + api_base=resolved_api_base, + api_key=resolved_api_key, + request_data=request_data, + logging_obj=litellm_logging_obj, + timeout=timeout or request_timeout, + provider_config=provider_config, + model=model_name, + extra_headers=kwargs.get("extra_headers"), + client=kwargs.get("client"), + api_version=litellm_params.api_version, + ) + + +@wrapper_client +async def arealtime_calls( + openai_ephemeral_key: str, + sdp_body: bytes, + model: Optional[str] = None, + session: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, +): + model_name = model or "gpt-4o-realtime-preview" + litellm_logging_obj: LiteLLMLogging = kwargs.get("litellm_logging_obj") # type: ignore + litellm_params = GenericLiteLLMParams(**kwargs) + + ( + model_name, + custom_llm_provider, + dynamic_api_key, + dynamic_api_base, + ) = get_llm_provider( + model=model_name, + api_base=litellm_params.api_base, + api_key=litellm_params.api_key, + ) + provider_config, resolved_api_base, _ = _get_realtime_http_provider_config( + custom_llm_provider=custom_llm_provider, + dynamic_api_base=dynamic_api_base, + dynamic_api_key=dynamic_api_key, + litellm_params=litellm_params, + ) + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=model_name, + optional_params={"realtime_calls": True, "session": session}, + litellm_params={"api_base": resolved_api_base}, + custom_llm_provider=custom_llm_provider, + ) + return await base_llm_http_handler.async_realtime_calls_handler( + api_base=resolved_api_base, + openai_ephemeral_key=openai_ephemeral_key, + sdp_body=sdp_body, + logging_obj=litellm_logging_obj, + timeout=timeout or request_timeout, + provider_config=provider_config, + model=model_name, + session_config=session, + extra_headers=kwargs.get("extra_headers"), + client=kwargs.get("client"), + api_version=litellm_params.api_version, + ) + + +@wrapper_client +async def _arealtime( # noqa: PLR0915 + model: str, + websocket: Any, # fastapi websocket + api_base: Optional[str] = None, + api_key: Optional[str] = None, + api_version: Optional[str] = None, + azure_ad_token: Optional[str] = None, + client: Optional[Any] = None, + timeout: Optional[float] = None, + query_params: Optional[RealtimeQueryParams] = None, + **kwargs, +): + """ + Private function to handle the realtime API call. + + For PROXY use only. + """ + headers = cast(Optional[dict], kwargs.get("headers")) + extra_headers = cast(Optional[dict], kwargs.get("extra_headers")) + if headers is None: + headers = {} + if extra_headers is not None: + headers.update(extra_headers) + litellm_logging_obj: LiteLLMLogging = kwargs.get("litellm_logging_obj") # type: ignore + user = kwargs.get("user", None) + litellm_params = GenericLiteLLMParams(**kwargs) + + litellm_params_dict = get_litellm_params(**kwargs) + + model, _custom_llm_provider, dynamic_api_key, dynamic_api_base = get_llm_provider( + model=model, + api_base=api_base, + api_key=api_key, + ) + + # Ensure query params use the normalized provider model (no proxy aliases). + if query_params is not None: + query_params = {**query_params, "model": model} + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=model, + user=user, + optional_params={}, + litellm_params=litellm_params_dict, + custom_llm_provider=_custom_llm_provider, + ) + + provider_config: Optional[BaseRealtimeConfig] = None + if _custom_llm_provider in LlmProviders._member_map_.values(): + provider_config = ProviderConfigManager.get_provider_realtime_config( + model=model, + provider=LlmProviders(_custom_llm_provider), + ) + if provider_config is not None: + await base_llm_http_handler.async_realtime( + model=model, + websocket=websocket, + logging_obj=litellm_logging_obj, + provider_config=provider_config, + api_base=api_base, + api_key=api_key, + client=client, + timeout=timeout, + headers=headers, + user_api_key_dict=kwargs.get("user_api_key_dict"), + litellm_metadata=_build_litellm_metadata(kwargs), + ) + elif _custom_llm_provider == "azure": + api_base = ( + dynamic_api_base + or litellm_params.api_base + or litellm.api_base + or get_secret_str("AZURE_API_BASE") + ) + # set API KEY + api_key = ( + dynamic_api_key + or litellm.api_key + or litellm.openai_key + or get_secret_str("AZURE_API_KEY") + ) + + api_version = api_version or litellm_params.api_version or "2024-10-01-preview" + + realtime_protocol = ( + kwargs.get("realtime_protocol") + or litellm_params.get("realtime_protocol") + or os.environ.get("LITELLM_AZURE_REALTIME_PROTOCOL") + or "beta" + ) + await azure_realtime.async_realtime( + model=model, + websocket=websocket, + api_base=api_base, + api_key=api_key, + api_version=api_version, + azure_ad_token=None, + client=None, + timeout=timeout, + logging_obj=litellm_logging_obj, + realtime_protocol=realtime_protocol, + user_api_key_dict=kwargs.get("user_api_key_dict"), + litellm_metadata=_build_litellm_metadata(kwargs), + ) + elif _custom_llm_provider == "openai": + api_base = ( + dynamic_api_base + or litellm_params.api_base + or litellm.api_base + or "https://api.openai.com/" + ) + # set API KEY + api_key = ( + dynamic_api_key + or litellm.api_key + or litellm.openai_key + or get_secret_str("OPENAI_API_KEY") + ) + + await openai_realtime.async_realtime( + model=model, + websocket=websocket, + logging_obj=litellm_logging_obj, + api_base=api_base, + api_key=api_key, + client=None, + timeout=timeout, + query_params=query_params, + user_api_key_dict=kwargs.get("user_api_key_dict"), + litellm_metadata=_build_litellm_metadata(kwargs), + ) + elif _custom_llm_provider == "bedrock": + # Extract AWS parameters from kwargs + aws_region_name = kwargs.get("aws_region_name") + aws_access_key_id = kwargs.get("aws_access_key_id") + aws_secret_access_key = kwargs.get("aws_secret_access_key") + aws_session_token = kwargs.get("aws_session_token") + aws_role_name = kwargs.get("aws_role_name") + aws_session_name = kwargs.get("aws_session_name") + aws_profile_name = kwargs.get("aws_profile_name") + aws_web_identity_token = kwargs.get("aws_web_identity_token") + aws_sts_endpoint = kwargs.get("aws_sts_endpoint") + aws_bedrock_runtime_endpoint = kwargs.get("aws_bedrock_runtime_endpoint") + aws_external_id = kwargs.get("aws_external_id") + + await bedrock_realtime.async_realtime( + model=model, + websocket=websocket, + logging_obj=litellm_logging_obj, + api_base=dynamic_api_base or api_base, + api_key=dynamic_api_key or api_key, + timeout=timeout, + aws_region_name=aws_region_name, + aws_access_key_id=aws_access_key_id, + aws_secret_access_key=aws_secret_access_key, + aws_session_token=aws_session_token, + aws_role_name=aws_role_name, + aws_session_name=aws_session_name, + aws_profile_name=aws_profile_name, + aws_web_identity_token=aws_web_identity_token, + aws_sts_endpoint=aws_sts_endpoint, + aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, + aws_external_id=aws_external_id, + ) + elif _custom_llm_provider == "xai": + api_base = ( + dynamic_api_base + or litellm_params.api_base + or get_secret_str("XAI_API_BASE") + or "https://api.x.ai/v1" + ) + # set API KEY + api_key = dynamic_api_key or litellm.api_key or get_secret_str("XAI_API_KEY") + + await xai_realtime.async_realtime( + model=model, + websocket=websocket, + logging_obj=litellm_logging_obj, + api_base=api_base, + api_key=api_key, + client=None, + timeout=timeout, + query_params=query_params, + user_api_key_dict=kwargs.get("user_api_key_dict"), + litellm_metadata=_build_litellm_metadata(kwargs), + ) + elif _custom_llm_provider == "vertex_ai": + vertex_credentials = ( + kwargs.get("vertex_credentials") + or kwargs.get("vertex_ai_credentials") + or get_secret_str("VERTEXAI_CREDENTIALS") + ) + vertex_project = ( + kwargs.get("vertex_project") + or kwargs.get("vertex_ai_project") + or litellm.vertex_project + or get_secret_str("VERTEXAI_PROJECT") + ) + vertex_location = ( + kwargs.get("vertex_location") + or kwargs.get("vertex_ai_location") + or litellm.vertex_location + or get_secret_str("VERTEXAI_LOCATION") + ) + + resolved_location = vertex_llm_base.get_vertex_region( + vertex_region=vertex_location, model=model + ) + + ( + access_token, + resolved_project, + ) = await vertex_llm_base._ensure_access_token_async( + credentials=vertex_credentials, + project_id=vertex_project, + custom_llm_provider="vertex_ai", + ) + + vertex_realtime_config = VertexAIRealtimeConfig( + access_token=access_token, + project=resolved_project, + location=resolved_location, + ) + + await base_llm_http_handler.async_realtime( + model=model, + websocket=websocket, + logging_obj=litellm_logging_obj, + provider_config=vertex_realtime_config, + api_base=dynamic_api_base or litellm_params.api_base, + api_key=None, + client=client, + timeout=timeout, + headers=headers, + user_api_key_dict=kwargs.get("user_api_key_dict"), + litellm_metadata=_build_litellm_metadata(kwargs), + ) + else: + raise ValueError(f"Unsupported model: {model}") + + +async def _realtime_health_check( + model: str, + custom_llm_provider: str, + api_key: Optional[str], + api_base: Optional[str] = None, + api_version: Optional[str] = None, + realtime_protocol: Optional[str] = None, +): + """ + Health check for realtime API - tries connection to the realtime API websocket + + Args: + model: str - model name + api_base: str - api base + api_version: Optional[str] - api version + api_key: str - api key + custom_llm_provider: str - custom llm provider + realtime_protocol: Optional[str] - protocol version ("GA"/"v1" for GA path, "beta"/None for beta path) + + Returns: + bool - True if connection is successful, False otherwise + Raises: + Exception - if the connection is not successful + """ + import websockets + + url: Optional[str] = None + if custom_llm_provider == "azure": + url = azure_realtime._construct_url( + api_base=api_base or "", + model=model, + api_version=api_version or "2024-10-01-preview", + realtime_protocol=realtime_protocol, + ) + elif custom_llm_provider == "openai": + url = openai_realtime._construct_url( + api_base=api_base or "https://api.openai.com/", + query_params={"model": model}, + ) + elif custom_llm_provider == "xai": + url = xai_realtime._construct_url( + api_base=api_base or "https://api.x.ai/v1", query_params={"model": model} + ) + elif custom_llm_provider == "vertex_ai": + vertex_location = litellm.vertex_location or get_secret_str("VERTEXAI_LOCATION") + resolved_location = vertex_llm_base.get_vertex_region( + vertex_region=vertex_location, model=model + ) + ( + access_token, + resolved_project, + ) = await vertex_llm_base._ensure_access_token_async( + credentials=None, + project_id=litellm.vertex_project or get_secret_str("VERTEXAI_PROJECT"), + custom_llm_provider="vertex_ai", + ) + vertex_realtime_config = VertexAIRealtimeConfig( + access_token=access_token, + project=resolved_project, + location=resolved_location, + ) + url = vertex_realtime_config.get_complete_url(api_base=api_base, model=model) + ssl_context = get_shared_realtime_ssl_context() + headers = vertex_realtime_config.validate_environment( + headers={}, model=model, api_key=None + ) + async with websockets.connect( # type: ignore + url, + additional_headers=headers, + max_size=REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, + ssl=ssl_context, + ): + return True + else: + raise ValueError(f"Unsupported model: {model}") + ssl_context = get_shared_realtime_ssl_context() + async with websockets.connect( # type: ignore + url, + additional_headers={ + "api-key": api_key, # type: ignore + }, + max_size=REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES, + ssl=ssl_context, + ): + return True diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/add_retry_fallback_headers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/add_retry_fallback_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..6b921a0db8a3d1f21cdc019afe45c4b1963b3291 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/add_retry_fallback_headers.py @@ -0,0 +1,70 @@ +from typing import Any, Optional, Union + +from pydantic import BaseModel + +from litellm.types.utils import HiddenParams + + +def _add_headers_to_response(response: Any, headers: dict) -> Any: + """ + Helper function to add headers to a response's hidden params + """ + if response is None or not isinstance(response, BaseModel): + return response + + hidden_params: Optional[Union[dict, HiddenParams]] = getattr( + response, "_hidden_params", {} + ) + + if hidden_params is None: + hidden_params_dict = {} + elif isinstance(hidden_params, HiddenParams): + hidden_params_dict = hidden_params.model_dump() + else: + hidden_params_dict = hidden_params + + hidden_params_dict.setdefault("additional_headers", {}) + hidden_params_dict["additional_headers"].update(headers) + + setattr(response, "_hidden_params", hidden_params_dict) + return response + + +def add_retry_headers_to_response( + response: Any, + attempted_retries: int, + max_retries: Optional[int] = None, +) -> Any: + """ + Add retry headers to the request + """ + retry_headers = { + "x-litellm-attempted-retries": attempted_retries, + } + if max_retries is not None: + retry_headers["x-litellm-max-retries"] = max_retries + + return _add_headers_to_response(response, retry_headers) + + +def add_fallback_headers_to_response( + response: Any, + attempted_fallbacks: int, +) -> Any: + """ + Add fallback headers to the response + + Args: + response: The response to add the headers to + attempted_fallbacks: The number of fallbacks attempted + + Returns: + The response with the headers added + + Note: It's intentional that we don't add max_fallbacks in response headers + Want to avoid bloat in the response headers for performance. + """ + fallback_headers = { + "x-litellm-attempted-fallbacks": attempted_fallbacks, + } + return _add_headers_to_response(response, fallback_headers) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/batch_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/batch_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5e58479825bae74a8f4708ecfefc54bc5d141efa --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/batch_utils.py @@ -0,0 +1,150 @@ +import io +import json +from os import PathLike +from typing import List, Optional + +from litellm._logging import verbose_logger +from litellm.types.llms.openai import FileTypes, OpenAIFilesPurpose + + +class InMemoryFile(io.BytesIO): + def __init__( + self, content: bytes, name: str, content_type: str = "application/jsonl" + ): + super().__init__(content) + self.name = name + self.content_type = content_type + + +def parse_jsonl_with_embedded_newlines(content: str) -> List[dict]: + """ + Parse JSONL content that may contain JSON objects with embedded newlines in string values. + + Unlike splitlines(), this function properly handles cases where JSON string values + contain literal newline characters, which would otherwise break simple line-based parsing. + + Args: + content: The JSONL file content as a string + + Returns: + List of parsed JSON objects + + Example: + >>> content = '{"id":1,"msg":"Line 1\\nLine 2"}\\n{"id":2,"msg":"test"}' + >>> parse_jsonl_with_embedded_newlines(content) + [{"id":1,"msg":"Line 1\\nLine 2"}, {"id":2,"msg":"test"}] + """ + json_objects = [] + buffer = "" + + for char in content: + buffer += char + if char == "\n": + # Try to parse what we have so far + try: + json_object = json.loads(buffer.strip()) + json_objects.append(json_object) + buffer = "" # Reset buffer for next JSON object + except json.JSONDecodeError: + # Not a complete JSON object yet, keep accumulating + continue + + # Handle any remaining content in buffer + if buffer.strip(): + try: + json_object = json.loads(buffer.strip()) + json_objects.append(json_object) + except json.JSONDecodeError as e: + verbose_logger.error( + f"error parsing final buffer: {buffer[:100]}..., error: {e}" + ) + raise e + + return json_objects + + +def should_replace_model_in_jsonl( + purpose: OpenAIFilesPurpose, +) -> bool: + """ + Check if the model name should be replaced in the JSONL file for the deployment model name. + + Azure raises an error on create batch if the model name for deployment is not in the .jsonl. + """ + if purpose == "batch": + return True + return False + + +def replace_model_in_jsonl(file_content: FileTypes, new_model_name: str) -> FileTypes: + try: + ## if pathlike, return the original file content + if isinstance(file_content, PathLike): + return file_content + + # Decode the bytes to a string and split into lines + # If file_content is a file-like object, read the bytes + if hasattr(file_content, "read"): + file_content_bytes = file_content.read() # type: ignore + elif isinstance(file_content, tuple): + file_content_bytes = file_content[1] + else: + file_content_bytes = file_content + + # Decode the bytes to a string and split into lines + if isinstance(file_content_bytes, bytes): + file_content_str = file_content_bytes.decode("utf-8") + elif isinstance(file_content_bytes, str): + file_content_str = file_content_bytes + else: + return file_content + + # Parse JSONL properly, handling potential multiline JSON objects + json_objects = parse_jsonl_with_embedded_newlines(file_content_str) + + # If no valid JSON objects were found, return the original content + if len(json_objects) == 0: + return file_content + + modified_lines = [] + for json_object in json_objects: + # Replace the model name if it exists + if "body" in json_object: + json_object["body"]["model"] = new_model_name + + # Convert the modified JSON object back to a string + modified_lines.append(json.dumps(json_object)) + + # Reassemble the modified lines and return as bytes + modified_file_content = "\n".join(modified_lines).encode("utf-8") + + return InMemoryFile(modified_file_content, name="modified_file.jsonl", content_type="application/jsonl") # type: ignore + + except (json.JSONDecodeError, UnicodeDecodeError, TypeError): + # return the original file content if there is an error replacing the model name + return file_content + + +def _get_router_metadata_variable_name(function_name: Optional[str]) -> str: + """ + Helper to return what the "metadata" field should be called in the request data + + For all /thread or /assistant endpoints we need to call this "litellm_metadata" + + For ALL other endpoints we call this "metadata + """ + ROUTER_METHODS_USING_LITELLM_METADATA = set( + [ + "batch", + "generic_api_call", + "_acreate_batch", + "file", + "_ageneric_api_call_with_fallbacks", + ] + ) + if function_name and any( + method in function_name for method in ROUTER_METHODS_USING_LITELLM_METADATA + ): + return "litellm_metadata" + else: + return "metadata" diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/client_initalization_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/client_initalization_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e24d237853e67607d65f9010e2906cccb3dc3684 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/client_initalization_utils.py @@ -0,0 +1,37 @@ +import asyncio +from typing import TYPE_CHECKING, Any + +from litellm.utils import calculate_max_parallel_requests + +if TYPE_CHECKING: + from litellm.router import Router as _Router + + LitellmRouter = _Router +else: + LitellmRouter = Any + + +class InitalizeCachedClient: + @staticmethod + def set_max_parallel_requests_client( + litellm_router_instance: LitellmRouter, model: dict + ): + litellm_params = model.get("litellm_params", {}) + model_id = model["model_info"]["id"] + rpm = litellm_params.get("rpm", None) + tpm = litellm_params.get("tpm", None) + max_parallel_requests = litellm_params.get("max_parallel_requests", None) + calculated_max_parallel_requests = calculate_max_parallel_requests( + rpm=rpm, + max_parallel_requests=max_parallel_requests, + tpm=tpm, + default_max_parallel_requests=litellm_router_instance.default_max_parallel_requests, + ) + if calculated_max_parallel_requests: + semaphore = asyncio.Semaphore(calculated_max_parallel_requests) + cache_key = f"{model_id}_max_parallel_requests_client" + litellm_router_instance.cache.set_cache( + key=cache_key, + value=semaphore, + local_only=True, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/clientside_credential_handler.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/clientside_credential_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..45ade81b2dd2c7d94718a274b0e086a81290f030 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/clientside_credential_handler.py @@ -0,0 +1,104 @@ +""" +Utils for handling clientside credentials + +Supported clientside credentials: +- api_key +- api_base +- base_url + +If given, generate a unique model_id for the deployment. + +Ensures cooldowns are applied correctly. +""" + +from typing import List + +clientside_credential_keys = ["api_key", "api_base", "base_url"] + + +def _admin_config_fields_to_clear_on_base_override() -> List[str]: + """ + Provider-specific credential / endpoint-targeting fields that must NOT + flow through to a client-redirected upstream. + + Built dynamically from ``CredentialLiteLLMParams.model_fields`` so any + new provider field added there (Bedrock endpoint, Watsonx region, etc.) + is gated automatically — plus a fixed list of kwargs-only fields that + aren't declared on the typed model. + """ + from litellm.types.router import CredentialLiteLLMParams + + typed_fields = [ + f + for f in CredentialLiteLLMParams.model_fields + if f not in clientside_credential_keys + ] + kwargs_only_fields = [ + # Caller-supplied via **kwargs, not declared on CredentialLiteLLMParams. + "organization", + "extra_body", + "extra_headers", + "default_headers", + "api_type", + "azure_ad_token", + "azure_ad_token_provider", + "aws_session_token", + "aws_sts_endpoint", + "aws_web_identity_token", + "aws_role_name", + # OCI provider — consumed by litellm/llms/oci/* via optional_params + # and not declared on CredentialLiteLLMParams. Without these here, + # an admin's OCI signing key / tenancy / fingerprint would flow + # through to an attacker-redirected upstream. + "oci_signer", + "oci_user", + "oci_fingerprint", + "oci_tenancy", + "oci_key", + "oci_key_file", + ] + return typed_fields + kwargs_only_fields + + +_ADMIN_CONFIG_FIELDS_TO_CLEAR_ON_BASE_OVERRIDE = ( + _admin_config_fields_to_clear_on_base_override() +) + + +def is_clientside_credential(request_kwargs: dict) -> bool: + """ + Check if the credential is a clientside credential. + """ + return any(key in request_kwargs for key in clientside_credential_keys) + + +def get_dynamic_litellm_params(litellm_params: dict, request_kwargs: dict) -> dict: + """ + Generate a unique model_id for the deployment. + + Returns + - litellm_params: dict + + for generating a unique model_id. + """ + # update litellm_params with clientside credentials + for key in clientside_credential_keys: + if key in request_kwargs: + litellm_params[key] = request_kwargs[key] + + # If the caller redirected api_base/base_url to a client-controlled value, + # don't forward the admin's organization / extra_body / region / token / + # vertex / aws fields — those were meant for the original upstream. + # Always drop the admin's value first, then write the caller's value back + # if they resupplied the field. The naive + # ``if field not in request_kwargs: pop`` shape lets a caller *echo* a + # field name (with any value, including an empty string) to keep the + # admin's value in ``litellm_params`` and have it forwarded to the + # redirected upstream. + if "api_base" in request_kwargs or "base_url" in request_kwargs: + for field in _ADMIN_CONFIG_FIELDS_TO_CLEAR_ON_BASE_OVERRIDE: + litellm_params.pop(field, None) + if field in request_kwargs: + litellm_params[field] = request_kwargs[field] + + return litellm_params diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/common_utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/common_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f6da26ccd7fc962522358cf9a83fab77eee8884b --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/common_utils.py @@ -0,0 +1,137 @@ +import hashlib +import json +from typing import TYPE_CHECKING, Dict, List, Optional, Union + +if TYPE_CHECKING: + from litellm.types.llms.openai import OpenAIFileObject + +from litellm.types.router import CredentialLiteLLMParams +from litellm._logging import verbose_logger + + +def get_litellm_params_sensitive_credential_hash(litellm_params: dict) -> str: + """ + Hash of the credential params, used for mapping the file id to the right model + """ + sensitive_params = CredentialLiteLLMParams(**litellm_params) + return hashlib.sha256( + json.dumps(sensitive_params.model_dump()).encode() + ).hexdigest() + + +def add_model_file_id_mappings( + healthy_deployments: Union[List[Dict], Dict], responses: List["OpenAIFileObject"] +) -> dict: + """ + Create a mapping of model id to file id + { + "model_id": "file_id", + "model_id": "file_id", + } + + `healthy_deployments` may be either a list of deployment dicts (multiple + matched deployments) or a single deployment dict (when the router resolved + a specific deployment, e.g. because the requested model matched a + `model_info.id`). Both shapes must be handled by extracting + `model_info.id` from each deployment. + """ + model_file_id_mapping: Dict[str, str] = {} + deployments_list: List[Dict] = ( + healthy_deployments + if isinstance(healthy_deployments, list) + else [healthy_deployments] + ) + for deployment, response in zip(deployments_list, responses): + model_id = deployment.get("model_info", {}).get("id") + if model_id is not None: + model_file_id_mapping[model_id] = response.id + return model_file_id_mapping + + +def filter_team_based_models( + healthy_deployments: Union[List[Dict], Dict], + request_kwargs: Optional[Dict] = None, +) -> Union[List[Dict], Dict]: + """ + If a model has a team_id + + Only use if request is from that team + """ + if request_kwargs is None: + return healthy_deployments + + metadata = request_kwargs.get("metadata") or {} + litellm_metadata = request_kwargs.get("litellm_metadata") or {} + request_team_id = metadata.get("user_api_key_team_id") or litellm_metadata.get( + "user_api_key_team_id" + ) + ids_to_remove = set() + if isinstance(healthy_deployments, dict): + return healthy_deployments + for deployment in healthy_deployments: + _model_info = deployment.get("model_info") or {} + model_team_id = _model_info.get("team_id") + if model_team_id is None: + continue + if model_team_id != request_team_id: + ids_to_remove.add(_model_info.get("id")) + + return [ + deployment + for deployment in healthy_deployments + if deployment.get("model_info", {}).get("id") not in ids_to_remove + ] + + +def _deployment_supports_web_search(deployment: Dict) -> bool: + """ + Check if a deployment supports web search. + + Priority: + 1. Check config-level override in model_info.supports_web_search + 2. Default to True (assume supported unless explicitly disabled) + + Note: Ideally we'd fall back to litellm.supports_web_search() but + model_prices_and_context_window.json doesn't have supports_web_search + tags on all models yet. TODO: backfill and add fallback. + """ + model_info = deployment.get("model_info", {}) + + if "supports_web_search" in model_info: + return model_info["supports_web_search"] + + return True + + +def filter_web_search_deployments( + healthy_deployments: Union[List[Dict], Dict], + request_kwargs: Optional[Dict] = None, +) -> Union[List[Dict], Dict]: + """ + If the request is websearch, filter out deployments that don't support web search + """ + if request_kwargs is None: + return healthy_deployments + # When a specific deployment was already chosen, it's returned as a dict + # rather than a list - nothing to filter, just pass through + if isinstance(healthy_deployments, dict): + return healthy_deployments + + is_web_search_request = False + tools = request_kwargs.get("tools") or [] + for tool in tools: + # These are the two websearch tools for OpenAI / Azure. + if tool.get("type") == "web_search" or tool.get("type") == "web_search_preview": + is_web_search_request = True + break + + if not is_web_search_request: + return healthy_deployments + + # Filter out deployments that don't support web search + final_deployments = [ + d for d in healthy_deployments if _deployment_supports_web_search(d) + ] + if len(healthy_deployments) > 0 and len(final_deployments) == 0: + verbose_logger.warning("No deployments support web search for request") + return final_deployments diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..b210ea44596555bed57d628a40f30a76bf804867 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_cache.py @@ -0,0 +1,193 @@ +""" +Wrapper around router cache. Meant to handle model cooldown logic +""" + +import functools +import time +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union + +from typing_extensions import TypedDict + +from litellm import verbose_logger +from litellm.caching.caching import DualCache +from litellm.caching.in_memory_cache import InMemoryCache +from litellm.litellm_core_utils.sensitive_data_masker import SensitiveDataMasker + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + Span = Union[_Span, Any] +else: + Span = Any + + +class CooldownCacheValue(TypedDict): + exception_received: str + status_code: str + timestamp: float + cooldown_time: float + + +class CooldownCache: + def __init__(self, cache: DualCache, default_cooldown_time: float): + self.cache = cache + self.default_cooldown_time = default_cooldown_time + self.in_memory_cache = InMemoryCache() + # Initialize the masker with custom settings for exception strings + self.exception_masker = SensitiveDataMasker( + visible_prefix=50, # Show first 50 characters + visible_suffix=0, # Show last 0 characters + mask_char="*", # Use * for masking + ) + + def _common_add_cooldown_logic( + self, model_id: str, original_exception, exception_status, cooldown_time: float + ) -> Tuple[str, CooldownCacheValue]: + try: + current_time = time.time() + cooldown_key = CooldownCache.get_cooldown_cache_key(model_id) + + # Store the cooldown information for the deployment separately + cooldown_data = CooldownCacheValue( + exception_received=self.exception_masker._mask_value( + str(original_exception) + ), + status_code=str(exception_status), + timestamp=current_time, + cooldown_time=cooldown_time, + ) + + return cooldown_key, cooldown_data + except Exception as e: + verbose_logger.error( + "CooldownCache::_common_add_cooldown_logic - Exception occurred - {}".format( + str(e) + ) + ) + raise e + + def add_deployment_to_cooldown( + self, + model_id: str, + original_exception: Exception, + exception_status: int, + cooldown_time: Optional[float], + ): + try: + ######################################################### + # get cooldown time + # 1. If dynamic cooldown time is set for the model/deployment, use that + # 2. If no dynamic cooldown time is set, use the default cooldown time set on CooldownCache + _cooldown_time = cooldown_time + if _cooldown_time is None: + _cooldown_time = self.default_cooldown_time + ######################################################### + + cooldown_key, cooldown_data = self._common_add_cooldown_logic( + model_id=model_id, + original_exception=original_exception, + exception_status=exception_status, + cooldown_time=_cooldown_time, + ) + + # Set the cache with a TTL equal to the cooldown time + self.cache.set_cache( + value=cooldown_data, + key=cooldown_key, + ttl=_cooldown_time, + ) + except Exception as e: + verbose_logger.error( + "CooldownCache::add_deployment_to_cooldown - Exception occurred - {}".format( + str(e) + ) + ) + raise e + + @staticmethod + @functools.lru_cache(maxsize=1024) + def get_cooldown_cache_key(model_id: str) -> str: + return "deployment:" + model_id + ":cooldown" + + async def async_get_active_cooldowns( + self, model_ids: List[str], parent_otel_span: Optional[Span] + ) -> List[Tuple[str, CooldownCacheValue]]: + # Generate the keys for the deployments + keys = [ + CooldownCache.get_cooldown_cache_key(model_id) for model_id in model_ids + ] + + # Retrieve the values for the keys using mget + ## more likely to be none if no models ratelimited. So just check redis every 1s + ## each redis call adds ~100ms latency. + + ## check in memory cache first + results = await self.cache.async_batch_get_cache( + keys=keys, parent_otel_span=parent_otel_span + ) + active_cooldowns: List[Tuple[str, CooldownCacheValue]] = [] + + if results is None or all(v is None for v in results): + return active_cooldowns + + # Process the results + for model_id, result in zip(model_ids, results): + if result and isinstance(result, dict): + cooldown_cache_value = CooldownCacheValue(**result) # type: ignore + active_cooldowns.append((model_id, cooldown_cache_value)) + + return active_cooldowns + + def get_active_cooldowns( + self, model_ids: List[str], parent_otel_span: Optional[Span] + ) -> List[Tuple[str, CooldownCacheValue]]: + # Generate the keys for the deployments + keys = [ + CooldownCache.get_cooldown_cache_key(model_id) for model_id in model_ids + ] + # Retrieve the values for the keys using mget + results = ( + self.cache.batch_get_cache(keys=keys, parent_otel_span=parent_otel_span) + or [] + ) + + active_cooldowns = [] + # Process the results + for model_id, result in zip(model_ids, results): + if result and isinstance(result, dict): + cooldown_cache_value = CooldownCacheValue(**result) # type: ignore + active_cooldowns.append((model_id, cooldown_cache_value)) + + return active_cooldowns + + def get_min_cooldown( + self, model_ids: List[str], parent_otel_span: Optional[Span] + ) -> float: + """Return min cooldown time required for a group of model id's.""" + + # Generate the keys for the deployments + keys = [f"deployment:{model_id}:cooldown" for model_id in model_ids] + + # Retrieve the values for the keys using mget + results = ( + self.cache.batch_get_cache(keys=keys, parent_otel_span=parent_otel_span) + or [] + ) + + min_cooldown_time: Optional[float] = None + # Process the results + for model_id, result in zip(model_ids, results): + if result and isinstance(result, dict): + cooldown_cache_value = CooldownCacheValue(**result) # type: ignore + if min_cooldown_time is None: + min_cooldown_time = cooldown_cache_value["cooldown_time"] + elif cooldown_cache_value["cooldown_time"] < min_cooldown_time: + min_cooldown_time = cooldown_cache_value["cooldown_time"] + + return min_cooldown_time or self.default_cooldown_time + + +# Usage example: +# cooldown_cache = CooldownCache(cache=your_cache_instance, cooldown_time=your_cooldown_time) +# cooldown_cache.add_deployment_to_cooldown(deployment, original_exception, exception_status) +# active_cooldowns = cooldown_cache.get_active_cooldowns() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_callbacks.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..343328dacf3c895e3284d2f7314732eb577cdb9f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_callbacks.py @@ -0,0 +1,101 @@ +""" +Callbacks triggered on cooling down deployments +""" + +import copy +from typing import TYPE_CHECKING, Any, Optional, Union + +import litellm +from litellm._logging import verbose_logger + +if TYPE_CHECKING: + from litellm.router import Router as _Router + + LitellmRouter = _Router + from litellm.integrations.prometheus import PrometheusLogger +else: + LitellmRouter = Any + PrometheusLogger = Any + + +async def router_cooldown_event_callback( + litellm_router_instance: LitellmRouter, + deployment_id: str, + exception_status: Union[str, int], + cooldown_time: Optional[float], +): + """ + Callback triggered when a deployment is put into cooldown by litellm + + - Updates deployment state on Prometheus + - Increments cooldown metric for deployment on Prometheus + """ + verbose_logger.debug("In router_cooldown_event_callback - updating prometheus") + _deployment = litellm_router_instance.get_deployment(model_id=deployment_id) + if _deployment is None: + verbose_logger.warning( + f"in router_cooldown_event_callback but _deployment is None for deployment_id={deployment_id}. Doing nothing" + ) + return + _litellm_params = _deployment["litellm_params"] + temp_litellm_params = copy.deepcopy(_litellm_params) + temp_litellm_params = dict(temp_litellm_params) + _model_name = _deployment.get("model_name", None) or "" + _api_base = ( + litellm.get_api_base(model=_model_name, optional_params=temp_litellm_params) + or "" + ) + model_info = _deployment["model_info"] + model_id = model_info.id + + litellm_model_name = temp_litellm_params.get("model") or "" + llm_provider = "" + try: + _, llm_provider, _, _ = litellm.get_llm_provider( + model=litellm_model_name, + custom_llm_provider=temp_litellm_params.get("custom_llm_provider"), + ) + except Exception: + pass + + # get the prometheus logger from in memory loggers + prometheusLogger: Optional[PrometheusLogger] = ( + _get_prometheus_logger_from_callbacks() + ) + + if prometheusLogger is not None: + prometheusLogger.set_deployment_complete_outage( + litellm_model_name=_model_name, + model_id=model_id, + api_base=_api_base, + api_provider=llm_provider, + ) + + prometheusLogger.increment_deployment_cooled_down( + litellm_model_name=_model_name, + model_id=model_id, + api_base=_api_base, + api_provider=llm_provider, + exception_status=str(exception_status), + ) + + return + + +def _get_prometheus_logger_from_callbacks() -> Optional[PrometheusLogger]: + """ + Checks if prometheus is a initalized callback, if yes returns it + """ + from litellm.integrations.prometheus import PrometheusLogger + + if PrometheusLogger is None: + return None + + for _callback in litellm._async_success_callback: + if isinstance(_callback, PrometheusLogger): + return _callback + for global_callback in litellm.callbacks: + if isinstance(global_callback, PrometheusLogger): + return global_callback + + return None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_handlers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..81bfac2ad191effb0754012ca2d653fb2c62cf9c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/cooldown_handlers.py @@ -0,0 +1,459 @@ +""" +Router cooldown handlers +- _set_cooldown_deployments: puts a deployment in the cooldown list +- get_cooldown_deployments: returns the list of deployments in the cooldown list +- async_get_cooldown_deployments: ASYNC: returns the list of deployments in the cooldown list + +""" + +import asyncio +import math +from typing import TYPE_CHECKING, Any, List, Optional, Union + +import litellm +from litellm._logging import verbose_router_logger +from litellm.constants import ( + DEFAULT_COOLDOWN_TIME_SECONDS, + DEFAULT_FAILURE_THRESHOLD_MINIMUM_REQUESTS, + DEFAULT_FAILURE_THRESHOLD_PERCENT, + SINGLE_DEPLOYMENT_TRAFFIC_FAILURE_THRESHOLD, +) +from litellm.router_utils.cooldown_callbacks import router_cooldown_event_callback + +from .router_callbacks.track_deployment_metrics import ( + get_deployment_failures_for_current_minute, + get_deployment_successes_for_current_minute, +) + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + from litellm.router import Router as _Router + + LitellmRouter = _Router + Span = Union[_Span, Any] +else: + LitellmRouter = Any + Span = Any + + +def _is_cooldown_required( + litellm_router_instance: LitellmRouter, + model_id: str, + exception_status: Union[str, int], + exception_str: Optional[str] = None, +) -> bool: + """ + A function to determine if a cooldown is required based on the exception status. + + Parameters: + model_id (str) The id of the model in the model list + exception_status (Union[str, int]): The status of the exception. + + Returns: + bool: True if a cooldown is required, False otherwise. + """ + try: + ignored_strings = ["APIConnectionError"] + if ( + exception_str is not None + ): # don't cooldown on litellm api connection errors errors + for ignored_string in ignored_strings: + if ignored_string in exception_str: + return False + + if isinstance(exception_status, str): + if len(exception_status) == 0: + return False + exception_status = int(exception_status) + + if exception_status >= 400 and exception_status < 500: + if exception_status == 429: + # Cool down 429 Rate Limit Errors + return True + + elif exception_status == 401: + # Cool down 401 Auth Errors + return True + + elif exception_status == 408: + return True + + elif exception_status == 404: + return True + + else: + # Do NOT cool down all other 4XX Errors + return False + + else: + # should cool down for all other errors + return True + + except Exception: + # Catch all - if any exceptions default to cooling down + return True + + +def _should_run_cooldown_logic( + litellm_router_instance: LitellmRouter, + deployment: Optional[str], + exception_status: Union[str, int], + original_exception: Any, + time_to_cooldown: Optional[float] = None, +) -> bool: + """ + Helper that decides if cooldown logic should be run + Returns False if cooldown logic should not be run + + Does not run cooldown logic when: + - router.disable_cooldowns is True + - deployment is None + - _is_cooldown_required() returns False + - deployment is in litellm_router_instance.provider_default_deployment_ids + - exception_status is not one that should be immediately retried (e.g. 401) + """ + if ( + deployment is None + or litellm_router_instance.get_model_group(id=deployment) is None + ): + verbose_router_logger.debug( + "Should Not Run Cooldown Logic: deployment id is none or model group can't be found." + ) + return False + + ######################################################### + # If time_to_cooldown is 0 or 0.0000000, don't run cooldown logic + ######################################################### + if time_to_cooldown is not None and math.isclose( + a=time_to_cooldown, b=0.0, abs_tol=1e-9 + ): + verbose_router_logger.debug( + "Should Not Run Cooldown Logic: time_to_cooldown is effectively 0" + ) + return False + + if litellm_router_instance.disable_cooldowns: + verbose_router_logger.debug( + "Should Not Run Cooldown Logic: disable_cooldowns is True" + ) + return False + + if deployment is None: + verbose_router_logger.debug("Should Not Run Cooldown Logic: deployment is None") + return False + + if not _is_cooldown_required( + litellm_router_instance=litellm_router_instance, + model_id=deployment, + exception_status=exception_status, + exception_str=str(original_exception), + ): + verbose_router_logger.debug( + "Should Not Run Cooldown Logic: _is_cooldown_required returned False" + ) + return False + + if deployment in litellm_router_instance.provider_default_deployment_ids: + verbose_router_logger.debug( + "Should Not Run Cooldown Logic: deployment is in provider_default_deployment_ids" + ) + return False + + return True + + +def _should_cooldown_deployment( + litellm_router_instance: LitellmRouter, + deployment: str, + exception_status: Union[str, int], + original_exception: Any, +) -> bool: + """ + Helper that decides if a deployment should be put in cooldown + + Returns True if the deployment should be put in cooldown + Returns False if the deployment should not be put in cooldown + + + Deployment is put in cooldown when: + - v2 logic (Current): + cooldown if: + - got a 429 error from LLM API + - if %fails/%(successes + fails) > ALLOWED_FAILURE_RATE_PER_MINUTE + - got 401 Auth error, 404 NotFounder - checked by litellm._should_retry() + + + + - v1 logic (Legacy): if allowed fails or allowed fail policy set, coolsdown if num fails in this minute > allowed fails + """ + ## BASE CASE - single deployment + model_group = litellm_router_instance.get_model_group(id=deployment) + is_single_deployment_model_group = False + if model_group is not None and len(model_group) == 1: + is_single_deployment_model_group = True + if ( + litellm_router_instance.allowed_fails_policy is None + and _is_allowed_fails_set_on_router( + litellm_router_instance=litellm_router_instance + ) + is False + ): + num_successes_this_minute = get_deployment_successes_for_current_minute( + litellm_router_instance=litellm_router_instance, deployment_id=deployment + ) + num_fails_this_minute = get_deployment_failures_for_current_minute( + litellm_router_instance=litellm_router_instance, deployment_id=deployment + ) + + total_requests_this_minute = num_successes_this_minute + num_fails_this_minute + percent_fails = 0.0 + if total_requests_this_minute > 0: + percent_fails = num_fails_this_minute / ( + num_successes_this_minute + num_fails_this_minute + ) + verbose_router_logger.debug( + "percent fails for deployment = %s, percent fails = %s, num successes = %s, num fails = %s", + deployment, + percent_fails, + num_successes_this_minute, + num_fails_this_minute, + ) + + exception_status_int = cast_exception_status_to_int(exception_status) + if exception_status_int == 429 and not is_single_deployment_model_group: + return True + elif ( + percent_fails == 1.0 + and total_requests_this_minute + >= SINGLE_DEPLOYMENT_TRAFFIC_FAILURE_THRESHOLD + ): + # Cooldown if all requests failed and we have reasonable traffic + return True + elif ( + percent_fails > DEFAULT_FAILURE_THRESHOLD_PERCENT + and total_requests_this_minute >= DEFAULT_FAILURE_THRESHOLD_MINIMUM_REQUESTS + and not is_single_deployment_model_group # by default we should avoid cooldowns on single deployment model groups + ): + # Only apply error rate cooldown when we have enough requests to make the percentage meaningful + return True + + elif ( + litellm._should_retry( + status_code=cast_exception_status_to_int(exception_status) + ) + is False + ): + return True + + return False + else: + return should_cooldown_based_on_allowed_fails_policy( + litellm_router_instance=litellm_router_instance, + deployment=deployment, + original_exception=original_exception, + ) + + return False + + +def _set_cooldown_deployments( + litellm_router_instance: LitellmRouter, + original_exception: Any, + exception_status: Union[str, int], + deployment: Optional[str] = None, + time_to_cooldown: Optional[float] = None, +) -> bool: + """ + Add a model to the list of models being cooled down for that minute, if it exceeds the allowed fails / minute + + or + + the exception is not one that should be immediately retried (e.g. 401) + + Returns: + - True if the deployment should be put in cooldown + - False if the deployment should not be put in cooldown + """ + verbose_router_logger.debug("checks 'should_run_cooldown_logic'") + + if ( + _should_run_cooldown_logic( + litellm_router_instance=litellm_router_instance, + deployment=deployment, + exception_status=exception_status, + original_exception=original_exception, + time_to_cooldown=time_to_cooldown, + ) + is False + or deployment is None + ): + verbose_router_logger.debug("should_run_cooldown_logic returned False") + return False + + exception_status_int = cast_exception_status_to_int(exception_status) + verbose_router_logger.debug(f"Attempting to add {deployment} to cooldown list") + + if _should_cooldown_deployment( + litellm_router_instance=litellm_router_instance, + deployment=deployment, + exception_status=exception_status, + original_exception=original_exception, + ): + litellm_router_instance.cooldown_cache.add_deployment_to_cooldown( + model_id=deployment, + original_exception=original_exception, + exception_status=exception_status_int, + cooldown_time=time_to_cooldown, + ) + + # Trigger cooldown callback handler + asyncio.create_task( + router_cooldown_event_callback( + litellm_router_instance=litellm_router_instance, + deployment_id=deployment, + exception_status=exception_status, + cooldown_time=time_to_cooldown, + ) + ) + return True + return False + + +async def _async_get_cooldown_deployments( + litellm_router_instance: LitellmRouter, + parent_otel_span: Optional[Span], +) -> List[str]: + """ + Async implementation of '_get_cooldown_deployments' + """ + model_ids = litellm_router_instance.get_model_ids() + cooldown_models = ( + await litellm_router_instance.cooldown_cache.async_get_active_cooldowns( + model_ids=model_ids, + parent_otel_span=parent_otel_span, + ) + ) + + cached_value_deployment_ids = [] + if ( + cooldown_models is not None + and isinstance(cooldown_models, list) + and len(cooldown_models) > 0 + and isinstance(cooldown_models[0], tuple) + ): + cached_value_deployment_ids = [cv[0] for cv in cooldown_models] + + verbose_router_logger.debug(f"retrieve cooldown models: {cooldown_models}") + return cached_value_deployment_ids + + +async def _async_get_cooldown_deployments_with_debug_info( + litellm_router_instance: LitellmRouter, + parent_otel_span: Optional[Span], +) -> List[tuple]: + """ + Async implementation of '_get_cooldown_deployments' + """ + model_ids = litellm_router_instance.get_model_ids() + cooldown_models = ( + await litellm_router_instance.cooldown_cache.async_get_active_cooldowns( + model_ids=model_ids, parent_otel_span=parent_otel_span + ) + ) + + verbose_router_logger.debug(f"retrieve cooldown models: {cooldown_models}") + return cooldown_models + + +def _get_cooldown_deployments( + litellm_router_instance: LitellmRouter, parent_otel_span: Optional[Span] +) -> List[str]: + """ + Get the list of models being cooled down for this minute + """ + # get the current cooldown list for that minute + + # ---------------------- + # Return cooldown models + # ---------------------- + model_ids = litellm_router_instance.get_model_ids() + + cooldown_models = litellm_router_instance.cooldown_cache.get_active_cooldowns( + model_ids=model_ids, parent_otel_span=parent_otel_span + ) + + cached_value_deployment_ids = [] + if ( + cooldown_models is not None + and isinstance(cooldown_models, list) + and len(cooldown_models) > 0 + and isinstance(cooldown_models[0], tuple) + ): + cached_value_deployment_ids = [cv[0] for cv in cooldown_models] + + return cached_value_deployment_ids + + +def should_cooldown_based_on_allowed_fails_policy( + litellm_router_instance: LitellmRouter, + deployment: str, + original_exception: Any, +) -> bool: + """ + Check if fails are within the allowed limit and update the number of fails. + + Returns: + - True if fails exceed the allowed limit (should cooldown) + - False if fails are within the allowed limit (should not cooldown) + """ + allowed_fails = ( + litellm_router_instance.get_allowed_fails_from_policy( + exception=original_exception, + ) + or litellm_router_instance.allowed_fails + ) + cooldown_time = ( + litellm_router_instance.cooldown_time or DEFAULT_COOLDOWN_TIME_SECONDS + ) + + current_fails = litellm_router_instance.failed_calls.get_cache(key=deployment) or 0 + updated_fails = current_fails + 1 + + if updated_fails > allowed_fails: + return True + else: + litellm_router_instance.failed_calls.set_cache( + key=deployment, value=updated_fails, ttl=cooldown_time + ) + + return False + + +def _is_allowed_fails_set_on_router( + litellm_router_instance: LitellmRouter, +) -> bool: + """ + Check if Router.allowed_fails is set or is Non-default Value + + Returns: + - True if Router.allowed_fails is set or is Non-default Value + - False if Router.allowed_fails is None or is Default Value + """ + if litellm_router_instance.allowed_fails is None: + return False + if litellm_router_instance.allowed_fails != litellm.allowed_fails: + return True + return False + + +def cast_exception_status_to_int(exception_status: Union[str, int]) -> int: + if isinstance(exception_status, str): + try: + exception_status = int(exception_status) + except Exception: + verbose_router_logger.debug( + f"Unable to cast exception status to int {exception_status}. Defaulting to status=500." + ) + exception_status = 500 + return exception_status diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/fallback_event_handlers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/fallback_event_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..62e706a0cf5d52e8a1c43035b802a13b29dfbaa3 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/fallback_event_handlers.py @@ -0,0 +1,257 @@ +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union + +import litellm +from litellm._logging import verbose_router_logger +from litellm.integrations.custom_logger import CustomLogger +from litellm.router_utils.add_retry_fallback_headers import ( + add_fallback_headers_to_response, +) +from litellm.types.router import LiteLLMParamsTypedDict + +if TYPE_CHECKING: + from litellm.router import Router as _Router + + LitellmRouter = _Router +else: + LitellmRouter = Any + + +def _check_stripped_model_group(model_group: str, fallback_key: str) -> bool: + """ + Handles wildcard routing scenario + + where fallbacks set like: + [{"gpt-3.5-turbo": ["claude-3-haiku"]}] + + but model_group is like: + "openai/gpt-3.5-turbo" + + Returns: + - True if the stripped model group == fallback_key + """ + for provider in litellm.provider_list: + if isinstance(provider, Enum): + _provider = provider.value + else: + _provider = provider + if model_group.startswith(f"{_provider}/"): + stripped_model_group = model_group.replace(f"{_provider}/", "") + if stripped_model_group == fallback_key: + return True + return False + + +def get_fallback_model_group( + fallbacks: List[Any], model_group: str +) -> Tuple[Optional[List[str]], Optional[int]]: + """ + Returns: + - fallback_model_group: List[str] of fallback model groups. example: ["gpt-4", "gpt-3.5-turbo"] + - generic_fallback_idx: int of the index of the generic fallback in the fallbacks list. + + Checks: + - exact match + - stripped model group match + - generic fallback + """ + generic_fallback_idx: Optional[int] = None + stripped_model_fallback: Optional[List[str]] = None + fallback_model_group: Optional[List[str]] = None + ## check for specific model group-specific fallbacks + for idx, item in enumerate(fallbacks): + if isinstance(item, dict): + if list(item.keys())[0] == model_group: # check exact match + fallback_model_group = item[model_group] + break + elif _check_stripped_model_group( + model_group=model_group, fallback_key=list(item.keys())[0] + ): # check generic fallback + stripped_model_fallback = item[list(item.keys())[0]] + elif list(item.keys())[0] == "*": # check generic fallback + generic_fallback_idx = idx + elif isinstance(item, str): + fallback_model_group = [fallbacks.pop(idx)] # returns single-item list + ## if none, check for generic fallback + if fallback_model_group is None: + if stripped_model_fallback is not None: + fallback_model_group = stripped_model_fallback + elif generic_fallback_idx is not None: + fallback_model_group = fallbacks[generic_fallback_idx]["*"] + + return fallback_model_group, generic_fallback_idx + + +async def run_async_fallback( + *args: Tuple[Any], + litellm_router: LitellmRouter, + fallback_model_group: List[str], + original_model_group: str, + original_exception: Exception, + max_fallbacks: int, + fallback_depth: int, + **kwargs, +) -> Any: + """ + Loops through all the fallback model groups and calls kwargs["original_function"] with the arguments and keyword arguments provided. + + If the call is successful, it logs the success and returns the response. + If the call fails, it logs the failure and continues to the next fallback model group. + If all fallback model groups fail, it raises the most recent exception. + + Args: + litellm_router: The litellm router instance. + *args: Positional arguments. + fallback_model_group: List[str] of fallback model groups. example: ["gpt-4", "gpt-3.5-turbo"] + original_model_group: The original model group. example: "gpt-3.5-turbo" + original_exception: The original exception. + **kwargs: Keyword arguments. + + Returns: + The response from the successful fallback model group. + Raises: + The most recent exception if all fallback model groups fail. + """ + + ### BASE CASE ### MAX FALLBACK DEPTH REACHED + if fallback_depth >= max_fallbacks: + raise original_exception + + error_from_fallbacks = original_exception + + for mg in fallback_model_group: + if mg == original_model_group: + continue + try: + # LOGGING + kwargs = litellm_router.log_retry(kwargs=kwargs, e=original_exception) + verbose_router_logger.info(f"Falling back to model_group = {mg}") + if isinstance(mg, str): + kwargs["model"] = mg + elif isinstance(mg, dict): + kwargs.update(mg) + kwargs.setdefault("metadata", {}).update( + {"model_group": kwargs.get("model", None)} + ) # update model_group used, if fallbacks are done + fallback_depth = fallback_depth + 1 + kwargs["fallback_depth"] = fallback_depth + kwargs["max_fallbacks"] = max_fallbacks + response = await litellm_router.async_function_with_fallbacks( + *args, **kwargs + ) + verbose_router_logger.info("Successful fallback b/w models.") + response = add_fallback_headers_to_response( + response=response, + attempted_fallbacks=fallback_depth, + ) + # callback for successfull_fallback_event(): + await log_success_fallback_event( + original_model_group=original_model_group, + kwargs=kwargs, + original_exception=original_exception, + ) + return response + except Exception as e: + error_from_fallbacks = e + await log_failure_fallback_event( + original_model_group=original_model_group, + kwargs=kwargs, + original_exception=original_exception, + ) + raise error_from_fallbacks + + +async def log_success_fallback_event( + original_model_group: str, kwargs: dict, original_exception: Exception +): + """ + Log a successful fallback event to all registered callbacks. + + Uses LoggingCallbackManager.get_custom_loggers_for_type() to get deduplicated + CustomLogger instances from all callback lists. + + Args: + original_model_group (str): The original model group before fallback. + kwargs (dict): kwargs for the request + + Note: + Errors during logging are caught and reported but do not interrupt the process. + """ + # Get deduplicated CustomLogger instances from all callback lists + custom_loggers = litellm.logging_callback_manager.get_custom_loggers_for_type( + CustomLogger + ) + + for _callback_custom_logger in custom_loggers: + try: + await _callback_custom_logger.log_success_fallback_event( + original_model_group=original_model_group, + kwargs=kwargs, + original_exception=original_exception, + ) + except Exception as e: + verbose_router_logger.error( + f"Error in log_success_fallback_event: {str(e)}" + ) + + +async def log_failure_fallback_event( + original_model_group: str, kwargs: dict, original_exception: Exception +): + """ + Log a failed fallback event to all registered callbacks. + + Uses LoggingCallbackManager.get_custom_loggers_for_type() to get deduplicated + CustomLogger instances from all callback lists. + + Args: + original_model_group (str): The original model group before fallback. + kwargs (dict): kwargs for the request + + Note: + Errors during logging are caught and reported but do not interrupt the process. + """ + # Get deduplicated CustomLogger instances from all callback lists + custom_loggers = litellm.logging_callback_manager.get_custom_loggers_for_type( + CustomLogger + ) + + for _callback_custom_logger in custom_loggers: + try: + await _callback_custom_logger.log_failure_fallback_event( + original_model_group=original_model_group, + kwargs=kwargs, + original_exception=original_exception, + ) + except Exception as e: + verbose_router_logger.error( + f"Error in log_failure_fallback_event: {str(e)}" + ) + + +def _check_non_standard_fallback_format(fallbacks: Optional[List[Any]]) -> bool: + """ + Checks if the fallbacks list is a list of strings or a list of dictionaries. + + If + - List[str]: e.g. ["claude-3-haiku", "openai/o-1"] + - List[Dict[, Any]]: e.g. [{"model": "claude-3-haiku", "messages": [{"role": "user", "content": "Hey, how's it going?"}]}] + + If [{"gpt-3.5-turbo": ["claude-3-haiku"]}] then standard format. + """ + if fallbacks is None or not isinstance(fallbacks, list) or len(fallbacks) == 0: + return False + if all(isinstance(item, str) for item in fallbacks): + return True + elif all(isinstance(item, dict) for item in fallbacks): + for key in LiteLLMParamsTypedDict.__annotations__.keys(): + if key in fallbacks[0].keys(): + return True + + return False + + +def run_non_standard_fallback_format( + fallbacks: Union[List[str], List[Dict[str, Any]]], model_group: str +): + pass diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/get_retry_from_policy.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/get_retry_from_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ec326ebb50d0a5741ef53559dff6b6e2a76022b0 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/get_retry_from_policy.py @@ -0,0 +1,71 @@ +""" +Get num retries for an exception. + +- Account for retry policy by exception type. +""" + +from typing import Dict, Optional, Union + +from litellm.exceptions import ( + AuthenticationError, + BadRequestError, + ContentPolicyViolationError, + RateLimitError, + Timeout, +) +from litellm.types.router import RetryPolicy + + +def get_num_retries_from_retry_policy( + exception: Exception, + retry_policy: Optional[Union[RetryPolicy, dict]] = None, + model_group: Optional[str] = None, + model_group_retry_policy: Optional[Dict[str, RetryPolicy]] = None, +): + """ + BadRequestErrorRetries: Optional[int] = None + AuthenticationErrorRetries: Optional[int] = None + TimeoutErrorRetries: Optional[int] = None + RateLimitErrorRetries: Optional[int] = None + ContentPolicyViolationErrorRetries: Optional[int] = None + """ + # if we can find the exception then in the retry policy -> return the number of retries + + if ( + model_group_retry_policy is not None + and model_group is not None + and model_group in model_group_retry_policy + ): + retry_policy = model_group_retry_policy.get(model_group, None) # type: ignore + + if retry_policy is None: + return None + if isinstance(retry_policy, dict): + retry_policy = RetryPolicy(**retry_policy) + + if ( + isinstance(exception, AuthenticationError) + and retry_policy.AuthenticationErrorRetries is not None + ): + return retry_policy.AuthenticationErrorRetries + if isinstance(exception, Timeout) and retry_policy.TimeoutErrorRetries is not None: + return retry_policy.TimeoutErrorRetries + if ( + isinstance(exception, RateLimitError) + and retry_policy.RateLimitErrorRetries is not None + ): + return retry_policy.RateLimitErrorRetries + if ( + isinstance(exception, ContentPolicyViolationError) + and retry_policy.ContentPolicyViolationErrorRetries is not None + ): + return retry_policy.ContentPolicyViolationErrorRetries + if ( + isinstance(exception, BadRequestError) + and retry_policy.BadRequestErrorRetries is not None + ): + return retry_policy.BadRequestErrorRetries + + +def reset_retry_policy() -> RetryPolicy: + return RetryPolicy() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/handle_error.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/handle_error.py new file mode 100644 index 0000000000000000000000000000000000000000..c23e6ce473a560b68ffe325e340b5fd14eb95d49 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/handle_error.py @@ -0,0 +1,98 @@ +from typing import TYPE_CHECKING, Any, Optional, Union + +from litellm._logging import redact_secrets, verbose_router_logger +from litellm.constants import MAX_EXCEPTION_MESSAGE_LENGTH +from litellm.router_utils.cooldown_handlers import ( + _async_get_cooldown_deployments_with_debug_info, +) +from litellm.types.integrations.slack_alerting import AlertType +from litellm.types.router import RouterRateLimitError + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + from litellm.router import Router as _Router + + LitellmRouter = _Router + Span = Union[_Span, Any] +else: + LitellmRouter = Any + Span = Any + + +async def send_llm_exception_alert( + litellm_router_instance: LitellmRouter, + request_kwargs: dict, + error_traceback_str: str, + original_exception, +): + """ + Only runs if router.slack_alerting_logger is set + Sends a Slack / MS Teams alert for the LLM API call failure. Only if router.slack_alerting_logger is set. + + Parameters: + litellm_router_instance (_Router): The LitellmRouter instance. + original_exception (Any): The original exception that occurred. + + Returns: + None + """ + if litellm_router_instance is None: + return + + if not hasattr(litellm_router_instance, "slack_alerting_logger"): + return + + if litellm_router_instance.slack_alerting_logger is None: + return + + if "proxy_server_request" in request_kwargs: + # Do not send any alert if it's a request from litellm proxy server request + # the proxy is already instrumented to send LLM API call failures + return + + litellm_debug_info = getattr(original_exception, "litellm_debug_info", None) + exception_str = str(original_exception) + if litellm_debug_info is not None: + exception_str += litellm_debug_info + exception_str += f"\n\n{error_traceback_str[:MAX_EXCEPTION_MESSAGE_LENGTH]}" + + # Redact secrets before sending to external service (Slack / MS Teams) + exception_str = redact_secrets(exception_str) + + await litellm_router_instance.slack_alerting_logger.send_alert( + message=f"LLM API call failed: `{exception_str}`", + level="High", + alert_type=AlertType.llm_exceptions, + alerting_metadata={}, + ) + + +async def async_raise_no_deployment_exception( + litellm_router_instance: LitellmRouter, model: str, parent_otel_span: Optional[Span] +): + """ + Raises a RouterRateLimitError if no deployment is found for the given model. + """ + verbose_router_logger.info( + f"get_available_deployment for model: {model}, No deployment available" + ) + model_ids = litellm_router_instance.get_model_ids(model_name=model) + _cooldown_time = litellm_router_instance.cooldown_cache.get_min_cooldown( + model_ids=model_ids, parent_otel_span=parent_otel_span + ) + _cooldown_list = await _async_get_cooldown_deployments_with_debug_info( + litellm_router_instance=litellm_router_instance, + parent_otel_span=parent_otel_span, + ) + verbose_router_logger.info( + f"No deployment found for model: {model}, cooldown_list with debug info: {_cooldown_list}" + ) + + cooldown_list_ids = [cooldown_model[0] for cooldown_model in (_cooldown_list or [])] + return RouterRateLimitError( + model=model, + cooldown_time=_cooldown_time, + enable_pre_call_checks=litellm_router_instance.enable_pre_call_checks, + cooldown_list=cooldown_list_ids, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/health_state_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/health_state_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..65b064f19d27aad44552a1cb26220b9ae73c438f --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/health_state_cache.py @@ -0,0 +1,100 @@ +""" +Wrapper around router cache for health-check-driven routing. + +Stores per-deployment health state from background health checks +and exposes it for router candidate filtering. +""" + +import time +from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Union + +from typing_extensions import TypedDict + +from litellm import verbose_logger +from litellm.caching.caching import DualCache + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + Span = Union[_Span, Any] +else: + Span = Any + + +class DeploymentHealthStateValue(TypedDict): + is_healthy: bool + timestamp: float + reason: str + + +class DeploymentHealthCache: + """ + Cache for deployment health states produced by background health checks. + + Stores a single dict mapping deployment_id -> DeploymentHealthStateValue. + Staleness is enforced at read time: entries older than staleness_threshold + are treated as healthy (unknown). + """ + + CACHE_KEY = "litellm:health_check:deployment_health_state" + + def __init__(self, cache: DualCache, staleness_threshold: float): + self.cache = cache + self.staleness_threshold = staleness_threshold + + def set_deployment_health_states( + self, states: Dict[str, DeploymentHealthStateValue] + ) -> None: + """Bulk-write all deployment health states as a single cache entry.""" + try: + self.cache.set_cache( + key=self.CACHE_KEY, + value=states, + ttl=int(self.staleness_threshold * 1.5), + ) + except Exception as e: + verbose_logger.error( + "DeploymentHealthCache::set_deployment_health_states - Exception: %s", + str(e), + ) + + def _extract_unhealthy_ids(self, raw: Any) -> Set[str]: + """Given raw cache value, return set of non-stale unhealthy deployment IDs.""" + if not raw or not isinstance(raw, dict): + return set() + now = time.time() + return { + model_id + for model_id, state in raw.items() + if isinstance(state, dict) + and not state.get("is_healthy", True) + and (now - state.get("timestamp", 0)) < self.staleness_threshold + } + + async def async_get_unhealthy_deployment_ids( + self, parent_otel_span: Optional[Span] = None + ) -> Set[str]: + """Return set of deployment IDs currently marked unhealthy and not stale.""" + try: + raw = await self.cache.async_get_cache(key=self.CACHE_KEY) + return self._extract_unhealthy_ids(raw) + except Exception as e: + verbose_logger.debug( + "DeploymentHealthCache::async_get_unhealthy_deployment_ids - Exception: %s", + str(e), + ) + return set() + + def get_unhealthy_deployment_ids( + self, parent_otel_span: Optional[Span] = None + ) -> Set[str]: + """Sync version: return set of deployment IDs currently marked unhealthy and not stale.""" + try: + raw = self.cache.get_cache(key=self.CACHE_KEY) + return self._extract_unhealthy_ids(raw) + except Exception as e: + verbose_logger.debug( + "DeploymentHealthCache::get_unhealthy_deployment_ids - Exception: %s", + str(e), + ) + return set() diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/pattern_match_deployments.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/pattern_match_deployments.py new file mode 100644 index 0000000000000000000000000000000000000000..17b453d6031f8f5b4b7cfe6cdc52f127c2805da4 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/pattern_match_deployments.py @@ -0,0 +1,266 @@ +""" +Class to handle llm wildcard routing and regex pattern matching +""" + +import copy +import re +from re import Match +from typing import Dict, List, Optional, Tuple + +from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider +from litellm._logging import verbose_router_logger + + +class PatternUtils: + @staticmethod + def calculate_pattern_specificity(pattern: str) -> Tuple[int, int]: + """ + Calculate pattern specificity based on length and complexity. + + Args: + pattern: Regex pattern to analyze + + Returns: + Tuple of (length, complexity) for sorting + """ + complexity_chars = ["*", "+", "?", "\\", "^", "$", "|", "(", ")"] + ret_val = ( + len(pattern), # Longer patterns more specific + sum( + pattern.count(char) for char in complexity_chars + ), # More regex complexity + ) + return ret_val + + @staticmethod + def sorted_patterns( + patterns: Dict[str, List[Dict]] + ) -> List[Tuple[str, List[Dict]]]: + """ + Cached property for patterns sorted by specificity. + + Returns: + Sorted list of pattern-deployment tuples + """ + return sorted( + patterns.items(), + key=lambda x: PatternUtils.calculate_pattern_specificity(x[0]), + reverse=True, + ) + + +class PatternMatchRouter: + """ + Class to handle llm wildcard routing and regex pattern matching + + doc: https://docs.litellm.ai/docs/proxy/configs#provider-specific-wildcard-routing + + This class will store a mapping for regex pattern: List[Deployments] + """ + + def __init__(self): + self.patterns: Dict[str, List] = {} + + def add_pattern(self, pattern: str, llm_deployment: Dict): + """ + Add a regex pattern and the corresponding llm deployments to the patterns + + Args: + pattern: str + llm_deployment: str or List[str] + """ + # Convert the pattern to a regex + regex = self._pattern_to_regex(pattern) + if regex not in self.patterns: + self.patterns[regex] = [] + self.patterns[regex].append(llm_deployment) + + def _pattern_to_regex(self, pattern: str) -> str: + """ + Convert a wildcard pattern to a regex pattern + + example: + pattern: openai/* + regex: openai/.* + + pattern: openai/fo::*::static::* + regex: openai/fo::.*::static::.* + + Args: + pattern: str + + Returns: + str: regex pattern + """ + # # Replace '*' with '.*' for regex matching + # regex = pattern.replace("*", ".*") + # # Escape other special characters + # regex = re.escape(regex).replace(r"\.\*", ".*") + # return f"^{regex}$" + return re.escape(pattern).replace(r"\*", "(.*)") + + def _return_pattern_matched_deployments( + self, matched_pattern: Match, deployments: List[Dict] + ) -> List[Dict]: + new_deployments = [] + for deployment in deployments: + new_deployment = copy.deepcopy(deployment) + new_deployment["litellm_params"]["model"] = ( + PatternMatchRouter.set_deployment_model_name( + matched_pattern=matched_pattern, + litellm_deployment_litellm_model=deployment["litellm_params"][ + "model" + ], + ) + ) + new_deployments.append(new_deployment) + + return new_deployments + + def route( + self, request: Optional[str], filtered_model_names: Optional[List[str]] = None + ) -> Optional[List[Dict]]: + """ + Route a requested model to the corresponding llm deployments based on the regex pattern + + loop through all the patterns and find the matching pattern + if a pattern is found, return the corresponding llm deployments + if no pattern is found, return None + + Args: + request: str - the received model name from the user (can be a wildcard route). If none, No deployments will be returned. + filtered_model_names: Optional[List[str]] - if provided, only return deployments that match the filtered_model_names + Returns: + Optional[List[Deployment]]: llm deployments + """ + try: + if request is None: + return None + + sorted_patterns = PatternUtils.sorted_patterns(self.patterns) + regex_filtered_model_names = ( + [self._pattern_to_regex(m) for m in filtered_model_names] + if filtered_model_names is not None + else [] + ) + for pattern, llm_deployments in sorted_patterns: + if ( + filtered_model_names is not None + and pattern not in regex_filtered_model_names + ): + continue + pattern_match = re.match(pattern, request) + if pattern_match: + return self._return_pattern_matched_deployments( + matched_pattern=pattern_match, deployments=llm_deployments + ) + except Exception as e: + verbose_router_logger.debug(f"Error in PatternMatchRouter.route: {str(e)}") + + return None # No matching pattern found + + @staticmethod + def set_deployment_model_name( + matched_pattern: Match, + litellm_deployment_litellm_model: str, + ) -> str: + """ + Set the model name for the matched pattern llm deployment + + E.g.: + + Case 1: + model_name: llmengine/* (can be any regex pattern or wildcard pattern) + litellm_params: + model: openai/* + + if model_name = "llmengine/foo" -> model = "openai/foo" + + Case 2: + model_name: llmengine/fo::*::static::* + litellm_params: + model: openai/fo::*::static::* + + if model_name = "llmengine/foo::bar::static::baz" -> model = "openai/foo::bar::static::baz" + + Case 3: + model_name: *meta.llama3* + litellm_params: + model: bedrock/meta.llama3* + + if model_name = "hello-world-meta.llama3-70b" -> model = "bedrock/meta.llama3-70b" + """ + + ## BASE CASE: if the deployment model name does not contain a wildcard, return the deployment model name + if "*" not in litellm_deployment_litellm_model: + return litellm_deployment_litellm_model + + wildcard_count = litellm_deployment_litellm_model.count("*") + + # Extract all dynamic segments from the request + dynamic_segments = matched_pattern.groups() + + if len(dynamic_segments) > wildcard_count: + return ( + matched_pattern.string + ) # default to the user input, if unable to map based on wildcards. + # Replace the corresponding wildcards in the litellm model pattern with extracted segments + for segment in dynamic_segments: + litellm_deployment_litellm_model = litellm_deployment_litellm_model.replace( + "*", segment, 1 + ) + + return litellm_deployment_litellm_model + + def get_pattern( + self, model: str, custom_llm_provider: Optional[str] = None + ) -> Optional[List[Dict]]: + """ + Check if a pattern exists for the given model and custom llm provider + + Args: + model: str + custom_llm_provider: Optional[str] + + Returns: + bool: True if pattern exists, False otherwise + """ + if custom_llm_provider is None: + try: + ( + _, + custom_llm_provider, + _, + _, + ) = get_llm_provider(model=model) + except Exception: + # get_llm_provider raises exception when provider is unknown + pass + return self.route(model) or self.route(f"{custom_llm_provider}/{model}") + + def get_deployments_by_pattern( + self, model: str, custom_llm_provider: Optional[str] = None + ) -> List[Dict]: + """ + Get the deployments by pattern + + Args: + model: str + custom_llm_provider: Optional[str] + + Returns: + List[Dict]: llm deployments matching the pattern + """ + pattern_match = self.get_pattern(model, custom_llm_provider) + if pattern_match: + return pattern_match + return [] + + +# Example usage: +# router = PatternRouter() +# router.add_pattern('openai/*', [Deployment(), Deployment()]) +# router.add_pattern('openai/fo::*::static::*', Deployment()) +# print(router.route('openai/gpt-4')) # Output: [Deployment(), Deployment()] +# print(router.route('openai/fo::hi::static::hi')) # Output: [Deployment()] +# print(router.route('something/else')) # Output: None diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/prompt_caching_cache.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/prompt_caching_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..eab342e54021addb02b6838bf891c5e49e64e192 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/prompt_caching_cache.py @@ -0,0 +1,259 @@ +""" +Wrapper around router cache. Meant to store model id when prompt caching supported prompt is called. +""" + +import hashlib +import json +from typing import TYPE_CHECKING, Any, List, Optional, Union, cast + +from typing_extensions import TypedDict + +from litellm.caching.caching import DualCache +from litellm.caching.in_memory_cache import InMemoryCache +from litellm.types.llms.openai import AllMessageValues, ChatCompletionToolParam + +if TYPE_CHECKING: + from opentelemetry.trace import Span as _Span + + from litellm.router import Router + + litellm_router = Router + Span = Union[_Span, Any] +else: + Span = Any + litellm_router = Any + + +class PromptCachingCacheValue(TypedDict): + model_id: str + + +class PromptCachingCache: + def __init__(self, cache: DualCache): + self.cache = cache + self.in_memory_cache = InMemoryCache() + + @staticmethod + def serialize_object(obj: Any) -> Any: + """Helper function to serialize Pydantic objects, dictionaries, or fallback to string.""" + if hasattr(obj, "dict"): + # If the object is a Pydantic model, use its `dict()` method + return obj.dict() + elif isinstance(obj, dict): + # If the object is a dictionary, serialize it with sorted keys + return json.dumps( + obj, sort_keys=True, separators=(",", ":") + ) # Standardize serialization + + elif isinstance(obj, list): + # Serialize lists by ensuring each element is handled properly + return [PromptCachingCache.serialize_object(item) for item in obj] + elif isinstance(obj, (int, float, bool)): + return obj # Keep primitive types as-is + return str(obj) + + @staticmethod + def extract_cacheable_prefix( + messages: List[AllMessageValues], + ) -> List[AllMessageValues]: + """ + Extract the cacheable prefix from messages. + + The cacheable prefix is everything UP TO AND INCLUDING the LAST content block + (across all messages) that has cache_control. This includes ALL blocks before + the last cacheable block (even if they don't have cache_control). + + Args: + messages: List of messages to extract cacheable prefix from + + Returns: + List of messages containing only the cacheable prefix + """ + if not messages: + return messages + + # Find the last content block (across all messages) that has cache_control + last_cacheable_message_idx = None + last_cacheable_content_idx = None + + for msg_idx, message in enumerate(messages): + content = message.get("content") + + # Check for cache_control at message level (when content is a string) + # This handles the case where cache_control is a sibling of string content: + # {"role": "user", "content": "...", "cache_control": {"type": "ephemeral"}} + message_level_cache_control = message.get("cache_control") + if ( + message_level_cache_control is not None + and isinstance(message_level_cache_control, dict) + and message_level_cache_control.get("type") == "ephemeral" + ): + last_cacheable_message_idx = msg_idx + # Set to None to indicate the entire message content is cacheable + # (not a specific content block index within a list) + last_cacheable_content_idx = None + + # Also check for cache_control within content blocks (when content is a list) + if not isinstance(content, list): + continue + + for content_idx, content_block in enumerate(content): + if isinstance(content_block, dict): + cache_control = content_block.get("cache_control") + if ( + cache_control is not None + and isinstance(cache_control, dict) + and cache_control.get("type") == "ephemeral" + ): + last_cacheable_message_idx = msg_idx + last_cacheable_content_idx = content_idx + + # If no cacheable block found, return empty list (no cacheable prefix) + if last_cacheable_message_idx is None: + return [] + + # Build the cacheable prefix: all messages up to and including the last cacheable message + cacheable_prefix = [] + + for msg_idx, message in enumerate(messages): + if msg_idx < last_cacheable_message_idx: + # Include entire message (comes before last cacheable block) + cacheable_prefix.append(message) + elif msg_idx == last_cacheable_message_idx: + # Include message but only up to and including the last cacheable content block + content = message.get("content") + if isinstance(content, list) and last_cacheable_content_idx is not None: + # Create a copy of the message with only cacheable content blocks + message_copy = cast( + AllMessageValues, + { + **message, + "content": content[: last_cacheable_content_idx + 1], + }, + ) + cacheable_prefix.append(message_copy) + else: + # Content is not a list or cacheable content idx is None, include full message + cacheable_prefix.append(message) + else: + # Message comes after last cacheable block, don't include + break + + return cacheable_prefix + + @staticmethod + def get_prompt_caching_cache_key( + messages: Optional[List[AllMessageValues]], + tools: Optional[List[ChatCompletionToolParam]], + ) -> Optional[str]: + if messages is None and tools is None: + return None + + # Extract cacheable prefix from messages (only include up to last cache_control block) + cacheable_messages = None + if messages is not None: + cacheable_messages = PromptCachingCache.extract_cacheable_prefix(messages) + # If no cacheable prefix found, return None (can't cache) + if not cacheable_messages: + return None + + # Use serialize_object for consistent and stable serialization + data_to_hash = {} + if cacheable_messages is not None: + serialized_messages = PromptCachingCache.serialize_object( + cacheable_messages + ) + data_to_hash["messages"] = serialized_messages + if tools is not None: + serialized_tools = PromptCachingCache.serialize_object(tools) + data_to_hash["tools"] = serialized_tools + + # Combine serialized data into a single string + data_to_hash_str = json.dumps( + data_to_hash, + sort_keys=True, + separators=(",", ":"), + ) + + # Create a hash of the serialized data for a stable cache key + hashed_data = hashlib.sha256(data_to_hash_str.encode()).hexdigest() + return f"deployment:{hashed_data}:prompt_caching" + + def add_model_id( + self, + model_id: str, + messages: Optional[List[AllMessageValues]], + tools: Optional[List[ChatCompletionToolParam]], + ) -> None: + if messages is None and tools is None: + return None + + cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools) + # If no cacheable prefix found, don't cache (can't generate cache key) + if cache_key is None: + return None + + self.cache.set_cache( + cache_key, PromptCachingCacheValue(model_id=model_id), ttl=300 + ) + return None + + async def async_add_model_id( + self, + model_id: str, + messages: Optional[List[AllMessageValues]], + tools: Optional[List[ChatCompletionToolParam]], + ) -> None: + if messages is None and tools is None: + return None + + cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools) + # If no cacheable prefix found, don't cache (can't generate cache key) + if cache_key is None: + return None + + await self.cache.async_set_cache( + cache_key, + PromptCachingCacheValue(model_id=model_id), + ttl=300, # store for 5 minutes + ) + return None + + async def async_get_model_id( + self, + messages: Optional[List[AllMessageValues]], + tools: Optional[List[ChatCompletionToolParam]], + ) -> Optional[PromptCachingCacheValue]: + """ + Get model ID from cache using the cacheable prefix. + + The cache key is based on the cacheable prefix (everything up to and including + the last cache_control block), so requests with the same cacheable prefix but + different user messages will have the same cache key. + """ + if messages is None and tools is None: + return None + + # Generate cache key using cacheable prefix + cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools) + if cache_key is None: + return None + + # Perform cache lookup + cache_result = await self.cache.async_get_cache(key=cache_key) + return cache_result + + def get_model_id( + self, + messages: Optional[List[AllMessageValues]], + tools: Optional[List[ChatCompletionToolParam]], + ) -> Optional[PromptCachingCacheValue]: + if messages is None and tools is None: + return None + + cache_key = PromptCachingCache.get_prompt_caching_cache_key(messages, tools) + # If no cacheable prefix found, return None (can't cache) + if cache_key is None: + return None + + return self.cache.get_cache(cache_key) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/response_headers.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/response_headers.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/search_api_router.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/search_api_router.py new file mode 100644 index 0000000000000000000000000000000000000000..9bcbcd83653d2681ba40d5ab9861f2c1dacd2624 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/router_utils/search_api_router.py @@ -0,0 +1,250 @@ +""" +Router utilities for Search API integration. + +Handles search tool selection, load balancing, and fallback logic for search requests. +""" + +import asyncio +import random +import traceback +from functools import partial +from typing import Any, Callable, Dict, Optional, Tuple + +from litellm._logging import verbose_router_logger + + +class SearchAPIRouter: + """ + Static utility class for routing search API calls through the LiteLLM router. + + Provides methods for search tool selection, load balancing, and fallback handling. + """ + + @staticmethod + def _resolve_search_provider_credentials( + *, + tool_litellm_params: Dict[str, Any], + ) -> Tuple[Optional[str], Optional[str]]: + """ + Resolve search provider credentials from tool configuration ONLY. + + Credentials are stored only in search_tool.litellm_params, never in team/key metadata. + This ensures secrets are not exposed in team/key API responses. + + Args: + tool_litellm_params: Search tool litellm_params with credentials + + Returns: + Tuple of (api_key, api_base) from tool configuration + """ + resolved_api_key: Optional[str] = tool_litellm_params.get("api_key") + resolved_api_base: Optional[str] = tool_litellm_params.get("api_base") + + return resolved_api_key, resolved_api_base + + @staticmethod + async def update_router_search_tools(router_instance: Any, search_tools: list): + """ + Update the router with search tools from the database. + + This method is called by a cron job to sync search tools from DB to router. + + Args: + router_instance: The Router instance to update + search_tools: List of search tool configurations from the database + """ + try: + from litellm.types.router import SearchToolTypedDict + + verbose_router_logger.debug( + f"Adding {len(search_tools)} search tools to router" + ) + + # Convert search tools to the format expected by the router + router_search_tools: list = [] + for tool in search_tools: + # Create dict that matches SearchToolTypedDict structure + router_search_tool: SearchToolTypedDict = { # type: ignore + "search_tool_id": tool.get("search_tool_id"), + "search_tool_name": tool.get("search_tool_name"), + "litellm_params": tool.get("litellm_params", {}), + "search_tool_info": tool.get("search_tool_info"), + } + router_search_tools.append(router_search_tool) + + # Update the router's search_tools list + router_instance.search_tools = router_search_tools + + verbose_router_logger.info( + f"Successfully updated router with {len(router_search_tools)} search tool(s)" + ) + + except Exception as e: + verbose_router_logger.exception( + f"Error updating router with search tools: {str(e)}" + ) + raise e + + @staticmethod + def get_matching_search_tools( + router_instance: Any, + search_tool_name: str, + ) -> list: + """ + Get all search tools matching the given name. + + Args: + router_instance: The Router instance + search_tool_name: Name of the search tool to find + + Returns: + List of matching search tool configurations + + Raises: + ValueError: If no matching search tools are found + """ + matching_tools = [ + tool + for tool in router_instance.search_tools + if tool.get("search_tool_name") == search_tool_name + ] + + if not matching_tools: + raise ValueError( + f"Search tool '{search_tool_name}' not found in router.search_tools" + ) + + return matching_tools + + @staticmethod + async def async_search_with_fallbacks( + router_instance: Any, + original_function: Callable, + **kwargs, + ): + """ + Helper function to make a search API call through the router with load balancing and fallbacks. + Reuses the router's retry/fallback infrastructure. + + Args: + router_instance: The Router instance + original_function: The original litellm.asearch function + **kwargs: Search parameters including search_tool_name, query, etc. + + Returns: + SearchResponse from the search API + """ + try: + search_tool_name = kwargs.get("search_tool_name", kwargs.get("model")) + + if not search_tool_name: + raise ValueError( + "search_tool_name or model parameter is required for search" + ) + + # Set up kwargs for the fallback system + kwargs["model"] = ( + search_tool_name # Use model field for compatibility with fallback system + ) + kwargs["original_generic_function"] = original_function + # Bind router_instance to the helper method using partial + kwargs["original_function"] = partial( + SearchAPIRouter.async_search_with_fallbacks_helper, + router_instance=router_instance, + ) + + # Update kwargs before fallbacks (for logging, metadata, etc) + router_instance._update_kwargs_before_fallbacks( + model=search_tool_name, + kwargs=kwargs, + metadata_variable_name="litellm_metadata", + ) + + available_search_tool_names = [ + tool.get("search_tool_name") for tool in router_instance.search_tools + ] + verbose_router_logger.debug( + f"Inside SearchAPIRouter.async_search_with_fallbacks() - search_tool_name: {search_tool_name}, Available Search Tools: {available_search_tool_names}, kwargs: {kwargs}" + ) + + # Use the existing retry/fallback infrastructure + response = await router_instance.async_function_with_fallbacks(**kwargs) + return response + + except Exception as e: + from litellm.router_utils.handle_error import send_llm_exception_alert + + asyncio.create_task( + send_llm_exception_alert( + litellm_router_instance=router_instance, + request_kwargs=kwargs, + error_traceback_str=traceback.format_exc(), + original_exception=e, + ) + ) + raise e + + @staticmethod + async def async_search_with_fallbacks_helper( + router_instance: Any, + model: str, + original_generic_function: Callable, + **kwargs, + ): + """ + Helper function for search API calls - selects a search tool and calls the original function. + Called by async_function_with_fallbacks for each retry attempt. + + Args: + router_instance: The Router instance + model: The search tool name (passed as model for compatibility) + original_generic_function: The original litellm.asearch function + **kwargs: Search parameters + + Returns: + SearchResponse from the selected search provider + """ + search_tool_name = model # model field contains the search_tool_name + + try: + # Find matching search tools + matching_tools = SearchAPIRouter.get_matching_search_tools( + router_instance=router_instance, + search_tool_name=search_tool_name, + ) + + # Simple random selection for load balancing across multiple providers with same name + # For search tools, we use simple random choice since they don't have TPM/RPM constraints + selected_tool = random.choice(matching_tools) + + # Extract search provider and other params from litellm_params + litellm_params = selected_tool.get("litellm_params", {}) + search_provider = litellm_params.get("search_provider") + if not search_provider: + raise ValueError( + f"search_provider not found in litellm_params for search tool '{search_tool_name}'" + ) + + api_key, api_base = SearchAPIRouter._resolve_search_provider_credentials( + tool_litellm_params=litellm_params, + ) + + verbose_router_logger.debug( + f"Selected search tool with provider: {search_provider}" + ) + + # Call the original search function with the provider config + response = await original_generic_function( + search_provider=search_provider, + api_key=api_key, + api_base=api_base, + **kwargs, + ) + + return response + + except Exception as e: + verbose_router_logger.error( + f"Error in SearchAPIRouter.async_search_with_fallbacks_helper for {search_tool_name}: {str(e)}" + ) + raise e diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51f311618e304904c64d2eb4701284dcb46cb76c --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/__init__.py @@ -0,0 +1,8 @@ +""" +LiteLLM Search API module. +""" + +from litellm.search.cost_calculator import search_provider_cost_per_query +from litellm.search.main import asearch, search + +__all__ = ["search", "asearch", "search_provider_cost_per_query"] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/cost_calculator.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/cost_calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..841c003dff397761040a972a3fad5abf332f20bd --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/cost_calculator.py @@ -0,0 +1,54 @@ +""" +Cost calculation for search providers. +""" + +from typing import Optional, Tuple + +from litellm.utils import get_model_info + + +def search_provider_cost_per_query( + model: str, + custom_llm_provider: Optional[str] = None, + number_of_queries: int = 1, + optional_params: Optional[dict] = None, +) -> Tuple[float, float]: + """ + Calculate cost for search-only providers. + + Returns (input_cost, output_cost) where input_cost = queries * cost_per_query + Supports tiered pricing based on max_results parameter. + + Args: + model: Model name (e.g., "exa_ai/search", "tavily/search") + custom_llm_provider: Provider name (e.g., "exa_ai", "tavily") + number_of_queries: Number of search queries performed (default: 1) + optional_params: Optional parameters including max_results for tiered pricing + + Returns: + Tuple of (input_cost, output_cost) where output_cost is always 0.0 + """ + model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider) + + # Check for tiered pricing (e.g., Exa AI based on max_results) + tiered_pricing = model_info.get("tiered_pricing") + if tiered_pricing and isinstance(tiered_pricing, list): + max_results = (optional_params or {}).get( + "max_results", 10 + ) # default 10 results + cost_per_query = 0.0 + + for tier in tiered_pricing: + range_min, range_max = tier["max_results_range"] + if range_min <= max_results <= range_max: + cost_per_query = tier["input_cost_per_query"] + break + else: + # Fallback to highest tier if out of range + cost_per_query = tiered_pricing[-1]["input_cost_per_query"] + else: + # Simple flat rate + cost_per_query = float(model_info.get("input_cost_per_query") or 0.0) + + total_cost = number_of_queries * cost_per_query + return (total_cost, 0.0) # (input_cost, output_cost) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/main.py new file mode 100644 index 0000000000000000000000000000000000000000..7711dee6e543a6c4808680a75293a66626032fb7 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/search/main.py @@ -0,0 +1,324 @@ +""" +Main Search function for LiteLLM. +""" + +import asyncio +import contextvars +from functools import partial +from typing import Any, Coroutine, Dict, List, Optional, Union + +import httpx + +import litellm +from litellm._logging import verbose_logger +from litellm.constants import request_timeout +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.search.transformation import BaseSearchConfig, SearchResponse +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.types.utils import SearchProviders +from litellm.utils import ProviderConfigManager, client, filter_out_litellm_params + +####### ENVIRONMENT VARIABLES ################### +base_llm_http_handler = BaseLLMHTTPHandler() +################################################# + + +def _build_search_optional_params( + max_results: Optional[int] = None, + search_domain_filter: Optional[List[str]] = None, + max_tokens_per_page: Optional[int] = None, + country: Optional[str] = None, +) -> Dict[str, Any]: + """ + Helper function to build optional_params dict from Perplexity Search API parameters. + + Args: + max_results: Maximum number of results (1-20) + search_domain_filter: List of domains to filter (max 20) + max_tokens_per_page: Max tokens per page + country: Country code filter + + Returns: + Dict with non-None optional parameters + """ + optional_params: Dict[str, Any] = {} + + if max_results is not None: + optional_params["max_results"] = max_results + if search_domain_filter is not None: + optional_params["search_domain_filter"] = search_domain_filter + if max_tokens_per_page is not None: + optional_params["max_tokens_per_page"] = max_tokens_per_page + if country is not None: + optional_params["country"] = country + + return optional_params + + +@client +async def asearch( + query: Union[str, List[str]], + search_provider: str, + max_results: Optional[int] = None, + search_domain_filter: Optional[List[str]] = None, + max_tokens_per_page: Optional[int] = None, + country: Optional[str] = None, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + extra_headers: Optional[Dict[str, Any]] = None, + **kwargs, +) -> SearchResponse: + """ + Async Search function. + + Args: + query: Search query (string or list of strings) + search_provider: Provider name (e.g., "perplexity") + max_results: Optional maximum number of results (1-20), default 10 + search_domain_filter: Optional list of domains to filter (max 20) + max_tokens_per_page: Optional max tokens per page, default 1024 + country: Optional country code filter (e.g., 'US', 'GB', 'DE') + api_key: Optional API key + api_base: Optional API base URL + timeout: Optional timeout + extra_headers: Optional extra headers + **kwargs: Additional parameters + + Returns: + SearchResponse with results list following Perplexity format + + Example: + ```python + import litellm + + # Basic search + response = await litellm.asearch( + query="latest AI developments 2024", + search_provider="perplexity" + ) + + # Search with options + response = await litellm.asearch( + query="AI developments", + search_provider="perplexity", + max_results=10, + search_domain_filter=["arxiv.org", "nature.com"], + max_tokens_per_page=1024, + country="US" + ) + + # Access results + for result in response.results: + print(f"{result.title}: {result.url}") + print(f"Snippet: {result.snippet}") + ``` + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["asearch"] = True + + func = partial( + search, + query=query, + search_provider=search_provider, + max_results=max_results, + search_domain_filter=search_domain_filter, + max_tokens_per_page=max_tokens_per_page, + country=country, + api_key=api_key, + api_base=api_base, + timeout=timeout, + extra_headers=extra_headers, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + + if response is None: + raise ValueError( + f"Got an unexpected None response from the Search API: {response}" + ) + + return response + except Exception as e: + model_name = f"{search_provider}/search" + raise litellm.exception_type( + model=model_name, + custom_llm_provider=search_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def search( + query: Union[str, List[str]], + search_provider: str, + max_results: Optional[int] = None, + search_domain_filter: Optional[List[str]] = None, + max_tokens_per_page: Optional[int] = None, + country: Optional[str] = None, + api_key: Optional[str] = None, + api_base: Optional[str] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + extra_headers: Optional[Dict[str, Any]] = None, + **kwargs, +) -> Union[SearchResponse, Coroutine[Any, Any, SearchResponse]]: + """ + Synchronous Search function. + + Args: + query: Search query (string or list of strings) + search_provider: Provider name (e.g., "perplexity") + max_results: Optional maximum number of results (1-20), default 10 + search_domain_filter: Optional list of domains to filter (max 20) + max_tokens_per_page: Optional max tokens per page, default 1024 + country: Optional country code filter (e.g., 'US', 'GB', 'DE') + api_key: Optional API key + api_base: Optional API base URL + timeout: Optional timeout + extra_headers: Optional extra headers + **kwargs: Additional parameters + + Returns: + SearchResponse with results list following Perplexity format + + Example: + ```python + import litellm + + # Basic search + response = litellm.search( + query="latest AI developments 2024", + search_provider="perplexity" + ) + + # Search with options + response = litellm.search( + query="AI developments", + search_provider="perplexity", + max_results=10, + search_domain_filter=["arxiv.org", "nature.com"], + max_tokens_per_page=1024, + country="US" + ) + + # Multi-query search + response = litellm.search( + query=["AI developments", "machine learning trends"], + search_provider="perplexity" + ) + + # Access results + for result in response.results: + print(f"{result.title}: {result.url}") + print(f"Snippet: {result.snippet}") + if result.date: + print(f"Date: {result.date}") + ``` + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.pop("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("asearch", False) is True + + # Validate query parameter + if not isinstance(query, (str, list)): + raise ValueError( + f"query must be a string or list of strings, got {type(query)}" + ) + + if isinstance(query, list) and not all(isinstance(q, str) for q in query): + raise ValueError("All items in query list must be strings") + + # Get provider config + search_provider_config: Optional[BaseSearchConfig] = ( + ProviderConfigManager.get_provider_search_config( + provider=SearchProviders(search_provider), + ) + ) + + if search_provider_config is None: + raise ValueError(f"Search is not supported for provider: {search_provider}") + + verbose_logger.debug(f"Search call - provider: {search_provider}") + + # Build optional_params from explicit parameters + optional_params = _build_search_optional_params( + max_results=max_results, + search_domain_filter=search_domain_filter, + max_tokens_per_page=max_tokens_per_page, + country=country, + ) + + # Filter out internal LiteLLM parameters from kwargs + filtered_kwargs = filter_out_litellm_params(kwargs=kwargs) + + # Add remaining kwargs to optional_params (for provider-specific params) + for key, value in filtered_kwargs.items(): + if key not in optional_params: + optional_params[key] = value + + verbose_logger.debug(f"Search optional_params: {optional_params}") + + # Validate environment and get headers + headers = search_provider_config.validate_environment( + api_key=api_key, + api_base=api_base, + headers=extra_headers or {}, + ) + + # Get complete URL + complete_url = search_provider_config.get_complete_url( + api_base=api_base, + optional_params=optional_params, + ) + + # Pre Call logging + model_name = f"{search_provider}/search" + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=model_name, + optional_params=optional_params, + litellm_params={ + "litellm_call_id": litellm_call_id, + "api_base": complete_url, + }, + custom_llm_provider=search_provider, + ) + + # Call the handler + response = base_llm_http_handler.search( + query=query, + optional_params=optional_params, + timeout=timeout or request_timeout, + logging_obj=litellm_logging_obj, + api_key=api_key, + api_base=complete_url, + custom_llm_provider=search_provider, + asearch=_is_async, + headers=headers, + provider_config=search_provider_config, + ) + + return response + except Exception as e: + model_name = f"{search_provider}/search" + raise litellm.exception_type( + model=model_name, + custom_llm_provider=search_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/skills/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/skills/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..96147d5a10f3405b5e9579120385a6feae02fb0d --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/skills/__init__.py @@ -0,0 +1,23 @@ +"""Skills API integration for LiteLLM""" + +from .main import ( + acreate_skill, + adelete_skill, + aget_skill, + alist_skills, + create_skill, + delete_skill, + get_skill, + list_skills, +) + +__all__ = [ + "create_skill", + "acreate_skill", + "list_skills", + "alist_skills", + "get_skill", + "aget_skill", + "delete_skill", + "adelete_skill", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/skills/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/skills/main.py new file mode 100644 index 0000000000000000000000000000000000000000..cee811d84fd53caa89f430fec6398b7967c2bf67 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/skills/main.py @@ -0,0 +1,787 @@ +""" +Main entry point for Skills API operations +Provides create, list, get, and delete operations for skills +""" + +import asyncio +import contextvars +from functools import partial +from typing import Any, Coroutine, Dict, List, Optional, Union + +import httpx + +import litellm +from litellm.constants import request_timeout +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.base_llm.skills.transformation import BaseSkillsAPIConfig +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.types.llms.anthropic_skills import ( + CreateSkillRequest, + DeleteSkillResponse, + ListSkillsParams, + ListSkillsResponse, + Skill, +) +from litellm.types.router import GenericLiteLLMParams +from litellm.types.utils import LlmProviders +from litellm.utils import ProviderConfigManager, client + +# Initialize HTTP handler +base_llm_http_handler = BaseLLMHTTPHandler() +DEFAULT_ANTHROPIC_API_BASE = "https://api.anthropic.com/v1" + +# Initialize LiteLLM skills handler (lazy - only used when custom_llm_provider="litellm") +_litellm_skills_handler = None + + +def _get_user_api_key_auth_from_kwargs(kwargs: Dict[str, Any]) -> Optional[Any]: + for metadata_key in ("metadata", "litellm_metadata"): + metadata = kwargs.get(metadata_key) + if isinstance(metadata, dict) and metadata.get("user_api_key_auth") is not None: + return metadata["user_api_key_auth"] + return None + + +def _get_skill_request_metadata( + kwargs: Dict[str, Any], + extra_body: Optional[Dict[str, Any]], +) -> Optional[Dict[str, Any]]: + if extra_body and isinstance(extra_body.get("metadata"), dict): + return extra_body["metadata"] + + metadata = kwargs.get("metadata") + if isinstance(metadata, dict) and isinstance( + metadata.get("requester_metadata"), dict + ): + return metadata["requester_metadata"] + return None + + +def _get_litellm_skills_handler(): + """Lazy initialization of LiteLLM skills handler to avoid import overhead.""" + global _litellm_skills_handler + if _litellm_skills_handler is None: + from litellm.llms.litellm_proxy.skills.transformation import ( + LiteLLMSkillsTransformationHandler, + ) + + _litellm_skills_handler = LiteLLMSkillsTransformationHandler() + return _litellm_skills_handler + + +@client +async def acreate_skill( + files: Optional[List[Any]] = None, + display_title: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Skill: + """ + Async: Create a new skill + + Args: + files: Files to upload for the skill. All files must be in the same top-level directory and must include a SKILL.md file at the root. + display_title: Optional display title for the skill + extra_headers: Additional headers for the request + extra_query: Additional query parameters + extra_body: Additional body parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + Skill object + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["acreate_skill"] = True + + func = partial( + create_skill, + files=files, + display_title=display_title, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def create_skill( + files: Optional[List[Any]] = None, + display_title: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[Skill, Coroutine[Any, Any, Skill]]: + """ + Create a new skill + + Args: + files: Files to upload for the skill. All files must be in the same top-level directory and must include a SKILL.md file at the root. + display_title: Optional display title for the skill + extra_headers: Additional headers for the request + extra_query: Additional query parameters + extra_body: Additional body parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + Skill object + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("acreate_skill", False) is True + + # Get LiteLLM parameters + litellm_params = GenericLiteLLMParams(**kwargs) + + # Determine provider + if custom_llm_provider is None: + custom_llm_provider = "anthropic" + + # Build create request + create_request: CreateSkillRequest = {} + if display_title is not None: + create_request["display_title"] = display_title + if files is not None: + create_request["files"] = files + + # Merge extra_body if provided + if extra_body: + create_request.update(extra_body) # type: ignore + + # Route to LiteLLM DB if custom_llm_provider="litellm_proxy" + if custom_llm_provider == LlmProviders.LITELLM_PROXY.value: + return _get_litellm_skills_handler().create_skill_handler( + display_title=display_title, + files=files, + metadata=_get_skill_request_metadata(kwargs, extra_body), + user_id=kwargs.get("user_id"), + user_api_key_dict=_get_user_api_key_auth_from_kwargs(kwargs), + _is_async=_is_async, + logging_obj=litellm_logging_obj, + litellm_call_id=litellm_call_id, + ) + + # Get provider config for external providers (Anthropic, etc.) + skills_api_provider_config: Optional[BaseSkillsAPIConfig] = ( + ProviderConfigManager.get_provider_skills_api_config( + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if skills_api_provider_config is None: + raise ValueError(f"CREATE skill is not supported for {custom_llm_provider}") + + # Validate environment and get headers + headers = extra_headers or {} + headers = skills_api_provider_config.validate_environment( + headers=headers, litellm_params=litellm_params + ) + + # Transform request + request_body = skills_api_provider_config.transform_create_skill_request( + create_request=create_request, + litellm_params=litellm_params, + headers=headers, + ) + + # Get API base and URL + from litellm.llms.anthropic.common_utils import AnthropicModelInfo + + api_base = AnthropicModelInfo.get_api_base(litellm_params.api_base) + url = skills_api_provider_config.get_complete_url( + api_base=api_base, endpoint="skills" + ) + + # Pre-call logging + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params=request_body, + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Make HTTP request + response = base_llm_http_handler.create_skill_handler( + url=url, + request_body=request_body, + skills_api_provider_config=skills_api_provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=headers, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + shared_session=kwargs.get("shared_session"), + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def alist_skills( + limit: Optional[int] = None, + page: Optional[str] = None, + source: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> ListSkillsResponse: + """ + Async: List all skills + + Args: + limit: Number of results to return per page (max 100, default 20) + page: Pagination token for fetching a specific page of results + source: Filter skills by source ('custom' or 'anthropic') + extra_headers: Additional headers for the request + extra_query: Additional query parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + ListSkillsResponse object + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["alist_skills"] = True + + func = partial( + list_skills, + limit=limit, + page=page, + source=source, + extra_headers=extra_headers, + extra_query=extra_query, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def list_skills( + limit: Optional[int] = None, + page: Optional[str] = None, + source: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[ListSkillsResponse, Coroutine[Any, Any, ListSkillsResponse]]: + """ + List all skills + + Args: + limit: Number of results to return per page (max 100, default 20) + page: Pagination token for fetching a specific page of results + source: Filter skills by source ('custom' or 'anthropic') + extra_headers: Additional headers for the request + extra_query: Additional query parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + ListSkillsResponse object + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("alist_skills", False) is True + + # Get LiteLLM parameters + litellm_params = GenericLiteLLMParams(**kwargs) + + # Determine provider + if custom_llm_provider is None: + custom_llm_provider = "anthropic" + + # Route to LiteLLM DB if custom_llm_provider="litellm_proxy" + if custom_llm_provider == LlmProviders.LITELLM_PROXY.value: + return _get_litellm_skills_handler().list_skills_handler( + limit=limit or 20, + offset=0, + user_api_key_dict=_get_user_api_key_auth_from_kwargs(kwargs), + _is_async=_is_async, + logging_obj=litellm_logging_obj, + litellm_call_id=litellm_call_id, + ) + + # Get provider config for external providers (Anthropic, etc.) + skills_api_provider_config: Optional[BaseSkillsAPIConfig] = ( + ProviderConfigManager.get_provider_skills_api_config( + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if skills_api_provider_config is None: + raise ValueError(f"LIST skills is not supported for {custom_llm_provider}") + + # Build list parameters + list_params: ListSkillsParams = {} + if limit is not None: + list_params["limit"] = limit + if page is not None: + list_params["page"] = page + if source is not None: + list_params["source"] = source + + # Merge extra_query if provided + if extra_query: + list_params.update(extra_query) # type: ignore + + # Validate environment and get headers + headers = extra_headers or {} + headers = skills_api_provider_config.validate_environment( + headers=headers, litellm_params=litellm_params + ) + + # Transform request + url, query_params = skills_api_provider_config.transform_list_skills_request( + list_params=list_params, + litellm_params=litellm_params, + headers=headers, + ) + + # Pre-call logging + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params=query_params, + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Make HTTP request + response = base_llm_http_handler.list_skills_handler( + url=url, + query_params=query_params, + skills_api_provider_config=skills_api_provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=headers, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + shared_session=kwargs.get("shared_session"), + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def aget_skill( + skill_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Skill: + """ + Async: Get a skill by ID + + Args: + skill_id: The ID of the skill to fetch + extra_headers: Additional headers for the request + extra_query: Additional query parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + Skill object + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["aget_skill"] = True + + func = partial( + get_skill, + skill_id=skill_id, + extra_headers=extra_headers, + extra_query=extra_query, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def get_skill( + skill_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[Skill, Coroutine[Any, Any, Skill]]: + """ + Get a skill by ID + + Args: + skill_id: The ID of the skill to fetch + extra_headers: Additional headers for the request + extra_query: Additional query parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + Skill object + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("aget_skill", False) is True + + # Get LiteLLM parameters + litellm_params = GenericLiteLLMParams(**kwargs) + + # Determine provider + if custom_llm_provider is None: + custom_llm_provider = "anthropic" + + # Route to LiteLLM DB if custom_llm_provider="litellm_proxy" + if custom_llm_provider == LlmProviders.LITELLM_PROXY.value: + return _get_litellm_skills_handler().get_skill_handler( + skill_id=skill_id, + user_api_key_dict=_get_user_api_key_auth_from_kwargs(kwargs), + _is_async=_is_async, + logging_obj=litellm_logging_obj, + litellm_call_id=litellm_call_id, + ) + + # Get provider config for external providers (Anthropic, etc.) + skills_api_provider_config: Optional[BaseSkillsAPIConfig] = ( + ProviderConfigManager.get_provider_skills_api_config( + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if skills_api_provider_config is None: + raise ValueError(f"GET skill is not supported for {custom_llm_provider}") + + # Validate environment and get headers + headers = extra_headers or {} + headers = skills_api_provider_config.validate_environment( + headers=headers, litellm_params=litellm_params + ) + + # Get API base + from litellm.llms.anthropic.common_utils import AnthropicModelInfo + + api_base = AnthropicModelInfo.get_api_base(litellm_params.api_base) + + # Transform request + url, headers = skills_api_provider_config.transform_get_skill_request( + skill_id=skill_id, + api_base=api_base or DEFAULT_ANTHROPIC_API_BASE, + litellm_params=litellm_params, + headers=headers, + ) + + # Pre-call logging + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={"skill_id": skill_id}, + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Make HTTP request + response = base_llm_http_handler.get_skill_handler( + url=url, + skills_api_provider_config=skills_api_provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=headers, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + shared_session=kwargs.get("shared_session"), + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def adelete_skill( + skill_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> DeleteSkillResponse: + """ + Async: Delete a skill by ID + + Args: + skill_id: The ID of the skill to delete + extra_headers: Additional headers for the request + extra_query: Additional query parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + DeleteSkillResponse object + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["adelete_skill"] = True + + func = partial( + delete_skill, + skill_id=skill_id, + extra_headers=extra_headers, + extra_query=extra_query, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def delete_skill( + skill_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[DeleteSkillResponse, Coroutine[Any, Any, DeleteSkillResponse]]: + """ + Delete a skill by ID + + Args: + skill_id: The ID of the skill to delete + extra_headers: Additional headers for the request + extra_query: Additional query parameters + timeout: Request timeout + custom_llm_provider: Provider name (e.g., 'anthropic') + **kwargs: Additional parameters + + Returns: + DeleteSkillResponse object + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("adelete_skill", False) is True + + # Get LiteLLM parameters + litellm_params = GenericLiteLLMParams(**kwargs) + + # Determine provider + if custom_llm_provider is None: + custom_llm_provider = "anthropic" + + # Route to LiteLLM DB if custom_llm_provider="litellm_proxy" + if custom_llm_provider == LlmProviders.LITELLM_PROXY.value: + return _get_litellm_skills_handler().delete_skill_handler( + skill_id=skill_id, + user_api_key_dict=_get_user_api_key_auth_from_kwargs(kwargs), + _is_async=_is_async, + logging_obj=litellm_logging_obj, + litellm_call_id=litellm_call_id, + ) + + # Get provider config for external providers (Anthropic, etc.) + skills_api_provider_config: Optional[BaseSkillsAPIConfig] = ( + ProviderConfigManager.get_provider_skills_api_config( + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if skills_api_provider_config is None: + raise ValueError(f"DELETE skill is not supported for {custom_llm_provider}") + + # Validate environment and get headers + headers = extra_headers or {} + headers = skills_api_provider_config.validate_environment( + headers=headers, litellm_params=litellm_params + ) + + # Get API base + from litellm.llms.anthropic.common_utils import AnthropicModelInfo + + api_base = AnthropicModelInfo.get_api_base(litellm_params.api_base) + + # Transform request + url, headers = skills_api_provider_config.transform_delete_skill_request( + skill_id=skill_id, + api_base=api_base or DEFAULT_ANTHROPIC_API_BASE, + litellm_params=litellm_params, + headers=headers, + ) + + # Pre-call logging + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={"skill_id": skill_id}, + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Make HTTP request + response = base_llm_http_handler.delete_skill_handler( + url=url, + skills_api_provider_config=skills_api_provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=headers, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + shared_session=kwargs.get("shared_session"), + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/__init__.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..07c66de3678a9c0502a685bc873f452d106a7afc --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/__init__.py @@ -0,0 +1,29 @@ +from .main import ( + acreate, + adelete, + alist, + aretrieve, + aretrieve_content, + aupdate, + create, + delete, + list, + retrieve, + retrieve_content, + update, +) + +__all__ = [ + "create", + "acreate", + "list", + "alist", + "retrieve", + "aretrieve", + "retrieve_content", + "aretrieve_content", + "update", + "aupdate", + "delete", + "adelete", +] diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/main.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/main.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4d516d03a8ff4fcd12456094f48a62731e2902 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/main.py @@ -0,0 +1,776 @@ +"""LiteLLM SDK functions for managing vector store files.""" + +import asyncio +import contextvars +from functools import partial +from typing import Any, Coroutine, Dict, Optional, Union + +import httpx + +import litellm +from litellm.constants import request_timeout +from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj +from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler +from litellm.types.router import GenericLiteLLMParams +from litellm.types.utils import LlmProviders +from litellm.types.vector_store_files import ( + VectorStoreFileContentResponse, + VectorStoreFileCreateRequest, + VectorStoreFileDeleteResponse, + VectorStoreFileListQueryParams, + VectorStoreFileListResponse, + VectorStoreFileObject, + VectorStoreFileUpdateRequest, +) +from litellm.utils import ProviderConfigManager, client +from litellm.vector_store_files.utils import VectorStoreFileRequestUtils + +base_llm_http_handler = BaseLLMHTTPHandler() + +VectorStoreFileAttributeValue = Union[str, int, float, bool] +VectorStoreFileAttributes = Dict[str, VectorStoreFileAttributeValue] + + +def _ensure_provider(custom_llm_provider: Optional[str]) -> str: + return custom_llm_provider or "openai" + + +def _prepare_registry_credentials( + *, + vector_store_id: str, + kwargs: Dict[str, Any], +) -> None: + if litellm.vector_store_registry is None: + return + try: + registry_credentials = ( + litellm.vector_store_registry.get_credentials_for_vector_store( + vector_store_id + ) + ) + if registry_credentials: + kwargs.update(registry_credentials) + except Exception: + pass + + +@client +async def acreate( + *, + vector_store_id: str, + file_id: str, + attributes: Optional[VectorStoreFileAttributes] = None, + chunking_strategy: Optional[Dict[str, Any]] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> VectorStoreFileObject: + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["acreate"] = True + + func = partial( + create, + vector_store_id=vector_store_id, + file_id=file_id, + attributes=attributes, + chunking_strategy=chunking_strategy, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def create( + *, + vector_store_id: str, + file_id: str, + attributes: Optional[VectorStoreFileAttributes] = None, + chunking_strategy: Optional[Dict[str, Any]] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[VectorStoreFileObject, Coroutine[Any, Any, VectorStoreFileObject]]: + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id") + _is_async = kwargs.pop("acreate", False) is True + + custom_llm_provider = _ensure_provider(custom_llm_provider) + + _prepare_registry_credentials(vector_store_id=vector_store_id, kwargs=kwargs) + + litellm_params = GenericLiteLLMParams(vector_store_id=vector_store_id, **kwargs) + + provider_config = ProviderConfigManager.get_provider_vector_store_files_config( + provider=LlmProviders(custom_llm_provider) + ) + if provider_config is None: + raise ValueError( + f"Vector store file create is not supported for {custom_llm_provider}" + ) + + local_vars.update(kwargs) + create_request: VectorStoreFileCreateRequest = ( + VectorStoreFileRequestUtils.get_create_request_params(local_vars) + ) + create_request["file_id"] = file_id + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={ + "vector_store_id": vector_store_id, + **create_request, + }, + litellm_params={ + "vector_store_id": vector_store_id, + "litellm_call_id": litellm_call_id, + **litellm_params.model_dump(exclude_none=True), + }, + custom_llm_provider=custom_llm_provider, + ) + + response = base_llm_http_handler.vector_store_file_create_handler( + vector_store_id=vector_store_id, + create_request=create_request, + vector_store_files_provider_config=provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + client=kwargs.get("client"), + _is_async=_is_async, + ) + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def alist( + *, + vector_store_id: str, + after: Optional[str] = None, + before: Optional[str] = None, + filter: Optional[str] = None, + limit: Optional[int] = None, + order: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> VectorStoreFileListResponse: + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["alist"] = True + + func = partial( + list, + vector_store_id=vector_store_id, + after=after, + before=before, + filter=filter, + limit=limit, + order=order, + extra_headers=extra_headers, + extra_query=extra_query, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def list( + *, + vector_store_id: str, + after: Optional[str] = None, + before: Optional[str] = None, + filter: Optional[str] = None, + limit: Optional[int] = None, + order: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[ + VectorStoreFileListResponse, Coroutine[Any, Any, VectorStoreFileListResponse] +]: + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id") + _is_async = kwargs.pop("alist", False) is True + + custom_llm_provider = _ensure_provider(custom_llm_provider) + + _prepare_registry_credentials(vector_store_id=vector_store_id, kwargs=kwargs) + + litellm_params = GenericLiteLLMParams(vector_store_id=vector_store_id, **kwargs) + + provider_config = ProviderConfigManager.get_provider_vector_store_files_config( + provider=LlmProviders(custom_llm_provider) + ) + if provider_config is None: + raise ValueError( + f"Vector store file list is not supported for {custom_llm_provider}" + ) + + local_vars.update(kwargs) + list_query: VectorStoreFileListQueryParams = ( + VectorStoreFileRequestUtils.get_list_query_params(local_vars) + ) + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={"vector_store_id": vector_store_id, **list_query}, + litellm_params={ + "vector_store_id": vector_store_id, + "litellm_call_id": litellm_call_id, + **litellm_params.model_dump(exclude_none=True), + }, + custom_llm_provider=custom_llm_provider, + ) + + response = base_llm_http_handler.vector_store_file_list_handler( + vector_store_id=vector_store_id, + query_params=list_query, + vector_store_files_provider_config=provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + extra_query=extra_query, + timeout=timeout or request_timeout, + client=kwargs.get("client"), + _is_async=_is_async, + ) + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def aretrieve( + *, + vector_store_id: str, + file_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> VectorStoreFileObject: + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["aretrieve"] = True + + func = partial( + retrieve, + vector_store_id=vector_store_id, + file_id=file_id, + extra_headers=extra_headers, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def retrieve( + *, + vector_store_id: str, + file_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[VectorStoreFileObject, Coroutine[Any, Any, VectorStoreFileObject]]: + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id") + _is_async = kwargs.pop("aretrieve", False) is True + + custom_llm_provider = _ensure_provider(custom_llm_provider) + + _prepare_registry_credentials(vector_store_id=vector_store_id, kwargs=kwargs) + + litellm_params = GenericLiteLLMParams(vector_store_id=vector_store_id, **kwargs) + + provider_config = ProviderConfigManager.get_provider_vector_store_files_config( + provider=LlmProviders(custom_llm_provider) + ) + if provider_config is None: + raise ValueError( + f"Vector store file retrieve is not supported for {custom_llm_provider}" + ) + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={ + "vector_store_id": vector_store_id, + "file_id": file_id, + }, + litellm_params={ + "vector_store_id": vector_store_id, + "litellm_call_id": litellm_call_id, + **litellm_params.model_dump(exclude_none=True), + }, + custom_llm_provider=custom_llm_provider, + ) + + response = base_llm_http_handler.vector_store_file_retrieve_handler( + vector_store_id=vector_store_id, + file_id=file_id, + vector_store_files_provider_config=provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + timeout=timeout or request_timeout, + client=kwargs.get("client"), + _is_async=_is_async, + ) + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def aretrieve_content( + *, + vector_store_id: str, + file_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> VectorStoreFileContentResponse: + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["aretrieve_content"] = True + + func = partial( + retrieve_content, + vector_store_id=vector_store_id, + file_id=file_id, + extra_headers=extra_headers, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def retrieve_content( + *, + vector_store_id: str, + file_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[ + VectorStoreFileContentResponse, Coroutine[Any, Any, VectorStoreFileContentResponse] +]: + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id") + _is_async = kwargs.pop("aretrieve_content", False) is True + + custom_llm_provider = _ensure_provider(custom_llm_provider) + + _prepare_registry_credentials(vector_store_id=vector_store_id, kwargs=kwargs) + + litellm_params = GenericLiteLLMParams(vector_store_id=vector_store_id, **kwargs) + + provider_config = ProviderConfigManager.get_provider_vector_store_files_config( + provider=LlmProviders(custom_llm_provider) + ) + if provider_config is None: + raise ValueError( + f"Vector store file content retrieve is not supported for {custom_llm_provider}" + ) + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={ + "vector_store_id": vector_store_id, + "file_id": file_id, + }, + litellm_params={ + "vector_store_id": vector_store_id, + "litellm_call_id": litellm_call_id, + **litellm_params.model_dump(exclude_none=True), + }, + custom_llm_provider=custom_llm_provider, + ) + + response = base_llm_http_handler.vector_store_file_content_handler( + vector_store_id=vector_store_id, + file_id=file_id, + vector_store_files_provider_config=provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + timeout=timeout or request_timeout, + client=kwargs.get("client"), + _is_async=_is_async, + ) + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def aupdate( + *, + vector_store_id: str, + file_id: str, + attributes: VectorStoreFileAttributes, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> VectorStoreFileObject: + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["aupdate"] = True + + func = partial( + update, + vector_store_id=vector_store_id, + file_id=file_id, + attributes=attributes, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def update( + *, + vector_store_id: str, + file_id: str, + attributes: VectorStoreFileAttributes, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[VectorStoreFileObject, Coroutine[Any, Any, VectorStoreFileObject]]: + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id") + _is_async = kwargs.pop("aupdate", False) is True + + custom_llm_provider = _ensure_provider(custom_llm_provider) + + _prepare_registry_credentials(vector_store_id=vector_store_id, kwargs=kwargs) + + litellm_params = GenericLiteLLMParams(vector_store_id=vector_store_id, **kwargs) + + provider_config = ProviderConfigManager.get_provider_vector_store_files_config( + provider=LlmProviders(custom_llm_provider) + ) + if provider_config is None: + raise ValueError( + f"Vector store file update is not supported for {custom_llm_provider}" + ) + + local_vars.update(kwargs) + update_request: VectorStoreFileUpdateRequest = ( + VectorStoreFileRequestUtils.get_update_request_params(local_vars) + ) + update_request["attributes"] = attributes + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={ + "vector_store_id": vector_store_id, + "file_id": file_id, + **update_request, + }, + litellm_params={ + "vector_store_id": vector_store_id, + "litellm_call_id": litellm_call_id, + **litellm_params.model_dump(exclude_none=True), + }, + custom_llm_provider=custom_llm_provider, + ) + + response = base_llm_http_handler.vector_store_file_update_handler( + vector_store_id=vector_store_id, + file_id=file_id, + update_request=update_request, + vector_store_files_provider_config=provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + client=kwargs.get("client"), + _is_async=_is_async, + ) + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +async def adelete( + *, + vector_store_id: str, + file_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> VectorStoreFileDeleteResponse: + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["adelete"] = True + + func = partial( + delete, + vector_store_id=vector_store_id, + file_id=file_id, + extra_headers=extra_headers, + timeout=timeout, + custom_llm_provider=custom_llm_provider, + **kwargs, + ) + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def delete( + *, + vector_store_id: str, + file_id: str, + extra_headers: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[ + VectorStoreFileDeleteResponse, Coroutine[Any, Any, VectorStoreFileDeleteResponse] +]: + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id") + _is_async = kwargs.pop("adelete", False) is True + + custom_llm_provider = _ensure_provider(custom_llm_provider) + + _prepare_registry_credentials(vector_store_id=vector_store_id, kwargs=kwargs) + + litellm_params = GenericLiteLLMParams(vector_store_id=vector_store_id, **kwargs) + + provider_config = ProviderConfigManager.get_provider_vector_store_files_config( + provider=LlmProviders(custom_llm_provider) + ) + if provider_config is None: + raise ValueError( + f"Vector store file delete is not supported for {custom_llm_provider}" + ) + + litellm_logging_obj.update_from_kwargs( + kwargs=kwargs, + model=None, + optional_params={ + "vector_store_id": vector_store_id, + "file_id": file_id, + }, + litellm_params={ + "vector_store_id": vector_store_id, + "litellm_call_id": litellm_call_id, + **litellm_params.model_dump(exclude_none=True), + }, + custom_llm_provider=custom_llm_provider, + ) + + response = base_llm_http_handler.vector_store_file_delete_handler( + vector_store_id=vector_store_id, + file_id=file_id, + vector_store_files_provider_config=provider_config, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + timeout=timeout or request_timeout, + client=kwargs.get("client"), + _is_async=_is_async, + ) + return response + except Exception as e: # noqa: BLE001 + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) diff --git a/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/utils.py b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe73516bda963e39b645920e6d0f925a5fdcd86 --- /dev/null +++ b/data/tefig/envs/olmes-eval/lib/python3.10/site-packages/litellm/vector_store_files/utils.py @@ -0,0 +1,45 @@ +from typing import Any, Dict, cast, get_type_hints + +from litellm.types.vector_store_files import ( + VectorStoreFileCreateRequest, + VectorStoreFileListQueryParams, + VectorStoreFileUpdateRequest, +) + + +class VectorStoreFileRequestUtils: + """Helper utilities for constructing vector store file requests.""" + + @staticmethod + def _filter_params(params: Dict[str, Any], model: Any) -> Dict[str, Any]: + valid_keys = get_type_hints(model).keys() + return { + key: value + for key, value in params.items() + if key in valid_keys and value is not None + } + + @staticmethod + def get_create_request_params( + params: Dict[str, Any] + ) -> VectorStoreFileCreateRequest: + filtered = VectorStoreFileRequestUtils._filter_params( + params=params, model=VectorStoreFileCreateRequest + ) + return cast(VectorStoreFileCreateRequest, filtered) + + @staticmethod + def get_list_query_params(params: Dict[str, Any]) -> VectorStoreFileListQueryParams: + filtered = VectorStoreFileRequestUtils._filter_params( + params=params, model=VectorStoreFileListQueryParams + ) + return cast(VectorStoreFileListQueryParams, filtered) + + @staticmethod + def get_update_request_params( + params: Dict[str, Any] + ) -> VectorStoreFileUpdateRequest: + filtered = VectorStoreFileRequestUtils._filter_params( + params=params, model=VectorStoreFileUpdateRequest + ) + return cast(VectorStoreFileUpdateRequest, filtered)