diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 23b520e2ad5f..7e705ec4f8f8 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -11,3 +11,9 @@ # style(ui): run prettier --write across the dashboard (#29622) 7edf3a9cb55548b143df1692f4ed7c4681d7fcf7 + +# style: reformat litellm/ with ruff format (#31317) +430b5b8f1b12dc261a49fda99ac5d1b22381a428 + +# style: unify ruff format width on 120 (#31518) +3dfbeabe626d203ac9de86024519d9a96c484ce4 diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.yml index ff6c40ac9ae5..f093caef0738 100644 --- a/.github/workflows/test-linting.yml +++ b/.github/workflows/test-linting.yml @@ -59,7 +59,7 @@ jobs: echo "No changed litellm Python files to check with ruff format." exit 0 fi - xargs uv run --no-sync ruff format --check --line-length 88 --exclude '/enterprise/' < "$RUNNER_TEMP/ruff_format_files.txt" + xargs uv run --no-sync ruff format --check --exclude '/enterprise/' < "$RUNNER_TEMP/ruff_format_files.txt" - name: Debug - Check file state run: | diff --git a/Makefile b/Makefile index 7c74526e130b..7701f54e15ce 100644 --- a/Makefile +++ b/Makefile @@ -82,13 +82,13 @@ install-hooks: ./scripts/install_git_hooks.sh # Formatting -# 88-column wrap matches the Black width the whole repo is formatted to; ruff.toml's -# global line-length is 120 (for E501/isort), so 88 is forced here. +# Wrap width is ruff.toml's single source of truth (line-length = 120), shared by the +# formatter, E501, and the import sorter so there's no 88-vs-120 split to reconcile. format: install-dev - cd litellm && $(UV_RUN) ruff format --line-length 88 --exclude '/enterprise/' . && cd .. + cd litellm && $(UV_RUN) ruff format --exclude '/enterprise/' . && cd .. format-check: install-dev - cd litellm && $(UV_RUN) ruff format --check --line-length 88 --exclude '/enterprise/' . && cd .. + cd litellm && $(UV_RUN) ruff format --check --exclude '/enterprise/' . && cd .. # Linting targets lint-ruff: install-dev diff --git a/litellm/__init__.py b/litellm/__init__.py index 5ae5942f32fb..15e95ded9067 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -6,9 +6,7 @@ warnings.filterwarnings("ignore", message=".*conflict with protected namespace.*") # Suppress Pydantic 2.11+ deprecation warning about accessing model_fields on instances # This warning can accumulate during streaming and cause memory leaks -warnings.filterwarnings( - "ignore", message=".*Accessing the.*attribute on the instance is deprecated.*" -) +warnings.filterwarnings("ignore", message=".*Accessing the.*attribute on the instance is deprecated.*") ### INIT VARIABLES ######################### import threading import os @@ -166,13 +164,9 @@ def _dev_env_hot_reload_enabled() -> bool: ] cold_storage_custom_logger: Optional[_custom_logger_compatible_callbacks_literal] = None logged_real_time_event_types: Optional[Union[List[str], Literal["*"]]] = None -_known_custom_logger_compatible_callbacks: List = list( - get_args(_custom_logger_compatible_callbacks_literal) -) +_known_custom_logger_compatible_callbacks: List = list(get_args(_custom_logger_compatible_callbacks_literal)) callbacks: List[ - Union[ - Callable, _custom_logger_compatible_callbacks_literal, "CustomLogger" - ] # CustomLogger is lazy-loaded + Union[Callable, _custom_logger_compatible_callbacks_literal, "CustomLogger"] # CustomLogger is lazy-loaded ] = [] callback_settings: Dict[str, Dict[str, Any]] = {} initialized_langfuse_clients: int = 0 @@ -183,26 +177,16 @@ def _dev_env_hot_reload_enabled() -> bool: require_auth_for_metrics_endpoint: Optional[bool] = True argilla_batch_size: Optional[int] = None datadog_use_v1: Optional[bool] = False # if you want to use v1 datadog logged payload. -gcs_pub_sub_use_v1: Optional[bool] = ( - False # if you want to use v1 gcs pubsub logged payload -) -generic_api_use_v1: Optional[bool] = ( - False # if you want to use v1 generic api logged payload -) +gcs_pub_sub_use_v1: Optional[bool] = False # if you want to use v1 gcs pubsub logged payload +generic_api_use_v1: Optional[bool] = False # if you want to use v1 generic api logged payload argilla_transformation_object: Optional[Dict[str, Any]] = None -_async_input_callback: List[ - Union[str, Callable, "CustomLogger"] -] = ( # CustomLogger is lazy-loaded +_async_input_callback: List[Union[str, Callable, "CustomLogger"]] = ( # CustomLogger is lazy-loaded [] ) # internal variable - async custom callbacks are routed here. -_async_success_callback: List[ - Union[str, Callable, "CustomLogger"] -] = ( # CustomLogger is lazy-loaded +_async_success_callback: List[Union[str, Callable, "CustomLogger"]] = ( # CustomLogger is lazy-loaded [] ) # internal variable - async custom callbacks are routed here. -_async_failure_callback: List[ - Union[str, Callable, "CustomLogger"] -] = ( # CustomLogger is lazy-loaded +_async_failure_callback: List[Union[str, Callable, "CustomLogger"]] = ( # CustomLogger is lazy-loaded [] ) # internal variable - async custom callbacks are routed here. pre_call_rules: List[Callable] = [] @@ -261,9 +245,7 @@ def _dev_env_hot_reload_enabled() -> bool: ) # When True, routes all OpenAI /chat/completions requests through the Responses API bridge # When True, Gemini/Vertex Live setup is deferred until client `session.update`. # Default False preserves historical behavior (auto-send setup on connect). -gemini_live_defer_setup: bool = ( - os.getenv("LITELLM_GEMINI_LIVE_DEFER_SETUP", "false").lower() == "true" -) +gemini_live_defer_setup: bool = os.getenv("LITELLM_GEMINI_LIVE_DEFER_SETUP", "false").lower() == "true" use_legacy_interactions_schema: bool = ( os.getenv("LITELLM_USE_LEGACY_INTERACTIONS_SCHEMA", "false").lower() == "true" ) # When True, sends Api-Revision: 2026-05-07 to Google so responses use the legacy `outputs` @@ -317,9 +299,7 @@ def _dev_env_hot_reload_enabled() -> bool: "params": ["project", "region_name", "token"], "providers": ["vertex_ai", "bedrock", "watsonx", "azure", "vertex_ai_beta"], } -use_litellm_proxy: bool = ( - False # when True, requests will be sent to the specified litellm proxy endpoint -) +use_litellm_proxy: bool = False # when True, requests will be sent to the specified litellm proxy endpoint use_client: bool = False ssl_verify: Union[str, bool] = True ssl_security_level: Optional[str] = None @@ -327,9 +307,7 @@ def _dev_env_hot_reload_enabled() -> bool: user_url_validation: bool = True user_url_allowed_hosts: List[str] = [] provider_url_destination_allowed_hosts: List[str] = [] -ssl_ecdh_curve: Optional[str] = ( - None # Set to 'X25519' to disable PQC and improve performance -) +ssl_ecdh_curve: Optional[str] = None # Set to 'X25519' to disable PQC and improve performance disable_streaming_logging: bool = False disable_token_counter: bool = False disable_add_transform_inline_image_block: bool = False @@ -370,9 +348,7 @@ def _dev_env_hot_reload_enabled() -> bool: ################## ### PREVIEW FEATURES ### enable_preview_features: bool = False -return_response_headers: bool = ( - False # get response headers from LLM Api providers - example x-remaining-requests, -) +return_response_headers: bool = False # get response headers from LLM Api providers - example x-remaining-requests, enable_json_schema_validation: bool = False enable_model_config_credential_overrides: bool = False enable_key_alias_format_validation: bool = ( @@ -384,17 +360,13 @@ def _dev_env_hot_reload_enabled() -> bool: #################### logging: bool = True enable_loadbalancing_on_batch_endpoints: Optional[bool] = None -require_managed_files: bool = ( - False # proxy only - require target_model_names on POST /v1/files -) +require_managed_files: bool = False # proxy only - require target_model_names on POST /v1/files enable_caching_on_provider_specific_optional_params: bool = ( False # feature-flag for caching on optional params - e.g. 'top_k' ) caching: bool = False # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 caching_with_models: bool = False # # Not used anymore, will be removed in next MAJOR release - https://github.com/BerriAI/litellm/discussions/648 -cache: Optional["Cache"] = ( - None # cache object <- use this - https://docs.litellm.ai/docs/caching -) +cache: Optional["Cache"] = None # cache object <- use this - https://docs.litellm.ai/docs/caching default_in_memory_ttl: Optional[float] = None default_redis_ttl: Optional[float] = None default_redis_batch_cache_expiry: Optional[float] = None @@ -404,15 +376,15 @@ def _dev_env_hot_reload_enabled() -> bool: budget_duration: Optional[str] = ( None # proxy only - resets budget after fixed duration. You can set duration as seconds ("30s"), minutes ("30m"), hours ("30h"), days ("30d"). ) -default_soft_budget: float = ( - DEFAULT_SOFT_BUDGET # by default all litellm proxy keys have a soft budget of 50.0 -) +default_soft_budget: float = DEFAULT_SOFT_BUDGET # by default all litellm proxy keys have a soft budget of 50.0 forward_traceparent_to_llm_provider: bool = False _current_cost = 0.0 # private variable, used if max budget is set error_logs: Dict = {} -add_function_to_prompt: bool = False # if function calling not supported by api, append function call details to system prompt +add_function_to_prompt: bool = ( + False # if function calling not supported by api, append function call details to system prompt +) client_session: Optional[httpx.Client] = None aclient_session: Optional[httpx.AsyncClient] = None model_fallbacks: Optional[List] = None # Deprecated for 'litellm.fallbacks' @@ -476,9 +448,7 @@ def _dev_env_hot_reload_enabled() -> bool: prometheus_end_user_metrics_max_series_per_metric: Optional[int] = 10000 prometheus_end_user_metrics_ttl_seconds: Optional[float] = 3600.0 prometheus_end_user_metrics_cleanup_interval_seconds: Optional[float] = 60.0 -disable_add_prefix_to_prompt: bool = ( - False # used by anthropic, to disable adding prefix to prompt -) +disable_add_prefix_to_prompt: bool = False # used by anthropic, to disable adding prefix to prompt disable_copilot_system_to_assistant: bool = False # If false (default), converts all 'system' role messages to 'assistant' for GitHub Copilot compatibility. Set to true to disable this behavior. public_mcp_servers: Optional[List[str]] = None public_mcp_hub_strict_whitelist: bool = True @@ -489,9 +459,7 @@ def _dev_env_hot_reload_enabled() -> bool: # Old format: { "displayName": "url" } (for backward compatibility) public_model_groups_links: Dict[str, Union[str, Dict[str, Any]]] = {} #### REQUEST PRIORITIZATION ####### -priority_reservation: Optional[Dict[str, Union[float, "PriorityReservationDict"]]] = ( - None -) +priority_reservation: Optional[Dict[str, Union[float, "PriorityReservationDict"]]] = None # priority_reservation_settings is lazy-loaded via __getattr__ # Only declare for type checking - at runtime __getattr__ handles it if TYPE_CHECKING: @@ -502,9 +470,7 @@ def _dev_env_hot_reload_enabled() -> bool: use_aiohttp_transport: bool = True # Older variable, aiohttp is now the default. use disable_aiohttp_transport instead. aiohttp_trust_env: bool = False # set to true to use HTTP_ Proxy settings disable_aiohttp_transport: bool = False # Set this to true to use httpx instead -disable_aiohttp_trust_env: bool = ( - False # When False, aiohttp will respect HTTP(S)_PROXY env vars -) +disable_aiohttp_trust_env: bool = False # When False, aiohttp will respect HTTP(S)_PROXY env vars force_ipv4: bool = False # when True, litellm will force ipv4 for all LLM requests. Some users have seen httpx ConnectionError when using ipv6. network_mock: bool = False # When True, use mock transport — no real network calls @@ -520,9 +486,7 @@ def _dev_env_hot_reload_enabled() -> bool: content_policy_fallbacks: Optional[List] = None allowed_fails: int = 3 allow_dynamic_callback_disabling: bool = True -num_retries_per_request: Optional[int] = ( - None # for the request overall (incl. fallbacks + model retries) -) +num_retries_per_request: Optional[int] = None # for the request overall (incl. fallbacks + model retries) ####### SECRET MANAGERS ##################### secret_manager_client: Optional[Any] = ( None # list of instantiated key management clients - e.g. azure kv, infisical, etc. @@ -539,9 +503,7 @@ def _dev_env_hot_reload_enabled() -> bool: from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map model_cost = get_model_cost_map(url=model_cost_map_url) -cost_discount_config: Dict[ - str, float -] = {} # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount +cost_discount_config: Dict[str, float] = {} # Provider-specific cost discounts {"vertex_ai": 0.05} = 5% discount cost_margin_config: Dict[ str, Union[float, Dict[str, float]] ] = {} # Provider-specific or global cost margins. Examples: @@ -727,9 +689,7 @@ def is_openai_finetune_model(key: str) -> bool: def add_known_models(model_cost_map: Optional[Dict] = None): _map = model_cost_map if model_cost_map is not None else model_cost for key, value in _map.items(): - if value.get("litellm_provider") == "openai" and not is_openai_finetune_model( - key - ): + if value.get("litellm_provider") == "openai" and not is_openai_finetune_model(key): open_ai_chat_completion_models.add(key) elif value.get("litellm_provider") == "text-completion-openai": open_ai_text_completion_models.add(key) @@ -807,9 +767,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): nlp_cloud_models.add(key) elif value.get("litellm_provider") == "aleph_alpha": aleph_alpha_models.add(key) - elif value.get( - "litellm_provider" - ) == "bedrock" and not is_bedrock_pricing_only_model(key): + elif value.get("litellm_provider") == "bedrock" and not is_bedrock_pricing_only_model(key): bedrock_models.add(key) elif value.get("litellm_provider") == "bedrock_converse": bedrock_converse_models.add(key) @@ -1445,9 +1403,7 @@ def add_known_models(model_cost_map: Optional[Dict] = None): from .types.llms.custom_llm import CustomLLMItem custom_provider_map: List[CustomLLMItem] = [] -_custom_providers: List[ - str -] = [] # internal helper util, used to track names of custom providers +_custom_providers: List[str] = [] # internal helper util, used to track names of custom providers disable_hf_tokenizer_download: Optional[bool] = ( None # disable huggingface tokenizer download. Defaults to openai clk100 ) diff --git a/litellm/_lazy_imports.py b/litellm/_lazy_imports.py index 4d811c3d7d9b..b04fae86e475 100644 --- a/litellm/_lazy_imports.py +++ b/litellm/_lazy_imports.py @@ -205,9 +205,7 @@ def _get_lazy_import_registry() -> dict[str, Callable[[str], Any]]: return _LAZY_IMPORT_REGISTRY -def _generic_lazy_import( - name: str, import_map: dict[str, tuple[str, str]], category: str -) -> Any: +def _generic_lazy_import(name: str, import_map: dict[str, tuple[str, str]], category: str) -> Any: """ Generic function that handles lazy importing for most attributes. @@ -325,9 +323,7 @@ def _lazy_import_litellm_logging(name: str) -> Any: def _lazy_import_llm_provider_logic(name: str) -> Any: """Handler for LLM provider logic functions (get_llm_provider, etc.)""" - return _generic_lazy_import( - name, _LLM_PROVIDER_LOGIC_IMPORT_MAP, "LLM provider logic" - ) + return _generic_lazy_import(name, _LLM_PROVIDER_LOGIC_IMPORT_MAP, "LLM provider logic") def _lazy_import_utils_module(name: str) -> Any: diff --git a/litellm/_logging.py b/litellm/_logging.py index bb743c328781..5f3c483869d9 100644 --- a/litellm/_logging.py +++ b/litellm/_logging.py @@ -17,9 +17,7 @@ "`litellm.set_verbose` is deprecated. Please set `os.environ['LITELLM_LOG'] = 'DEBUG'` for debug logs." ) -_ENABLE_SECRET_REDACTION = ( - os.getenv("LITELLM_DISABLE_REDACT_SECRETS", "").lower() != "true" -) +_ENABLE_SECRET_REDACTION = os.getenv("LITELLM_DISABLE_REDACT_SECRETS", "").lower() != "true" def _redact_string(value: str) -> str: @@ -64,9 +62,7 @@ def filter(self, record: logging.LogRecord) -> bool: # Redact exception tracebacks if record.exc_info and record.exc_info[1] is not None: try: - record.exc_text = _redact_string( - self._formatter.formatException(record.exc_info) - ) + record.exc_text = _redact_string(self._formatter.formatException(record.exc_info)) except Exception: pass @@ -189,9 +185,7 @@ def format(self, record): json_record["logger"] = f"{record.filename}:{record.lineno}" if record.exc_info: - json_record["stacktrace"] = record.exc_text or self.formatException( - record.exc_info - ) + json_record["stacktrace"] = record.exc_text or self.formatException(record.exc_info) return safe_dumps(json_record) diff --git a/litellm/_redis.py b/litellm/_redis.py index fdae674d55df..2bcce0e10830 100644 --- a/litellm/_redis.py +++ b/litellm/_redis.py @@ -187,8 +187,7 @@ def _build_azure_credential( ) except ImportError: raise ImportError( - "azure-identity is required for Azure AD Redis authentication. " - "Install it with: pip install azure-identity" + "azure-identity is required for Azure AD Redis authentication. Install it with: pip install azure-identity" ) _client_id = azure_client_id or os.environ.get("AZURE_CLIENT_ID") @@ -292,9 +291,7 @@ def get_redis_url_from_environment(): return os.environ["REDIS_URL"] if "REDIS_HOST" not in os.environ or "REDIS_PORT" not in os.environ: - raise ValueError( - "Either 'REDIS_URL' or both 'REDIS_HOST' and 'REDIS_PORT' must be specified for Redis." - ) + raise ValueError("Either 'REDIS_URL' or both 'REDIS_HOST' and 'REDIS_PORT' must be specified for Redis.") if "REDIS_SSL" in os.environ and os.environ["REDIS_SSL"].lower() == "true": redis_protocol = "rediss" @@ -327,9 +324,7 @@ def _get_redis_client_logic(**env_overrides): **env_overrides, } - _startup_nodes: Optional[Union[str, list]] = redis_kwargs.get( - "startup_nodes", None - ) or get_secret( # type: ignore + _startup_nodes: Optional[Union[str, list]] = redis_kwargs.get("startup_nodes", None) or get_secret( # type: ignore "REDIS_CLUSTER_NODES" ) @@ -340,18 +335,16 @@ def _get_redis_client_logic(**env_overrides): elif _startup_nodes is None: redis_kwargs.pop("startup_nodes", None) - _sentinel_nodes: Optional[Union[str, list]] = redis_kwargs.get( - "sentinel_nodes", None - ) or get_secret( # type: ignore + _sentinel_nodes: Optional[Union[str, list]] = redis_kwargs.get("sentinel_nodes", None) or get_secret( # type: ignore "REDIS_SENTINEL_NODES" ) if _sentinel_nodes is not None and isinstance(_sentinel_nodes, str): redis_kwargs["sentinel_nodes"] = json.loads(_sentinel_nodes) - _sentinel_password: Optional[str] = redis_kwargs.get( - "sentinel_password", None - ) or get_secret_str("REDIS_SENTINEL_PASSWORD") + _sentinel_password: Optional[str] = redis_kwargs.get("sentinel_password", None) or get_secret_str( + "REDIS_SENTINEL_PASSWORD" + ) if _sentinel_password is not None: redis_kwargs["sentinel_password"] = _sentinel_password @@ -364,17 +357,11 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs["service_name"] = _service_name # Handle GCP IAM authentication - _gcp_service_account = redis_kwargs.get("gcp_service_account") or get_secret_str( - "REDIS_GCP_SERVICE_ACCOUNT" - ) - _gcp_ssl_ca_certs = redis_kwargs.get("gcp_ssl_ca_certs") or get_secret_str( - "REDIS_GCP_SSL_CA_CERTS" - ) + _gcp_service_account = redis_kwargs.get("gcp_service_account") or get_secret_str("REDIS_GCP_SERVICE_ACCOUNT") + _gcp_ssl_ca_certs = redis_kwargs.get("gcp_ssl_ca_certs") or get_secret_str("REDIS_GCP_SSL_CA_CERTS") if _gcp_service_account is not None: - verbose_logger.debug( - "Setting up GCP IAM authentication for Redis with service account." - ) + verbose_logger.debug("Setting up GCP IAM authentication for Redis with service account.") redis_kwargs["redis_connect_func"] = create_gcp_iam_redis_connect_func( service_account=_gcp_service_account, ssl_ca_certs=_gcp_ssl_ca_certs ) @@ -390,14 +377,9 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs["ssl_ca_certs"] = _gcp_ssl_ca_certs # Handle Azure AD authentication (after GCP IAM block) - _azure_redis_ad_token = redis_kwargs.get("azure_redis_ad_token") or get_secret( - "REDIS_AZURE_AD_TOKEN" - ) + _azure_redis_ad_token = redis_kwargs.get("azure_redis_ad_token") or get_secret("REDIS_AZURE_AD_TOKEN") - _azure_ad_enabled = ( - _azure_redis_ad_token is not None - and str(_azure_redis_ad_token).lower() == "true" - ) + _azure_ad_enabled = _azure_redis_ad_token is not None and str(_azure_redis_ad_token).lower() == "true" if _azure_ad_enabled and _gcp_service_account is not None: verbose_logger.warning( @@ -406,15 +388,9 @@ def _get_redis_client_logic(**env_overrides): ) if _azure_ad_enabled and _gcp_service_account is None: - _azure_client_id = redis_kwargs.get("azure_client_id") or get_secret_str( - "AZURE_CLIENT_ID" - ) - _azure_tenant_id = redis_kwargs.get("azure_tenant_id") or get_secret_str( - "AZURE_TENANT_ID" - ) - _azure_client_secret = redis_kwargs.get( - "azure_client_secret" - ) or get_secret_str("AZURE_CLIENT_SECRET") + _azure_client_id = redis_kwargs.get("azure_client_id") or get_secret_str("AZURE_CLIENT_ID") + _azure_tenant_id = redis_kwargs.get("azure_tenant_id") or get_secret_str("AZURE_TENANT_ID") + _azure_client_secret = redis_kwargs.get("azure_client_secret") or get_secret_str("AZURE_CLIENT_SECRET") verbose_logger.debug("Setting up Azure AD authentication for Redis.") redis_kwargs["redis_connect_func"] = create_azure_ad_redis_connect_func( @@ -446,9 +422,7 @@ def _get_redis_client_logic(**env_overrides): redis_kwargs.pop("password", None) elif "startup_nodes" in redis_kwargs and redis_kwargs["startup_nodes"] is not None: pass - elif ( - "sentinel_nodes" in redis_kwargs and redis_kwargs["sentinel_nodes"] is not None - ): + elif "sentinel_nodes" in redis_kwargs and redis_kwargs["sentinel_nodes"] is not None: pass elif "host" not in redis_kwargs or redis_kwargs["host"] is None: raise ValueError("Either 'host' or 'url' must be specified for redis.") @@ -505,9 +479,7 @@ def _init_redis_sentinel(redis_kwargs) -> redis.Redis: sentinel_kwargs["password"] = sentinel_password if not sentinel_nodes or not service_name: - raise ValueError( - "Both 'sentinel_nodes' and 'service_name' are required for Redis Sentinel." - ) + raise ValueError("Both 'sentinel_nodes' and 'service_name' are required for Redis Sentinel.") verbose_logger.debug("init_redis_sentinel: sentinel nodes are being initialized.") @@ -532,9 +504,7 @@ def _init_async_redis_sentinel(redis_kwargs) -> async_redis.Redis: sentinel_kwargs["password"] = sentinel_password if not sentinel_nodes or not service_name: - raise ValueError( - "Both 'sentinel_nodes' and 'service_name' are required for Redis Sentinel." - ) + raise ValueError("Both 'sentinel_nodes' and 'service_name' are required for Redis Sentinel.") verbose_logger.debug("init_redis_sentinel: sentinel nodes are being initialized.") @@ -593,9 +563,7 @@ def get_redis_async_client( # connection — mirrors the sync path where redis_connect_func is invoked # per connection. Without this, the token would expire after ~1 hour. if redis_connect_func and hasattr(redis_connect_func, "_gcp_service_account"): - cluster_kwargs["credential_provider"] = GCPIAMCredentialProvider( - redis_connect_func._gcp_service_account - ) + cluster_kwargs["credential_provider"] = GCPIAMCredentialProvider(redis_connect_func._gcp_service_account) # Handle Azure AD authentication for async clusters via CredentialProvider # so the credential's internal cache + silent refresh runs per connection # (mirrors GCP IAM above; avoids static-token-baked-in-pool expiry). @@ -629,9 +597,7 @@ def get_redis_async_client( url_kwargs[arg] = redis_kwargs[arg] else: verbose_logger.debug( - "REDIS: ignoring argument: {}. Not an allowed async_redis.Redis.from_url arg.".format( - arg - ) + "REDIS: ignoring argument: {}. Not an allowed async_redis.Redis.from_url arg.".format(arg) ) return async_redis.Redis.from_url(**url_kwargs) @@ -650,9 +616,7 @@ def get_redis_async_client( username=os.environ.get("REDIS_USERNAME") or None, ) elif redis_connect_func and hasattr(redis_connect_func, "_gcp_service_account"): - redis_kwargs["credential_provider"] = GCPIAMCredentialProvider( - redis_connect_func._gcp_service_account - ) + redis_kwargs["credential_provider"] = GCPIAMCredentialProvider(redis_connect_func._gcp_service_account) _pretty_print_redis_config(redis_kwargs=redis_kwargs) @@ -698,18 +662,14 @@ def get_redis_connection_pool( username=os.environ.get("REDIS_USERNAME") or None, ) elif redis_connect_func and hasattr(redis_connect_func, "_gcp_service_account"): - redis_kwargs["credential_provider"] = GCPIAMCredentialProvider( - redis_connect_func._gcp_service_account - ) + redis_kwargs["credential_provider"] = GCPIAMCredentialProvider(redis_connect_func._gcp_service_account) connection_class = async_redis.Connection if "ssl" in redis_kwargs: connection_class = async_redis.SSLConnection redis_kwargs.pop("ssl", None) redis_kwargs["connection_class"] = connection_class - return async_redis.BlockingConnectionPool( - timeout=REDIS_CONNECTION_POOL_TIMEOUT, **redis_kwargs - ) + return async_redis.BlockingConnectionPool(timeout=REDIS_CONNECTION_POOL_TIMEOUT, **redis_kwargs) def _pretty_print_redis_config(redis_kwargs: dict) -> None: diff --git a/litellm/_redis_credential_provider.py b/litellm/_redis_credential_provider.py index 586b1c7716c3..b973e292a17d 100644 --- a/litellm/_redis_credential_provider.py +++ b/litellm/_redis_credential_provider.py @@ -100,9 +100,7 @@ def get_credentials(self) -> Tuple[str]: return (token,) async def get_credentials_async(self) -> Tuple[str]: - token = await asyncio.to_thread( - _get_cached_gcp_iam_token, self._gcp_service_account - ) + token = await asyncio.to_thread(_get_cached_gcp_iam_token, self._gcp_service_account) return (token,) @@ -128,9 +126,7 @@ def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]: return (token,) async def get_credentials_async(self) -> Union[Tuple[str], Tuple[str, str]]: - token_obj = await asyncio.to_thread( - self._credential.get_token, AZURE_REDIS_SCOPE - ) + token_obj = await asyncio.to_thread(self._credential.get_token, AZURE_REDIS_SCOPE) if self._username: return (self._username, token_obj.token) return (token_obj.token,) diff --git a/litellm/_service_logger.py b/litellm/_service_logger.py index b290b4340e77..b1bd0a3bba22 100644 --- a/litellm/_service_logger.py +++ b/litellm/_service_logger.py @@ -79,9 +79,7 @@ def _is_otel_logger(obj: Any) -> bool: if callback == "otel": from litellm.proxy.proxy_server import open_telemetry_logger - if open_telemetry_logger is not None and _is_otel_logger( - open_telemetry_logger - ): + if open_telemetry_logger is not None and _is_otel_logger(open_telemetry_logger): return open_telemetry_logger return None @@ -142,9 +140,7 @@ def service_success_hook( ) ) - def service_failure_hook( - self, service: ServiceTypes, duration: float, error: Exception, call_type: str - ): + def service_failure_hook(self, service: ServiceTypes, duration: float, error: Exception, call_type: str): """ [TODO] Not implemented for sync calls yet. V0 is focused on async monitoring (used by proxy). """ @@ -186,9 +182,7 @@ async def async_service_success_hook( for callback in litellm.service_callback: if callback == "prometheus_system": await self.init_prometheus_services_logger_if_none() - await self.prometheusServicesLogger.async_service_success_hook( - payload=payload - ) + await self.prometheusServicesLogger.async_service_success_hook(payload=payload) elif callback == "datadog" or isinstance(callback, DataDogLogger): await self.init_datadog_logger_if_none() await self.dd_logger.async_service_success_hook( @@ -205,10 +199,7 @@ async def async_service_success_hook( # here is what hid those calls from traces entirely. The OTel # logger decides what to do with a missing parent — legacy V1 # no-ops, V2 emits a root span (and skips metrics-only pings). - if ( - _otel_logger_to_use is not None - and id(_otel_logger_to_use) not in emitted_otel_logger_ids - ): + if _otel_logger_to_use is not None and id(_otel_logger_to_use) not in emitted_otel_logger_ids: emitted_otel_logger_ids.add(id(_otel_logger_to_use)) await _otel_logger_to_use.async_service_success_hook( payload=payload, @@ -249,9 +240,7 @@ async def init_otel_logger_if_none(self): from litellm.proxy.proxy_server import open_telemetry_logger if not hasattr(self, "otel_logger"): - if open_telemetry_logger is not None and isinstance( - open_telemetry_logger, OpenTelemetry - ): + if open_telemetry_logger is not None and isinstance(open_telemetry_logger, OpenTelemetry): self.otel_logger: OpenTelemetry = open_telemetry_logger else: verbose_logger.warning( @@ -319,10 +308,7 @@ async def async_service_failure_hook( # See the success hook: no parent gate, so background failures # are traced too. V1 no-ops without a parent; V2 emits a root. - if ( - _otel_logger_to_use is not None - and id(_otel_logger_to_use) not in emitted_otel_logger_ids - ): + if _otel_logger_to_use is not None and id(_otel_logger_to_use) not in emitted_otel_logger_ids: emitted_otel_logger_ids.add(id(_otel_logger_to_use)) await _otel_logger_to_use.async_service_failure_hook( payload=payload, @@ -361,9 +347,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti pass else: raise Exception( - "Duration={} is not a float or timedelta object. type={}".format( - _duration, type(_duration) - ) + "Duration={} is not a float or timedelta object. type={}".format(_duration, type(_duration)) ) # invalid _duration value # Batch polling callbacks (check_batch_cost) don't include call_type in kwargs. # Use .get() to avoid KeyError. diff --git a/litellm/a2a_protocol/card_resolver.py b/litellm/a2a_protocol/card_resolver.py index 4c5dd3e3ba6c..1955b5268e13 100644 --- a/litellm/a2a_protocol/card_resolver.py +++ b/litellm/a2a_protocol/card_resolver.py @@ -119,17 +119,13 @@ async def get_agent_card( last_error = None for path in paths: try: - verbose_logger.debug( - f"Attempting to fetch agent card from {self.base_url}{path}" - ) + 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}" - ) + verbose_logger.debug(f"Failed to fetch agent card from {self.base_url}{path}: {e}") last_error = e continue @@ -138,7 +134,4 @@ async def get_agent_card( 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)}" - ) + raise Exception(f"Failed to fetch agent card from {self.base_url}. Tried paths: {', '.join(paths)}") diff --git a/litellm/a2a_protocol/client.py b/litellm/a2a_protocol/client.py index 05e21284af15..a05f8dc390ca 100644 --- a/litellm/a2a_protocol/client.py +++ b/litellm/a2a_protocol/client.py @@ -87,9 +87,7 @@ async def get_agent_card(self) -> "AgentCard": extra_headers=self.extra_headers, ) - async def send_message( - self, request: "SendMessageRequest" - ) -> LiteLLMSendMessageResponse: + async def send_message(self, request: "SendMessageRequest") -> LiteLLMSendMessageResponse: """Send a message to the A2A agent.""" from litellm.a2a_protocol.main import asend_message @@ -103,7 +101,5 @@ async def send_message_streaming( 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 - ): + async for chunk in asend_message_streaming(a2a_client=a2a_client, request=request): yield chunk diff --git a/litellm/a2a_protocol/cost_calculator.py b/litellm/a2a_protocol/cost_calculator.py index f64174f8be5f..f3e84c5b84d6 100644 --- a/litellm/a2a_protocol/cost_calculator.py +++ b/litellm/a2a_protocol/cost_calculator.py @@ -97,11 +97,7 @@ def _calculate_token_based_cost( 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 - ) + 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/litellm/a2a_protocol/exception_mapping_utils.py b/litellm/a2a_protocol/exception_mapping_utils.py index 49dbb22b1586..99706e15cee6 100644 --- a/litellm/a2a_protocol/exception_mapping_utils.py +++ b/litellm/a2a_protocol/exception_mapping_utils.py @@ -181,10 +181,7 @@ def handle_a2a_localhost_retry( 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" - ) + 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( diff --git a/litellm/a2a_protocol/exceptions.py b/litellm/a2a_protocol/exceptions.py index 546b23105be9..b672971e7274 100644 --- a/litellm/a2a_protocol/exceptions.py +++ b/litellm/a2a_protocol/exceptions.py @@ -139,10 +139,7 @@ def __init__( 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}'." - ) + message = f"Agent card contains localhost/internal URL '{localhost_url}'. Retrying with base URL '{base_url}'." super().__init__( message=message, url=localhost_url, diff --git a/litellm/a2a_protocol/litellm_completion_bridge/handler.py b/litellm/a2a_protocol/litellm_completion_bridge/handler.py index a3502f21f953..a84b23a21707 100644 --- a/litellm/a2a_protocol/litellm_completion_bridge/handler.py +++ b/litellm/a2a_protocol/litellm_completion_bridge/handler.py @@ -75,9 +75,7 @@ async def handle_non_streaming( ) if a2a_provider_config is not None: - verbose_logger.info( - f"A2A: Using provider config for {custom_llm_provider}" - ) + verbose_logger.info(f"A2A: Using provider config for {custom_llm_provider}") return await a2a_provider_config.handle_non_streaming( request_id=request_id, @@ -91,9 +89,7 @@ async def handle_non_streaming( message = params.get("message", {}) # Transform A2A message to OpenAI format - openai_messages = ( - A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) - ) + openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) # Get completion params custom_llm_provider = litellm_params.get("custom_llm_provider") @@ -106,9 +102,7 @@ async def handle_non_streaming( else: full_model = model - verbose_logger.info( - f"A2A completion bridge: model={full_model}, api_base={api_base}" - ) + verbose_logger.info(f"A2A completion bridge: model={full_model}, api_base={api_base}") # Build completion params dict completion_params: Dict[str, Any] = { @@ -143,11 +137,9 @@ async def handle_non_streaming( response = await litellm.acompletion(**completion_params) # Transform response to A2A format - a2a_response = ( - A2ACompletionBridgeTransformation.openai_response_to_a2a_response( - response=response, - request_id=request_id, - ) + a2a_response = A2ACompletionBridgeTransformation.openai_response_to_a2a_response( + response=response, + request_id=request_id, ) verbose_logger.info(f"A2A completion bridge completed: request_id={request_id}") @@ -192,9 +184,7 @@ async def handle_streaming( ) if a2a_provider_config is not None: - verbose_logger.info( - f"A2A: Using provider config for {custom_llm_provider} (streaming)" - ) + verbose_logger.info(f"A2A: Using provider config for {custom_llm_provider} (streaming)") async for chunk in a2a_provider_config.handle_streaming( request_id=request_id, @@ -217,9 +207,7 @@ async def handle_streaming( ) # Transform A2A message to OpenAI format - openai_messages = ( - A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) - ) + openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message) # Get completion params custom_llm_provider = litellm_params.get("custom_llm_provider") @@ -232,9 +220,7 @@ async def handle_streaming( else: full_model = model - verbose_logger.info( - f"A2A completion bridge streaming: model={full_model}, api_base={api_base}" - ) + verbose_logger.info(f"A2A completion bridge streaming: model={full_model}, api_base={api_base}") # Build completion params dict completion_params: Dict[str, Any] = { @@ -299,11 +285,9 @@ async def handle_streaming( # Emit artifact update with accumulated content if accumulated_text: - artifact_event = ( - A2ACompletionBridgeTransformation.create_artifact_update_event( - ctx=ctx, - text=accumulated_text, - ) + artifact_event = A2ACompletionBridgeTransformation.create_artifact_update_event( + ctx=ctx, + text=accumulated_text, ) yield artifact_event @@ -315,9 +299,7 @@ async def handle_streaming( ) yield completed_event - verbose_logger.info( - f"A2A completion bridge streaming completed: request_id={request_id}, chunks={chunk_count}" - ) + verbose_logger.info(f"A2A completion bridge streaming completed: request_id={request_id}, chunks={chunk_count}") # Convenience functions that delegate to the class methods diff --git a/litellm/a2a_protocol/litellm_completion_bridge/transformation.py b/litellm/a2a_protocol/litellm_completion_bridge/transformation.py index 06c0a8fc82f2..b32963dd6fba 100644 --- a/litellm/a2a_protocol/litellm_completion_bridge/transformation.py +++ b/litellm/a2a_protocol/litellm_completion_bridge/transformation.py @@ -104,16 +104,12 @@ def apply_forward_metadata_to_completion_params( # ``extra_body.metadata`` so the configured keys remain authoritative # and an A2A caller cannot overwrite server-set run metadata. existing_metadata = extra_body.get("metadata") - existing_dict: Dict[str, Any] = ( - existing_metadata if isinstance(existing_metadata, dict) else {} - ) + existing_dict: Dict[str, Any] = existing_metadata if isinstance(existing_metadata, dict) else {} merged_metadata: Dict[str, Any] = {**forward_metadata, **existing_dict} extra_body = {**extra_body, "metadata": merged_metadata} completion_params["extra_body"] = extra_body - verbose_logger.debug( - f"A2A -> completion forward metadata keys={list(forward_metadata.keys())}" - ) + verbose_logger.debug(f"A2A -> completion forward metadata keys={list(forward_metadata.keys())}") @staticmethod def a2a_message_to_openai_messages( @@ -149,9 +145,7 @@ def a2a_message_to_openai_messages( # once at run level via extra_body.metadata (LangGraph POST /runs/wait shape). openai_message: Dict[str, Any] = {"role": openai_role, "content": content} - verbose_logger.debug( - f"A2A -> OpenAI transform: role={role} -> {openai_role}, content_length={len(content)}" - ) + verbose_logger.debug(f"A2A -> OpenAI transform: role={role} -> {openai_role}, content_length={len(content)}") return [openai_message] diff --git a/litellm/a2a_protocol/main.py b/litellm/a2a_protocol/main.py index 2b6f2cd12b42..6694c5c4af32 100644 --- a/litellm/a2a_protocol/main.py +++ b/litellm/a2a_protocol/main.py @@ -120,9 +120,7 @@ def _get_a2a_model_info(a2a_client: Any, kwargs: Dict[str, Any]) -> str: 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 - ) + litellm_logging_obj.model_call_details["custom_llm_provider"] = custom_llm_provider return agent_name @@ -139,19 +137,13 @@ async def _send_message_via_completion_bridge( 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}" - ) + 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) - ) + 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), @@ -161,9 +153,7 @@ async def _send_message_via_completion_bridge( agent_extra_headers=agent_extra_headers, ) - return LiteLLMSendMessageResponse.from_dict( - response_dict, request_id=str(request.id) - ) + return LiteLLMSendMessageResponse.from_dict(response_dict, request_id=str(request.id)) async def _execute_a2a_send_with_retry( @@ -203,9 +193,7 @@ async def _execute_a2a_send_with_retry( except Exception: raise if a2a_response is None: - raise RuntimeError( - "A2A send_message failed: no response received after retry attempts." - ) + raise RuntimeError("A2A send_message failed: no response received after retry attempts.") return a2a_response @@ -295,9 +283,7 @@ async def asend_message( # 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" - ) + 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: @@ -305,9 +291,7 @@ async def asend_message( # 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 - ) + 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 @@ -317,9 +301,7 @@ async def asend_message( 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 - ) + 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 a2a_response = await _execute_a2a_send_with_retry( @@ -334,9 +316,7 @@ async def asend_message( 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, request_id=str(request.id) - ) + response = LiteLLMSendMessageResponse.from_a2a_response(a2a_response, request_id=str(request.id)) # Calculate token usage from request and response response_dict = a2a_response.model_dump(mode="json", exclude_none=True) @@ -389,9 +369,7 @@ def send_message( 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) - ) + return asyncio.run(asend_message(a2a_client=a2a_client, request=request, **kwargs)) def _build_streaming_logging_obj( @@ -492,9 +470,7 @@ async def asend_message_streaming( 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}" - ) + verbose_logger.info(f"A2A streaming using completion bridge: provider={custom_llm_provider}") from litellm.a2a_protocol.litellm_completion_bridge.handler import ( A2ACompletionBridgeHandler, @@ -502,9 +478,7 @@ async def asend_message_streaming( # Extract params from request params = ( - request.params.model_dump(mode="json") - if hasattr(request.params, "model_dump") - else dict(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( @@ -524,9 +498,7 @@ async def asend_message_streaming( # 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" - ) + 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), @@ -535,9 +507,7 @@ async def asend_message_streaming( 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 - ) + 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 @@ -545,9 +515,7 @@ async def asend_message_streaming( 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 - ) + 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" @@ -645,8 +613,7 @@ async def create_a2a_client( """ if not A2A_SDK_AVAILABLE: raise ImportError( - "The 'a2a' package is required for A2A agent invocation. " - "Install it with: pip install a2a-sdk" + "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}") @@ -671,9 +638,7 @@ async def create_a2a_client( 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())}" - ) + verbose_proxy_logger.debug(f"A2A client created with extra_headers={list(extra_headers.keys())}") # Resolve agent card resolver = A2ACardResolver( @@ -682,9 +647,7 @@ async def create_a2a_client( ) agent_card = await resolver.get_agent_card() - verbose_logger.debug( - f"Resolved agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}" - ) + verbose_logger.debug(f"Resolved agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}") # Create A2A client a2a_client = _A2AClient( @@ -718,8 +681,7 @@ async def aget_agent_card( """ if not A2A_SDK_AVAILABLE: raise ImportError( - "The 'a2a' package is required for A2A agent invocation. " - "Install it with: pip install a2a-sdk" + "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}") @@ -737,7 +699,5 @@ async def aget_agent_card( ) agent_card = await resolver.get_agent_card() - verbose_logger.info( - f"Fetched agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}" - ) + verbose_logger.info(f"Fetched agent card: {agent_card.name if hasattr(agent_card, 'name') else 'unknown'}") return agent_card diff --git a/litellm/a2a_protocol/providers/bedrock_agentcore/config.py b/litellm/a2a_protocol/providers/bedrock_agentcore/config.py index e7f38c6488ca..f624aa393ede 100644 --- a/litellm/a2a_protocol/providers/bedrock_agentcore/config.py +++ b/litellm/a2a_protocol/providers/bedrock_agentcore/config.py @@ -30,8 +30,7 @@ async def handle_non_streaming( litellm_params = kwargs.get("litellm_params") if not litellm_params: raise ValueError( - "litellm_params is required for BedrockAgentCoreA2AConfig " - "(must contain model with AgentCore ARN)" + "litellm_params is required for BedrockAgentCoreA2AConfig (must contain model with AgentCore ARN)" ) return await BedrockAgentCoreA2AHandler.handle_non_streaming( request_id=request_id, @@ -51,8 +50,7 @@ async def handle_streaming( litellm_params = kwargs.get("litellm_params") if not litellm_params: raise ValueError( - "litellm_params is required for BedrockAgentCoreA2AConfig " - "(must contain model with AgentCore ARN)" + "litellm_params is required for BedrockAgentCoreA2AConfig (must contain model with AgentCore ARN)" ) async for chunk in BedrockAgentCoreA2AHandler.handle_streaming( request_id=request_id, diff --git a/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py b/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py index 2f93895099bd..c613b68668f5 100644 --- a/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py +++ b/litellm/a2a_protocol/providers/bedrock_agentcore/handler.py @@ -44,19 +44,15 @@ async def handle_non_streaming( Returns: A2A JSON-RPC response dict from the AgentCore agent """ - url, headers, body = ( - BedrockAgentCoreA2ATransformation.get_url_and_signed_request( - request_id=request_id, - params=params, - litellm_params=litellm_params, - method="message/send", - agent_extra_headers=agent_extra_headers, - ) + url, headers, body = BedrockAgentCoreA2ATransformation.get_url_and_signed_request( + request_id=request_id, + params=params, + litellm_params=litellm_params, + method="message/send", + agent_extra_headers=agent_extra_headers, ) - verbose_logger.info( - f"BedrockAgentCore A2A: Sending non-streaming request to {url}" - ) + verbose_logger.info(f"BedrockAgentCore A2A: Sending non-streaming request to {url}") client = get_async_httpx_client( llm_provider=cast(Any, httpxSpecialProvider.A2AProvider), @@ -70,9 +66,7 @@ async def handle_non_streaming( response_data = response.json() if "error" in response_data: - verbose_logger.warning( - f"BedrockAgentCore A2A: Agent returned error: {response_data['error']}" - ) + verbose_logger.warning(f"BedrockAgentCore A2A: Agent returned error: {response_data['error']}") return response_data @@ -96,15 +90,13 @@ async def handle_streaming( Yields: A2A streaming response events from the AgentCore agent """ - url, headers, body = ( - BedrockAgentCoreA2ATransformation.get_url_and_signed_request( - request_id=request_id, - params=params, - litellm_params=litellm_params, - method="message/send", - stream=True, - agent_extra_headers=agent_extra_headers, - ) + url, headers, body = BedrockAgentCoreA2ATransformation.get_url_and_signed_request( + request_id=request_id, + params=params, + litellm_params=litellm_params, + method="message/send", + stream=True, + agent_extra_headers=agent_extra_headers, ) verbose_logger.info(f"BedrockAgentCore A2A: Sending streaming request to {url}") @@ -126,15 +118,12 @@ async def handle_streaming( if "application/json" in content_type: # Single JSON response fallback (not SSE) verbose_logger.debug( - "BedrockAgentCore A2A streaming: received JSON instead of SSE, " - "yielding as single event" + "BedrockAgentCore A2A streaming: received JSON instead of SSE, yielding as single event" ) response_body = await response.aread() response_data = json.loads(response_body) yield response_data else: # SSE stream — parse data: lines - async for event in BedrockAgentCoreA2ATransformation.parse_sse_events( - response - ): + async for event in BedrockAgentCoreA2ATransformation.parse_sse_events(response): yield event diff --git a/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py b/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py index f868845bb584..091a13ccea58 100644 --- a/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py +++ b/litellm/a2a_protocol/providers/bedrock_agentcore/transformation.py @@ -50,9 +50,7 @@ def _filter_reserved_headers( dropped: list = [] for k, v in agent_extra_headers.items(): k_lower = k.lower() - if k_lower in _RESERVED_EXACT_HEADERS or any( - k_lower.startswith(prefix) for prefix in _RESERVED_PREFIX_HEADERS - ): + if k_lower in _RESERVED_EXACT_HEADERS or any(k_lower.startswith(prefix) for prefix in _RESERVED_PREFIX_HEADERS): dropped.append(k) continue filtered[k] = v @@ -115,11 +113,7 @@ def get_url_and_signed_request( agentcore_model = model # Build optional_params from litellm_params (everything except model and custom_llm_provider) - optional_params = { - k: v - for k, v in litellm_params.items() - if k not in ("model", "custom_llm_provider") - } + optional_params = {k: v for k, v in litellm_params.items() if k not in ("model", "custom_llm_provider")} agentcore_config = AmazonAgentCoreConfig() @@ -200,7 +194,5 @@ async def parse_sse_events(response: Any) -> AsyncIterator[Dict[str, Any]]: event = json.loads(data_str) yield event except json.JSONDecodeError: - verbose_logger.debug( - f"BedrockAgentCore A2A: Skipping non-JSON SSE line: {data_str[:100]}" - ) + verbose_logger.debug(f"BedrockAgentCore A2A: Skipping non-JSON SSE line: {data_str[:100]}") continue diff --git a/litellm/a2a_protocol/providers/langflow/config.py b/litellm/a2a_protocol/providers/langflow/config.py index 9302c38126b9..9edaf151c718 100644 --- a/litellm/a2a_protocol/providers/langflow/config.py +++ b/litellm/a2a_protocol/providers/langflow/config.py @@ -22,8 +22,7 @@ async def handle_non_streaming( litellm_params = kwargs.get("litellm_params") if not litellm_params: raise ValueError( - "litellm_params is required for LangFlowA2AConfig " - "(must contain custom_llm_provider and model)" + "litellm_params is required for LangFlowA2AConfig (must contain custom_llm_provider and model)" ) litellm_params = merge_a2a_session_into_litellm_params( litellm_params, params, litellm_params.get(A2A_USER_API_KEY_HASH_PARAM) @@ -46,8 +45,7 @@ async def handle_streaming( litellm_params = kwargs.get("litellm_params") if not litellm_params: raise ValueError( - "litellm_params is required for LangFlowA2AConfig " - "(must contain custom_llm_provider and model)" + "litellm_params is required for LangFlowA2AConfig (must contain custom_llm_provider and model)" ) litellm_params = merge_a2a_session_into_litellm_params( litellm_params, params, litellm_params.get(A2A_USER_API_KEY_HASH_PARAM) diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py index b5d3f262a63c..352005ff5499 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/handler.py @@ -91,9 +91,7 @@ async def handle_streaming( """ if api_base is None: raise ValueError("api_base is required for Pydantic AI agents") - verbose_logger.info( - f"Pydantic AI: Faking streaming for Pydantic AI agent at {api_base}" - ) + verbose_logger.info(f"Pydantic AI: Faking streaming for Pydantic AI agent at {api_base}") # Get raw task response first (not the transformed A2A format) raw_response = await PydanticAITransformation.send_and_get_raw_response( diff --git a/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py b/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py index 8fac43e7ae13..b9943d83c8a4 100644 --- a/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py +++ b/litellm/a2a_protocol/providers/pydantic_ai_agents/transformation.py @@ -41,17 +41,9 @@ def _remove_none_values(obj: Any) -> Any: Cleaned object with None values removed """ if isinstance(obj, dict): - return { - k: PydanticAITransformation._remove_none_values(v) - for k, v in obj.items() - if v is not None - } + return {k: PydanticAITransformation._remove_none_values(v) for k, v in obj.items() if v is not None} elif isinstance(obj, list): - return [ - PydanticAITransformation._remove_none_values(item) - for item in obj - if item is not None - ] + return [PydanticAITransformation._remove_none_values(item) for item in obj if item is not None] else: return obj @@ -125,9 +117,7 @@ async def _poll_for_completion( status = result.get("status", {}) state = status.get("state", "") - verbose_logger.debug( - f"Pydantic AI: Poll attempt {attempt + 1}/{max_attempts}, state={state}" - ) + verbose_logger.debug(f"Pydantic AI: Poll attempt {attempt + 1}/{max_attempts}, state={state}") if state == "completed": return poll_data @@ -136,9 +126,7 @@ async def _poll_for_completion( await asyncio.sleep(poll_interval) - raise TimeoutError( - f"Task {task_id} did not complete within {max_attempts * poll_interval} seconds" - ) + raise TimeoutError(f"Task {task_id} did not complete within {max_attempts * poll_interval} seconds") @staticmethod async def _send_and_poll_raw( @@ -211,9 +199,7 @@ async def _send_and_poll_raw( # Need to poll for completion task_id = result.get("id") if task_id: - verbose_logger.info( - f"Pydantic AI: Task {task_id} submitted, polling for completion..." - ) + verbose_logger.info(f"Pydantic AI: Task {task_id} submitted, polling for completion...") response_data = await PydanticAITransformation._poll_for_completion( client=client, endpoint=endpoint, @@ -222,9 +208,7 @@ async def _send_and_poll_raw( agent_extra_headers=agent_extra_headers, ) - verbose_logger.info( - f"Pydantic AI: Received completed response for request_id={request_id}" - ) + verbose_logger.info(f"Pydantic AI: Received completed response for request_id={request_id}") return response_data @@ -325,9 +309,7 @@ def _transform_to_a2a_response( Standard A2A non-streaming response format """ # Extract the agent response text - full_text, message_id, parts = PydanticAITransformation._extract_response_text( - response_data - ) + full_text, message_id, parts = PydanticAITransformation._extract_response_text(response_data) # Build standard A2A message a2a_message = { @@ -424,9 +406,7 @@ async def fake_streaming_from_response( A2A streaming response events """ # Extract the response text from completed task - full_text, message_id, parts = PydanticAITransformation._extract_response_text( - response_data - ) + full_text, message_id, parts = PydanticAITransformation._extract_response_text(response_data) # Extract input message from raw response for history result = response_data.get("result", {}) @@ -455,9 +435,7 @@ async def fake_streaming_from_response( "contextId": context_id, "kind": "message", "messageId": input_message_id, - "parts": input_message.get( - "parts", [{"kind": "text", "text": ""}] - ), + "parts": input_message.get("parts", [{"kind": "text", "text": ""}]), "role": "user", "taskId": task_id, } @@ -539,6 +517,4 @@ async def fake_streaming_from_response( } yield completed_event - verbose_logger.info( - f"Pydantic AI: Fake streaming completed for request_id={request_id}" - ) + verbose_logger.info(f"Pydantic AI: Fake streaming completed for request_id={request_id}") diff --git a/litellm/a2a_protocol/providers/watsonx_orchestrate/handler.py b/litellm/a2a_protocol/providers/watsonx_orchestrate/handler.py index dbc0247618e3..07235c1118c8 100644 --- a/litellm/a2a_protocol/providers/watsonx_orchestrate/handler.py +++ b/litellm/a2a_protocol/providers/watsonx_orchestrate/handler.py @@ -56,9 +56,7 @@ def _token_cache_key( return hashlib.sha256(material.encode()).hexdigest() @staticmethod - def _cp4d_token_ttl_seconds( - expiration: Any, now_wall: Optional[float] = None - ) -> int: + def _cp4d_token_ttl_seconds(expiration: Any, now_wall: Optional[float] = None) -> int: # CP4D returns expiration as absolute Unix epoch seconds, not a duration. expires_at = int(expiration) wall = now_wall if now_wall is not None else time.time() @@ -72,9 +70,7 @@ async def _get_bearer_token( username: Optional[str] = None, client: Optional[AsyncHTTPHandler] = None, ) -> str: - cache_key = WatsonxOrchestrateHandler._token_cache_key( - auth_mode, cp4d_host, api_key, username - ) + cache_key = WatsonxOrchestrateHandler._token_cache_key(auth_mode, cp4d_host, api_key, username) now = time.monotonic() cached = _token_cache.get(cache_key) if cached and cached[1] > now: @@ -98,9 +94,7 @@ async def _get_bearer_token( ttl_s = int(payload.get("expires_in", 3600)) else: if not username: - raise ValueError( - "'username' is required in litellm_params when auth_mode='cp4d'" - ) + raise ValueError("'username' is required in litellm_params when auth_mode='cp4d'") token_url = f"{cp4d_host.rstrip('/')}/icp4d-api/v1/authorize" response = await client.post( token_url, @@ -140,15 +134,12 @@ async def _poll_run( response.raise_for_status() result: Dict[str, Any] = response.json() status = result.get("status", "") - verbose_logger.debug( - f"WXO: Poll {attempt + 1}/{max_attempts} run='{run_id}' status='{status}'" - ) + verbose_logger.debug(f"WXO: Poll {attempt + 1}/{max_attempts} run='{run_id}' status='{status}'") if status in WatsonxOrchestrateTransformation.TERMINAL_STATES: return result raise asyncio.TimeoutError( - f"WXO run '{run_id}' did not reach a terminal state after " - f"{max_attempts * interval_s:.0f}s" + f"WXO run '{run_id}' did not reach a terminal state after {max_attempts * interval_s:.0f}s" ) @staticmethod @@ -172,9 +163,7 @@ async def _get_successful_run_data( status = run_data.get("status", "") if status not in WatsonxOrchestrateTransformation.SUCCESS_STATES: - raise RuntimeError( - f"WXO run ended with non-success status '{status}': {run_data}" - ) + raise RuntimeError(f"WXO run ended with non-success status '{status}': {run_data}") return run_data @@ -191,9 +180,7 @@ async def _accumulate_wxo_sse_text(response: Any) -> str: event = json.loads(data_str) except json.JSONDecodeError: continue - chunk_text = WatsonxOrchestrateTransformation.extract_text_from_wxo_result( - event - ) + chunk_text = WatsonxOrchestrateTransformation.extract_text_from_wxo_result(event) if chunk_text: accumulated_text += chunk_text return accumulated_text @@ -208,13 +195,9 @@ def _extract_litellm_params(litellm_params: Dict[str, Any]) -> WXORequestParams: if not cp4d_host: raise ValueError("'cp4d_host' is required in litellm_params for WXO agents") if not instance_id: - raise ValueError( - "'instance_id' is required in litellm_params for WXO agents" - ) + raise ValueError("'instance_id' is required in litellm_params for WXO agents") if not wxo_agent_id: - raise ValueError( - "'wxo_agent_id' is required in litellm_params for WXO agents" - ) + raise ValueError("'wxo_agent_id' is required in litellm_params for WXO agents") if not api_key: raise ValueError("'api_key' is required in litellm_params for WXO agents") @@ -244,9 +227,7 @@ async def handle_non_streaming( username=wxo.username, client=client, ) - base_url = WatsonxOrchestrateTransformation.get_api_base_url( - wxo.cp4d_host, wxo.instance_id - ) + base_url = WatsonxOrchestrateTransformation.get_api_base_url(wxo.cp4d_host, wxo.instance_id) auth_headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json", @@ -273,12 +254,8 @@ async def handle_non_streaming( client=client, ) - response_text = WatsonxOrchestrateTransformation.extract_text_from_wxo_result( - run_data - ) - return WatsonxOrchestrateTransformation.build_a2a_message_response( - request_id=request_id, text=response_text - ) + response_text = WatsonxOrchestrateTransformation.extract_text_from_wxo_result(run_data) + return WatsonxOrchestrateTransformation.build_a2a_message_response(request_id=request_id, text=response_text) @staticmethod async def handle_streaming( @@ -298,9 +275,7 @@ async def handle_streaming( username=wxo.username, client=client, ) - base_url = WatsonxOrchestrateTransformation.get_api_base_url( - wxo.cp4d_host, wxo.instance_id - ) + base_url = WatsonxOrchestrateTransformation.get_api_base_url(wxo.cp4d_host, wxo.instance_id) auth_headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json", @@ -330,14 +305,8 @@ async def handle_streaming( params=params, litellm_params=litellm_params, ) - response_text = ( - WatsonxOrchestrateTransformation.extract_text_from_a2a_message_response( - result - ) - ) - async for ( - chunk - ) in WatsonxOrchestrateTransformation.fake_streaming_from_text( + response_text = WatsonxOrchestrateTransformation.extract_text_from_a2a_message_response(result) + async for chunk in WatsonxOrchestrateTransformation.fake_streaming_from_text( text=response_text, request_id=request_id, chunk_size=chunk_size, @@ -356,13 +325,9 @@ async def handle_streaming( auth_headers=auth_headers, client=client, ) - accumulated_text = ( - WatsonxOrchestrateTransformation.extract_text_from_wxo_result(result) - ) + accumulated_text = WatsonxOrchestrateTransformation.extract_text_from_wxo_result(result) else: - accumulated_text = await WatsonxOrchestrateHandler._accumulate_wxo_sse_text( - response - ) + accumulated_text = await WatsonxOrchestrateHandler._accumulate_wxo_sse_text(response) async for chunk in WatsonxOrchestrateTransformation.fake_streaming_from_text( text=accumulated_text, diff --git a/litellm/a2a_protocol/providers/watsonx_orchestrate/transformation.py b/litellm/a2a_protocol/providers/watsonx_orchestrate/transformation.py index 824e9dbcdd2e..c9bda822aaeb 100644 --- a/litellm/a2a_protocol/providers/watsonx_orchestrate/transformation.py +++ b/litellm/a2a_protocol/providers/watsonx_orchestrate/transformation.py @@ -19,9 +19,7 @@ class WatsonxOrchestrateTransformation: Handles request/response transformation between A2A and the WXO REST API. """ - TERMINAL_STATES = frozenset( - {"completed", "succeeded", "failed", "error", "cancelled"} - ) + TERMINAL_STATES = frozenset({"completed", "succeeded", "failed", "error", "cancelled"}) SUCCESS_STATES = frozenset({"completed", "succeeded"}) @staticmethod @@ -114,11 +112,7 @@ def extract_text_from_a2a_message_response(a2a_response: Dict[str, Any]) -> str: verbose_logger.warning("WXO: A2A result has no parts list") return "" for part in parts: - if ( - isinstance(part, dict) - and part.get("kind") == "text" - and part.get("text") - ): + if isinstance(part, dict) and part.get("kind") == "text" and part.get("text"): return str(part["text"]) verbose_logger.warning("WXO: A2A result parts contained no text") return "" @@ -219,6 +213,4 @@ async def fake_streaming_from_text( }, } - verbose_logger.debug( - f"WXO: Fake streaming completed for request_id={request_id}" - ) + verbose_logger.debug(f"WXO: Fake streaming completed for request_id={request_id}") diff --git a/litellm/a2a_protocol/streaming_iterator.py b/litellm/a2a_protocol/streaming_iterator.py index c5ae9bcdc3cf..529154919f33 100644 --- a/litellm/a2a_protocol/streaming_iterator.py +++ b/litellm/a2a_protocol/streaming_iterator.py @@ -71,11 +71,7 @@ async def __anext__(self) -> "SendStreamingMessageResponse": 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 {} - ) + 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) @@ -85,11 +81,7 @@ def _collect_text_from_chunk(self, chunk: Any) -> None: 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 {} - ) + 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", {}) @@ -110,9 +102,7 @@ async def _handle_stream_complete(self) -> None: 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 "" - ) + 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 @@ -168,9 +158,7 @@ def _build_logging_result(self, usage: litellm.Usage) -> Dict[str, Any]: 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) - ), + "usage": (usage.model_dump() if hasattr(usage, "model_dump") else dict(usage)), } # Add final chunk result if available diff --git a/litellm/anthropic_beta_headers_manager.py b/litellm/anthropic_beta_headers_manager.py index 97d223088fa9..d0082498b096 100644 --- a/litellm/anthropic_beta_headers_manager.py +++ b/litellm/anthropic_beta_headers_manager.py @@ -48,9 +48,7 @@ def load_local_beta_headers_config() -> Dict: """Load the local backup beta headers config bundled with the package.""" try: content = json.loads( - files("litellm") - .joinpath("anthropic_beta_headers_config.json") - .read_text(encoding="utf-8") + files("litellm").joinpath("anthropic_beta_headers_config.json").read_text(encoding="utf-8") ) return content except Exception as e: @@ -70,16 +68,14 @@ def _check_is_valid_dict(fetched_config: dict) -> bool: """Check if fetched config is a non-empty dict with expected structure.""" if not isinstance(fetched_config, dict): verbose_logger.warning( - "LiteLLM: Fetched beta headers config is not a dict (type=%s). " - "Falling back to local backup.", + "LiteLLM: Fetched beta headers config is not a dict (type=%s). Falling back to local backup.", type(fetched_config).__name__, ) return False if len(fetched_config) == 0: verbose_logger.warning( - "LiteLLM: Fetched beta headers config is empty. " - "Falling back to local backup.", + "LiteLLM: Fetched beta headers config is empty. Falling back to local backup.", ) return False @@ -95,8 +91,7 @@ def _check_is_valid_dict(fetched_config: dict) -> bool: if not has_provider: verbose_logger.warning( - "LiteLLM: Fetched beta headers config missing provider keys. " - "Falling back to local backup.", + "LiteLLM: Fetched beta headers config missing provider keys. Falling back to local backup.", ) return False @@ -147,20 +142,16 @@ def get_beta_headers_config(url: str) -> dict: content = GetAnthropicBetaHeadersConfig.fetch_remote_beta_headers_config(url) except Exception as e: verbose_logger.warning( - "LiteLLM: Failed to fetch remote beta headers config from %s: %s. " - "Falling back to local backup.", + "LiteLLM: Failed to fetch remote beta headers config from %s: %s. Falling back to local backup.", url, str(e), ) return GetAnthropicBetaHeadersConfig.load_local_beta_headers_config() # Validate the fetched config - if not GetAnthropicBetaHeadersConfig.validate_beta_headers_config( - fetched_config=content - ): + if not GetAnthropicBetaHeadersConfig.validate_beta_headers_config(fetched_config=content): verbose_logger.warning( - "LiteLLM: Fetched beta headers config failed integrity check. " - "Using local backup instead. url=%s", + "LiteLLM: Fetched beta headers config failed integrity check. Using local backup instead. url=%s", url, ) return GetAnthropicBetaHeadersConfig.load_local_beta_headers_config() @@ -256,9 +247,7 @@ def filter_and_transform_beta_headers( # Check if header is in the mapping if header not in provider_mapping: - verbose_logger.debug( - f"Dropping unknown beta header '{header}' for provider '{provider}' (not in mapping)" - ) + verbose_logger.debug(f"Dropping unknown beta header '{header}' for provider '{provider}' (not in mapping)") continue # Get the mapped header value @@ -266,9 +255,7 @@ def filter_and_transform_beta_headers( # Skip if header is unsupported (null value) if mapped_header is None: - verbose_logger.debug( - f"Dropping unsupported beta header '{header}' for provider '{provider}'" - ) + verbose_logger.debug(f"Dropping unsupported beta header '{header}' for provider '{provider}'") continue # Add the mapped header diff --git a/litellm/anthropic_interface/exceptions/exception_mapping_utils.py b/litellm/anthropic_interface/exceptions/exception_mapping_utils.py index 4548185bbdc6..b4ec83517eec 100644 --- a/litellm/anthropic_interface/exceptions/exception_mapping_utils.py +++ b/litellm/anthropic_interface/exceptions/exception_mapping_utils.py @@ -148,9 +148,7 @@ def transform_to_anthropic_error( parsed = None # If parsed and already in Anthropic format - passthrough - if parsed is not None and AnthropicExceptionMapping._is_anthropic_error_dict( - parsed - ): + if parsed is not None and AnthropicExceptionMapping._is_anthropic_error_dict(parsed): # Optionally add request_id if provided and not present if request_id and "request_id" not in parsed: parsed["request_id"] = request_id @@ -158,9 +156,7 @@ def transform_to_anthropic_error( # Extract message - use parsed dict if available, otherwise raw string if parsed is not None: - message = AnthropicExceptionMapping._extract_message_from_dict( - parsed, raw_message - ) + message = AnthropicExceptionMapping._extract_message_from_dict(parsed, raw_message) else: message = raw_message diff --git a/litellm/anthropic_interface/messages/__init__.py b/litellm/anthropic_interface/messages/__init__.py index f71279b226df..52c9ecd5aa43 100644 --- a/litellm/anthropic_interface/messages/__init__.py +++ b/litellm/anthropic_interface/messages/__init__.py @@ -102,9 +102,7 @@ def create( AnthropicMessagesResponse, Iterator[bytes], AsyncIterator[Any], - Coroutine[ - Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any], Iterator[bytes]] - ], + Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any], Iterator[bytes]]], ]: """ Async wrapper for Anthropic's messages API diff --git a/litellm/assistants/main.py b/litellm/assistants/main.py index b7dfed6b1698..d515cb278bca 100644 --- a/litellm/assistants/main.py +++ b/litellm/assistants/main.py @@ -81,12 +81,8 @@ def get_assistants( ) -> 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 - ) + 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 ### @@ -138,15 +134,9 @@ def get_assistants( 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_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_version = optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -184,9 +174,7 @@ def get_assistants( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) @@ -200,9 +188,7 @@ def get_assistants( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) @@ -266,18 +252,10 @@ def create_assistants( 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 - ) + 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 ### @@ -310,9 +288,7 @@ def create_assistants( } # 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 - } + 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": @@ -348,15 +324,9 @@ def create_assistants( 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_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_version = optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -398,9 +368,7 @@ def create_assistants( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) if response is None: @@ -459,21 +427,13 @@ def delete_assistant( 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 - ) + 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" - ) + 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 @@ -491,9 +451,7 @@ def delete_assistant( elif timeout is None: timeout = 600.0 - response: Optional[ - Union[AssistantDeleted, Coroutine[Any, Any, AssistantDeleted]] - ] = None + response: Optional[Union[AssistantDeleted, Coroutine[Any, Any, AssistantDeleted]]] = None if custom_llm_provider == "openai": api_base = ( optional_params.api_base @@ -503,18 +461,10 @@ def delete_assistant( or "https://api.openai.com/v1" ) organization = ( - optional_params.organization - or litellm.organization - or os.getenv("OPENAI_ORGANIZATION", None) - or None + 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") - ) + 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, @@ -527,15 +477,9 @@ def delete_assistant( 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_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_version = optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -577,9 +521,7 @@ def delete_assistant( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="delete_assistant", url="https://github.com/BerriAI/litellm" - ), + request=httpx.Request(method="delete_assistant", url="https://github.com/BerriAI/litellm"), ), ) if response is None: @@ -594,9 +536,7 @@ def delete_assistant( ### THREADS ### -async def acreate_thread( - custom_llm_provider: Literal["openai", "azure"], **kwargs -) -> Thread: +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 @@ -716,9 +656,7 @@ def create_thread( 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_base = optional_params.api_base or litellm.api_base or get_secret("AZURE_API_BASE") # type: ignore api_key = ( optional_params.api_key @@ -729,9 +667,7 @@ def create_thread( ) # type: ignore api_version: Optional[str] = ( - optional_params.api_version - or litellm.api_version - or get_secret("AZURE_API_VERSION") + optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") ) # type: ignore extra_body = optional_params.get("extra_body", {}) @@ -767,9 +703,7 @@ def create_thread( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response # type: ignore @@ -874,14 +808,10 @@ def get_thread( 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_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") + optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") ) # type: ignore api_key = ( @@ -924,9 +854,7 @@ def get_thread( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response # type: ignore @@ -1000,9 +928,7 @@ def add_message( ) -> OpenAIMessage: ### COMMON OBJECTS ### a_add_message = kwargs.pop("a_add_message", None) - _message_data = MessageData( - role=role, content=content, attachments=attachments, metadata=metadata - ) + _message_data = MessageData(role=role, content=content, attachments=attachments, metadata=metadata) litellm_params_dict = get_litellm_params(**kwargs) optional_params = GenericLiteLLMParams(**kwargs) @@ -1065,14 +991,10 @@ def add_message( 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_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") + optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") ) # type: ignore api_key = ( @@ -1113,9 +1035,7 @@ def add_message( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) @@ -1228,14 +1148,10 @@ def get_messages( 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_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") + optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") ) # type: ignore api_key = ( @@ -1275,9 +1191,7 @@ def get_messages( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) @@ -1438,15 +1352,9 @@ def run_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_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_version = optional_params.api_version or litellm.api_version or get_secret("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -1492,9 +1400,7 @@ def run_thread( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response # type: ignore diff --git a/litellm/assistants/utils.py b/litellm/assistants/utils.py index bde279602ad8..f775c1b65088 100644 --- a/litellm/assistants/utils.py +++ b/litellm/assistants/utils.py @@ -43,11 +43,7 @@ def get_optional_params_add_message( "metadata": None, } - non_default_params = { - k: v - for k, v in passed_params.items() - if (k in default_params and v != default_params[k]) - } + 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 @@ -55,9 +51,7 @@ 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 + 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( @@ -108,11 +102,7 @@ def get_optional_params_image_gen( "user": None, } - non_default_params = { - k: v - for k, v in passed_params.items() - if (k in default_params and v != default_params[k]) - } + 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 @@ -120,9 +110,7 @@ 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 + 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( diff --git a/litellm/batch_completion/main.py b/litellm/batch_completion/main.py index 446e3f2f9902..664977dc8d68 100644 --- a/litellm/batch_completion/main.py +++ b/litellm/batch_completion/main.py @@ -106,9 +106,7 @@ def chunks(lst, n): original_kwargs = {} if "kwargs" in kwargs_modified: original_kwargs = kwargs_modified.pop("kwargs") - future = executor.submit( - litellm.completion, **kwargs_modified, **original_kwargs - ) + future = executor.submit(litellm.completion, **kwargs_modified, **original_kwargs) completions.append(future) # Retrieve the results from the futures @@ -153,13 +151,9 @@ def batch_completion_models(*args, **kwargs): futures = {} with ThreadPoolExecutor(max_workers=len(models)) as executor: for model in models: - futures[model] = executor.submit( - litellm.completion, *args, model=model, **kwargs - ) + futures[model] = executor.submit(litellm.completion, *args, model=model, **kwargs) - for model, future in sorted( - futures.items(), key=lambda x: models.index(x[0]) - ): + for model, future in sorted(futures.items(), key=lambda x: models.index(x[0])): if future.result() is not None: return future.result() elif "deployments" in kwargs: @@ -171,14 +165,10 @@ def batch_completion_models(*args, **kwargs): with ThreadPoolExecutor(max_workers=len(deployments)) as executor: for deployment in deployments: for key in kwargs.keys(): - if ( - key not in deployment - ): # don't override deployment values e.g. model name, api base, etc. + if key not in deployment: # don't override deployment values e.g. model name, api base, etc. deployment[key] = kwargs[key] kwargs = {**deployment, **nested_kwargs} - futures[deployment["model"]] = executor.submit( - litellm.completion, **kwargs - ) + futures[deployment["model"]] = executor.submit(litellm.completion, **kwargs) while futures: # wait for the first returned future @@ -191,9 +181,7 @@ def batch_completion_models(*args, **kwargs): return result except Exception: # if model 1 fails, continue with response from model 2, model3 - print_verbose( - "\n\ngot an exception, ignoring, removing from futures" - ) + print_verbose("\n\ngot an exception, ignoring, removing from futures") print_verbose(futures) new_futures = {} for key, value in futures.items(): @@ -254,10 +242,7 @@ def batch_completion_models_all_responses(*args, **kwargs): responses = [] with concurrent.futures.ThreadPoolExecutor(max_workers=len(models)) as executor: - futures = [ - executor.submit(litellm.completion, *args, model=model, **kwargs) - for model in models - ] + futures = [executor.submit(litellm.completion, *args, model=model, **kwargs) for model in models] for future in futures: try: @@ -265,9 +250,7 @@ def batch_completion_models_all_responses(*args, **kwargs): if result is not None: responses.append(result) except Exception as e: - print_verbose( - f"batch_completion_models_all_responses: model request failed: {str(e)}" - ) + print_verbose(f"batch_completion_models_all_responses: model request failed: {str(e)}") continue return responses diff --git a/litellm/batches/batch_utils.py b/litellm/batches/batch_utils.py index aeec58f1dfcb..985198ce7ced 100644 --- a/litellm/batches/batch_utils.py +++ b/litellm/batches/batch_utils.py @@ -10,9 +10,7 @@ async def calculate_batch_cost_and_usage( file_content_dictionary: List[dict], - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" - ], + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"], model_name: Optional[str] = None, model_info: Optional[ModelInfo] = None, ) -> Tuple[float, Usage, List[str]]: @@ -36,18 +34,14 @@ async def calculate_batch_cost_and_usage( custom_llm_provider=custom_llm_provider, model_name=model_name, ) - batch_models = _get_batch_models_from_file_content( - file_content_dictionary, model_name - ) + batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name) return batch_cost, batch_usage, batch_models async def _handle_completed_batch( batch: Batch, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" - ], + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"], model_name: Optional[str] = None, litellm_params: Optional[dict] = None, ) -> Tuple[float, Usage, List[str]]: @@ -76,9 +70,7 @@ async def _handle_completed_batch( model_name=model_name, ) - batch_models = _get_batch_models_from_file_content( - file_content_dictionary, model_name - ) + batch_models = _get_batch_models_from_file_content(file_content_dictionary, model_name) return batch_cost, batch_usage, batch_models @@ -104,9 +96,7 @@ def _get_batch_models_from_file_content( def _batch_cost_calculator( file_content_dictionary: List[dict], - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", model_name: Optional[str] = None, model_info: Optional[ModelInfo] = None, ) -> float: @@ -118,9 +108,7 @@ def _batch_cost_calculator( and model_name and getattr(litellm, "disable_vertex_batch_output_transformation", False) ): - batch_cost, _ = calculate_vertex_ai_batch_cost_and_usage( - file_content_dictionary, model_name - ) + batch_cost, _ = calculate_vertex_ai_batch_cost_and_usage(file_content_dictionary, model_name) verbose_logger.debug("vertex_ai_total_cost=%s", batch_cost) return batch_cost @@ -181,9 +169,7 @@ def calculate_vertex_ai_batch_cost_and_usage( ) total_cost += p_cost + c_cost except Exception as e: - verbose_logger.debug( - "vertex_ai batch cost calculation error for line: %s", str(e) - ) + verbose_logger.debug("vertex_ai batch cost calculation error for line: %s", str(e)) prompt_tokens += _prompt completion_tokens += _completion @@ -206,9 +192,7 @@ def calculate_vertex_ai_batch_cost_and_usage( async def _get_batch_output_file_content_as_dictionary( batch: Batch, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", litellm_params: Optional[dict] = None, ) -> List[dict]: """ @@ -235,12 +219,8 @@ async def _get_batch_output_file_content_as_dictionary( is_base64_unified_file_id = _is_base64_encoded_unified_file_id(file_id) if is_base64_unified_file_id: try: - file_id = is_base64_unified_file_id.split("llm_output_file_id,")[1].split( - ";" - )[0] - verbose_logger.debug( - f"Extracted LLM output file ID from unified file ID: {file_id}" - ) + file_id = is_base64_unified_file_id.split("llm_output_file_id,")[1].split(";")[0] + verbose_logger.debug(f"Extracted LLM output file ID from unified file ID: {file_id}") except (IndexError, AttributeError) as e: verbose_logger.error( f"Failed to extract LLM output file ID from unified file ID: {batch.output_file_id}, error: {e}" @@ -380,9 +360,7 @@ def _count_entry_tokens( def _get_batch_job_cost_from_file_content( file_content_dictionary: List[dict], - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", model_info: Optional[ModelInfo] = None, ) -> float: """ @@ -393,9 +371,7 @@ def _get_batch_job_cost_from_file_content( try: total_cost: float = 0.0 # parse the file content as json - verbose_logger.debug( - "file_content_dictionary=%s", json.dumps(file_content_dictionary, indent=4) - ) + verbose_logger.debug("file_content_dictionary=%s", json.dumps(file_content_dictionary, indent=4)) for _item in file_content_dictionary: if _batch_response_was_successful(_item): _response_body = _get_response_from_batch_job_output_file(_item) @@ -424,9 +400,7 @@ def _get_batch_job_cost_from_file_content( def _get_batch_job_total_usage_from_file_content( file_content_dictionary: List[dict], - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"] = "openai", model_name: Optional[str] = None, ) -> Usage: """ @@ -437,9 +411,7 @@ def _get_batch_job_total_usage_from_file_content( and model_name and getattr(litellm, "disable_vertex_batch_output_transformation", False) ): - _, batch_usage = calculate_vertex_ai_batch_cost_and_usage( - file_content_dictionary, model_name - ) + _, batch_usage = calculate_vertex_ai_batch_cost_and_usage(file_content_dictionary, model_name) return batch_usage # For other providers, use the existing logic @@ -488,11 +460,7 @@ def _count_prompt_or_input_tokens(model: str, value: Any) -> int: # Nested pre-tokenized prompt: every int contributes a # token. Mixed string/int items still count. total += sum(1 if isinstance(t, int) else 0 for t in chunk) - total += sum( - token_counter(model=model, text=t) - for t in chunk - if isinstance(t, str) - ) + total += sum(token_counter(model=model, text=t) for t in chunk if isinstance(t, str)) return total return 0 diff --git a/litellm/batches/main.py b/litellm/batches/main.py index c5f1c86a4e1b..3a2d9e13f77b 100644 --- a/litellm/batches/main.py +++ b/litellm/batches/main.py @@ -79,11 +79,7 @@ def _resolve_timeout( Returns: Resolved timeout as float """ - timeout = ( - optional_params.timeout - or kwargs.get("request_timeout", default_timeout) - or default_timeout - ) + timeout = optional_params.timeout or kwargs.get("request_timeout", default_timeout) or default_timeout # Handle httpx.Timeout objects if isinstance(timeout, httpx.Timeout): @@ -109,9 +105,7 @@ async def acreate_batch( completion_window: Literal["24h"], endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm"] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -161,9 +155,7 @@ def create_batch( completion_window: Literal["24h"], endpoint: Literal["/v1/chat/completions", "/v1/embeddings", "/v1/completions"], input_file_id: str, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm"] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -194,9 +186,7 @@ def create_batch( _is_async = kwargs.pop("acreate_batch", False) is True litellm_params = dict(GenericLiteLLMParams(**kwargs)) - litellm_logging_obj: LiteLLMLoggingObj = cast( - LiteLLMLoggingObj, kwargs.get("litellm_logging_obj", None) - ) + litellm_logging_obj: LiteLLMLoggingObj = cast(LiteLLMLoggingObj, kwargs.get("litellm_logging_obj", None)) ### TIMEOUT LOGIC ### timeout = _resolve_timeout(optional_params, kwargs, custom_llm_provider) litellm_logging_obj.update_from_kwargs( @@ -224,9 +214,7 @@ def create_batch( extra_body=extra_body, ) if output_expires_after is not None: - _create_batch_request["output_expires_after"] = cast( - FileExpiresAfter, output_expires_after - ) + _create_batch_request["output_expires_after"] = cast(FileExpiresAfter, output_expires_after) if model is not None: provider_config = ProviderConfigManager.get_provider_batches_config( model=model, @@ -244,12 +232,7 @@ def create_batch( api_key=optional_params.api_key, logging_obj=litellm_logging_obj, _is_async=_is_async, - client=( - client - if client is not None - and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) - else None - ), + client=(client if client is not None and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) else None), timeout=timeout, model=model, ) @@ -288,16 +271,8 @@ def create_batch( _is_async=_is_async, ) elif custom_llm_provider == "azure": - api_base = ( - optional_params.api_base - or litellm.api_base - or get_secret_str("AZURE_API_BASE") - ) - api_version = ( - optional_params.api_version - or litellm.api_version - or get_secret_str("AZURE_API_VERSION") - ) + api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") + api_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") api_key = ( optional_params.api_key @@ -326,18 +301,12 @@ def create_batch( 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") + 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" + 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_batches_instance.create_batch( _is_async=_is_async, @@ -351,17 +320,13 @@ def create_batch( ) else: raise litellm.exceptions.BadRequestError( - message="LiteLLM doesn't support custom_llm_provider={} for 'create_batch'".format( - custom_llm_provider - ), + message="LiteLLM doesn't support custom_llm_provider={} for 'create_batch'".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_batch", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_batch", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -372,9 +337,7 @@ def create_batch( @client async def aretrieve_batch( batch_id: str, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic"] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -420,9 +383,7 @@ def _handle_retrieve_batch_providers_without_provider_config( litellm_params: dict, _retrieve_batch_request: RetrieveBatchRequest, _is_async: bool, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic"] = "openai", logging_obj: Optional[Any] = None, ): api_base: Optional[str] = None @@ -459,16 +420,8 @@ def _handle_retrieve_batch_providers_without_provider_config( max_retries=optional_params.max_retries, ) elif custom_llm_provider == "azure": - api_base = ( - optional_params.api_base - or litellm.api_base - or get_secret_str("AZURE_API_BASE") - ) - api_version = ( - optional_params.api_version - or litellm.api_version - or get_secret_str("AZURE_API_VERSION") - ) + api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") + api_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") api_key = ( optional_params.api_key @@ -497,18 +450,12 @@ def _handle_retrieve_batch_providers_without_provider_config( 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") + 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" + 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_batches_instance.retrieve_batch( _is_async=_is_async, @@ -528,12 +475,7 @@ def _handle_retrieve_batch_providers_without_provider_config( or get_secret_str("ANTHROPIC_API_BASE") or get_secret_str("ANTHROPIC_BASE_URL") ) - api_key = ( - optional_params.api_key - or litellm.api_key - or litellm.azure_key - or get_secret_str("ANTHROPIC_API_KEY") - ) + api_key = optional_params.api_key or litellm.api_key or litellm.azure_key or get_secret_str("ANTHROPIC_API_KEY") response = anthropic_batches_instance.retrieve_batch( _is_async=_is_async, @@ -555,9 +497,7 @@ def _handle_retrieve_batch_providers_without_provider_config( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="retrieve_batch", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="retrieve_batch", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -566,9 +506,7 @@ def _handle_retrieve_batch_providers_without_provider_config( @client def retrieve_batch( batch_id: str, - custom_llm_provider: Literal[ - "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic" - ] = "openai", + custom_llm_provider: Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic"] = "openai", metadata: Optional[Dict[str, str]] = None, extra_headers: Optional[Dict[str, str]] = None, extra_body: Optional[Dict[str, str]] = None, @@ -581,9 +519,7 @@ def retrieve_batch( """ try: optional_params = GenericLiteLLMParams(**kwargs) - litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get( - "litellm_logging_obj", None - ) + litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get("litellm_logging_obj", None) ### TIMEOUT LOGIC ### timeout = optional_params.timeout or kwargs.get("request_timeout", 600) or 600 litellm_params = get_litellm_params( @@ -680,12 +616,7 @@ def retrieve_batch( function_id="batch_retrieve", ), _is_async=_is_async, - client=( - client - if client is not None - and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) - else None - ), + client=(client if client is not None and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) else None), timeout=timeout, model=model, ) @@ -823,16 +754,8 @@ def list_batches( max_retries=optional_params.max_retries, ) 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") - ) + 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") api_key = ( optional_params.api_key @@ -860,18 +783,12 @@ def list_batches( 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") + 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" + 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_batches_instance.list_batches( _is_async=_is_async, @@ -895,9 +812,7 @@ def list_batches( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -1014,17 +929,9 @@ def cancel_batch( 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") + 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_batches_instance.cancel_batch( _is_async=_is_async, @@ -1036,16 +943,8 @@ def cancel_batch( max_retries=optional_params.max_retries, ) elif custom_llm_provider == "azure": - api_base = ( - optional_params.api_base - or litellm.api_base - or get_secret_str("AZURE_API_BASE") - ) - api_version = ( - optional_params.api_version - or litellm.api_version - or get_secret_str("AZURE_API_VERSION") - ) + api_base = optional_params.api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") + api_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") api_key = ( optional_params.api_key @@ -1074,18 +973,12 @@ def cancel_batch( elif custom_llm_provider == "vertex_ai": api_base = optional_params.api_base or None vertex_ai_project = ( - optional_params.vertex_project - or litellm.vertex_project - or get_secret_str("VERTEXAI_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" + 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_batches_instance.cancel_batch( _is_async=_is_async, @@ -1107,9 +1000,7 @@ def cancel_batch( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="cancel_batch", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="cancel_batch", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -1117,9 +1008,7 @@ def cancel_batch( raise e -def _handle_async_invoke_status( - batch_id: str, aws_region_name: str, logging_obj=None, **kwargs -) -> "LiteLLMBatch": +def _handle_async_invoke_status(batch_id: str, aws_region_name: str, logging_obj=None, **kwargs) -> "LiteLLMBatch": """ Handle async invoke status check for AWS Bedrock. @@ -1168,9 +1057,7 @@ async def _async_get_status(): # Get output S3 URI safely output_s3_uri = "" try: - output_s3_uri = status_response["outputDataConfig"]["s3OutputDataConfig"][ - "s3Uri" - ] + output_s3_uri = status_response["outputDataConfig"]["s3OutputDataConfig"]["s3Uri"] except (KeyError, TypeError): pass @@ -1186,15 +1073,12 @@ async def _async_get_status(): failed_at, _, _, - ) = BedrockBatchesConfig()._parse_timestamps_and_status( - status_response, aws_status_raw - ) + ) = BedrockBatchesConfig()._parse_timestamps_and_status(status_response, aws_status_raw) result = LiteLLMBatch( id=status_response["invocationArn"], object="batch", status=normalized_status, - created_at=created_at - or int(time.time()), # Provide default timestamp if None + created_at=created_at or int(time.time()), # Provide default timestamp if None in_progress_at=in_progress_at, completed_at=completed_at, failed_at=failed_at, diff --git a/litellm/budget_manager.py b/litellm/budget_manager.py index 915c22b90ecf..26f888c8077e 100644 --- a/litellm/budget_manager.py +++ b/litellm/budget_manager.py @@ -62,9 +62,7 @@ def load_data(self): # Load the user_dict from hosted db url = self.api_base + "/get_budget" data = {"project_name": self.project_name} - response = litellm.module_level_client.post( - url, headers=self.headers, json=data - ) + response = litellm.module_level_client.post(url, headers=self.headers, json=data) response = response.json() if response["status"] == "error": self.user_dict = {} # assume this means the user dict hasn't been stored yet @@ -91,9 +89,7 @@ def create_budget( elif duration == "yearly": duration_in_days = DAYS_IN_A_YEAR else: - raise ValueError( - """duration needs to be one of ["daily", "weekly", "monthly", "yearly"]""" - ) + raise ValueError("""duration needs to be one of ["daily", "weekly", "monthly", "yearly"]""") self.user_dict[user] = { "total_budget": total_budget, "duration": duration_in_days, @@ -106,9 +102,7 @@ def create_budget( def projected_cost(self, model: str, messages: list, user: str): text = "".join(message["content"] for message in messages) prompt_tokens = litellm.token_counter(model=model, text=text) - prompt_cost, _ = litellm.cost_per_token( - model=model, prompt_tokens=prompt_tokens, completion_tokens=0 - ) + prompt_cost, _ = litellm.cost_per_token(model=model, prompt_tokens=prompt_tokens, completion_tokens=0) current_cost = self.user_dict[user].get("current_cost", 0) projected_cost = prompt_cost + current_cost return projected_cost @@ -125,12 +119,8 @@ def update_cost( output_text: Optional[str] = None, ): if model and input_text and output_text: - prompt_tokens = litellm.token_counter( - model=model, messages=[{"role": "user", "content": input_text}] - ) - completion_tokens = litellm.token_counter( - model=model, messages=[{"role": "user", "content": output_text}] - ) + prompt_tokens = litellm.token_counter(model=model, messages=[{"role": "user", "content": input_text}]) + completion_tokens = litellm.token_counter(model=model, messages=[{"role": "user", "content": output_text}]) ( prompt_tokens_cost_usd_dollar, completion_tokens_cost_usd_dollar, @@ -142,21 +132,15 @@ def update_cost( cost = prompt_tokens_cost_usd_dollar + completion_tokens_cost_usd_dollar elif completion_obj: cost = litellm.completion_cost(completion_response=completion_obj) - model = completion_obj[ - "model" - ] # if this throws an error try, model = completion_obj['model'] + model = completion_obj["model"] # if this throws an error try, model = completion_obj['model'] else: raise ValueError( "Either a chat completion object or the text response needs to be passed in. Learn more - https://docs.litellm.ai/docs/budget_manager" ) - self.user_dict[user]["current_cost"] = cost + self.user_dict[user].get( - "current_cost", 0 - ) + self.user_dict[user]["current_cost"] = cost + self.user_dict[user].get("current_cost", 0) if "model_cost" in self.user_dict[user]: - self.user_dict[user]["model_cost"][model] = cost + self.user_dict[user][ - "model_cost" - ].get(model, 0) + self.user_dict[user]["model_cost"][model] = cost + self.user_dict[user]["model_cost"].get(model, 0) else: self.user_dict[user]["model_cost"] = {model: cost} @@ -198,9 +182,7 @@ def reset_on_duration(self, user: str): current_time = time.time() # Convert duration from days to seconds - duration_in_seconds = ( - self.user_dict[user]["duration"] * HOURS_IN_A_DAY * 60 * 60 - ) + duration_in_seconds = self.user_dict[user]["duration"] * HOURS_IN_A_DAY * 60 * 60 # Check if duration has elapsed if current_time - last_updated_at >= duration_in_seconds: @@ -215,9 +197,7 @@ def update_budget_all_users(self): self.reset_on_duration(user) def _save_data_thread(self): - thread = threading.Thread( - target=self.save_data - ) # [Non-Blocking]: saves data without blocking execution + thread = threading.Thread(target=self.save_data) # [Non-Blocking]: saves data without blocking execution thread.start() def save_data(self): @@ -226,15 +206,11 @@ def save_data(self): # save the user dict with open("user_cost.json", "w") as json_file: - json.dump( - self.user_dict, json_file, indent=4 - ) # Indent for pretty formatting + json.dump(self.user_dict, json_file, indent=4) # Indent for pretty formatting return {"status": "success"} elif self.client_type == "hosted": url = self.api_base + "/set_budget" data = {"project_name": self.project_name, "user_dict": self.user_dict} - response = litellm.module_level_client.post( - url, headers=self.headers, json=data - ) + response = litellm.module_level_client.post(url, headers=self.headers, json=data) response = response.json() return response diff --git a/litellm/caching/_embedding_router.py b/litellm/caching/_embedding_router.py index 1ec898012e92..ec886b14020a 100644 --- a/litellm/caching/_embedding_router.py +++ b/litellm/caching/_embedding_router.py @@ -27,9 +27,7 @@ def resolve_embedding_router( if llm_router is None: return None router_model_names: list[str] = ( - [m["model_name"] for m in llm_model_list if "model_name" in m] - if llm_model_list is not None - else [] + [m["model_name"] for m in llm_model_list if "model_name" in m] if llm_model_list is not None else [] ) if embedding_model in router_model_names: return llm_router diff --git a/litellm/caching/azure_blob_cache.py b/litellm/caching/azure_blob_cache.py index a2246640c30e..fca7cf203138 100644 --- a/litellm/caching/azure_blob_cache.py +++ b/litellm/caching/azure_blob_cache.py @@ -52,9 +52,7 @@ 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 - ) + 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}") diff --git a/litellm/caching/caching.py b/litellm/caching/caching.py index 5f2269d1945a..34badaa3e8a5 100644 --- a/litellm/caching/caching.py +++ b/litellm/caching/caching.py @@ -171,9 +171,7 @@ def __init__( # 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 - ): + 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: @@ -271,7 +269,9 @@ def __init__( 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.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 @@ -294,9 +294,7 @@ def __init__( # Params whose values carry prompt content. Excluded from semantic-cache # scope keys so differently worded prompts share a bucket and match via # vector similarity rather than being split into per-wording buckets. - _SEMANTIC_CACHE_SCOPE_EXCLUDED_PARAMS: frozenset = frozenset( - {"messages", "prompt", "input"} - ) + _SEMANTIC_CACHE_SCOPE_EXCLUDED_PARAMS: frozenset = frozenset({"messages", "prompt", "input"}) # Server-set identity (from proxy auth) used to isolate semantic-cache # buckets per tenant. Required once the prompt is out of the scope key, so a @@ -349,11 +347,7 @@ def get_cache_key(self, **kwargs) -> str: combined_kwargs = ModelParamHelper._get_all_llm_api_params() litellm_param_kwargs = all_litellm_params is_semantic_cache = self._is_semantic_cache() - scope_excluded_params = ( - self._SEMANTIC_CACHE_SCOPE_EXCLUDED_PARAMS - if is_semantic_cache - else frozenset() - ) + scope_excluded_params = self._SEMANTIC_CACHE_SCOPE_EXCLUDED_PARAMS if is_semantic_cache else frozenset() for param in kwargs: if param in scope_excluded_params: continue @@ -361,12 +355,8 @@ def get_cache_key(self, **kwargs) -> str: 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 + 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] @@ -385,9 +375,7 @@ def get_cache_key(self, **kwargs) -> str: # 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 - ) + self._set_preset_cache_key_in_kwargs(preset_cache_key=hashed_cache_key, **kwargs_for_preset) return hashed_cache_key def _get_param_value( @@ -415,15 +403,11 @@ def _get_model_param_value(self, kwargs: dict) -> str: 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") + 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]: + 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: @@ -503,11 +487,7 @@ def _add_namespace_to_cache_key(self, hash_hex: str, **kwargs) -> str: """ 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 - ) + 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) @@ -537,11 +517,7 @@ def _get_cache_logic( 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 - ): + if cached_result is not None and isinstance(cached_result, dict) and "timestamp" in cached_result: timestamp = cached_result["timestamp"] current_time = time.time() @@ -586,15 +562,11 @@ def _update_metadata_from_cache_lookup_kwargs( ) -> None: original_metadata = original_kwargs.get("metadata") cache_lookup_metadata = cache_lookup_kwargs.get("metadata") - if not isinstance(original_metadata, dict) or not isinstance( - cache_lookup_metadata, dict - ): + if not isinstance(original_metadata, dict) or not isinstance(cache_lookup_metadata, dict): return if "semantic-similarity" in cache_lookup_metadata: - original_metadata["semantic-similarity"] = cache_lookup_metadata[ - "semantic-similarity" - ] + original_metadata["semantic-similarity"] = cache_lookup_metadata["semantic-similarity"] def get_cache(self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): """ @@ -616,34 +588,22 @@ def get_cache(self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): 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") - ) + max_age = cache_control_args.get("s-maxage") or cache_control_args.get("s-max-age") or float("inf") cache_lookup_kwargs = self._get_safe_cache_lookup_kwargs(kwargs) if dynamic_cache_object is not None: - cached_result = dynamic_cache_object.get_cache( - cache_key, **cache_lookup_kwargs - ) + cached_result = dynamic_cache_object.get_cache(cache_key, **cache_lookup_kwargs) else: - cached_result = self.cache.get_cache( - cache_key, **cache_lookup_kwargs - ) + cached_result = self.cache.get_cache(cache_key, **cache_lookup_kwargs) self._update_metadata_from_cache_lookup_kwargs( original_kwargs=kwargs, cache_lookup_kwargs=cache_lookup_kwargs, ) - return self._get_cache_logic( - cached_result=cached_result, max_age=max_age - ) + 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 def async_get_cache(self, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): """ Async get cache implementation. @@ -660,20 +620,12 @@ async def async_get_cache( 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")) - ) + 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 - ) + 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 - ) + 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 @@ -722,16 +674,12 @@ def add_cache(self, result, **kwargs): try: if self.should_use_cache(**kwargs) is not True: return - cache_key, cached_data, kwargs = self._add_cache_logic( - result=result, **kwargs - ) + 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 def async_add_cache(self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): """ Async implementation of add_cache """ @@ -742,13 +690,9 @@ async def async_add_cache( # 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 - ) + 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 - ) + 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: @@ -899,9 +843,7 @@ def add_embedding_response_to_cache( ) return cache_key, cached_data, kwargs - async def async_add_cache_pipeline( - self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs - ): + async def async_add_cache_pipeline(self, result, dynamic_cache_object: Optional[BaseCache] = None, **kwargs): """ Async implementation of add_cache for Embedding calls @@ -925,19 +867,13 @@ async def async_add_cache_pipeline( ) = 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_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 - ) + 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 - ) + 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)}") diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.py index 1ff4ee04080b..c860f8e540d0 100644 --- a/litellm/caching/caching_handler.py +++ b/litellm/caching/caching_handler.py @@ -163,11 +163,9 @@ async def _async_get_cache( """ # 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) + (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 @@ -183,9 +181,7 @@ async def _async_get_cache( 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 - ): + 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, @@ -204,9 +200,7 @@ async def _async_get_cache( 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 + cache_duration_ms = (cache_check_end_time - cache_check_start_time) * 1000 self._update_litellm_logging_obj_environment( logging_obj=logging_obj, model=model, @@ -250,9 +244,7 @@ async def _async_get_cache( 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. + and not isinstance(litellm.cache.cache, S3Cache) # s3 doesn't support bulk writing. Exclude. ): ( final_embedding_cached_response, @@ -291,9 +283,7 @@ def _sync_get_cache( 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 - ): + 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() @@ -376,9 +366,7 @@ def handle_kwargs_input_list_or_str(self, kwargs: Dict[str, Any]) -> List[str]: 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]: + 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. @@ -461,9 +449,7 @@ def _process_async_embedding_cached_response( elif 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 - ) + 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: @@ -471,9 +457,7 @@ def _process_async_embedding_cached_response( aggregated_details = {} for key, value in item_details.items(): if isinstance(value, (int, float)): - aggregated_details[key] = ( - aggregated_details.get(key, 0) + value - ) + aggregated_details[key] = aggregated_details.get(key, 0) + value else: aggregated_details[key] = value @@ -483,9 +467,7 @@ def _process_async_embedding_cached_response( from litellm.types.utils import PromptTokensDetailsWrapper try: - prompt_tokens_details = PromptTokensDetailsWrapper( - **aggregated_details - ) + prompt_tokens_details = PromptTokensDetailsWrapper(**aggregated_details) except Exception: prompt_tokens_details = None usage = Usage( @@ -554,16 +536,8 @@ def _merge_prompt_tokens_details( 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 {} - ) + 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()): @@ -632,9 +606,7 @@ def _combine_cached_embedding_response_with_api_result( 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._hidden_params["cache_hit"] = True _caching_handler_response.final_embedding_cached_response._response_ms = ( end_time - start_time ).total_seconds() * 1000 @@ -730,9 +702,7 @@ async def _retrieve_from_cache( 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} - ) + preset_cache_key = litellm.cache.get_cache_key(**{**new_kwargs, "input": i}) tasks.append( litellm.cache.async_get_cache( cache_key=preset_cache_key, @@ -750,18 +720,14 @@ async def _retrieve_from_cache( 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) - ) + 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) - ) + 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, @@ -808,10 +774,9 @@ def _convert_cached_result_to_model_response( """ 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 (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, @@ -825,8 +790,7 @@ def _convert_cached_result_to_model_response( model_response_object=ModelResponse(), ) if ( - call_type == CallTypes.atext_completion.value - or call_type == CallTypes.text_completion.value + 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( @@ -837,28 +801,26 @@ def _convert_cached_result_to_model_response( ) else: cached_result = TextCompletionResponse(**cached_result) - elif ( - call_type == CallTypes.aembedding.value - or call_type == CallTypes.embedding.value - ) and isinstance(cached_result, dict): + 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): + 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): + 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, @@ -870,16 +832,12 @@ def _convert_cached_result_to_model_response( response_type="audio_transcription", hidden_params=hidden_params, ) - elif (call_type == "aresponses" or call_type == "responses") and isinstance( - cached_result, dict - ): + elif (call_type == "aresponses" or call_type == "responses") and isinstance(cached_result, dict): use_chat_completion_cache = _is_chat_completion_cached_dict(cached_result) if use_chat_completion_cache: if kwargs.get("stream", False) is True: bridge_call_type = ( - CallTypes.acompletion.value - if call_type == "aresponses" - else CallTypes.completion.value + CallTypes.acompletion.value if call_type == "aresponses" else CallTypes.completion.value ) cached_result = self._convert_cached_stream_response( cached_result=cached_result, @@ -949,10 +907,7 @@ def _convert_cached_stream_response( ) _stream_cached_result: Union[AsyncGenerator, Generator] - if ( - call_type == CallTypes.acompletion.value - or call_type == CallTypes.atext_completion.value - ): + 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, ) @@ -1005,9 +960,7 @@ async def async_set_cache( 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 self._should_store_result_in_cache(original_function=original_function, kwargs=new_kwargs): if ( isinstance(result, litellm.ModelResponse) or isinstance(result, litellm.EmbeddingResponse) @@ -1018,9 +971,7 @@ async def async_set_cache( if ( isinstance(result, EmbeddingResponse) and litellm.cache is not None - and not isinstance( - litellm.cache.cache, S3Cache - ) # s3 doesn't support bulk writing. Exclude. + and not isinstance(litellm.cache.cache, S3Cache) # s3 doesn't support bulk writing. Exclude. ): asyncio.create_task( litellm.cache.async_add_cache_pipeline( @@ -1058,16 +1009,12 @@ def sync_set_cache( if litellm.cache is None: return - if self._should_store_result_in_cache( - original_function=self.original_function, kwargs=new_kwargs - ): + 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: + 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. @@ -1113,15 +1060,15 @@ async def _add_streaming_response_to_cache(self, processed_chunk: ModelResponse) """ - 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, + 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: @@ -1135,15 +1082,15 @@ 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, + 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 @@ -1191,9 +1138,7 @@ def _update_litellm_logging_obj_environment( } if litellm.cache is not None: - litellm_params["preset_cache_key"] = ( - litellm.cache._get_preset_cache_key_from_kwargs(**kwargs) - ) + litellm_params["preset_cache_key"] = litellm.cache._get_preset_cache_key_from_kwargs(**kwargs) else: litellm_params["preset_cache_key"] = None @@ -1202,11 +1147,7 @@ def _update_litellm_logging_obj_environment( user=kwargs.get("user", None), optional_params={}, litellm_params=litellm_params, - input=( - kwargs.get("messages", "") - if not is_embedding - else kwargs.get("input", "") - ), + 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, diff --git a/litellm/caching/disk_cache.py b/litellm/caching/disk_cache.py index e32c29b3bc66..b51acbe9cfd0 100644 --- a/litellm/caching/disk_cache.py +++ b/litellm/caching/disk_cache.py @@ -16,9 +16,7 @@ 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 + 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: diff --git a/litellm/caching/dual_cache.py b/litellm/caching/dual_cache.py index 8060a65b78d4..be618815a537 100644 --- a/litellm/caching/dual_cache.py +++ b/litellm/caching/dual_cache.py @@ -69,23 +69,15 @@ def __init__( 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 = 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 + 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] - ): + 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 @@ -125,9 +117,7 @@ def set_cache(self, key, value, local_only: bool = False, **kwargs): except Exception as e: print_verbose(e) - def increment_cache( - self, key, value: int, local_only: bool = False, **kwargs - ) -> int: + def increment_cache(self, key, value: int, local_only: bool = False, **kwargs) -> int: """ Key - the key in cache @@ -166,9 +156,7 @@ def get_cache( 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 - ) + 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 @@ -196,9 +184,7 @@ def run_in_new_loop(): 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) - ) + return new_loop.run_until_complete(self.async_batch_get_cache(**received_args)) finally: new_loop.close() asyncio.set_event_loop(None) @@ -225,14 +211,10 @@ async def async_get_cache( ): # Try to fetch from in-memory cache first try: - print_verbose( - f"async get cache: cache key: {key}; local_only: {local_only}" - ) + 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 - ) + 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: @@ -240,15 +222,11 @@ async def async_get_cache( 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 - ) + 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 - ) + await self.in_memory_cache.async_set_cache(key, redis_result, **kwargs) result = redis_result @@ -277,20 +255,15 @@ def _reserve_redis_batch_keys( 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 + 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 - ) + 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: + 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: @@ -308,9 +281,7 @@ async def async_batch_get_cache( 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 - ) + 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 @@ -321,9 +292,7 @@ async def async_batch_get_cache( - check the redis cache """ current_time = time.time() - sublist_keys, previous_access_times = self._reserve_redis_batch_keys( - current_time, keys, result - ) + 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: @@ -334,15 +303,11 @@ async def async_batch_get_cache( ) except Exception: # Do not throttle subsequent callers if the Redis read fails. - self._rollback_redis_batch_key_reservations( - previous_access_times - ) + 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() - ): + 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 @@ -353,18 +318,14 @@ async def async_batch_get_cache( 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 - ) + 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}" - ) + 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: @@ -374,36 +335,26 @@ async def async_set_cache(self, key, value, local_only: bool = False, **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)}" - ) + 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 - ): + 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}" - ) + 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 - ) + 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)}" - ) + verbose_logger.exception(f"LiteLLM Cache: Excepton async add_cache: {str(e)}") async def async_increment_cache( self, @@ -428,9 +379,7 @@ async def async_increment_cache( result: Optional[float] = None try: if self.in_memory_cache is not None: - result = await self.in_memory_cache.async_increment( - key, value, **kwargs - ) + 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( @@ -478,9 +427,7 @@ async def async_increment_cache_pipeline( ) return result - async def async_set_cache_sadd( - self, key, value: List, local_only: bool = False, **kwargs - ) -> None: + async def async_set_cache_sadd(self, key, value: List, local_only: bool = False, **kwargs) -> None: """ Add value to a set @@ -492,14 +439,10 @@ async def async_set_cache_sadd( """ 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) - ) + _ = 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) - ) + _ = await self.redis_cache.async_set_cache_sadd(key, value, ttl=kwargs.get("ttl", None)) return None except Exception as e: diff --git a/litellm/caching/gcs_cache.py b/litellm/caching/gcs_cache.py index 0e6a111eb2bb..3345f8fc5ebe 100644 --- a/litellm/caching/gcs_cache.py +++ b/litellm/caching/gcs_cache.py @@ -26,15 +26,10 @@ def __init__( ) -> 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.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.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.sync_client = _get_httpx_client() def _construct_headers(self) -> dict: @@ -64,9 +59,7 @@ async def async_set_cache(self, key, value, **kwargs): 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}" - ) + print_verbose(f"GCS Caching: async_set_cache() - Got exception from GCS: {e}") def get_cache(self, key, **kwargs): try: @@ -83,9 +76,7 @@ def get_cache(self, key, **kwargs): return cached_response return None except Exception as e: - verbose_logger.error( - f"GCS Caching: get_cache() - Got exception from GCS: {e}" - ) + verbose_logger.error(f"GCS Caching: get_cache() - Got exception from GCS: {e}") async def async_get_cache(self, key, **kwargs): try: @@ -98,9 +89,7 @@ async def async_get_cache(self, key, **kwargs): 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}" - ) + verbose_logger.error(f"GCS Caching: async_get_cache() - Got exception from GCS: {e}") def flush_cache(self): pass diff --git a/litellm/caching/in_memory_cache.py b/litellm/caching/in_memory_cache.py index ba446dd4f608..2ad3f3f11b73 100644 --- a/litellm/caching/in_memory_cache.py +++ b/litellm/caching/in_memory_cache.py @@ -40,9 +40,7 @@ def __init__( 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 + 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 = {} @@ -58,8 +56,7 @@ def check_value_size(self, value: Any): # 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 + and len(str(value)) < self.max_size_per_item * MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB ): # Conservative estimate return True @@ -73,9 +70,7 @@ def check_value_size(self, value: Any): return size <= self.max_size_per_item # Fallback for complex types - if isinstance(value, BaseModel) and hasattr( - value, "model_dump" - ): # Pydantic v2 + 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 @@ -257,9 +252,7 @@ async def async_increment_pipeline( ) -> Optional[List[float]]: results = [] for increment in increment_list: - result = await self.async_increment( - increment["key"], increment["increment_value"], **kwargs - ) + result = await self.async_increment(increment["key"], increment["increment_value"], **kwargs) results.append(result) return results diff --git a/litellm/caching/qdrant_semantic_cache.py b/litellm/caching/qdrant_semantic_cache.py index 504ef8a54ebc..5ed1bb47eba8 100644 --- a/litellm/caching/qdrant_semantic_cache.py +++ b/litellm/caching/qdrant_semantic_cache.py @@ -51,34 +51,24 @@ def __init__( 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}" - ) + 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 - ) + 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/" - ): + 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/" - ): + 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_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: @@ -94,22 +84,16 @@ def __init__( self.headers = headers self.sync_client = _get_httpx_client() - self.async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.Caching - ) + 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." - ) + 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}" - ) + 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( @@ -117,9 +101,7 @@ def __init__( headers=self.headers, ) self.collection_info = collection_details.json() - print_verbose( - f"Collection already exists.\nCollection details:{self.collection_info}" - ) + print_verbose(f"Collection already exists.\nCollection details:{self.collection_info}") self._ensure_cache_key_payload_index() else: quantization_params: Dict[str, Any] @@ -138,13 +120,9 @@ def __init__( } } elif quantization_config == "product": - quantization_params = { - "product": {"compression": "x16", "always_ram": False} - } + quantization_params = {"product": {"compression": "x16", "always_ram": False}} else: - raise Exception( - "Quantization config must be one of 'scalar', 'binary' or 'product'" - ) + 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}", @@ -160,9 +138,7 @@ def __init__( headers=self.headers, ) self.collection_info = collection_details.json() - print_verbose( - f"New collection created.\nCollection details:{self.collection_info}" - ) + 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") @@ -171,9 +147,7 @@ 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 + cached_response = json.loads(cached_response) # Convert string to dictionary except Exception: cached_response = ast.literal_eval(cached_response) return cached_response @@ -202,15 +176,9 @@ def _ensure_cache_key_payload_index(self) -> None: }, ) if response.status_code not in (200, 201): - print_verbose( - "Qdrant semantic-cache could not create cache-key payload index: " - f"{response.text}" - ) + print_verbose(f"Qdrant semantic-cache could not create cache-key payload index: {response.text}") except Exception as exc: - print_verbose( - "Qdrant semantic-cache could not create cache-key payload index: " - f"{str(exc)}" - ) + print_verbose(f"Qdrant semantic-cache could not create cache-key payload index: {str(exc)}") def _payload_matches_cache_key(self, payload: dict, key: str) -> bool: # Pre-isolation points stored only prompt + response with no cache-key @@ -220,9 +188,7 @@ def _payload_matches_cache_key(self, payload: dict, key: str) -> bool: cached_key = payload.get(self.CACHE_KEY_FIELD_NAME) return cached_key is not None and str(cached_key) == str(key) - def _get_embedding( - self, prompt: str, metadata: Dict[str, Any] | None = None - ) -> EmbeddingResponse: + def _get_embedding(self, prompt: str, metadata: Dict[str, Any] | None = None) -> EmbeddingResponse: """Embed via the proxy Router when it serves the model, else direct.""" try: from litellm.proxy.proxy_server import llm_model_list, llm_router @@ -230,9 +196,7 @@ def _get_embedding( llm_model_list = None llm_router = None - router = resolve_embedding_router( - self.embedding_model, llm_router, llm_model_list - ) + router = resolve_embedding_router(self.embedding_model, llm_router, llm_model_list) if router is not None: return router.embedding( model=self.embedding_model, @@ -246,18 +210,14 @@ def _get_embedding( cache={"no-store": True, "no-cache": True}, ) - async def _get_async_embedding( - self, prompt: str, metadata: Dict[str, Any] | None = None - ) -> EmbeddingResponse: + async def _get_async_embedding(self, prompt: str, metadata: Dict[str, Any] | None = None) -> EmbeddingResponse: try: from litellm.proxy.proxy_server import llm_model_list, llm_router except ImportError: llm_model_list = None llm_router = None - router = resolve_embedding_router( - self.embedding_model, llm_router, llm_model_list - ) + router = resolve_embedding_router(self.embedding_model, llm_router, llm_model_list) if router is not None: return await router.aembedding( model=self.embedding_model, @@ -394,9 +354,7 @@ async def async_set_cache(self, key, value, **kwargs): # get the prompt messages = kwargs["messages"] prompt = get_str_from_messages(messages) - embedding_response = await self._get_async_embedding( - prompt, metadata=kwargs.get("metadata") - ) + embedding_response = await self._get_async_embedding(prompt, metadata=kwargs.get("metadata")) # get the embedding embedding = embedding_response["data"][0]["embedding"] @@ -432,9 +390,7 @@ async def async_get_cache(self, key, **kwargs): messages = kwargs["messages"] prompt = get_str_from_messages(messages) - embedding_response = await self._get_async_embedding( - prompt, metadata=kwargs.get("metadata") - ) + embedding_response = await self._get_async_embedding(prompt, metadata=kwargs.get("metadata")) # get the embedding embedding = embedding_response["data"][0]["embedding"] diff --git a/litellm/caching/redis_cache.py b/litellm/caching/redis_cache.py index 5c9f74e4c189..dd1c152a4214 100644 --- a/litellm/caching/redis_cache.py +++ b/litellm/caching/redis_cache.py @@ -15,6 +15,7 @@ import inspect import json import time +from collections.abc import Awaitable, Callable, Sequence from datetime import timedelta from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast @@ -152,8 +153,7 @@ def record_failure(self) -> None: 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", + "Redis circuit breaker OPENED after %d consecutive failures — fast-failing Redis calls for %ds", self._failure_count, self.recovery_timeout, ) @@ -178,9 +178,7 @@ def _redis_circuit_breaker_guard(method): # type: ignore @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__}" - ) + raise Exception(f"Redis circuit breaker is open — skipping {method.__name__}") try: result = await method(self, *args, **kwargs) self._circuit_breaker.record_success() @@ -232,9 +230,7 @@ def __init__( 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_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) @@ -273,9 +269,7 @@ def _setup_health_pings(self): _ = 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." - ) + verbose_logger.debug("Ignoring async redis ping. No running event loop.") else: verbose_logger.error( "Error connecting to Async Redis client - {}".format(str(e)), @@ -288,9 +282,7 @@ def _setup_health_pings(self): 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)} - ) + 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): @@ -349,18 +341,12 @@ def init_async_client( 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 - ) + 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 - ) + 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 @@ -407,9 +393,7 @@ def _parse_redis_major_version(self) -> int: 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}" - ) + 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() @@ -425,13 +409,9 @@ def set_cache(self, key, value, **kwargs): ) 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)}" - ) + 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: + 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) @@ -535,7 +515,7 @@ async def async_scan_iter(self, pattern: str, count: int = 100) -> list: ) raise e - def async_register_script(self, script: str) -> Any: + def async_register_script(self, script: str) -> Callable[..., Awaitable[Any]]: """ Register a Lua script with Redis asynchronously. Works with both standalone Redis and Redis Cluster. @@ -545,39 +525,69 @@ def async_register_script(self, script: str) -> Any: scripts would operate on raw keys while the rest of the cache uses the namespace, leaving rate-limit and lock keys outside the configured prefix. + Registration is deferred to call time and cached per running event loop + (via in_memory_llm_clients_cache, which keys its entries on the loop). A + registered script is bound to the connection of the loop it was created + on; awaiting it from another loop raises "got Future attached to a + different loop". Binding lazily on the calling loop gives the script the + same per-loop scoping init_async_client already gives the clients, so a + script registered once at startup is never reused across loops. + Args: script (str): The Lua script to register Returns: - Any: A script object that can be called with keys and args + A callable ``(keys, args, client=None)`` that runs the script + against the calling loop's Redis client. """ - try: - _redis_client = self.init_async_client() - # For standalone Redis - if hasattr(_redis_client, "register_script"): - registered_script = _redis_client.register_script(script) # type: ignore - - async def namespaced_script( - keys: list[str], args: list[Any], client: Any = None - ) -> Any: - keys = [self.check_and_fix_namespace(key=key) for key in keys] - return await registered_script(keys=keys, args=args, client=client) - - return namespaced_script - # 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: - keys = [self.check_and_fix_namespace(key=key) for key in keys] - 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 + # Keyed by connection params and namespace as well as the script, so + # two RedisCache instances pointing at different servers or using + # different key prefixes never share an executor; in_memory_llm_clients_cache + # then adds the running loop, completing the per-(client, namespace, loop) + # scoping. + script_cache_key = ( + f"redis-registered-script-{self._get_async_client_cache_key()}-" + f"{self.namespace}-{hashlib.sha256(script.encode()).hexdigest()[:16]}" + ) + + async def run_script(keys: Sequence[str], args: Sequence[Any], client: Any = None) -> Any: + executor: Optional[Callable[..., Awaitable[Any]]] = litellm.in_memory_llm_clients_cache.get_cache( + key=script_cache_key + ) + if executor is None: + executor = self._register_script_for_current_loop(script) + litellm.in_memory_llm_clients_cache.set_cache(key=script_cache_key, value=executor) + return await executor(keys=keys, args=args, client=client) + + return run_script + + def _register_script_for_current_loop(self, script: str) -> Callable[..., Awaitable[Any]]: + """ + Register the script against the current event loop's Redis client. + + Kept separate from async_register_script so each loop caches its own + executor; see that method for why the binding must be per loop. + """ + _redis_client: Any = self.init_async_client() + if hasattr(_redis_client, "register_script"): + registered_script = _redis_client.register_script(script) + + async def standalone_executor(keys: Sequence[str], args: Sequence[Any], client: Any = None) -> Any: + namespaced_keys = tuple(self.check_and_fix_namespace(key=key) for key in keys) + return await registered_script(keys=namespaced_keys, args=args, client=client) + + return standalone_executor + + if hasattr(_redis_client, "script_load"): + script_sha = _redis_client.script_load(script) + + async def cluster_executor(keys: Sequence[str], args: Sequence[Any], client: Any = None) -> Any: + namespaced_keys = tuple(self.check_and_fix_namespace(key=key) for key in keys) + return await _redis_client.evalsha(script_sha, len(namespaced_keys), *namespaced_keys, *args) + + return cluster_executor + + raise ValueError("Redis client does not support Lua script registration") @_redis_circuit_breaker_guard async def async_set_cache(self, key, value, **kwargs): @@ -629,9 +639,7 @@ async def async_set_cache(self, key, value, **kwargs): nx=nx, ex=ttl, ) - print_verbose( - f"Successfully Set ASYNC Redis Cache: key: {key}\nValue {value}\nttl={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( @@ -680,9 +688,7 @@ async def _pipeline_helper( # 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}" - ) + 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 @@ -698,9 +704,7 @@ async def _pipeline_helper( return results @_redis_circuit_breaker_guard - async def async_set_cache_pipeline( - self, cache_list: List[Tuple[Any, Any]], ttl: Optional[float] = None, **kwargs - ): + 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 """ @@ -711,9 +715,7 @@ async def async_set_cache_pipeline( _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}" - ) + 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: @@ -775,9 +777,7 @@ async def _set_cache_sadd_helper( raise @_redis_circuit_breaker_guard - async def async_set_cache_sadd( - self, key, value: List, ttl: Optional[float], **kwargs - ): + async def async_set_cache_sadd(self, key, value: List, ttl: Optional[float], **kwargs): from redis.asyncio import Redis start_time = time.time() @@ -808,12 +808,8 @@ async def async_set_cache_sadd( 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}" - ) + 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( @@ -957,9 +953,7 @@ async def async_set_max( return float(result) async def flush_cache_buffer(self): - print_verbose( - f"flushing to redis....reached size of buffer {len(self.redis_batch_writing_buffer)}" - ) + 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 = [] @@ -972,9 +966,7 @@ def _get_cache_logic(self, cached_response: Any): # 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 + cached_response = json.loads(cached_response) # Convert string to dictionary except Exception: cached_response = ast.literal_eval(cached_response) return cached_response @@ -995,15 +987,11 @@ def get_cache(self, key, parent_otel_span: Optional[Span] = None, **kwargs): end_time=end_time, parent_otel_span=parent_otel_span, ) - print_verbose( - f"Got Redis Cache: key: {key}, cached_response {cached_response}" - ) + 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 - ) + verbose_logger.error("litellm.caching.caching: get() - Got exception from REDIS: ", e) def _run_redis_mget_operation(self, keys: List[str]) -> List[Any]: """ @@ -1075,9 +1063,7 @@ def batch_get_cache( return key_value_dict @_redis_circuit_breaker_guard - async def async_get_cache( - self, key, parent_otel_span: Optional[Span] = None, **kwargs - ): + 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 @@ -1087,9 +1073,7 @@ async def async_get_cache( 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}" - ) + 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() @@ -1121,9 +1105,7 @@ async def async_get_cache( event_metadata={"key": key}, ) ) - print_verbose( - f"litellm.caching.caching: async get() - Got exception from REDIS: {str(e)}" - ) + print_verbose(f"litellm.caching.caching: async get() - Got exception from REDIS: {str(e)}") @_redis_circuit_breaker_guard async def async_batch_get_cache( @@ -1228,9 +1210,7 @@ def sync_ping(self) -> bool: 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)}" - ) + verbose_logger.error(f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}") raise e async def ping(self) -> bool: @@ -1264,9 +1244,7 @@ async def ping(self) -> bool: call_type=f"async_ping <- {_get_call_stack_info()}", ) ) - verbose_logger.error( - f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}" - ) + verbose_logger.error(f"LiteLLM Redis Cache PING: - Got exception from REDIS : {str(e)}") raise e @_redis_circuit_breaker_guard @@ -1366,9 +1344,7 @@ async def _pipeline_increment_helper( # 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}" - ) + 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 @@ -1392,9 +1368,7 @@ async def async_increment_pipeline( _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}" - ) + print_verbose(f"Increment Async Redis Cache Pipeline: increment list: {increment_list}") try: async with _redis_client.pipeline(transaction=False) as pipe: @@ -1508,9 +1482,7 @@ async def async_rpush( call_type=f"async_rpush <- {_get_call_stack_info()}", ) ) - verbose_logger.error( - f"LiteLLM Redis Cache RPUSH: - Got exception from REDIS : {str(e)}" - ) + verbose_logger.error(f"LiteLLM Redis Cache RPUSH: - Got exception from REDIS : {str(e)}") raise e async def _pipeline_rpush_helper( @@ -1584,9 +1556,7 @@ async def async_rpush_pipeline( ) raise e - async def handle_lpop_count_for_older_redis_versions( - self, pipe: pipeline, key: str, count: int - ) -> List[bytes]: + 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) @@ -1617,9 +1587,7 @@ async def async_lpop( 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 - ) + 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) @@ -1641,9 +1609,7 @@ async def async_lpop( return result.decode("utf-8") except Exception: return result - elif isinstance(result, list) and all( - isinstance(item, bytes) for item in 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: @@ -1662,9 +1628,7 @@ async def async_lpop( call_type=f"async_lpop <- {_get_call_stack_info()}", ) ) - verbose_logger.error( - f"LiteLLM Redis Cache LPOP: - Got exception from REDIS : {str(e)}" - ) + verbose_logger.error(f"LiteLLM Redis Cache LPOP: - Got exception from REDIS : {str(e)}") raise e async def _pipeline_lpop_helper( @@ -1700,9 +1664,7 @@ async def _pipeline_lpop_helper( raw_results = [] offset = 0 for count in counts: - key_results = [ - r for r in flat_results[offset : offset + count] if r is not None - ] + 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 @@ -1719,11 +1681,7 @@ async def _pipeline_lpop_helper( 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 - ] + [item.decode("utf-8") if isinstance(item, bytes) else item for item in r if item is not None] or None ) except Exception: diff --git a/litellm/caching/redis_cluster_cache.py b/litellm/caching/redis_cluster_cache.py index 2dc9224e7152..0698ebdcf2a9 100644 --- a/litellm/caching/redis_cluster_cache.py +++ b/litellm/caching/redis_cluster_cache.py @@ -37,9 +37,7 @@ def init_async_client(self): 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 - ) + _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 diff --git a/litellm/caching/redis_semantic_cache.py b/litellm/caching/redis_semantic_cache.py index e79392bb7f0a..d4288cc777c3 100644 --- a/litellm/caching/redis_semantic_cache.py +++ b/litellm/caching/redis_semantic_cache.py @@ -97,8 +97,7 @@ def __init__( # 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." + f"Missing required Redis configuration: {missing_var}. Provide {missing_var} or redis_url." ) from e redis_url = f"redis://:{password}@{host}:{port}" @@ -158,10 +157,7 @@ def _init_semantic_cache( ) -> 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") - ) + return any(phrase in error_message for phrase in ("schema does not match", "index schema")) try: return semantic_cache_cls( @@ -310,9 +306,7 @@ def _coerce_response_input_value(value: Any) -> Any: return dict_method() return value - def _get_embedding( - self, prompt: str, metadata: Dict[str, Any] | None = None - ) -> List[float]: + def _get_embedding(self, prompt: str, metadata: Dict[str, Any] | None = None) -> List[float]: """ Routes through the proxy Router when the embedding model is a Router deployment so per-deployment auth (e.g. Bedrock aws_role_name) applies, @@ -324,9 +318,7 @@ def _get_embedding( llm_model_list = None llm_router = None - router = resolve_embedding_router( - self.embedding_model, llm_router, llm_model_list - ) + router = resolve_embedding_router(self.embedding_model, llm_router, llm_model_list) if router is not None: embedding_response = cast( EmbeddingResponse, @@ -398,9 +390,7 @@ def set_cache(self, key: str, value: Any, **kwargs) -> None: value_str = str(value) - prompt_embedding = self._get_embedding( - prompt, metadata=kwargs.get("metadata") - ) + prompt_embedding = self._get_embedding(prompt, metadata=kwargs.get("metadata")) store_kwargs: dict[str, Any] = { "vector": prompt_embedding, @@ -413,9 +403,7 @@ def set_cache(self, key: str, value: Any, **kwargs) -> 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)}" - ) + print_verbose(f"Error setting {value_str or value} in the Redis semantic cache: {str(e)}") def get_cache(self, key: str, **kwargs) -> Any: """ @@ -439,9 +427,7 @@ def get_cache(self, key: str, **kwargs) -> Any: # Check the cache for semantically similar prompts in this exact # LiteLLM cache-key scope. - prompt_embedding = self._get_embedding( - prompt, metadata=kwargs.get("metadata") - ) + prompt_embedding = self._get_embedding(prompt, metadata=kwargs.get("metadata")) check_kwargs: dict[str, Any] = { "prompt": prompt, "vector": prompt_embedding, @@ -485,9 +471,7 @@ def get_cache(self, key: str, **kwargs) -> Any: 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, metadata: Dict[str, Any] | None = None - ) -> List[float]: + async def _get_async_embedding(self, prompt: str, metadata: Dict[str, Any] | None = None) -> List[float]: """ Asynchronously generate an embedding for the given prompt. @@ -504,9 +488,7 @@ async def _get_async_embedding( llm_model_list = None llm_router = None - router = resolve_embedding_router( - self.embedding_model, llm_router, llm_model_list - ) + router = resolve_embedding_router(self.embedding_model, llm_router, llm_model_list) try: if router is not None: embedding_response = await router.aembedding( @@ -547,9 +529,7 @@ async def async_set_cache(self, key: str, value: Any, **kwargs) -> None: value_str = str(value) # Generate embedding for the value (response) to cache - prompt_embedding = await self._get_async_embedding( - prompt, metadata=kwargs.get("metadata") - ) + prompt_embedding = await self._get_async_embedding(prompt, metadata=kwargs.get("metadata")) store_kwargs: dict[str, Any] = { "vector": prompt_embedding, @@ -589,9 +569,7 @@ async def async_get_cache(self, key: str, **kwargs) -> Any: return None # Generate embedding for the prompt - prompt_embedding = await self._get_async_embedding( - prompt, metadata=kwargs.get("metadata") - ) + prompt_embedding = await self._get_async_embedding(prompt, metadata=kwargs.get("metadata")) # Check the cache for semantically similar prompts in this exact # LiteLLM cache-key scope. @@ -647,9 +625,7 @@ async def _index_info(self) -> Dict[str, Any]: 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: + async def async_set_cache_pipeline(self, cache_list: List[Tuple[str, Any]], **kwargs) -> None: """ Asynchronously store multiple values in the semantic cache. diff --git a/litellm/caching/s3_cache.py b/litellm/caching/s3_cache.py index e26fbe8981c7..1ada940a9c9a 100644 --- a/litellm/caching/s3_cache.py +++ b/litellm/caching/s3_cache.py @@ -110,9 +110,7 @@ async def async_set_cache(self, key, value, **kwargs): 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}" - ) + verbose_logger.error(f"S3 Caching: async_set_cache() - Got exception from S3: {e}") def get_cache(self, key, **kwargs): import botocore @@ -122,9 +120,7 @@ def get_cache(self, key, **kwargs): 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 - ) + cached_response = self.s3_client.get_object(Bucket=self.bucket_name, Key=key) if cached_response is not None: if "Expires" in cached_response: @@ -135,13 +131,9 @@ def get_cache(self, key, **kwargs): return None # cached_response is in `b{} convert it to ModelResponse - cached_response = ( - cached_response["Body"].read().decode("utf-8") - ) # Convert bytes to string + cached_response = cached_response["Body"].read().decode("utf-8") # Convert bytes to string try: - cached_response = json.loads( - cached_response - ) # Convert string to dictionary + 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): @@ -153,15 +145,11 @@ def get_cache(self, key, **kwargs): 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." - ) + 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}" - ) + verbose_logger.error(f"S3 Caching: get_cache() - Got exception from S3: {e}") async def async_get_cache(self, key, **kwargs): """ @@ -175,9 +163,7 @@ async def async_get_cache(self, 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}" - ) + verbose_logger.error(f"S3 Caching: async_get_cache() - Got exception from S3: {e}") return None def flush_cache(self): diff --git a/litellm/caching/valkey_semantic_cache.py b/litellm/caching/valkey_semantic_cache.py index bf368b74d076..746e91207d8f 100644 --- a/litellm/caching/valkey_semantic_cache.py +++ b/litellm/caching/valkey_semantic_cache.py @@ -84,31 +84,21 @@ def __init__( resolved_url = None if sync_client is None or async_client is None: - resolved_url = redis_url or self._build_valkey_url( - host, port, password, ssl - ) + resolved_url = redis_url or self._build_valkey_url(host, port, password, ssl) self.sync_client = ( sync_client if sync_client is not None else Redis.from_url(resolved_url) # type: ignore[arg-type] ) self.async_client = ( - async_client - if async_client is not None - else AsyncRedis.from_url(resolved_url) # type: ignore[arg-type] + async_client if async_client is not None else AsyncRedis.from_url(resolved_url) # type: ignore[arg-type] ) print_verbose(f"Valkey semantic-cache initializing index - {self.index_name}") @staticmethod - def _build_valkey_url( - host: str | None, port: str | None, password: str | None, ssl: bool = False - ) -> str: + def _build_valkey_url(host: str | None, port: str | None, password: str | None, ssl: bool = False) -> str: host = host or os.environ.get("VALKEY_HOST") or os.environ.get("REDIS_HOST") port = port or os.environ.get("VALKEY_PORT") or os.environ.get("REDIS_PORT") - password = ( - password - or os.environ.get("VALKEY_PASSWORD") - or os.environ.get("REDIS_PASSWORD") - ) + password = password or os.environ.get("VALKEY_PASSWORD") or os.environ.get("REDIS_PASSWORD") if not host or not port: raise ValueError( @@ -157,11 +147,7 @@ def _extract_index_dim(info: dict) -> int | None: for field in info.get("attributes") or []: if not isinstance(field, (list, tuple)): continue - flat = [ - sub - for item in field - for sub in (item if isinstance(item, (list, tuple)) else [item]) - ] + flat = [sub for item in field for sub in (item if isinstance(item, (list, tuple)) else [item])] for i, marker in enumerate(flat): if marker in (b"dimensions", "dimensions") and i + 1 < len(flat): return int(flat[i + 1]) @@ -207,9 +193,7 @@ async def _ensure_index_async(self, dim: int) -> None: def _doc_key(self, key: str) -> str: return f"{self.key_prefix}{self._scope_tag(key)}:{uuid.uuid4()}" - def _doc_mapping( - self, key: str, prompt: str, value_str: str, embedding: list[float] - ) -> dict: + def _doc_mapping(self, key: str, prompt: str, value_str: str, embedding: list[float]) -> dict: return { self.CACHE_KEY_FIELD_NAME: self._scope_tag(key), self.PROMPT_FIELD_NAME: prompt, @@ -223,11 +207,7 @@ def _knn_query(self, key: str) -> Query: f"(@{self.CACHE_KEY_FIELD_NAME}:{{{scope}}})" f"=>[KNN 1 @{self.EMBEDDING_FIELD_NAME} $vec AS {self.DISTANCE_FIELD_NAME}]" ) - return ( - Query(query_string) - .return_fields(self.RESPONSE_FIELD_NAME, self.DISTANCE_FIELD_NAME) - .dialect(2) - ) + return Query(query_string).return_fields(self.RESPONSE_FIELD_NAME, self.DISTANCE_FIELD_NAME).dialect(2) @classmethod def _first_hit(cls, search_result: Any) -> _ValkeyCacheHit | None: @@ -264,9 +244,7 @@ def set_cache(self, key: str, value: Any, **kwargs: Any) -> None: self._ensure_index_sync(len(embedding)) doc_key = self._doc_key(key) - self.sync_client.hset( - doc_key, mapping=self._doc_mapping(key, prompt, str(value), embedding) - ) + self.sync_client.hset(doc_key, mapping=self._doc_mapping(key, prompt, str(value), embedding)) ttl = self._get_ttl(**kwargs) if ttl is not None: self.sync_client.expire(doc_key, ttl) @@ -305,9 +283,7 @@ async def async_set_cache(self, key: str, value: Any, **kwargs: Any) -> None: await self._ensure_index_async(len(embedding)) doc_key = self._doc_key(key) - await self.async_client.hset( - doc_key, mapping=self._doc_mapping(key, prompt, str(value), embedding) - ) + await self.async_client.hset(doc_key, mapping=self._doc_mapping(key, prompt, str(value), embedding)) ttl = self._get_ttl(**kwargs) if ttl is not None: await self.async_client.expire(doc_key, ttl) @@ -334,20 +310,11 @@ async def async_get_cache(self, key: str, **kwargs: Any) -> Any: print_verbose(f"Error in async Valkey semantic-cache get_cache: {str(e)}") kwargs.setdefault("metadata", {})["semantic-similarity"] = 0.0 - async def async_set_cache_pipeline( - self, cache_list: list[tuple[str, Any]], **kwargs: Any - ) -> None: + async def async_set_cache_pipeline(self, cache_list: list[tuple[str, Any]], **kwargs: Any) -> None: try: - await asyncio.gather( - *[ - self.async_set_cache(key, value, **kwargs) - for key, value in cache_list - ] - ) + await asyncio.gather(*[self.async_set_cache(key, value, **kwargs) for key, value in cache_list]) except Exception as e: - print_verbose( - f"Error in Valkey semantic-cache async_set_cache_pipeline: {str(e)}" - ) + print_verbose(f"Error in Valkey semantic-cache async_set_cache_pipeline: {str(e)}") async def _index_info(self) -> dict: return await self.async_client.ft(self.index_name).info() diff --git a/litellm/completion_extras/litellm_responses_transformation/handler.py b/litellm/completion_extras/litellm_responses_transformation/handler.py index 87ac5d132d7e..8f12d8558808 100644 --- a/litellm/completion_extras/litellm_responses_transformation/handler.py +++ b/litellm/completion_extras/litellm_responses_transformation/handler.py @@ -41,10 +41,7 @@ def _resolve_stream_flag(optional_params: dict, litellm_params: dict) -> bool: def _is_preformatted_cached_chat_stream(result: Any) -> bool: from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper - return ( - isinstance(result, CustomStreamWrapper) - and result.custom_llm_provider == "cached_response" - ) + return isinstance(result, CustomStreamWrapper) and result.custom_llm_provider == "cached_response" @staticmethod def _coerce_response_object( @@ -85,9 +82,7 @@ def _collect_response_from_stream(self, stream_iter: Any) -> "ResponsesAPIRespon raise ValueError("Stream completed response is invalid") return response - async def _collect_response_from_stream_async( - self, stream_iter: Any - ) -> "ResponsesAPIResponse": + async def _collect_response_from_stream_async(self, stream_iter: Any) -> "ResponsesAPIResponse": async for _ in stream_iter: pass @@ -102,9 +97,7 @@ async def _collect_response_from_stream_async( raise ValueError("Stream completed response is invalid") return response - def validate_input_kwargs( - self, kwargs: dict - ) -> ResponsesToCompletionBridgeHandlerInputKwargs: + def validate_input_kwargs(self, kwargs: dict) -> ResponsesToCompletionBridgeHandlerInputKwargs: from litellm import LiteLLMLoggingObj from litellm.types.utils import ModelResponse @@ -234,9 +227,7 @@ def completion( ) else: if self._is_preformatted_cached_chat_stream(result): - return self._apply_post_stream_processing( - result, model, custom_llm_provider - ) + return self._apply_post_stream_processing(result, model, custom_llm_provider) completion_stream = self.transformation_handler.get_model_response_iterator( streaming_response=result, # type: ignore sync_stream=True, @@ -248,13 +239,9 @@ def completion( custom_llm_provider=custom_llm_provider, logging_obj=logging_obj, ) - return self._apply_post_stream_processing( - streamwrapper, model, custom_llm_provider - ) + return self._apply_post_stream_processing(streamwrapper, model, custom_llm_provider) - async def acompletion( - self, *args, **kwargs - ) -> Union["ModelResponse", "CustomStreamWrapper"]: + async def acompletion(self, *args, **kwargs) -> Union["ModelResponse", "CustomStreamWrapper"]: from litellm import aresponses from litellm.litellm_core_utils.streaming_handler import CustomStreamWrapper @@ -314,9 +301,7 @@ async def acompletion( elif isinstance(result, ModelResponse): return result elif not stream: - responses_api_response = await self._collect_response_from_stream_async( - result - ) + responses_api_response = await self._collect_response_from_stream_async(result) return self.transformation_handler.transform_response( model=model, raw_response=responses_api_response, @@ -332,9 +317,7 @@ async def acompletion( ) else: if self._is_preformatted_cached_chat_stream(result): - return self._apply_post_stream_processing( - result, model, custom_llm_provider - ) + return self._apply_post_stream_processing(result, model, custom_llm_provider) completion_stream = self.transformation_handler.get_model_response_iterator( streaming_response=result, # type: ignore sync_stream=False, @@ -346,9 +329,7 @@ async def acompletion( custom_llm_provider=custom_llm_provider, logging_obj=logging_obj, ) - return self._apply_post_stream_processing( - streamwrapper, model, custom_llm_provider - ) + return self._apply_post_stream_processing(streamwrapper, model, custom_llm_provider) @staticmethod def _apply_post_stream_processing( diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py index f7ac67927b65..aecb2552b530 100644 --- a/litellm/completion_extras/litellm_responses_transformation/transformation.py +++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py @@ -83,9 +83,7 @@ def _build_reasoning_item( summary: List[Dict[str, Any]] = [] for s in summary_raw or []: if isinstance(s, dict): - summary.append( - {"type": s.get("type", "summary_text"), "text": s.get("text", "")} - ) + summary.append({"type": s.get("type", "summary_text"), "text": s.get("text", "")}) else: summary.append( { @@ -138,9 +136,7 @@ def _normalize_tool_choice_for_responses_api(self, tool_choice: Any) -> Any: return {"type": "function", "name": fn_name} return tool_choice - def _handle_raw_dict_response_item( - self, item: Dict[str, Any], index: int - ) -> Tuple[Optional[Any], int]: + def _handle_raw_dict_response_item(self, item: Dict[str, Any], index: int) -> Tuple[Optional[Any], int]: """ Handle raw dict response items from Responses API (e.g., GPT-5 Codex format). @@ -183,13 +179,9 @@ def _handle_raw_dict_response_item( if item_type == "function_call": # Extract provider_specific_fields if present and pass through as-is provider_specific_fields = item.get("provider_specific_fields") - if provider_specific_fields and not isinstance( - provider_specific_fields, dict - ): + if provider_specific_fields and not isinstance(provider_specific_fields, dict): provider_specific_fields = ( - dict(provider_specific_fields) - if hasattr(provider_specific_fields, "__dict__") - else {} + dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {} ) tool_call_dict = { @@ -205,9 +197,7 @@ def _handle_raw_dict_response_item( if provider_specific_fields: tool_call_dict["provider_specific_fields"] = provider_specific_fields # Also add to function's provider_specific_fields for consistency - tool_call_dict["function"]["provider_specific_fields"] = ( - provider_specific_fields - ) + tool_call_dict["function"]["provider_specific_fields"] = provider_specific_fields msg = Message( content=None, @@ -301,9 +291,7 @@ def convert_chat_completion_messages_to_responses_api( { "type": "message", "role": role, - "content": self._convert_content_to_responses_format( - content, cast(str, role) - ), # type: ignore[arg-type] + "content": self._convert_content_to_responses_format(content, cast(str, role)), # type: ignore[arg-type] } ) @@ -321,10 +309,8 @@ def _map_optional_params_to_responses_api_request( if key in ("max_tokens", "max_completion_tokens"): responses_api_request["max_output_tokens"] = value elif key == "tools" and value is not None: - responses_api_request["tools"] = ( - self._convert_tools_to_responses_format( - cast(List[Dict[str, Any]], value) - ) + responses_api_request["tools"] = self._convert_tools_to_responses_format( + cast(List[Dict[str, Any]], value) ) elif key == "response_format": text_format = self._transform_response_format_to_text_format(value) @@ -345,13 +331,9 @@ def _map_optional_params_to_responses_api_request( def _build_sanitized_litellm_params(self, litellm_params: dict) -> Dict[str, Any]: """Build sanitized litellm_params with merged metadata.""" - responses_optional_param_keys = set( - ResponsesAPIOptionalRequestParams.__annotations__.keys() - ) + responses_optional_param_keys = set(ResponsesAPIOptionalRequestParams.__annotations__.keys()) sanitized: Dict[str, Any] = { - key: value - for key, value in litellm_params.items() - if key not in responses_optional_param_keys + key: value for key, value in litellm_params.items() if key not in responses_optional_param_keys } legacy_metadata = litellm_params.get("metadata") existing_litellm_metadata = litellm_params.get("litellm_metadata") @@ -427,9 +409,7 @@ def transform_request( if instructions: responses_api_request["instructions"] = instructions - self._map_optional_params_to_responses_api_request( - optional_params, responses_api_request - ) + self._map_optional_params_to_responses_api_request(optional_params, responses_api_request) stream = optional_params.get("stream") or litellm_params.get("stream", False) verbose_logger.debug(f"Chat provider: Stream parameter: {stream}") @@ -442,9 +422,7 @@ def transform_request( previous_response_id = optional_params.get("previous_response_id") if previous_response_id: # Use the existing session handler for responses API - verbose_logger.debug( - f"Chat provider: Warning ignoring previous response ID: {previous_response_id}" - ) + verbose_logger.debug(f"Chat provider: Warning ignoring previous response ID: {previous_response_id}") # Convert back to responses API format for the actual request @@ -464,13 +442,9 @@ def transform_request( "client": client, } - verbose_logger.debug( - f"Chat provider: Final request model={api_model}, input_items={len(input_items)}" - ) + verbose_logger.debug(f"Chat provider: Final request model={api_model}, input_items={len(input_items)}") - self._merge_responses_api_request_into_request_data( - request_data, responses_api_request, instructions - ) + self._merge_responses_api_request_into_request_data(request_data, responses_api_request, instructions) if headers: request_data["extra_headers"] = headers @@ -524,11 +498,7 @@ def _convert_response_output_to_choices( encrypted_content=getattr(item, "encrypted_content", None), summary_raw=item.summary, ) - reasoning_content = " ".join( - s["text"] - for s in pending_reasoning_item["summary"] - if s.get("text") - ) + reasoning_content = " ".join(s["text"] for s in pending_reasoning_item["summary"] if s.get("text")) elif isinstance(item, ResponseOutputMessage): for content in item.content: @@ -545,11 +515,7 @@ def _convert_response_output_to_choices( annotations=annotations, reasoning_items=cast( Optional[List[ChatCompletionReasoningItem]], - ( - [pending_reasoning_item] - if pending_reasoning_item is not None - else None - ), + ([pending_reasoning_item] if pending_reasoning_item is not None else None), ), ) @@ -570,23 +536,25 @@ def _convert_response_output_to_choices( LiteLLMCompletionResponsesConfig, ) - tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( - tool_call_item=item, - index=tool_call_index, + tool_call_dict = ( + LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( + tool_call_item=item, + index=tool_call_index, + ) ) accumulated_tool_calls.append(tool_call_dict) tool_call_index += 1 - elif ResponseApplyPatchToolCall is not None and isinstance( - item, ResponseApplyPatchToolCall - ): + elif ResponseApplyPatchToolCall is not None and isinstance(item, ResponseApplyPatchToolCall): from litellm.responses.litellm_completion_transformation.transformation import ( LiteLLMCompletionResponsesConfig, ) - tool_call_dict = LiteLLMCompletionResponsesConfig.convert_apply_patch_tool_call_to_chat_completion_tool_call( - tool_call_item=item, - index=tool_call_index, + tool_call_dict = ( + LiteLLMCompletionResponsesConfig.convert_apply_patch_tool_call_to_chat_completion_tool_call( + tool_call_item=item, + index=tool_call_index, + ) ) accumulated_tool_calls.append(tool_call_dict) tool_call_index += 1 @@ -607,25 +575,17 @@ def _convert_response_output_to_choices( reasoning_content=reasoning_content, reasoning_items=cast( Optional[List[ChatCompletionReasoningItem]], - ( - [pending_reasoning_item] - if pending_reasoning_item is not None - else None - ), + ([pending_reasoning_item] if pending_reasoning_item is not None else None), ), ) - choices.append( - Choices(message=msg, finish_reason="tool_calls", index=index) - ) + choices.append(Choices(message=msg, finish_reason="tool_calls", index=index)) reasoning_content = None pending_reasoning_item = None return choices @classmethod - def _extract_output_from_completed_event( - cls, parsed_chunk: Dict[str, Any] - ) -> Optional[List[Dict[str, Any]]]: + def _extract_output_from_completed_event(cls, parsed_chunk: Dict[str, Any]) -> Optional[List[Dict[str, Any]]]: response_payload = parsed_chunk.get("response") if not isinstance(response_payload, dict): return None @@ -635,9 +595,7 @@ def _extract_output_from_completed_event( return cast(List[Dict[str, Any]], response_output) @classmethod - def _recover_output_items_from_raw_sse( - cls, raw_sse: Optional[str] - ) -> List[Dict[str, Any]]: + def _recover_output_items_from_raw_sse(cls, raw_sse: Optional[str]) -> List[Dict[str, Any]]: if not raw_sse or not isinstance(raw_sse, str): return [] @@ -652,9 +610,7 @@ def _recover_output_items_from_raw_sse( event_type = parsed_chunk.get("type") if event_type == ResponsesAPIStreamEvents.RESPONSE_COMPLETED: - recovered_output = cls._extract_output_from_completed_event( - parsed_chunk - ) + recovered_output = cls._extract_output_from_completed_event(parsed_chunk) if recovered_output is not None: return recovered_output continue @@ -688,9 +644,7 @@ def _recover_output_items_from_raw_sse( return [] @classmethod - def _recover_output_items_from_logging( - cls, logging_obj: "LiteLLMLoggingObj" - ) -> List[Dict[str, Any]]: + def _recover_output_items_from_logging(cls, logging_obj: "LiteLLMLoggingObj") -> List[Dict[str, Any]]: model_call_details = getattr(logging_obj, "model_call_details", {}) or {} original_response = model_call_details.get("original_response") return cls._recover_output_items_from_raw_sse(original_response) @@ -721,9 +675,7 @@ def transform_response( output_items = raw_response.output if len(output_items) == 0: - recovered_output_items = self._recover_output_items_from_logging( - logging_obj - ) + recovered_output_items = self._recover_output_items_from_logging(logging_obj) if recovered_output_items: output_items = cast(Any, recovered_output_items) raw_response.output = cast(Any, recovered_output_items) @@ -739,17 +691,10 @@ def transform_response( ) if len(choices) == 0: - if ( - raw_response.incomplete_details is not None - and raw_response.incomplete_details.reason is not None - ): - raise ValueError( - f"{model} unable to complete request: {raw_response.incomplete_details.reason}" - ) + if raw_response.incomplete_details is not None and raw_response.incomplete_details.reason is not None: + raise ValueError(f"{model} unable to complete request: {raw_response.incomplete_details.reason}") else: - raise ValueError( - f"Unknown items in responses API response: {output_items}" - ) + raise ValueError(f"Unknown items in responses API response: {output_items}") setattr(model_response, "choices", choices) @@ -758,28 +703,21 @@ def transform_response( setattr( model_response, "usage", - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - raw_response.usage - ), + ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(raw_response.usage), ) # Preserve hidden params from the ResponsesAPIResponse, especially the headers # which contain important provider information like x-request-id raw_response_hidden_params = getattr(raw_response, "_hidden_params", {}) if raw_response_hidden_params: - if ( - not hasattr(model_response, "_hidden_params") - or model_response._hidden_params is None - ): + if not hasattr(model_response, "_hidden_params") or model_response._hidden_params is None: model_response._hidden_params = {} # Merge the raw_response hidden params with model_response hidden params # Preserve existing keys in model_response but add/override with raw_response params for key, value in raw_response_hidden_params.items(): if key == "additional_headers" and key in model_response._hidden_params: # Merge additional_headers to preserve both sets - existing_additional_headers = model_response._hidden_params.get( - "additional_headers", {} - ) + existing_additional_headers = model_response._hidden_params.get("additional_headers", {}) merged_headers = {**value, **existing_additional_headers} model_response._hidden_params[key] = merged_headers else: @@ -789,19 +727,13 @@ def transform_response( def get_model_response_iterator( self, - streaming_response: Union[ - Iterator[str], AsyncIterator[str], "ModelResponse", "BaseModel" - ], + streaming_response: Union[Iterator[str], AsyncIterator[str], "ModelResponse", "BaseModel"], sync_stream: bool, json_mode: Optional[bool] = False, ) -> BaseModelResponseIterator: - return OpenAiResponsesToChatCompletionStreamIterator( - streaming_response, sync_stream, json_mode - ) + return OpenAiResponsesToChatCompletionStreamIterator(streaming_response, sync_stream, json_mode) - def _convert_content_str_to_input_text( - self, content: str, role: str - ) -> Dict[str, Any]: + def _convert_content_str_to_input_text(self, content: str, role: str) -> Dict[str, Any]: if role == "user" or role == "system" or role == "tool": return {"type": "input_text", "text": content} else: @@ -828,9 +760,7 @@ def _convert_content_to_responses_format_image( if actual_image_url is None: raise ValueError(f"Invalid image URL: {content_image_url}") - image_param = ResponseInputImageParam( - image_url=actual_image_url, detail="auto", type="input_image" - ) + image_param = ResponseInputImageParam(image_url=actual_image_url, detail="auto", type="input_image") if detail: image_param["detail"] = detail @@ -857,9 +787,7 @@ def _convert_content_to_responses_format( """Convert chat completion content to responses API format""" from litellm.types.llms.openai import ChatCompletionImageObject - verbose_logger.debug( - f"Chat provider: Converting content to responses format - input type: {type(content)}" - ) + verbose_logger.debug(f"Chat provider: Converting content to responses format - input type: {type(content)}") if content is None: return [self._convert_content_str_to_input_text("", role)] @@ -870,9 +798,7 @@ def _convert_content_to_responses_format( elif isinstance(content, list): result = [] for i, item in enumerate(content): - verbose_logger.debug( - f"Chat provider: Processing content item {i}: {type(item)} = {item}" - ) + verbose_logger.debug(f"Chat provider: Processing content item {i}: {type(item)} = {item}") if isinstance(item, str): converted = self._convert_content_str_to_input_text(item, role) result.append(converted) @@ -881,9 +807,7 @@ def _convert_content_to_responses_format( # Handle multimodal content original_type = item.get("type") if original_type == "text": - converted = self._convert_content_str_to_input_text( - item.get("text", ""), role - ) + converted = self._convert_content_str_to_input_text(item.get("text", ""), role) result.append(converted) verbose_logger.debug(f"Chat provider: text -> {converted}") elif original_type == "image_url": @@ -895,18 +819,14 @@ def _convert_content_to_responses_format( ), ) result.append(converted) - verbose_logger.debug( - f"Chat provider: image_url -> {converted}" - ) + verbose_logger.debug(f"Chat provider: image_url -> {converted}") else: # Try to map other types to responses API format item_type = original_type or "input_text" if item_type == "image": converted = {"type": "input_image", **item} result.append(converted) - verbose_logger.debug( - f"Chat provider: image -> {converted}" - ) + verbose_logger.debug(f"Chat provider: image -> {converted}") elif item_type == "file": # Map Chat Completion file to Responses API input_file # {"type": "file", "file": {"file_data": "...", "filename": "..."}} @@ -918,9 +838,7 @@ def _convert_content_to_responses_format( if key in file_data: converted[key] = file_data[key] result.append(converted) - verbose_logger.debug( - f"Chat provider: file -> {converted}" - ) + verbose_logger.debug(f"Chat provider: file -> {converted}") elif item_type in [ "input_text", "input_image", @@ -932,18 +850,12 @@ def _convert_content_to_responses_format( ]: # Already in responses API format result.append(item) - verbose_logger.debug( - f"Chat provider: passthrough -> {item}" - ) + verbose_logger.debug(f"Chat provider: passthrough -> {item}") else: # Default to input_text for unknown types - converted = self._convert_content_str_to_input_text( - str(item.get("text", item)), role - ) + converted = self._convert_content_str_to_input_text(str(item.get("text", item)), role) result.append(converted) - verbose_logger.debug( - f"Chat provider: unknown({original_type}) -> {converted}" - ) + verbose_logger.debug(f"Chat provider: unknown({original_type}) -> {converted}") verbose_logger.debug(f"Chat provider: Final converted content: {result}") return result else: @@ -951,17 +863,13 @@ def _convert_content_to_responses_format( verbose_logger.debug(f"Chat provider: Other content type -> {result}") return result - def _convert_tools_to_responses_format( - self, tools: List[Dict[str, Any]] - ) -> List["ALL_RESPONSES_API_TOOL_PARAMS"]: + def _convert_tools_to_responses_format(self, tools: List[Dict[str, Any]]) -> List["ALL_RESPONSES_API_TOOL_PARAMS"]: """Convert chat completion tools to responses API tools format""" responses_tools: List["ALL_RESPONSES_API_TOOL_PARAMS"] = [] for tool in tools: # convert function tool from chat completion to responses API format if tool.get("type") == "function": - function_tool = cast( - ChatCompletionToolParamFunctionChunk, tool.get("function") - ) + function_tool = cast(ChatCompletionToolParamFunctionChunk, tool.get("function")) responses_tools.append( FunctionToolParam( name=function_tool["name"], @@ -987,9 +895,7 @@ def _extract_extra_body_params(self, optional_params: dict): if not extra_body: return optional_params - supported_responses_api_params = set( - ResponsesAPIOptionalRequestParams.__annotations__.keys() - ) + supported_responses_api_params = set(ResponsesAPIOptionalRequestParams.__annotations__.keys()) # Also include params we handle specially supported_responses_api_params.update( { @@ -1007,9 +913,7 @@ def _extract_extra_body_params(self, optional_params: dict): return optional_params - def _map_reasoning_effort( - self, reasoning_effort: Union[str, Dict[str, Any]] - ) -> Optional[Reasoning]: + def _map_reasoning_effort(self, reasoning_effort: Union[str, Dict[str, Any]]) -> Optional[Reasoning]: # If dict is passed, convert it directly to Reasoning object if isinstance(reasoning_effort, dict): return Reasoning(**reasoning_effort) # type: ignore[typeddict-item] @@ -1017,46 +921,25 @@ def _map_reasoning_effort( # Check if auto-summary is enabled via flag or environment variable # Priority: litellm.reasoning_auto_summary flag > LITELLM_REASONING_AUTO_SUMMARY env var auto_summary_enabled = ( - litellm.reasoning_auto_summary - or os.getenv("LITELLM_REASONING_AUTO_SUMMARY", "false").lower() == "true" + litellm.reasoning_auto_summary or os.getenv("LITELLM_REASONING_AUTO_SUMMARY", "false").lower() == "true" ) # If string is passed, map with optional summary based on flag/env var if reasoning_effort == "none": - return ( - Reasoning(effort="none", summary="detailed") - if auto_summary_enabled - else Reasoning(effort="none") - ) # type: ignore + return Reasoning(effort="none", summary="detailed") if auto_summary_enabled else Reasoning(effort="none") # type: ignore elif reasoning_effort == "high": - return ( - Reasoning(effort="high", summary="detailed") - if auto_summary_enabled - else Reasoning(effort="high") - ) + return Reasoning(effort="high", summary="detailed") if auto_summary_enabled else Reasoning(effort="high") elif reasoning_effort == "xhigh": - return ( - Reasoning(effort="xhigh", summary="detailed") - if auto_summary_enabled - else Reasoning(effort="xhigh") - ) # type: ignore[typeddict-item] + return Reasoning(effort="xhigh", summary="detailed") if auto_summary_enabled else Reasoning(effort="xhigh") # type: ignore[typeddict-item] elif reasoning_effort == "medium": return ( - Reasoning(effort="medium", summary="detailed") - if auto_summary_enabled - else Reasoning(effort="medium") + Reasoning(effort="medium", summary="detailed") if auto_summary_enabled else Reasoning(effort="medium") ) elif reasoning_effort == "low": - return ( - Reasoning(effort="low", summary="detailed") - if auto_summary_enabled - else Reasoning(effort="low") - ) + return Reasoning(effort="low", summary="detailed") if auto_summary_enabled else Reasoning(effort="low") elif reasoning_effort == "minimal": return ( - Reasoning(effort="minimal", summary="detailed") - if auto_summary_enabled - else Reasoning(effort="minimal") + Reasoning(effort="minimal", summary="detailed") if auto_summary_enabled else Reasoning(effort="minimal") ) return None @@ -1072,10 +955,7 @@ def _add_web_search_tool( responses_api_request: The responses API request dict to modify web_search_options: Web search configuration (dict or other value) """ - if ( - "tools" not in responses_api_request - or responses_api_request["tools"] is None - ): + if "tools" not in responses_api_request or responses_api_request["tools"] is None: responses_api_request["tools"] = [] # Get the tools list with proper type narrowing @@ -1165,17 +1045,13 @@ def _convert_annotations_to_chat_format( annotation_dict = annotation else: # Skip unsupported annotation types - verbose_logger.debug( - f"Skipping unsupported annotation type: {type(annotation)}" - ) + verbose_logger.debug(f"Skipping unsupported annotation type: {type(annotation)}") continue result.append(annotation_dict) # type: ignore except Exception as e: # Skip malformed annotations - verbose_logger.debug( - f"Skipping malformed annotation: {annotation}, error: {e}" - ) + verbose_logger.debug(f"Skipping malformed annotation: {annotation}, error: {e}") continue return result if result else None @@ -1196,9 +1072,7 @@ def _map_responses_status_to_finish_reason(self, status: Optional[str]) -> str: class OpenAiResponsesToChatCompletionStreamIterator(BaseModelResponseIterator): - def __init__( - self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False - ): + def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False): super().__init__(streaming_response, sync_stream, json_mode) def _handle_string_chunk( @@ -1211,9 +1085,7 @@ def _handle_string_chunk( if not str_line or str_line.startswith("event:"): # ignore. - return GenericStreamingChunk( - text="", tool_use=None, is_finished=False, finish_reason="", usage=None - ) + return GenericStreamingChunk(text="", tool_use=None, is_finished=False, finish_reason="", usage=None) index = str_line.find("data:") if index != -1: str_line = str_line[index + 5 :] @@ -1258,9 +1130,7 @@ def translate_responses_chunk_to_openai_stream( event_type = event_type.value if parsed_chunk.get("object") == "chat.completion.chunk" or ( - event_type is None - and isinstance(parsed_chunk.get("choices"), list) - and parsed_chunk.get("choices") + event_type is None and isinstance(parsed_chunk.get("choices"), list) and parsed_chunk.get("choices") ): return ModelResponseStream(**parsed_chunk) @@ -1284,13 +1154,9 @@ def translate_responses_chunk_to_openai_stream( if output_item.get("type") == "function_call": # Extract provider_specific_fields if present provider_specific_fields = output_item.get("provider_specific_fields") - if provider_specific_fields and not isinstance( - provider_specific_fields, dict - ): + if provider_specific_fields and not isinstance(provider_specific_fields, dict): provider_specific_fields = ( - dict(provider_specific_fields) - if hasattr(provider_specific_fields, "__dict__") - else {} + dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {} ) function_chunk = ChatCompletionToolCallFunctionChunk( @@ -1299,9 +1165,7 @@ def translate_responses_chunk_to_openai_stream( ) if provider_specific_fields: - function_chunk["provider_specific_fields"] = ( - provider_specific_fields - ) + function_chunk["provider_specific_fields"] = provider_specific_fields from litellm.responses.litellm_completion_transformation.transformation import ( LiteLLMCompletionResponsesConfig, @@ -1344,9 +1208,7 @@ def translate_responses_chunk_to_openai_stream( id=None, index=tool_call_index, type="function", - function=ChatCompletionToolCallFunctionChunk( - name=None, arguments=content_part - ), + function=ChatCompletionToolCallFunctionChunk(name=None, arguments=content_part), ) ] ), @@ -1355,22 +1217,16 @@ def translate_responses_chunk_to_openai_stream( ] ) else: - raise ValueError( - f"Chat provider: Invalid function argument delta {parsed_chunk}" - ) + raise ValueError(f"Chat provider: Invalid function argument delta {parsed_chunk}") elif event_type == ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE: # New output item added output_item = parsed_chunk.get("item", {}) if output_item.get("type") == "function_call": # Extract provider_specific_fields if present provider_specific_fields = output_item.get("provider_specific_fields") - if provider_specific_fields and not isinstance( - provider_specific_fields, dict - ): + if provider_specific_fields and not isinstance(provider_specific_fields, dict): provider_specific_fields = ( - dict(provider_specific_fields) - if hasattr(provider_specific_fields, "__dict__") - else {} + dict(provider_specific_fields) if hasattr(provider_specific_fields, "__dict__") else {} ) function_chunk = ChatCompletionToolCallFunctionChunk( @@ -1380,9 +1236,7 @@ def translate_responses_chunk_to_openai_stream( # Add provider_specific_fields to function if present if provider_specific_fields: - function_chunk["provider_specific_fields"] = ( - provider_specific_fields - ) + function_chunk["provider_specific_fields"] = provider_specific_fields tool_call_index = parsed_chunk.get("output_index", 0) tool_call_chunk = ChatCompletionToolCallChunk( @@ -1458,9 +1312,7 @@ def translate_responses_chunk_to_openai_stream( output_items = response_data.get("output", []) if response_data else [] has_function_calls = any( - item.get("type") == "function_call" - for item in output_items - if isinstance(item, dict) + item.get("type") == "function_call" for item in output_items if isinstance(item, dict) ) finish_reason = "tool_calls" if has_function_calls else "stop" @@ -1488,11 +1340,7 @@ def translate_responses_chunk_to_openai_stream( if response_data.get("usage"): from litellm.responses.utils import ResponseAPILoggingUtils - usage = ( - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - response_data.get("usage") - ) - ) + usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(response_data.get("usage")) return ModelResponseStream( choices=[ StreamingChoices( @@ -1509,9 +1357,7 @@ def translate_responses_chunk_to_openai_stream( else: pass # For any unhandled event types, create a minimal valid chunk or skip - verbose_logger.debug( - f"Chat provider: Unhandled event type '{event_type}', creating empty chunk" - ) + verbose_logger.debug(f"Chat provider: Unhandled event type '{event_type}', creating empty chunk") # Return a minimal valid chunk for unknown events return ModelResponseStream( @@ -1534,9 +1380,5 @@ def chunk_parser(self, chunk: dict) -> "ModelResponseStream": Returns: ModelResponseStream: OpenAI-formatted streaming chunk """ - verbose_logger.debug( - f"Chat provider: transform_streaming_response called with chunk: {chunk}" - ) - return OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream( - chunk - ) + verbose_logger.debug(f"Chat provider: transform_streaming_response called with chunk: {chunk}") + return OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(chunk) diff --git a/litellm/compression/compress.py b/litellm/compression/compress.py index 45795c9ca15d..004dd82cbaa0 100644 --- a/litellm/compression/compress.py +++ b/litellm/compression/compress.py @@ -107,8 +107,7 @@ def _normalize_messages_for_compression( """ 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)}." + f"Unsupported call_type={call_type!r} for compression. Expected one of: {sorted(_SUPPORTED_CALL_TYPES)}." ) original_messages: List[Dict[str, Any]] = [dict(m) for m in messages] @@ -334,9 +333,7 @@ def _select_kept_indices_for_budget( return kept_indices, truncated_overrides -def _get_dropped_tool_span_indices( - kept_indices: Set[int], tool_exchange_spans: List[Set[int]] -) -> Set[int]: +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): @@ -440,9 +437,7 @@ def compress( 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) - ) + 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, @@ -484,9 +479,7 @@ def compress( # 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 - ) + 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)) @@ -503,11 +496,7 @@ def compress( 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 - ), + compression_ratio=(round(1 - (compressed_tokens / original_tokens), 4) if original_tokens > 0 else 0.0), cache=cache, tools=tools, ) diff --git a/litellm/compression/content_detection.py b/litellm/compression/content_detection.py index 975117eb608a..4a072b63f2c4 100644 --- a/litellm/compression/content_detection.py +++ b/litellm/compression/content_detection.py @@ -33,9 +33,7 @@ def detect_content_type(content: str) -> str: 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() - ) + 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): diff --git a/litellm/compression/message_stubbing.py b/litellm/compression/message_stubbing.py index 2330f1bbc9ef..8d4e65752c1e 100644 --- a/litellm/compression/message_stubbing.py +++ b/litellm/compression/message_stubbing.py @@ -26,9 +26,7 @@ def extract_key(message: dict, fallback_index: int, used_keys: Set[str]) -> str: """ content = message.get("content", "") if isinstance(content, list): - content = " ".join( - p.get("text", "") if isinstance(p, dict) else str(p) for p in content - ) + content = " ".join(p.get("text", "") if isinstance(p, dict) else str(p) for p in content) key = None for pattern in _FILE_PATH_PATTERNS: @@ -62,9 +60,7 @@ def stub_message(message: dict, key: str) -> dict: """ content = message.get("content", "") if isinstance(content, list): - content = " ".join( - p.get("text", "") if isinstance(p, dict) else str(p) for p in content - ) + 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) @@ -91,9 +87,7 @@ def truncate_message(message: dict, max_tokens: int) -> dict: """ content = message.get("content", "") if isinstance(content, list): - content = " ".join( - p.get("text", "") if isinstance(p, dict) else str(p) for p in content - ) + 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) @@ -113,8 +107,6 @@ def truncate_message(message: dict, max_tokens: int) -> dict: 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:]) + "\n".join(lines[:first_count]) + "\n...[truncated for context window]...\n" + "\n".join(lines[-last_count:]) ) return {**message, "content": truncated} diff --git a/litellm/compression/retrieval_tool.py b/litellm/compression/retrieval_tool.py index 1ee24784a637..99431a2a15de 100644 --- a/litellm/compression/retrieval_tool.py +++ b/litellm/compression/retrieval_tool.py @@ -17,8 +17,7 @@ def build_retrieval_tool(available_keys: List[str]) -> dict: "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) + "content to answer accurately. Available keys: " + ", ".join(available_keys) ), "parameters": { "type": "object", diff --git a/litellm/compression/scoring/bm25.py b/litellm/compression/scoring/bm25.py index e8e1bf631eba..7f919ef16fb9 100644 --- a/litellm/compression/scoring/bm25.py +++ b/litellm/compression/scoring/bm25.py @@ -91,11 +91,7 @@ def _expand_tf(query_term: str, tf_counts: Counter) -> int: # type: ignore[type return exact if len(query_term) < 4: return 0 - return sum( - count - for token, count in tf_counts.items() - if token != query_term and token.startswith(query_term) - ) + return sum(count for token, count in tf_counts.items() if token != query_term and token.startswith(query_term)) # Score each document scores: List[float] = [] diff --git a/litellm/constants.py b/litellm/constants.py index d137c6397782..aeb74a658390 100644 --- a/litellm/constants.py +++ b/litellm/constants.py @@ -4,28 +4,16 @@ from litellm.litellm_core_utils.env_utils import get_env_int -DEFAULT_HEALTH_CHECK_PROMPT = str( - os.getenv("DEFAULT_HEALTH_CHECK_PROMPT", "test from litellm") -) -AZURE_DEFAULT_RESPONSES_API_VERSION = str( - os.getenv("AZURE_DEFAULT_RESPONSES_API_VERSION", "preview") -) +DEFAULT_HEALTH_CHECK_PROMPT = str(os.getenv("DEFAULT_HEALTH_CHECK_PROMPT", "test from litellm")) +AZURE_DEFAULT_RESPONSES_API_VERSION = str(os.getenv("AZURE_DEFAULT_RESPONSES_API_VERSION", "preview")) ROUTER_MAX_FALLBACKS = int(os.getenv("ROUTER_MAX_FALLBACKS", 5)) DEFAULT_BATCH_SIZE = int(os.getenv("DEFAULT_BATCH_SIZE", 512)) DEFAULT_FLUSH_INTERVAL_SECONDS = int(os.getenv("DEFAULT_FLUSH_INTERVAL_SECONDS", 5)) -DEFAULT_S3_FLUSH_INTERVAL_SECONDS = int( - os.getenv("DEFAULT_S3_FLUSH_INTERVAL_SECONDS", 10) -) +DEFAULT_S3_FLUSH_INTERVAL_SECONDS = int(os.getenv("DEFAULT_S3_FLUSH_INTERVAL_SECONDS", 10)) DEFAULT_S3_BATCH_SIZE = int(os.getenv("DEFAULT_S3_BATCH_SIZE", 512)) -DEFAULT_SQS_FLUSH_INTERVAL_SECONDS = int( - os.getenv("DEFAULT_SQS_FLUSH_INTERVAL_SECONDS", 10) -) -DEFAULT_NUM_WORKERS_LITELLM_PROXY = int( - os.getenv("DEFAULT_NUM_WORKERS_LITELLM_PROXY", 1) -) -DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE = int( - os.getenv("DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE", 1) -) +DEFAULT_SQS_FLUSH_INTERVAL_SECONDS = int(os.getenv("DEFAULT_SQS_FLUSH_INTERVAL_SECONDS", 10)) +DEFAULT_NUM_WORKERS_LITELLM_PROXY = int(os.getenv("DEFAULT_NUM_WORKERS_LITELLM_PROXY", 1)) +DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE = int(os.getenv("DYNAMIC_RATE_LIMIT_ERROR_THRESHOLD_PER_MINUTE", 1)) DEFAULT_SQS_BATCH_SIZE = int(os.getenv("DEFAULT_SQS_BATCH_SIZE", 512)) SQS_SEND_MESSAGE_ACTION = "SendMessage" SQS_API_VERSION = "2012-11-05" @@ -34,9 +22,7 @@ # radius: each record fans out to spend logs + every callback integration. MAX_CALLBACK_LOG_RECORDS = 1000 DEFAULT_MAX_RECURSE_DEPTH = int(os.getenv("DEFAULT_MAX_RECURSE_DEPTH", 100)) -DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER = int( - os.getenv("DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER", 10) -) +DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER = int(os.getenv("DEFAULT_MAX_RECURSE_DEPTH_SENSITIVE_DATA_MASKER", 10)) DEFAULT_FAILURE_THRESHOLD_PERCENT = float( os.getenv("DEFAULT_FAILURE_THRESHOLD_PERCENT", 0.5) ) # default cooldown a deployment if 50% of requests fail in a given minute @@ -44,12 +30,8 @@ DEFAULT_ALLOWED_FAILS = int(os.getenv("DEFAULT_ALLOWED_FAILS", 3)) DEFAULT_REDIS_SYNC_INTERVAL = int(os.getenv("DEFAULT_REDIS_SYNC_INTERVAL", 1)) DEFAULT_COOLDOWN_TIME_SECONDS = int(os.getenv("DEFAULT_COOLDOWN_TIME_SECONDS", 5)) -DEFAULT_REPLICATE_POLLING_RETRIES = int( - os.getenv("DEFAULT_REPLICATE_POLLING_RETRIES", 5) -) -DEFAULT_REPLICATE_POLLING_DELAY_SECONDS = int( - os.getenv("DEFAULT_REPLICATE_POLLING_DELAY_SECONDS", 1) -) +DEFAULT_REPLICATE_POLLING_RETRIES = int(os.getenv("DEFAULT_REPLICATE_POLLING_RETRIES", 5)) +DEFAULT_REPLICATE_POLLING_DELAY_SECONDS = int(os.getenv("DEFAULT_REPLICATE_POLLING_DELAY_SECONDS", 1)) DEFAULT_IMAGE_TOKEN_COUNT = int(os.getenv("DEFAULT_IMAGE_TOKEN_COUNT", 250)) # Maximum wall-clock seconds a streaming response is allowed to run. @@ -67,9 +49,7 @@ # When true, adds detailed per-phase timing breakdown headers to responses. # Headers: x-litellm-timing-{pre-processing,llm-api,post-processing,message-copy}-ms -LITELLM_DETAILED_TIMING = ( - os.getenv("LITELLM_DETAILED_TIMING", "false").lower() == "true" -) +LITELLM_DETAILED_TIMING = os.getenv("LITELLM_DETAILED_TIMING", "false").lower() == "true" # Model cost map validation constants MODEL_COST_MAP_MIN_MODEL_COUNT = int( @@ -88,6 +68,10 @@ MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB = int( os.getenv("MAX_SIZE_PER_ITEM_IN_MEMORY_CACHE_IN_KB", 1024) ) # 1MB = 1024KB +# Surrogate-repair fallback in _read_request_body runs two full-body re.sub passes +# that block the event loop on multi-MB malformed bodies. Skip the repair above this +# size and raise the existing 400 immediately. Set to 0 to disable the cap. +MAX_REQUEST_BODY_SIZE_TO_REPAIR_MB = get_env_int("MAX_REQUEST_BODY_SIZE_TO_REPAIR_MB", 1) SINGLE_DEPLOYMENT_TRAFFIC_FAILURE_THRESHOLD = int( os.getenv("SINGLE_DEPLOYMENT_TRAFFIC_FAILURE_THRESHOLD", 1000) ) # Minimum number of requests to consider "reasonable traffic". Used for single-deployment cooldown logic. @@ -95,42 +79,28 @@ os.getenv("DEFAULT_FAILURE_THRESHOLD_MINIMUM_REQUESTS", 5) ) # Minimum number of requests before applying error rate cooldown. Prevents cooldown from triggering on first failure. -DEFAULT_REASONING_EFFORT_DISABLE_THINKING_BUDGET = int( - os.getenv("DEFAULT_REASONING_EFFORT_DISABLE_THINKING_BUDGET", 0) -) +DEFAULT_REASONING_EFFORT_DISABLE_THINKING_BUDGET = int(os.getenv("DEFAULT_REASONING_EFFORT_DISABLE_THINKING_BUDGET", 0)) # MCP Semantic Tool Filter Defaults DEFAULT_MCP_SEMANTIC_FILTER_EMBEDDING_MODEL = str( os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_EMBEDDING_MODEL", "text-embedding-3-small") ) -DEFAULT_MCP_SEMANTIC_FILTER_TOP_K = int( - os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_TOP_K", 10) -) +DEFAULT_MCP_SEMANTIC_FILTER_TOP_K = int(os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_TOP_K", 10)) DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD = float( os.getenv("DEFAULT_MCP_SEMANTIC_FILTER_SIMILARITY_THRESHOLD", 0.3) ) -MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH = int( - os.getenv("MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH", 150) -) +MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH = int(os.getenv("MAX_MCP_SEMANTIC_FILTER_TOOLS_HEADER_LENGTH", 150)) # Semantic Guard Defaults DEFAULT_SEMANTIC_GUARD_EMBEDDING_MODEL = str( os.getenv("DEFAULT_SEMANTIC_GUARD_EMBEDDING_MODEL", "text-embedding-3-small") ) -DEFAULT_SEMANTIC_GUARD_SIMILARITY_THRESHOLD = float( - os.getenv("DEFAULT_SEMANTIC_GUARD_SIMILARITY_THRESHOLD", 0.75) -) +DEFAULT_SEMANTIC_GUARD_SIMILARITY_THRESHOLD = float(os.getenv("DEFAULT_SEMANTIC_GUARD_SIMILARITY_THRESHOLD", 0.75)) # MCP OAuth2 Client Credentials Defaults -MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS = int( - os.getenv("MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS", "60") -) -MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE = int( - os.getenv("MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE", "200") -) -MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL = int( - os.getenv("MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL", "3600") -) +MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS = int(os.getenv("MCP_OAUTH2_TOKEN_EXPIRY_BUFFER_SECONDS", "60")) +MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE = int(os.getenv("MCP_OAUTH2_TOKEN_CACHE_MAX_SIZE", "200")) +MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL = int(os.getenv("MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL", "3600")) # Default npm cache directory for STDIO MCP servers. # npm/npx needs a writable cache dir; in containers the default (~/.npm) @@ -143,9 +113,7 @@ MCP_PER_USER_TOKEN_DEFAULT_TTL = int( os.getenv("MCP_PER_USER_TOKEN_DEFAULT_TTL", "43200") # 12 hours ) -MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS = int( - os.getenv("MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS", "60") -) +MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS = int(os.getenv("MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS", "60")) # MCP timeout defaults (seconds). Override via env vars for slow/custom MCP servers. MCP_CLIENT_TIMEOUT = float(os.getenv("LITELLM_MCP_CLIENT_TIMEOUT", "60.0")) @@ -160,14 +128,11 @@ # Extend via LITELLM_MCP_STDIO_EXTRA_COMMANDS env var (comma-separated). _MCP_STDIO_EXTRA_COMMANDS = os.getenv("LITELLM_MCP_STDIO_EXTRA_COMMANDS", "") MCP_STDIO_ALLOWED_COMMANDS: frozenset = frozenset( - {"npx", "uvx", "python", "python3", "node", "docker", "deno"} - | (set(_MCP_STDIO_EXTRA_COMMANDS.split(",")) - {""}) + {"npx", "uvx", "python", "python3", "node", "docker", "deno"} | (set(_MCP_STDIO_EXTRA_COMMANDS.split(",")) - {""}) ) # MCP OAuth2 Token Exchange (OBO) Defaults -MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE = int( - os.getenv("MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE", "500") -) +MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE = int(os.getenv("MCP_TOKEN_EXCHANGE_CACHE_MAX_SIZE", "500")) LITELLM_UI_ALLOW_HEADERS = [ "x-litellm-semantic-filter", @@ -183,9 +148,7 @@ os.getenv("DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_PRO", 128) ) DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH_LITE = int( - os.getenv( - "DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH_LITE", 512 - ) + os.getenv("DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH_LITE", 512) ) # Maximum number of callbacks that can be registered @@ -217,31 +180,19 @@ OPEN_SANDBOX_READY_TIMEOUT = 30.0 OPEN_SANDBOX_POLL_INTERVAL = 0.2 -DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET = int( - os.getenv("DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET", 1024) -) +DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET = int(os.getenv("DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET", 1024)) DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET = int( os.getenv("DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET", 2048) ) -DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET = int( - os.getenv("DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET", 4096) -) -DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET = int( - os.getenv("DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET", 8192) -) -DEFAULT_REASONING_EFFORT_MAX_THINKING_BUDGET = int( - os.getenv("DEFAULT_REASONING_EFFORT_MAX_THINKING_BUDGET", 16384) -) +DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET = int(os.getenv("DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET", 4096)) +DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET = int(os.getenv("DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET", 8192)) +DEFAULT_REASONING_EFFORT_MAX_THINKING_BUDGET = int(os.getenv("DEFAULT_REASONING_EFFORT_MAX_THINKING_BUDGET", 16384)) MAX_TOKEN_TRIMMING_ATTEMPTS = int( os.getenv("MAX_TOKEN_TRIMMING_ATTEMPTS", 10) ) # Maximum number of attempts to trim the message -RUNWAYML_DEFAULT_API_VERSION = str( - os.getenv("RUNWAYML_DEFAULT_API_VERSION", "2024-11-06") -) -RUNWAYML_POLLING_TIMEOUT = int( - os.getenv("RUNWAYML_POLLING_TIMEOUT", 600) -) # 10 minutes default for image generation +RUNWAYML_DEFAULT_API_VERSION = str(os.getenv("RUNWAYML_DEFAULT_API_VERSION", "2024-11-06")) +RUNWAYML_POLLING_TIMEOUT = int(os.getenv("RUNWAYML_POLLING_TIMEOUT", 600)) # 10 minutes default for image generation ########## Networking constants ############################################################## _DEFAULT_TTL_FOR_HTTPX_CLIENTS = 3600 # 1 hour, re-use the same httpx client for 1 hour @@ -249,9 +200,7 @@ # Aiohttp connection pooling - prevents memory leaks from unbounded connection growth # Set to 0 for unlimited (not recommended for production) AIOHTTP_CONNECTOR_LIMIT = int(os.getenv("AIOHTTP_CONNECTOR_LIMIT", 1000)) -AIOHTTP_CONNECTOR_LIMIT_PER_HOST = int( - os.getenv("AIOHTTP_CONNECTOR_LIMIT_PER_HOST", 500) -) +AIOHTTP_CONNECTOR_LIMIT_PER_HOST = int(os.getenv("AIOHTTP_CONNECTOR_LIMIT_PER_HOST", 500)) AIOHTTP_KEEPALIVE_TIMEOUT = int(os.getenv("AIOHTTP_KEEPALIVE_TIMEOUT", 120)) AIOHTTP_TTL_DNS_CACHE = int(os.getenv("AIOHTTP_TTL_DNS_CACHE", 300)) # TCP keep-alive (SO_KEEPALIVE) — opt-in. Required when running behind NAT/LBs @@ -277,9 +226,7 @@ # Default to None (unlimited) to match OpenAI's official agents SDK behavior # https://github.com/openai/openai-agents-python/blob/cf1b933660e44fd37b4350c41febab8221801409/src/agents/realtime/openai_realtime.py#L235 _max_size_env = os.getenv("REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES") -REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES = ( - int(_max_size_env) if _max_size_env is not None else None -) +REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES = int(_max_size_env) if _max_size_env is not None else None # SSL/TLS cipher configuration for faster handshakes # Strategy: Strongly prefer fast modern ciphers, but allow fallback to commonly supported ones @@ -310,9 +257,7 @@ REDIS_DAILY_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_spend_update_buffer" REDIS_DAILY_TEAM_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_team_spend_update_buffer" REDIS_DAILY_ORG_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_org_spend_update_buffer" -REDIS_DAILY_END_USER_SPEND_UPDATE_BUFFER_KEY = ( - "litellm_daily_end_user_spend_update_buffer" -) +REDIS_DAILY_END_USER_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_end_user_spend_update_buffer" REDIS_DAILY_AGENT_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_agent_spend_update_buffer" REDIS_DAILY_TAG_SPEND_UPDATE_BUFFER_KEY = "litellm_daily_tag_spend_update_buffer" MAX_REDIS_BUFFER_DEQUEUE_COUNT = int(os.getenv("MAX_REDIS_BUFFER_DEQUEUE_COUNT", 100)) @@ -321,12 +266,8 @@ TOOL_POLICY_CACHE_TTL_SECONDS = int(os.getenv("TOOL_POLICY_CACHE_TTL_SECONDS", 60)) # Aggregation threshold: default to 80% of the asyncio queue maxsize so the check can always trigger. # Must be < LITELLM_ASYNCIO_QUEUE_MAXSIZE; if set higher the aggregation logic will never fire. -MAX_SIZE_IN_MEMORY_QUEUE = int( - os.getenv("MAX_SIZE_IN_MEMORY_QUEUE", int(LITELLM_ASYNCIO_QUEUE_MAXSIZE * 0.8)) -) -MAX_IN_MEMORY_QUEUE_FLUSH_COUNT = int( - os.getenv("MAX_IN_MEMORY_QUEUE_FLUSH_COUNT", 1000) -) +MAX_SIZE_IN_MEMORY_QUEUE = int(os.getenv("MAX_SIZE_IN_MEMORY_QUEUE", int(LITELLM_ASYNCIO_QUEUE_MAXSIZE * 0.8))) +MAX_IN_MEMORY_QUEUE_FLUSH_COUNT = int(os.getenv("MAX_IN_MEMORY_QUEUE_FLUSH_COUNT", 1000)) ############################################################################################### MINIMUM_PROMPT_CACHE_TOKEN_COUNT = int( os.getenv("MINIMUM_PROMPT_CACHE_TOKEN_COUNT", 1024) @@ -338,49 +279,31 @@ DAYS_IN_A_WEEK = int(os.getenv("DAYS_IN_A_WEEK", 7)) DAYS_IN_A_MONTH = int(os.getenv("DAYS_IN_A_MONTH", 28)) DAYS_IN_A_YEAR = int(os.getenv("DAYS_IN_A_YEAR", 365)) -REPLICATE_MODEL_NAME_WITH_ID_LENGTH = int( - os.getenv("REPLICATE_MODEL_NAME_WITH_ID_LENGTH", 64) -) +REPLICATE_MODEL_NAME_WITH_ID_LENGTH = int(os.getenv("REPLICATE_MODEL_NAME_WITH_ID_LENGTH", 64)) #### TOKEN COUNTING #### FUNCTION_DEFINITION_TOKEN_COUNT = int(os.getenv("FUNCTION_DEFINITION_TOKEN_COUNT", 9)) SYSTEM_MESSAGE_TOKEN_COUNT = int(os.getenv("SYSTEM_MESSAGE_TOKEN_COUNT", 4)) TOOL_CHOICE_OBJECT_TOKEN_COUNT = int(os.getenv("TOOL_CHOICE_OBJECT_TOKEN_COUNT", 4)) -DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT = int( - os.getenv("DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT", 10) -) -DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT = int( - os.getenv("DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT", 20) -) -MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES = int( - os.getenv("MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES", 768) -) -MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES = int( - os.getenv("MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES", 2000) -) +DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT = int(os.getenv("DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT", 10)) +DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT = int(os.getenv("DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT", 20)) +MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES = int(os.getenv("MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES", 768)) +MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES = int(os.getenv("MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES", 2000)) MAX_TILE_WIDTH = int(os.getenv("MAX_TILE_WIDTH", 512)) MAX_TILE_HEIGHT = int(os.getenv("MAX_TILE_HEIGHT", 512)) -OPENAI_FILE_SEARCH_COST_PER_1K_CALLS = float( - os.getenv("OPENAI_FILE_SEARCH_COST_PER_1K_CALLS", 2.5 / 1000) -) +OPENAI_FILE_SEARCH_COST_PER_1K_CALLS = float(os.getenv("OPENAI_FILE_SEARCH_COST_PER_1K_CALLS", 2.5 / 1000)) # Azure OpenAI Assistants feature costs # Source: https://azure.microsoft.com/en-us/pricing/details/cognitive-services/openai-service/ AZURE_FILE_SEARCH_COST_PER_GB_PER_DAY = float( os.getenv("AZURE_FILE_SEARCH_COST_PER_GB_PER_DAY", 0.1) # $0.1 USD per 1 GB/Day ) AZURE_COMPUTER_USE_INPUT_COST_PER_1K_TOKENS = float( - os.getenv( - "AZURE_COMPUTER_USE_INPUT_COST_PER_1K_TOKENS", 3.0 - ) # $0.003 USD per 1K Tokens + os.getenv("AZURE_COMPUTER_USE_INPUT_COST_PER_1K_TOKENS", 3.0) # $0.003 USD per 1K Tokens ) AZURE_COMPUTER_USE_OUTPUT_COST_PER_1K_TOKENS = float( - os.getenv( - "AZURE_COMPUTER_USE_OUTPUT_COST_PER_1K_TOKENS", 12.0 - ) # $0.012 USD per 1K Tokens + os.getenv("AZURE_COMPUTER_USE_OUTPUT_COST_PER_1K_TOKENS", 12.0) # $0.012 USD per 1K Tokens ) AZURE_VECTOR_STORE_COST_PER_GB_PER_DAY = float( - os.getenv( - "AZURE_VECTOR_STORE_COST_PER_GB_PER_DAY", 0.1 - ) # $0.1 USD per 1 GB/Day (same as file search) + os.getenv("AZURE_VECTOR_STORE_COST_PER_GB_PER_DAY", 0.1) # $0.1 USD per 1 GB/Day (same as file search) ) MIN_NON_ZERO_TEMPERATURE = float(os.getenv("MIN_NON_ZERO_TEMPERATURE", 0.0001)) #### RELIABILITY #### @@ -394,9 +317,7 @@ INITIAL_RETRY_DELAY = float(os.getenv("INITIAL_RETRY_DELAY", 0.5)) MAX_RETRY_DELAY = float(os.getenv("MAX_RETRY_DELAY", 8.0)) JITTER = float(os.getenv("JITTER", 0.75)) -DEFAULT_IN_MEMORY_TTL = int( - os.getenv("DEFAULT_IN_MEMORY_TTL", 5) -) # default time to live for the in-memory cache +DEFAULT_IN_MEMORY_TTL = int(os.getenv("DEFAULT_IN_MEMORY_TTL", 5)) # default time to live for the in-memory cache DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE = int( os.getenv("DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE", 1000) ) # default max size for redis batch cache @@ -404,23 +325,13 @@ os.getenv("DEFAULT_POLLING_INTERVAL", 0.03) ) # default polling interval for the scheduler AZURE_OPERATION_POLLING_TIMEOUT = int(os.getenv("AZURE_OPERATION_POLLING_TIMEOUT", 120)) -AZURE_DOCUMENT_INTELLIGENCE_API_VERSION = str( - os.getenv("AZURE_DOCUMENT_INTELLIGENCE_API_VERSION", "2024-11-30") -) -AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI = int( - os.getenv("AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI", 96) -) +AZURE_DOCUMENT_INTELLIGENCE_API_VERSION = str(os.getenv("AZURE_DOCUMENT_INTELLIGENCE_API_VERSION", "2024-11-30")) +AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI = int(os.getenv("AZURE_DOCUMENT_INTELLIGENCE_DEFAULT_DPI", 96)) REDIS_SOCKET_TIMEOUT = float(os.getenv("REDIS_SOCKET_TIMEOUT", 0.1)) REDIS_CONNECTION_POOL_TIMEOUT = int(os.getenv("REDIS_CONNECTION_POOL_TIMEOUT", 5)) -REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD = int( - os.getenv("REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD", 5) -) -REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT = int( - os.getenv("REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT", 60) -) -REDIS_CIRCUIT_BREAKER_ENABLED = ( - os.getenv("REDIS_CIRCUIT_BREAKER_ENABLED", "true").lower() == "true" -) +REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD = int(os.getenv("REDIS_CIRCUIT_BREAKER_FAILURE_THRESHOLD", 5)) +REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT = int(os.getenv("REDIS_CIRCUIT_BREAKER_RECOVERY_TIMEOUT", 60)) +REDIS_CIRCUIT_BREAKER_ENABLED = os.getenv("REDIS_CIRCUIT_BREAKER_ENABLED", "true").lower() == "true" # Default Redis major version to assume when version cannot be determined # Using 7 as it's the modern version that supports LPOP with count parameter DEFAULT_REDIS_MAJOR_VERSION = int(os.getenv("DEFAULT_REDIS_MAJOR_VERSION", 7)) @@ -430,17 +341,11 @@ MAX_EXCEPTION_MESSAGE_LENGTH = int(os.getenv("MAX_EXCEPTION_MESSAGE_LENGTH", 2000)) MAX_STRING_LENGTH_PROMPT_IN_DB = int(os.getenv("MAX_STRING_LENGTH_PROMPT_IN_DB", 2048)) BEDROCK_MAX_POLICY_SIZE = int(os.getenv("BEDROCK_MAX_POLICY_SIZE", 75)) -BEDROCK_MIN_THINKING_BUDGET_TOKENS = int( - os.getenv("BEDROCK_MIN_THINKING_BUDGET_TOKENS", 1024) -) +BEDROCK_MIN_THINKING_BUDGET_TOKENS = int(os.getenv("BEDROCK_MIN_THINKING_BUDGET_TOKENS", 1024)) # Anthropic's Messages API rejects thinking.budget_tokens < 1024. ANTHROPIC_MIN_THINKING_BUDGET_TOKENS = 1024 -REPLICATE_POLLING_DELAY_SECONDS = float( - os.getenv("REPLICATE_POLLING_DELAY_SECONDS", 0.5) -) -DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS = int( - os.getenv("DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS", 4096) -) +REPLICATE_POLLING_DELAY_SECONDS = float(os.getenv("REPLICATE_POLLING_DELAY_SECONDS", 0.5)) +DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS = int(os.getenv("DEFAULT_ANTHROPIC_CHAT_MAX_TOKENS", 4096)) DEFAULT_OCI_CHAT_MAX_TOKENS = 4096 TOGETHER_AI_4_B = int(os.getenv("TOGETHER_AI_4_B", 4)) TOGETHER_AI_8_B = int(os.getenv("TOGETHER_AI_8_B", 8)) @@ -469,13 +374,9 @@ # deadline and connect handshake (see ``http_handler`` cached handler paths). COMPLETION_HTTP_FALLBACK_SECONDS: float = 600.0 HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS: float = 5.0 -request_timeout: float = float( - os.getenv("REQUEST_TIMEOUT", str(int(DEFAULT_REQUEST_TIMEOUT_SECONDS))) -) +request_timeout: float = float(os.getenv("REQUEST_TIMEOUT", str(int(DEFAULT_REQUEST_TIMEOUT_SECONDS)))) request_timeout_explicitly_set: bool = "REQUEST_TIMEOUT" in os.environ -DEFAULT_A2A_AGENT_TIMEOUT: float = float( - os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000) -) # 10 minutes +DEFAULT_A2A_AGENT_TIMEOUT: float = float(os.getenv("DEFAULT_A2A_AGENT_TIMEOUT", 6000)) # 10 minutes # Patterns that indicate a localhost/internal URL in A2A agent cards that should be # replaced with the original base_url. This is a common misconfiguration where # developers deploy agents with development URLs in their agent cards. @@ -505,16 +406,10 @@ FIREWORKS_AI_80_B = int(os.getenv("FIREWORKS_AI_80_B", 80)) #### Logging callback constants #### REDACTED_BY_LITELM_STRING = "REDACTED_BY_LITELM" -MAX_LANGFUSE_INITIALIZED_CLIENTS = int( - os.getenv("MAX_LANGFUSE_INITIALIZED_CLIENTS", 50) -) -LOGGING_WORKER_CONCURRENCY = int( - os.getenv("LOGGING_WORKER_CONCURRENCY", 100) -) # Must be above 0 +MAX_LANGFUSE_INITIALIZED_CLIENTS = int(os.getenv("MAX_LANGFUSE_INITIALIZED_CLIENTS", 50)) +LOGGING_WORKER_CONCURRENCY = int(os.getenv("LOGGING_WORKER_CONCURRENCY", 100)) # Must be above 0 LOGGING_WORKER_MAX_QUEUE_SIZE = int(os.getenv("LOGGING_WORKER_MAX_QUEUE_SIZE", 50_000)) -LOGGING_WORKER_MAX_TIME_PER_COROUTINE = float( - os.getenv("LOGGING_WORKER_MAX_TIME_PER_COROUTINE", 20.0) -) +LOGGING_WORKER_MAX_TIME_PER_COROUTINE = float(os.getenv("LOGGING_WORKER_MAX_TIME_PER_COROUTINE", 20.0)) LOGGING_WORKER_CLEAR_PERCENTAGE = int( os.getenv("LOGGING_WORKER_CLEAR_PERCENTAGE", 50) ) # Percentage of queue to clear (default: 50%) @@ -529,17 +424,13 @@ LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED = 499 -EMAIL_BUDGET_ALERT_TTL = int( - os.getenv("EMAIL_BUDGET_ALERT_TTL", 24 * 60 * 60) -) # 24 hours in seconds +EMAIL_BUDGET_ALERT_TTL = int(os.getenv("EMAIL_BUDGET_ALERT_TTL", 24 * 60 * 60)) # 24 hours in seconds EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE = float( os.getenv("EMAIL_BUDGET_ALERT_MAX_SPEND_ALERT_PERCENTAGE", 0.8) ) # 80% of max budget ############### LLM Provider Constants ############### ### ANTHROPIC CONSTANTS ### -ANTHROPIC_TOKEN_COUNTING_BETA_VERSION = os.getenv( - "ANTHROPIC_TOKEN_COUNTING_BETA_VERSION", "token-counting-2024-11-01" -) +ANTHROPIC_TOKEN_COUNTING_BETA_VERSION = os.getenv("ANTHROPIC_TOKEN_COUNTING_BETA_VERSION", "token-counting-2024-11-01") ANTHROPIC_SKILLS_API_BETA_VERSION = "skills-2025-10-02" ANTHROPIC_WEB_SEARCH_TOOL_MAX_USES = { "low": 1, @@ -554,9 +445,7 @@ DEFAULT_IMAGE_ENDPOINT_MODEL = "dall-e-2" DEFAULT_VIDEO_ENDPOINT_MODEL = "sora-2" -DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS = int( - os.getenv("DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS", 8) -) +DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS = int(os.getenv("DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS", 8)) ### DATAFORSEO CONSTANTS ### DEFAULT_DATAFORSEO_LOCATION_CODE = int( @@ -939,8 +828,7 @@ "clarifai/qwen.qwenLM.Qwen3-30B-A3B-Instruct-2507", "clarifai/qwen.qwen3.qwen3-next-80B-A3B-Thinking", "clarifai/openai.chat-completion.gpt-oss-120b", - "clarifai/qwen.qwenLM.Qwen3-30B-A3B-Thinking-2507" - "clarifai/openai.chat-completion.gpt-5-nano", + "clarifai/qwen.qwenLM.Qwen3-30B-A3B-Thinking-2507clarifai/openai.chat-completion.gpt-5-nano", "clarifai/openai.chat-completion.gpt-4o", "clarifai/gcp.generate.gemini-2_5-pro", "clarifai/anthropic.completion.claude-sonnet-4", @@ -1369,9 +1257,7 @@ "tool_calls", "content_filter", ] -HUMANLOOP_PROMPT_CACHE_TTL_SECONDS = int( - os.getenv("HUMANLOOP_PROMPT_CACHE_TTL_SECONDS", 60) -) # 1 minute +HUMANLOOP_PROMPT_CACHE_TTL_SECONDS = int(os.getenv("HUMANLOOP_PROMPT_CACHE_TTL_SECONDS", 60)) # 1 minute RESPONSE_FORMAT_TOOL_NAME = "json_tool_call" # default tool name used when converting response format to tool call ########################### Logging Callback Constants ########################### @@ -1379,9 +1265,7 @@ PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES = int( os.getenv("PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES", 5) ) -CLOUDZERO_EXPORT_INTERVAL_MINUTES = int( - os.getenv("CLOUDZERO_EXPORT_INTERVAL_MINUTES", 60) -) +CLOUDZERO_EXPORT_INTERVAL_MINUTES = int(os.getenv("CLOUDZERO_EXPORT_INTERVAL_MINUTES", 60)) MCP_TOOL_NAME_PREFIX = "mcp_tool" MAXIMUM_TRACEBACK_LINES_TO_LOG = int(os.getenv("MAXIMUM_TRACEBACK_LINES_TO_LOG", 100)) @@ -1444,37 +1328,23 @@ BASE_MCP_ROUTE = "/mcp" -BATCH_STATUS_POLL_INTERVAL_SECONDS = int( - os.getenv("BATCH_STATUS_POLL_INTERVAL_SECONDS", 3600) -) # 1 hour -BATCH_STATUS_POLL_MAX_ATTEMPTS = int( - os.getenv("BATCH_STATUS_POLL_MAX_ATTEMPTS", 24) -) # for 24 hours - -HEALTH_CHECK_TIMEOUT_SECONDS = int( - os.getenv("HEALTH_CHECK_TIMEOUT_SECONDS", 60) -) # 60 seconds -_background_health_check_max_tokens_env = os.getenv( - "BACKGROUND_HEALTH_CHECK_MAX_TOKENS" -) +BATCH_STATUS_POLL_INTERVAL_SECONDS = int(os.getenv("BATCH_STATUS_POLL_INTERVAL_SECONDS", 3600)) # 1 hour +BATCH_STATUS_POLL_MAX_ATTEMPTS = int(os.getenv("BATCH_STATUS_POLL_MAX_ATTEMPTS", 24)) # for 24 hours + +HEALTH_CHECK_TIMEOUT_SECONDS = int(os.getenv("HEALTH_CHECK_TIMEOUT_SECONDS", 60)) # 60 seconds +_background_health_check_max_tokens_env = os.getenv("BACKGROUND_HEALTH_CHECK_MAX_TOKENS") try: _raw_background_health_check_max_tokens = ( - _background_health_check_max_tokens_env.strip() - if _background_health_check_max_tokens_env is not None - else "" + _background_health_check_max_tokens_env.strip() if _background_health_check_max_tokens_env is not None else "" ) BACKGROUND_HEALTH_CHECK_MAX_TOKENS: Optional[int] = ( - int(_raw_background_health_check_max_tokens) - if _raw_background_health_check_max_tokens - else None + int(_raw_background_health_check_max_tokens) if _raw_background_health_check_max_tokens else None ) except (ValueError, TypeError): BACKGROUND_HEALTH_CHECK_MAX_TOKENS = None -_background_health_check_max_tokens_reasoning_env = os.getenv( - "BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING" -) +_background_health_check_max_tokens_reasoning_env = os.getenv("BACKGROUND_HEALTH_CHECK_MAX_TOKENS_REASONING") try: _raw_background_health_check_max_tokens_reasoning = ( _background_health_check_max_tokens_reasoning_env.strip() @@ -1516,9 +1386,7 @@ os.getenv("LITELLM_KEY_ROTATION_LOCK_TTL_SECONDS", 600) ) # 10 minutes default — caps the deadlock window if a pod crashes mid-rotation UI_SESSION_TOKEN_TEAM_ID = "litellm-dashboard" -LITELLM_EXPIRED_UI_SESSION_KEY_CLEANUP_ENABLED = os.getenv( - "LITELLM_EXPIRED_UI_SESSION_KEY_CLEANUP_ENABLED", "false" -) +LITELLM_EXPIRED_UI_SESSION_KEY_CLEANUP_ENABLED = os.getenv("LITELLM_EXPIRED_UI_SESSION_KEY_CLEANUP_ENABLED", "false") LITELLM_EXPIRED_UI_SESSION_KEY_CLEANUP_INTERVAL_SECONDS = int( os.getenv("LITELLM_EXPIRED_UI_SESSION_KEY_CLEANUP_INTERVAL_SECONDS", 86400) ) # 24 hours default @@ -1535,15 +1403,11 @@ CLI_SESSION_KEY_PREFIX = "cli-session" # Support both CLI_JWT_EXPIRATION_HOURS and LITELLM_CLI_JWT_EXPIRATION_HOURS for backwards compatibility CLI_JWT_EXPIRATION_HOURS = int( - os.getenv("CLI_JWT_EXPIRATION_HOURS") - or os.getenv("LITELLM_CLI_JWT_EXPIRATION_HOURS") - or 24 + os.getenv("CLI_JWT_EXPIRATION_HOURS") or os.getenv("LITELLM_CLI_JWT_EXPIRATION_HOURS") or 24 ) # Comma-separated allowlisted OIDC claim map for CLI SSO polling, e.g. # "employment_type->acme_employment_type,org_info.department->department" -CLI_SSO_CLAIM_MAP = ( - os.getenv("CLI_SSO_CLAIM_MAP") or os.getenv("LITELLM_CLI_SSO_CLAIM_MAP") or "" -) +CLI_SSO_CLAIM_MAP = os.getenv("CLI_SSO_CLAIM_MAP") or os.getenv("LITELLM_CLI_SSO_CLAIM_MAP") or "" CLI_SSO_CLAIM_MAX_SCALAR_LENGTH = 1024 ########################### UI SESSION DURATION ########################### @@ -1557,54 +1421,34 @@ PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME = "prometheus_emit_budget_metrics" CLOUDZERO_EXPORT_USAGE_DATA_JOB_NAME = "cloudzero_export_usage_data" MAVVRIK_FOCUS_EXPORT_JOB_NAME = "mavvrik_focus_export_usage_data" -CLOUDZERO_MAX_FETCHED_DATA_RECORDS = int( - os.getenv("CLOUDZERO_MAX_FETCHED_DATA_RECORDS", 50000) -) +CLOUDZERO_MAX_FETCHED_DATA_RECORDS = int(os.getenv("CLOUDZERO_MAX_FETCHED_DATA_RECORDS", 50000)) SPEND_LOG_CLEANUP_JOB_NAME = "spend_log_cleanup" KEY_ROTATION_JOB_NAME = "litellm_key_rotation_job" EXPIRED_UI_SESSION_KEY_CLEANUP_JOB_NAME = "litellm_expired_ui_session_key_cleanup_job" SPEND_LOG_RUN_LOOPS = int(os.getenv("SPEND_LOG_RUN_LOOPS", 500)) SPEND_LOG_CLEANUP_BATCH_SIZE = int(os.getenv("SPEND_LOG_CLEANUP_BATCH_SIZE", 1000)) -SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES = int( - os.getenv("SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3) -) +SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES = int(os.getenv("SPEND_LOG_CLEANUP_MAX_CONSECUTIVE_BATCH_FAILURES", 3)) SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS = float( os.getenv("SPEND_LOG_CLEANUP_BATCH_FAILURE_BACKOFF_SECONDS", 0.5) ) SPEND_LOG_PARTITION_INTERVAL = os.getenv("SPEND_LOG_PARTITION_INTERVAL", "day") -SPEND_LOG_PARTITION_PRECREATE_AHEAD = int( - os.getenv("SPEND_LOG_PARTITION_PRECREATE_AHEAD", 7) -) +SPEND_LOG_PARTITION_PRECREATE_AHEAD = int(os.getenv("SPEND_LOG_PARTITION_PRECREATE_AHEAD", 7)) SPEND_LOG_QUEUE_SIZE_THRESHOLD = int(os.getenv("SPEND_LOG_QUEUE_SIZE_THRESHOLD", 100)) SPEND_LOG_QUEUE_POLL_INTERVAL = float(os.getenv("SPEND_LOG_QUEUE_POLL_INTERVAL", 2.0)) -SPEND_COUNTER_RESEED_LOCKS_MAX_SIZE = int( - os.getenv("SPEND_COUNTER_RESEED_LOCKS_MAX_SIZE", 10000) -) -DEFAULT_CRON_JOB_LOCK_TTL_SECONDS = int( - os.getenv("DEFAULT_CRON_JOB_LOCK_TTL_SECONDS", 60) -) # 1 minute -PROXY_BUDGET_RESCHEDULER_MIN_TIME = int( - os.getenv("PROXY_BUDGET_RESCHEDULER_MIN_TIME", 597) -) +SPEND_COUNTER_RESEED_LOCKS_MAX_SIZE = int(os.getenv("SPEND_COUNTER_RESEED_LOCKS_MAX_SIZE", 10000)) +DEFAULT_CRON_JOB_LOCK_TTL_SECONDS = int(os.getenv("DEFAULT_CRON_JOB_LOCK_TTL_SECONDS", 60)) # 1 minute +PROXY_BUDGET_RESCHEDULER_MIN_TIME = int(os.getenv("PROXY_BUDGET_RESCHEDULER_MIN_TIME", 597)) PROXY_BATCH_POLLING_INTERVAL = int(os.getenv("PROXY_BATCH_POLLING_INTERVAL", 3600)) MAX_OBJECTS_PER_POLL_CYCLE = max(1, int(os.getenv("MAX_OBJECTS_PER_POLL_CYCLE", 50))) -MANAGED_OBJECT_STALENESS_CUTOFF_DAYS = max( - 1, int(os.getenv("MANAGED_OBJECT_STALENESS_CUTOFF_DAYS", 7)) -) -STALE_OBJECT_CLEANUP_BATCH_SIZE = max( - 1, int(os.getenv("STALE_OBJECT_CLEANUP_BATCH_SIZE", 1000)) -) +MANAGED_OBJECT_STALENESS_CUTOFF_DAYS = max(1, int(os.getenv("MANAGED_OBJECT_STALENESS_CUTOFF_DAYS", 7))) +STALE_OBJECT_CLEANUP_BATCH_SIZE = max(1, int(os.getenv("STALE_OBJECT_CLEANUP_BATCH_SIZE", 1000))) # Set PROXY_BATCH_POLLING_ENABLED=false to disable the CheckBatchCost and # CheckResponsesCost background polling jobs entirely (e.g. to avoid DB load on # installations with large numbers of stale managed objects). _batch_polling_env = os.getenv("PROXY_BATCH_POLLING_ENABLED", "true").lower() PROXY_BATCH_POLLING_ENABLED = _batch_polling_env == "true" -PROXY_BUDGET_RESCHEDULER_MAX_TIME = int( - os.getenv("PROXY_BUDGET_RESCHEDULER_MAX_TIME", 605) -) -PROXY_BATCH_WRITE_AT = int( - os.getenv("PROXY_BATCH_WRITE_AT", 10) -) # in seconds, increased from 10 +PROXY_BUDGET_RESCHEDULER_MAX_TIME = int(os.getenv("PROXY_BUDGET_RESCHEDULER_MAX_TIME", 605)) +PROXY_BATCH_WRITE_AT = int(os.getenv("PROXY_BATCH_WRITE_AT", 10)) # in seconds, increased from 10 # APScheduler Configuration - MEMORY LEAK FIX # These settings prevent memory leaks in APScheduler's normalize() and _apply_jitter() functions @@ -1615,12 +1459,8 @@ APSCHEDULER_MISFIRE_GRACE_TIME = int( os.getenv("APSCHEDULER_MISFIRE_GRACE_TIME", 3600) ) # ignore runs older than 1 hour (was 120) -APSCHEDULER_MAX_INSTANCES = int( - os.getenv("APSCHEDULER_MAX_INSTANCES", 1) -) # prevent concurrent job instances -APSCHEDULER_REPLACE_EXISTING = os.getenv( - "APSCHEDULER_REPLACE_EXISTING", "True" -).lower() in [ +APSCHEDULER_MAX_INSTANCES = int(os.getenv("APSCHEDULER_MAX_INSTANCES", 1)) # prevent concurrent job instances +APSCHEDULER_REPLACE_EXISTING = os.getenv("APSCHEDULER_REPLACE_EXISTING", "True").lower() in [ "true", "1", ] # always replace existing jobs @@ -1629,38 +1469,24 @@ # This will run tag spcific tasks at a later time to smooth QPS DAILY_TAG_SPEND_BATCH_MULTIPLIER = 2.3 -DEFAULT_HEALTH_CHECK_INTERVAL = int( - os.getenv("DEFAULT_HEALTH_CHECK_INTERVAL", 300) -) # 5 minutes +DEFAULT_HEALTH_CHECK_INTERVAL = int(os.getenv("DEFAULT_HEALTH_CHECK_INTERVAL", 300)) # 5 minutes DEFAULT_SHARED_HEALTH_CHECK_TTL = int( os.getenv("DEFAULT_SHARED_HEALTH_CHECK_TTL", 300) ) # 5 minutes - TTL for cached health check results DEFAULT_SHARED_HEALTH_CHECK_LOCK_TTL = int( os.getenv("DEFAULT_SHARED_HEALTH_CHECK_LOCK_TTL", 60) ) # 1 minute - TTL for health check lock -DEFAULT_HEALTH_CHECK_STALENESS_MULTIPLIER = ( - 2 # health state is stale after interval * this -) -PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS = int( - os.getenv("PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS", 9) -) +DEFAULT_HEALTH_CHECK_STALENESS_MULTIPLIER = 2 # health state is stale after interval * this +PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS = int(os.getenv("PROMETHEUS_FALLBACK_STATS_SEND_TIME_HOURS", 9)) DEFAULT_MODEL_CREATED_AT_TIME = int( os.getenv("DEFAULT_MODEL_CREATED_AT_TIME", 1677610602) ) # returns on `/models` endpoint -DEFAULT_SLACK_ALERTING_THRESHOLD = int( - os.getenv("DEFAULT_SLACK_ALERTING_THRESHOLD", 300) -) +DEFAULT_SLACK_ALERTING_THRESHOLD = int(os.getenv("DEFAULT_SLACK_ALERTING_THRESHOLD", 300)) MAX_TEAM_LIST_LIMIT = int(os.getenv("MAX_TEAM_LIST_LIMIT", 20)) -MAX_POLICY_ESTIMATE_IMPACT_ROWS = int( - os.getenv("MAX_POLICY_ESTIMATE_IMPACT_ROWS", 1000) -) -DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD = float( - os.getenv("DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD", 0.7) -) +MAX_POLICY_ESTIMATE_IMPACT_ROWS = int(os.getenv("MAX_POLICY_ESTIMATE_IMPACT_ROWS", 1000)) +DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD = float(os.getenv("DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD", 0.7)) LENGTH_OF_LITELLM_GENERATED_KEY = int(os.getenv("LENGTH_OF_LITELLM_GENERATED_KEY", 16)) -SECRET_MANAGER_REFRESH_INTERVAL = int( - os.getenv("SECRET_MANAGER_REFRESH_INTERVAL", 86400) -) +SECRET_MANAGER_REFRESH_INTERVAL = int(os.getenv("SECRET_MANAGER_REFRESH_INTERVAL", 86400)) LITELLM_SETTINGS_SAFE_DB_OVERRIDES = [ "default_internal_user_params", "default_team_params", @@ -1672,9 +1498,7 @@ "cost_margin_config", ] SPECIAL_LITELLM_AUTH_TOKEN = ["ui-token"] -DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL = int( - os.getenv("DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL", 60) -) +DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL = int(os.getenv("DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL", 60)) DEFAULT_ACCESS_GROUP_CACHE_TTL = int(os.getenv("DEFAULT_ACCESS_GROUP_CACHE_TTL", 600)) # Short TTL for negative MCP access-group existence lookups. Keeps unauthenticated # callers from forcing a DB query per request for unknown names, while bounding @@ -1754,9 +1578,7 @@ ] # CoroutineChecker cache configuration -COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY = int( - os.getenv("COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY", 1000) -) +COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY = int(os.getenv("COROUTINE_CHECKER_MAX_SIZE_IN_MEMORY", 1000)) ########################### RAG Text Splitter Constants ########################### DEFAULT_CHUNK_SIZE = int(os.getenv("DEFAULT_CHUNK_SIZE", 1000)) @@ -1764,31 +1586,19 @@ ########################### S3 Vectors RAG Constants ########################### S3_VECTORS_DEFAULT_DIMENSION = int(os.getenv("S3_VECTORS_DEFAULT_DIMENSION", 1024)) -S3_VECTORS_DEFAULT_DISTANCE_METRIC = str( - os.getenv("S3_VECTORS_DEFAULT_DISTANCE_METRIC", "cosine") -) +S3_VECTORS_DEFAULT_DISTANCE_METRIC = str(os.getenv("S3_VECTORS_DEFAULT_DISTANCE_METRIC", "cosine")) S3_VECTORS_DEFAULT_NON_FILTERABLE_METADATA_KEYS = ["source_text"] ########################### Microsoft SSO Constants ########################### -MICROSOFT_USER_EMAIL_ATTRIBUTE = str( - os.getenv("MICROSOFT_USER_EMAIL_ATTRIBUTE", "userPrincipalName") -) -MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE = str( - os.getenv("MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE", "displayName") -) +MICROSOFT_USER_EMAIL_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_EMAIL_ATTRIBUTE", "userPrincipalName")) +MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_DISPLAY_NAME_ATTRIBUTE", "displayName")) MICROSOFT_USER_ID_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_ID_ATTRIBUTE", "id")) -MICROSOFT_USER_FIRST_NAME_ATTRIBUTE = str( - os.getenv("MICROSOFT_USER_FIRST_NAME_ATTRIBUTE", "givenName") -) -MICROSOFT_USER_LAST_NAME_ATTRIBUTE = str( - os.getenv("MICROSOFT_USER_LAST_NAME_ATTRIBUTE", "surname") -) +MICROSOFT_USER_FIRST_NAME_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_FIRST_NAME_ATTRIBUTE", "givenName")) +MICROSOFT_USER_LAST_NAME_ATTRIBUTE = str(os.getenv("MICROSOFT_USER_LAST_NAME_ATTRIBUTE", "surname")) # Maximum payload size (in bytes) to fully serialize for DEBUG logging. # Payloads larger than this are truncated to avoid multi-second json.dumps blocking the response. -MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG = int( - os.getenv("MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG", 102400) -) # 100 KB +MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG = int(os.getenv("MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG", 102400)) # 100 KB # Policy template enrichment MAX_COMPETITOR_NAMES = int(os.getenv("MAX_COMPETITOR_NAMES", 100)) diff --git a/litellm/containers/endpoint_factory.py b/litellm/containers/endpoint_factory.py index a5f6951862f7..bebdfa2f9e6f 100644 --- a/litellm/containers/endpoint_factory.py +++ b/litellm/containers/endpoint_factory.py @@ -97,9 +97,7 @@ def endpoint_func( ) if container_provider_config is None: - raise ValueError( - f"Container provider config not found for: {resolved_custom_llm_provider}" - ) + raise ValueError(f"Container provider config not found for: {resolved_custom_llm_provider}") # Build optional params for logging optional_params = {k: kwargs.get(k) for k in path_params if k in kwargs} @@ -239,9 +237,5 @@ def get_async_endpoint_names() -> List[str]: aretrieve_container_file = _generated_endpoints.get("aretrieve_container_file") delete_container_file = _generated_endpoints.get("delete_container_file") adelete_container_file = _generated_endpoints.get("adelete_container_file") -retrieve_container_file_content = _generated_endpoints.get( - "retrieve_container_file_content" -) -aretrieve_container_file_content = _generated_endpoints.get( - "aretrieve_container_file_content" -) +retrieve_container_file_content = _generated_endpoints.get("retrieve_container_file_content") +aretrieve_container_file_content = _generated_endpoints.get("aretrieve_container_file_content") diff --git a/litellm/containers/main.py b/litellm/containers/main.py index c0ca550c9a9a..caf6c6848449 100644 --- a/litellm/containers/main.py +++ b/litellm/containers/main.py @@ -211,31 +211,23 @@ def create_container( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[BaseContainerConfig] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError( - f"container operations are not supported for {custom_llm_provider}" - ) + raise ValueError(f"container operations are not supported for {custom_llm_provider}") local_vars.update(kwargs) # Get ContainerCreateOptionalRequestParams with only valid parameters container_create_optional_params: ContainerCreateOptionalRequestParams = ( - ContainerRequestUtils.get_requested_container_create_optional_param( - local_vars - ) + ContainerRequestUtils.get_requested_container_create_optional_param(local_vars) ) # Get optional parameters for the container API - container_create_request_params: Dict = ( - ContainerRequestUtils.get_optional_params_container_create( - container_provider_config=container_provider_config, - container_create_optional_params=container_create_optional_params, - ) + container_create_request_params: Dict = ContainerRequestUtils.get_optional_params_container_create( + container_provider_config=container_provider_config, + container_create_optional_params=container_create_optional_params, ) # Pre Call logging @@ -440,22 +432,16 @@ def list_containers( **kwargs, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(custom_llm_provider), - ) + container_provider_config: Optional[BaseContainerConfig] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(custom_llm_provider), ) if container_provider_config is None: - raise ValueError( - f"Container provider config not found for provider: {custom_llm_provider}" - ) + raise ValueError(f"Container provider config not found for provider: {custom_llm_provider}") # Get container list request parameters container_list_optional_params: ContainerListOptionalRequestParams = ( - ContainerRequestUtils.get_requested_container_list_optional_param( - local_vars - ) + ContainerRequestUtils.get_requested_container_list_optional_param(local_vars) ) # Pre Call logging @@ -641,27 +627,21 @@ def retrieve_container( ) # Decode container ID and extract provider info - original_container_id, resolved_custom_llm_provider, litellm_params = ( - decode_managed_container_id_for_request( - container_id=container_id, - custom_llm_provider=custom_llm_provider, - litellm_params=litellm_params, - ) + original_container_id, resolved_custom_llm_provider, litellm_params = decode_managed_container_id_for_request( + container_id=container_id, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, ) # True when input was a LiteLLM-managed ID (any length); needed to re-encode output for routing affinity was_encoded = original_container_id != container_id # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(resolved_custom_llm_provider), - ) + container_provider_config: Optional[BaseContainerConfig] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(resolved_custom_llm_provider), ) if container_provider_config is None: - raise ValueError( - f"Container provider config not found for provider: {resolved_custom_llm_provider}" - ) + raise ValueError(f"Container provider config not found for provider: {resolved_custom_llm_provider}") # Pre Call logging litellm_logging_obj.update_from_kwargs( @@ -865,27 +845,21 @@ def delete_container( ) # Decode container ID and extract provider info - original_container_id, resolved_custom_llm_provider, litellm_params = ( - decode_managed_container_id_for_request( - container_id=container_id, - custom_llm_provider=custom_llm_provider, - litellm_params=litellm_params, - ) + original_container_id, resolved_custom_llm_provider, litellm_params = decode_managed_container_id_for_request( + container_id=container_id, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, ) # True when input was a LiteLLM-managed ID (any length); needed to re-encode output for routing affinity was_encoded = original_container_id != container_id # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(resolved_custom_llm_provider), - ) + container_provider_config: Optional[BaseContainerConfig] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(resolved_custom_llm_provider), ) if container_provider_config is None: - raise ValueError( - f"Container provider config not found for provider: {resolved_custom_llm_provider}" - ) + raise ValueError(f"Container provider config not found for provider: {resolved_custom_llm_provider}") # Pre Call logging litellm_logging_obj.update_from_kwargs( @@ -1103,25 +1077,19 @@ def list_container_files( ) # Decode container ID and extract provider info - original_container_id, resolved_custom_llm_provider, litellm_params = ( - decode_managed_container_id_for_request( - container_id=container_id, - custom_llm_provider=custom_llm_provider, - litellm_params=litellm_params, - ) + original_container_id, resolved_custom_llm_provider, litellm_params = decode_managed_container_id_for_request( + container_id=container_id, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(resolved_custom_llm_provider), - ) + container_provider_config: Optional[BaseContainerConfig] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(resolved_custom_llm_provider), ) if container_provider_config is None: - raise ValueError( - f"Container provider config not found for provider: {resolved_custom_llm_provider}" - ) + raise ValueError(f"Container provider config not found for provider: {resolved_custom_llm_provider}") # Pre Call logging litellm_logging_obj.update_from_kwargs( @@ -1363,25 +1331,19 @@ def upload_container_file( ) # Decode container ID and extract provider info - original_container_id, resolved_custom_llm_provider, litellm_params = ( - decode_managed_container_id_for_request( - container_id=container_id, - custom_llm_provider=custom_llm_provider, - litellm_params=litellm_params, - ) + original_container_id, resolved_custom_llm_provider, litellm_params = decode_managed_container_id_for_request( + container_id=container_id, + custom_llm_provider=custom_llm_provider, + litellm_params=litellm_params, ) # get provider config - container_provider_config: Optional[BaseContainerConfig] = ( - ProviderConfigManager.get_provider_container_config( - provider=litellm.LlmProviders(resolved_custom_llm_provider), - ) + container_provider_config: Optional[BaseContainerConfig] = ProviderConfigManager.get_provider_container_config( + provider=litellm.LlmProviders(resolved_custom_llm_provider), ) if container_provider_config is None: - raise ValueError( - f"Container provider config not found for provider: {resolved_custom_llm_provider}" - ) + raise ValueError(f"Container provider config not found for provider: {resolved_custom_llm_provider}") # Pre Call logging litellm_logging_obj.update_from_kwargs( diff --git a/litellm/containers/utils.py b/litellm/containers/utils.py index 7c66eb70eb50..2b115c6b3c48 100644 --- a/litellm/containers/utils.py +++ b/litellm/containers/utils.py @@ -66,11 +66,7 @@ def get_optional_params_container_create( supported_params = container_provider_config.get_supported_openai_params() # Filter out unsupported parameters - filtered_params = { - k: v - for k, v in container_create_optional_params.items() - if k in supported_params - } + filtered_params = {k: v for k, v in container_create_optional_params.items() if k in supported_params} return container_provider_config.map_openai_params( container_create_optional_params=filtered_params, # type: ignore diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py index f95deda0f816..8ddc69f5396c 100644 --- a/litellm/cost_calculator.py +++ b/litellm/cost_calculator.py @@ -317,9 +317,7 @@ def cost_per_token( ### SERVICE TIER ### service_tier: Optional[str] = None, # for OpenAI service tier pricing ### DATA RESIDENCY ### - data_residency: Optional[ - str - ] = None, # for OpenAI regional-processing uplift (e.g. "eu", "us") + data_residency: Optional[str] = None, # for OpenAI regional-processing uplift (e.g. "eu", "us") response: Optional[Any] = None, ### REQUEST MODEL ### request_model: Optional[str] = None, # original request model for router detection @@ -376,9 +374,7 @@ def cost_per_token( # either `cache_write_tokens` (kimi-k2) or `cache_creation_tokens`. # Mirror db_spend_update_writer to stay symmetric. _cache_creation_tokens = float( - getattr(_pt_details, "cache_write_tokens", 0) - or getattr(_pt_details, "cache_creation_tokens", 0) - or 0 + getattr(_pt_details, "cache_write_tokens", 0) or getattr(_pt_details, "cache_creation_tokens", 0) or 0 ) _anthropic_read = getattr(usage_object, "cache_read_input_tokens", None) @@ -451,12 +447,8 @@ def cost_per_token( else: model_with_provider = f"{custom_llm_provider}/{model}" if region_name is not None: - model_with_provider_and_region = ( - f"{custom_llm_provider}/{region_name}/{model}" - ) - if ( - model_with_provider_and_region in model_cost_ref - ): # use region based pricing, if it's available + model_with_provider_and_region = f"{custom_llm_provider}/{region_name}/{model}" + if model_with_provider_and_region in model_cost_ref: # use region based pricing, if it's available model_with_provider = model_with_provider_and_region else: _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model) @@ -475,9 +467,7 @@ def cost_per_token( Option2. model = "openai/gpt-4" - model = provider/model Option3. model = "anthropic.claude-3" - model = model """ - if ( - model_with_provider in model_cost_ref - ): # Option 2. use model with provider, model = "openai/gpt-4" + if model_with_provider in model_cost_ref: # Option 2. use model with provider, model = "openai/gpt-4" model = model_with_provider elif model in model_cost_ref: # Option 1. use model passed, model="gpt-4" model = model @@ -488,9 +478,7 @@ def cost_per_token( # see this https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models if call_type == "speech" or call_type == "aspeech": - speech_model_info = litellm.get_model_info( - model=model_without_prefix, custom_llm_provider=custom_llm_provider - ) + speech_model_info = litellm.get_model_info(model=model_without_prefix, custom_llm_provider=custom_llm_provider) cost_metric = select_cost_metric_for_model(speech_model_info) prompt_cost: float = 0.0 completion_cost: float = 0.0 @@ -587,11 +575,7 @@ def cost_per_token( model=model, custom_llm_provider=custom_llm_provider, number_of_queries=number_of_queries or 1, - optional_params=( - response._hidden_params - if response and hasattr(response, "_hidden_params") - else None - ), + optional_params=(response._hidden_params if response and hasattr(response, "_hidden_params") else None), ) elif custom_llm_provider == "vertex_ai": cost_router = google_cost_router( @@ -615,13 +599,9 @@ def cost_per_token( service_tier=service_tier, ) elif custom_llm_provider == "anthropic": - return anthropic_cost_per_token( - model=model, usage=usage_block, service_tier=service_tier - ) + return anthropic_cost_per_token(model=model, usage=usage_block, service_tier=service_tier) elif custom_llm_provider == "bedrock": - return bedrock_cost_per_token( - model=model, usage=usage_block, service_tier=service_tier - ) + return bedrock_cost_per_token(model=model, usage=usage_block, service_tier=service_tier) elif custom_llm_provider == "openai": return openai_cost_per_token( model=model, @@ -641,9 +621,7 @@ def cost_per_token( service_tier=service_tier, ) elif custom_llm_provider == "gemini": - return gemini_cost_per_token( - model=model, usage=usage_block, service_tier=service_tier - ) + return gemini_cost_per_token(model=model, usage=usage_block, service_tier=service_tier) elif custom_llm_provider == "deepseek": return deepseek_cost_per_token(model=model, usage=usage_block) elif custom_llm_provider == "perplexity": @@ -667,13 +645,9 @@ def cost_per_token( service_tier=service_tier, ) else: - model_info = _cached_get_model_info_helper( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = _cached_get_model_info_helper(model=model, custom_llm_provider=custom_llm_provider) - if (model_info.get("input_cost_per_token") or 0.0) > 0 or ( - model_info.get("output_cost_per_token") or 0.0 - ) > 0: + if (model_info.get("input_cost_per_token") or 0.0) > 0 or (model_info.get("output_cost_per_token") or 0.0) > 0: return generic_cost_per_token( model=model, usage=usage_block, @@ -682,10 +656,7 @@ def cost_per_token( data_residency=data_residency, ) - if ( - model_info.get("input_cost_per_second", None) is not None - and response_time_ms is not None - ): + if model_info.get("input_cost_per_second", None) is not None and response_time_ms is not None: verbose_logger.debug( "For model=%s - input_cost_per_second: %s; response time: %s", model, @@ -697,10 +668,7 @@ def cost_per_token( model_info["input_cost_per_second"] * response_time_ms / 1000 # type: ignore ) - if ( - model_info.get("output_cost_per_second", None) is not None - and response_time_ms is not None - ): + if model_info.get("output_cost_per_second", None) is not None and response_time_ms is not None: verbose_logger.debug( "For model=%s - output_cost_per_second: %s; response time: %s", model, @@ -724,7 +692,9 @@ def cost_per_token( def get_replicate_completion_pricing(completion_response: dict, total_time=0.0): # see https://replicate.com/pricing # for all litellm currently supported LLMs, almost all requests go to a100_80gb - a100_80gb_price_per_second_public = DEFAULT_REPLICATE_GPU_PRICE_PER_SECOND # assume all calls sent to A100 80GB for now + a100_80gb_price_per_second_public = ( + DEFAULT_REPLICATE_GPU_PRICE_PER_SECOND # assume all calls sent to A100 80GB for now + ) if total_time == 0.0: # total time is in ms start_time = completion_response.get("created", time.time()) end_time = getattr(completion_response, "ended", time.time()) @@ -773,9 +743,7 @@ def _select_model_name_for_cost_calc( return_model: Optional[str] = None region_name: Optional[str] = None - custom_llm_provider = _get_provider_for_cost_calc( - model=model, custom_llm_provider=custom_llm_provider - ) + custom_llm_provider = _get_provider_for_cost_calc(model=model, custom_llm_provider=custom_llm_provider) completion_response_model: Optional[str] = None if completion_response is not None: @@ -788,10 +756,7 @@ def _select_model_name_for_cost_calc( if custom_pricing is True: if router_model_id is not None and router_model_id in litellm.model_cost: entry = litellm.model_cost[router_model_id] - if ( - entry.get("input_cost_per_token") is not None - or entry.get("input_cost_per_second") is not None - ): + if entry.get("input_cost_per_token") is not None or entry.get("input_cost_per_second") is not None: return_model = router_model_id else: return_model = model @@ -802,14 +767,9 @@ def _select_model_name_for_cost_calc( return_model = base_model elif completion_response_model is None and hidden_params is not None: - if ( - hidden_params.get("model", None) is not None - and len(hidden_params["model"]) > 0 - ): + if hidden_params.get("model", None) is not None and len(hidden_params["model"]) > 0: return_model = hidden_params.get("model", model) - elif ( - hidden_params is not None and hidden_params.get("region_name", None) is not None - ): + elif hidden_params is not None and hidden_params.get("region_name", None) is not None: region_name = hidden_params.get("region_name", None) if return_model is None and completion_response_model is not None: @@ -897,10 +857,7 @@ def _normalize_service_tier(service_tier: object) -> str | None: on the response usage) instead of crashing the downstream cost-key lookup, which calls service_tier.lower() """ - if ( - not isinstance(service_tier, str) - or service_tier.lower() == ServiceTier.AUTO.value - ): + if not isinstance(service_tier, str) or service_tier.lower() == ServiceTier.AUTO.value: return None return service_tier @@ -926,20 +883,12 @@ def _get_usage_object( and (isinstance(usage_obj, dict) or isinstance(usage_obj, ResponseAPIUsage)) and ResponseAPILoggingUtils._is_response_api_usage(usage_obj) ): - return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - usage_obj - ) - elif TranscriptionUsageObjectTransformation.is_transcription_usage_object( - usage_obj - ): - return ( - TranscriptionUsageObjectTransformation.transform_transcription_usage_object( - cast( - Union[ - TranscriptionUsageDurationObject, TranscriptionUsageTokensObject - ], - usage_obj, - ) + return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage_obj) + elif TranscriptionUsageObjectTransformation.is_transcription_usage_object(usage_obj): + return TranscriptionUsageObjectTransformation.transform_transcription_usage_object( + cast( + Union[TranscriptionUsageDurationObject, TranscriptionUsageTokensObject], + usage_obj, ) ) elif isinstance(usage_obj, dict): @@ -947,9 +896,7 @@ def _get_usage_object( elif isinstance(usage_obj, BaseModel): return Usage(**usage_obj.model_dump()) else: - verbose_logger.debug( - f"Unknown usage object type: {type(usage_obj)}, usage_obj: {usage_obj}" - ) + verbose_logger.debug(f"Unknown usage object type: {type(usage_obj)}, usage_obj: {usage_obj}") return None @@ -958,24 +905,18 @@ def _is_known_usage_objects(usage_obj): return ( isinstance(usage_obj, litellm.Usage) or isinstance(usage_obj, ResponseAPIUsage) - or TranscriptionUsageObjectTransformation.is_transcription_usage_object( - usage_obj - ) + or TranscriptionUsageObjectTransformation.is_transcription_usage_object(usage_obj) ) -def _infer_call_type( - call_type: Optional[CallTypesLiteral], completion_response: Any -) -> Optional[CallTypesLiteral]: +def _infer_call_type(call_type: Optional[CallTypesLiteral], completion_response: Any) -> Optional[CallTypesLiteral]: if call_type is not None: return call_type if completion_response is None: return None - if isinstance(completion_response, ModelResponse) or isinstance( - completion_response, ModelResponseStream - ): + if isinstance(completion_response, ModelResponse) or isinstance(completion_response, ModelResponseStream): return "completion" elif isinstance(completion_response, EmbeddingResponse): return "embedding" @@ -1053,9 +994,7 @@ def _apply_cost_margin( if custom_llm_provider and custom_llm_provider in litellm.cost_margin_config: margin_config = litellm.cost_margin_config[custom_llm_provider] if verbose_logger.isEnabledFor(logging.DEBUG): - verbose_logger.debug( - f"Found provider-specific margin config for {custom_llm_provider}: {margin_config}" - ) + verbose_logger.debug(f"Found provider-specific margin config for {custom_llm_provider}: {margin_config}") elif "global" in litellm.cost_margin_config: margin_config = litellm.cost_margin_config["global"] if verbose_logger.isEnabledFor(logging.DEBUG): @@ -1184,9 +1123,7 @@ def completion_cost( ### SERVICE TIER ### service_tier: Optional[str] = None, # for OpenAI service tier pricing ### DATA RESIDENCY ### - data_residency: Optional[ - str - ] = None, # for OpenAI regional-processing uplift (e.g. "eu", "us") + data_residency: Optional[str] = None, # for OpenAI regional-processing uplift (e.g. "eu", "us") ) -> float: """ Calculate the cost of a given completion call fot GPT-3.5-turbo, llama2, any litellm supported llm. @@ -1235,9 +1172,7 @@ def completion_cost( cache_creation_input_tokens: Optional[int] = None cache_read_input_tokens: Optional[int] = None audio_transcription_file_duration: float = 0.0 - cost_per_token_usage_object: Optional[Usage] = _get_usage_object( - completion_response=completion_response - ) + cost_per_token_usage_object: Optional[Usage] = _get_usage_object(completion_response=completion_response) rerank_billed_units: Optional[RerankBilledUnits] = None # Extract service_tier from optional_params if not provided directly @@ -1258,9 +1193,7 @@ def completion_cost( # Extract service_tier from usage object if not provided if service_tier is None and cost_per_token_usage_object is not None: if isinstance(cost_per_token_usage_object, BaseModel): - service_tier = getattr( - cost_per_token_usage_object, "service_tier", None - ) + service_tier = getattr(cost_per_token_usage_object, "service_tier", None) elif isinstance(cost_per_token_usage_object, dict): service_tier = cost_per_token_usage_object.get("service_tier") @@ -1285,23 +1218,16 @@ def completion_cost( for idx, model in enumerate(potential_model_names): try: if verbose_logger.isEnabledFor(logging.DEBUG): - verbose_logger.debug( - f"selected model name for cost calculation: {model}" - ) + verbose_logger.debug(f"selected model name for cost calculation: {model}") if completion_response is not None and ( - isinstance(completion_response, BaseModel) - or isinstance(completion_response, dict) + isinstance(completion_response, BaseModel) or isinstance(completion_response, dict) ): # tts returns a custom class if isinstance(completion_response, dict): - usage_obj: Optional[Union[dict, Usage]] = ( - completion_response.get("usage", {}) - ) + usage_obj: Optional[Union[dict, Usage]] = completion_response.get("usage", {}) else: usage_obj = getattr(completion_response, "usage", {}) - if isinstance(usage_obj, BaseModel) and not _is_known_usage_objects( - usage_obj=usage_obj - ): + if isinstance(usage_obj, BaseModel) and not _is_known_usage_objects(usage_obj=usage_obj): _usage_for_dump = cast(BaseModel, usage_obj) setattr( completion_response, @@ -1319,9 +1245,7 @@ def completion_cost( _usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( _usage ).model_dump() - elif TranscriptionUsageObjectTransformation.is_transcription_usage_object( - _usage - ): + elif TranscriptionUsageObjectTransformation.is_transcription_usage_object(_usage): tr_usage = TranscriptionUsageObjectTransformation.transform_transcription_usage_object( cast( Union[ @@ -1339,29 +1263,21 @@ def completion_cost( # get input/output tokens from completion_response prompt_tokens = _usage.get("prompt_tokens", 0) completion_tokens = _usage.get("completion_tokens", 0) - cache_creation_input_tokens = _usage.get( - "cache_creation_input_tokens", 0 - ) + cache_creation_input_tokens = _usage.get("cache_creation_input_tokens", 0) cache_read_input_tokens = _usage.get("cache_read_input_tokens", 0) if ( "prompt_tokens_details" in _usage and _usage["prompt_tokens_details"] != {} and _usage["prompt_tokens_details"] ): - prompt_tokens_details = ( - _usage.get("prompt_tokens_details") or {} - ) - cache_read_input_tokens = prompt_tokens_details.get( - "cached_tokens", 0 - ) + prompt_tokens_details = _usage.get("prompt_tokens_details") or {} + cache_read_input_tokens = prompt_tokens_details.get("cached_tokens", 0) total_time = getattr(completion_response, "_response_ms", 0) hidden_params = getattr(completion_response, "_hidden_params", None) if hidden_params is not None: - custom_llm_provider = hidden_params.get( - "custom_llm_provider", custom_llm_provider or None - ) + custom_llm_provider = hidden_params.get("custom_llm_provider", custom_llm_provider or None) region_name = hidden_params.get("region_name", region_name) # For Gemini/Vertex AI responses, trafficType is stored in @@ -1369,14 +1285,10 @@ def completion_cost( # by the cost key lookup (_priority / _flex suffixes) so that # ON_DEMAND_PRIORITY requests are billed at priority prices. if service_tier is None: - provider_specific = ( - hidden_params.get("provider_specific_fields") or {} - ) + provider_specific = hidden_params.get("provider_specific_fields") or {} raw_traffic_type = provider_specific.get("traffic_type") if raw_traffic_type: - service_tier = _map_traffic_type_to_service_tier( - raw_traffic_type - ) + service_tier = _map_traffic_type_to_service_tier(raw_traffic_type) else: if model is None: raise ValueError( @@ -1392,9 +1304,7 @@ def completion_cost( if call_type in _A2A_CALL_TYPES: from litellm.a2a_protocol.cost_calculator import A2ACostCalculator - return A2ACostCalculator.calculate_a2a_cost( - litellm_logging_obj=litellm_logging_obj - ) + return A2ACostCalculator.calculate_a2a_cost(litellm_logging_obj=litellm_logging_obj) if model is None: raise ValueError( @@ -1411,9 +1321,9 @@ def completion_cost( str(e) ) ) - if CostCalculatorUtils._call_type_has_image_response( - call_type - ) and isinstance(completion_response, ImageResponse): + if CostCalculatorUtils._call_type_has_image_response(call_type) and isinstance( + completion_response, ImageResponse + ): ### IMAGE GENERATION COST CALCULATION ### return CostCalculatorUtils.route_image_generation_cost_calculator( model=model, @@ -1430,9 +1340,7 @@ def completion_cost( # Extract custom model_info for deployment-specific pricing _video_model_info: Optional[ModelInfo] = None if custom_pricing and litellm_logging_obj is not None: - _litellm_params = getattr( - litellm_logging_obj, "litellm_params", None - ) + _litellm_params = getattr(litellm_logging_obj, "litellm_params", None) if _litellm_params is not None: _metadata = _litellm_params.get("metadata", {}) or {} _video_model_info = _metadata.get("model_info", None) @@ -1446,9 +1354,7 @@ def completion_cost( duration_seconds = usage_obj.get("duration_seconds", None) _vr = usage_obj.get("video_resolution", None) else: - duration_seconds = getattr( - usage_obj, "duration_seconds", None - ) + duration_seconds = getattr(usage_obj, "duration_seconds", None) _vr = getattr(usage_obj, "video_resolution", None) if _vr is not None: video_resolution = str(_vr).strip().lower() @@ -1487,9 +1393,7 @@ def completion_cost( getattr(completion_response, "duration", 0.0), ) elif call_type in _RERANK_CALL_TYPES: - if completion_response is not None and isinstance( - completion_response, RerankResponse - ): + if completion_response is not None and isinstance(completion_response, RerankResponse): meta_obj = completion_response.meta if meta_obj is not None: billed_units = meta_obj.get("billed_units", {}) or {} @@ -1501,9 +1405,7 @@ def completion_cost( total_tokens=billed_units.get("total_tokens"), ) - search_units = ( - billed_units.get("search_units") or 1 - ) # cohere charges per request by default. + search_units = billed_units.get("search_units") or 1 # cohere charges per request by default. completion_tokens = search_units elif call_type in _SEARCH_CALL_TYPES: from litellm.search import search_provider_cost_per_query @@ -1577,10 +1479,7 @@ def completion_cost( elif call_type == _AREALTIME_CALL_TYPE and isinstance( completion_response, LiteLLMRealtimeStreamLoggingObject ): - if ( - cost_per_token_usage_object is None - or custom_llm_provider is None - ): + if cost_per_token_usage_object is None or custom_llm_provider is None: raise ValueError( "usage object and custom_llm_provider must be provided for realtime stream cost calculation. Got cost_per_token_usage_object={}, custom_llm_provider={}".format( cost_per_token_usage_object, @@ -1599,59 +1498,36 @@ def completion_cost( MCPCostCalculator, ) - return MCPCostCalculator.calculate_mcp_tool_call_cost( - litellm_logging_obj=litellm_logging_obj - ) + return MCPCostCalculator.calculate_mcp_tool_call_cost(litellm_logging_obj=litellm_logging_obj) # Calculate cost based on prompt_tokens, completion_tokens - if ( - "togethercomputer" in model - or "together_ai" in model - or custom_llm_provider == "together_ai" - ): + if "togethercomputer" in model or "together_ai" in model or custom_llm_provider == "together_ai": # together ai prices based on size of llm # get_model_params_and_category takes a model name and returns the category of LLM size it is in model_prices_and_context_window.json - model = get_model_params_and_category( - model, call_type=CallTypes(call_type) - ) + model = get_model_params_and_category(model, call_type=CallTypes(call_type)) # replicate llms are calculate based on time for request running # see https://replicate.com/pricing - elif ( - model in litellm.replicate_models or "replicate" in model - ) and model not in litellm.model_cost: + elif (model in litellm.replicate_models or "replicate" in model) and model not in litellm.model_cost: # for unmapped replicate model, default to replicate's time tracking logic - return get_replicate_completion_pricing( - completion_response, total_time - ) # type: ignore + return get_replicate_completion_pricing(completion_response, total_time) # type: ignore if model is None: raise ValueError( f"Model is None and does not exist in passed completion_response. Passed completion_response={completion_response}, model={model}" ) - if ( - custom_llm_provider is not None - and custom_llm_provider == "vertex_ai" - ): + if custom_llm_provider is not None and custom_llm_provider == "vertex_ai": # Calculate the prompt characters + response characters if len(messages) > 0: prompt_string = litellm.utils.get_formatted_prompt( data={"messages": messages}, call_type="completion" ) - prompt_characters = litellm.utils._count_characters( - text=prompt_string - ) - if completion_response is not None and isinstance( - completion_response, ModelResponse - ): - completion_string = litellm.utils.get_response_string( - response_obj=completion_response - ) - completion_characters = litellm.utils._count_characters( - text=completion_string - ) + prompt_characters = litellm.utils._count_characters(text=prompt_string) + if completion_response is not None and isinstance(completion_response, ModelResponse): + completion_string = litellm.utils.get_response_string(response_obj=completion_response) + completion_characters = litellm.utils._count_characters(text=completion_string) # Get the original request model for router detection request_model_for_cost = None @@ -1688,12 +1564,8 @@ def completion_cost( if custom_llm_provider == "azure_ai": model_for_additional_costs = request_model_for_cost if completion_response is not None: - hidden_params = ( - getattr(completion_response, "_hidden_params", None) or {} - ) - hidden_model = hidden_params.get("model") or hidden_params.get( - "litellm_model_name" - ) + hidden_params = getattr(completion_response, "_hidden_params", None) or {} + hidden_model = hidden_params.get("model") or hidden_params.get("litellm_model_name") if hidden_model and ( "model_router" in (hidden_model or "").lower() or "model-router" in (hidden_model or "").lower() @@ -1712,17 +1584,13 @@ def completion_cost( else: additional_costs = None - _final_cost = ( - prompt_tokens_cost_usd_dollar + completion_tokens_cost_usd_dollar - ) - cost_for_built_in_tools = ( - StandardBuiltInToolCostTracking.get_cost_for_built_in_tools( - model=model, - response_object=completion_response, - usage=cost_per_token_usage_object, - standard_built_in_tools_params=standard_built_in_tools_params, - custom_llm_provider=custom_llm_provider, - ) + _final_cost = prompt_tokens_cost_usd_dollar + completion_tokens_cost_usd_dollar + cost_for_built_in_tools = StandardBuiltInToolCostTracking.get_cost_for_built_in_tools( + model=model, + response_object=completion_response, + usage=cost_per_token_usage_object, + standard_built_in_tools_params=standard_built_in_tools_params, + custom_llm_provider=custom_llm_provider, ) _final_cost += cost_for_built_in_tools if additional_costs: @@ -1763,23 +1631,17 @@ def completion_cost( _cache_read_cost: Optional[float] = None _cache_creation_cost: Optional[float] = None if cost_per_token_usage_object is not None: - _cr = getattr( - cost_per_token_usage_object, "cache_read_input_tokens", None - ) or (cost_per_token_usage_object.model_extra or {}).get( - "cache_read_input_tokens" - ) + _cr = getattr(cost_per_token_usage_object, "cache_read_input_tokens", None) or ( + cost_per_token_usage_object.model_extra or {} + ).get("cache_read_input_tokens") _cc = getattr( cost_per_token_usage_object, "cache_creation_input_tokens", None, - ) or (cost_per_token_usage_object.model_extra or {}).get( - "cache_creation_input_tokens" - ) + ) or (cost_per_token_usage_object.model_extra or {}).get("cache_creation_input_tokens") if (_cr or _cc) and model: try: - _mi = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + _mi = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) _cr_rate = _mi.get("cache_read_input_token_cost") if _cr and _cr_rate is not None: _cache_read_cost = float(_cr) * float(_cr_rate) @@ -1814,11 +1676,7 @@ def completion_cost( ) if idx == len(potential_model_names) - 1: raise e - raise Exception( - "Unable to calculat cost for received potential model names - {}".format( - potential_model_names - ) - ) + raise Exception("Unable to calculat cost for received potential model names - {}".format(potential_model_names)) except Exception as e: raise e @@ -1832,10 +1690,7 @@ def get_response_cost_from_hidden_params( _hidden_params_dict = hidden_params additional_headers = _hidden_params_dict.get("additional_headers", {}) - if ( - additional_headers - and "llm_provider-x-litellm-response-cost" in additional_headers - ): + if additional_headers and "llm_provider-x-litellm-response-cost" in additional_headers: response_cost = additional_headers["llm_provider-x-litellm-response-cost"] if response_cost is None: return None @@ -1892,9 +1747,7 @@ def response_cost_calculator( ### SERVICE TIER ### service_tier: Optional[str] = None, # for OpenAI service tier pricing ### DATA RESIDENCY ### - data_residency: Optional[ - str - ] = None, # for OpenAI regional-processing uplift (e.g. "eu", "us") + data_residency: Optional[str] = None, # for OpenAI regional-processing uplift (e.g. "eu", "us") ) -> float: """ Returns @@ -1908,9 +1761,7 @@ def response_cost_calculator( if isinstance(response_object, BaseModel): if hasattr(response_object, "_hidden_params"): response_object._hidden_params["optional_params"] = optional_params - provider_response_cost = get_response_cost_from_hidden_params( - response_object._hidden_params - ) + provider_response_cost = get_response_cost_from_hidden_params(response_object._hidden_params) if provider_response_cost is not None: return provider_response_cost @@ -1957,17 +1808,13 @@ def ocr_cost( # validate it's an OCR response ######################################################### if response is None or not isinstance(response, OCRResponse): - raise ValueError( - f"response must be of type OCRResponse got type={type(response)}" - ) + raise ValueError(f"response must be of type OCRResponse got type={type(response)}") if response.usage_info is None: raise ValueError("OCR response usage_info is None") try: - model_info: Optional[ModelInfo] = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info: Optional[ModelInfo] = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) except Exception: model_info = None @@ -2043,9 +1890,7 @@ def vector_store_search_cost( ) if config is None: - verbose_logger.debug( - f"Vector store search is not supported for {custom_llm_provider}" - ) + verbose_logger.debug(f"Vector store search is not supported for {custom_llm_provider}") return 0.0, 0.0 return config.calculate_vector_store_cost( @@ -2062,9 +1907,7 @@ def rerank_cost( Returns - float or None: cost of response OR none if error. """ - _, custom_llm_provider, _, _ = litellm.get_llm_provider( - model=model, custom_llm_provider=custom_llm_provider - ) + _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model, custom_llm_provider=custom_llm_provider) try: config = ProviderConfigManager.get_provider_rerank_config( @@ -2091,12 +1934,8 @@ def rerank_cost( raise e -def transcription_cost( - model: str, custom_llm_provider: Optional[str], duration: float -) -> Tuple[float, float]: - return openai_cost_per_second( - model=model, custom_llm_provider=custom_llm_provider, duration=duration - ) +def transcription_cost(model: str, custom_llm_provider: Optional[str], duration: float) -> Tuple[float, float]: + return openai_cost_per_second(model=model, custom_llm_provider=custom_llm_provider, duration=duration) def default_image_cost_calculator( @@ -2125,11 +1964,7 @@ def default_image_cost_calculator( """ # Standardize size format to use "-x-" size_str: str = size or "1024-x-1024" - size_str = ( - size_str.replace("x", "-x-") - if "x" in size_str and "-x-" not in size_str - else size_str - ) + size_str = size_str.replace("x", "-x-") if "x" in size_str and "-x-" not in size_str else size_str # Parse dimensions height, width = map(int, size_str.split("-x-")) @@ -2138,29 +1973,17 @@ def default_image_cost_calculator( base_model_name = f"{size_str}/{model}" model_name_without_custom_llm_provider: Optional[str] = None if custom_llm_provider and model.startswith(f"{custom_llm_provider}/"): - model_name_without_custom_llm_provider = model.replace( - f"{custom_llm_provider}/", "" - ) - base_model_name = ( - f"{custom_llm_provider}/{size_str}/{model_name_without_custom_llm_provider}" - ) - model_name_with_quality = ( - f"{quality}/{base_model_name}" if quality else base_model_name - ) + model_name_without_custom_llm_provider = model.replace(f"{custom_llm_provider}/", "") + base_model_name = f"{custom_llm_provider}/{size_str}/{model_name_without_custom_llm_provider}" + model_name_with_quality = f"{quality}/{base_model_name}" if quality else base_model_name # gpt-image-1 models use low, medium, high quality. If user did not specify quality, use medium fot gpt-image-1 model family - model_name_with_v2_quality = ( - f"{ImageGenerationRequestQuality.HIGH.value}/{base_model_name}" - ) + model_name_with_v2_quality = f"{ImageGenerationRequestQuality.HIGH.value}/{base_model_name}" - verbose_logger.debug( - f"Looking up cost for models: {model_name_with_quality}, {base_model_name}" - ) + verbose_logger.debug(f"Looking up cost for models: {model_name_with_quality}, {base_model_name}") model_without_provider = f"{size_str}/{model.split('/')[-1]}" - model_with_quality_without_provider = ( - f"{quality}/{model_without_provider}" if quality else model_without_provider - ) + model_with_quality_without_provider = f"{quality}/{model_without_provider}" if quality else model_without_provider # Try model with quality first, fall back to base model name cost_info: Optional[dict] = None @@ -2178,26 +2001,16 @@ def default_image_cost_calculator( cost_info = litellm.model_cost[_model] break if cost_info is None: - raise Exception( - f"Model not found in cost map. Tried checking {models_to_check}" - ) + raise Exception(f"Model not found in cost map. Tried checking {models_to_check}") # Priority 1: Use per-image pricing if available (for gpt-image-1 and similar models) - if ( - "input_cost_per_image" in cost_info - and cost_info["input_cost_per_image"] is not None - ): + if "input_cost_per_image" in cost_info and cost_info["input_cost_per_image"] is not None: return cost_info["input_cost_per_image"] * n # Priority 2: Fall back to per-pixel pricing for backward compatibility - elif ( - "input_cost_per_pixel" in cost_info - and cost_info["input_cost_per_pixel"] is not None - ): + elif "input_cost_per_pixel" in cost_info and cost_info["input_cost_per_pixel"] is not None: return cost_info["input_cost_per_pixel"] * height * width * n else: - raise Exception( - f"No pricing information found for model {model}. Tried checking {models_to_check}" - ) + raise Exception(f"No pricing information found for model {model}. Tried checking {models_to_check}") def default_video_cost_calculator( @@ -2234,12 +2047,8 @@ def default_video_cost_calculator( base_model_name = model model_name_without_custom_llm_provider: Optional[str] = None if custom_llm_provider and model.startswith(f"{custom_llm_provider}/"): - model_name_without_custom_llm_provider = model.replace( - f"{custom_llm_provider}/", "" - ) - base_model_name = ( - f"{custom_llm_provider}/{model_name_without_custom_llm_provider}" - ) + model_name_without_custom_llm_provider = model.replace(f"{custom_llm_provider}/", "") + base_model_name = f"{custom_llm_provider}/{model_name_without_custom_llm_provider}" verbose_logger.debug(f"Looking up cost for video model: {base_model_name}") @@ -2299,9 +2108,7 @@ def batch_cost_calculator( deployment-specific pricing is used. """ - _, custom_llm_provider, _, _ = litellm.get_llm_provider( - model=model, custom_llm_provider=custom_llm_provider - ) + _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model, custom_llm_provider=custom_llm_provider) verbose_logger.debug( "Calculating batch cost per token. model=%s, custom_llm_provider=%s", @@ -2311,9 +2118,7 @@ def batch_cost_calculator( if model_info is None: try: - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) except Exception: model_info = None elif not any( @@ -2329,9 +2134,7 @@ def batch_cost_calculator( # but carries no pricing fields. Fall back to the global pricing table so # that standard model pricing is used instead of silently returning $0. try: - global_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + global_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) if global_info: model_info = global_info except Exception: @@ -2358,13 +2161,8 @@ def batch_cost_calculator( # Add cache read cost if applicable details = _parse_prompt_tokens_details(usage) cache_read_tokens = details["cache_hit_tokens"] - cache_read_cost_key = _get_service_tier_cost_key( - "cache_read_input_token_cost", None - ) - total_prompt_cost += ( - calculate_cost_component(model_info, cache_read_cost_key, cache_read_tokens) - / 2 - ) + cache_read_cost_key = _get_service_tier_cost_key("cache_read_input_token_cost", None) + total_prompt_cost += calculate_cost_component(model_info, cache_read_cost_key, cache_read_tokens) / 2 if output_cost_per_token_batches: total_completion_cost = usage.completion_tokens * output_cost_per_token_batches elif output_cost_per_token: @@ -2409,10 +2207,7 @@ def combine_usage_objects(usage_objects: List[Usage]) -> Usage: setattr(combined, attr, current_val + new_val) # Handle nested prompt_tokens_details if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details: - if ( - not hasattr(combined, "prompt_tokens_details") - or not combined.prompt_tokens_details - ): + if not hasattr(combined, "prompt_tokens_details") or not combined.prompt_tokens_details: combined.prompt_tokens_details = PromptTokensDetailsWrapper() # Check what keys exist in the model's prompt_tokens_details @@ -2423,9 +2218,7 @@ def combine_usage_objects(usage_objects: List[Usage]) -> Usage: and not attr.startswith("_") and not callable(getattr(usage.prompt_tokens_details, attr)) ): - current_val = ( - getattr(combined.prompt_tokens_details, attr, 0) or 0 - ) + current_val = getattr(combined.prompt_tokens_details, attr, 0) or 0 new_val = getattr(usage.prompt_tokens_details, attr, 0) or 0 if new_val is not None and isinstance(new_val, (int, float)): setattr( @@ -2435,27 +2228,15 @@ def combine_usage_objects(usage_objects: List[Usage]) -> Usage: ) # Handle nested completion_tokens_details - if ( - hasattr(usage, "completion_tokens_details") - and usage.completion_tokens_details - ): - if ( - not hasattr(combined, "completion_tokens_details") - or not combined.completion_tokens_details - ): - combined.completion_tokens_details = ( - CompletionTokensDetailsWrapper() - ) + if hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details: + if not hasattr(combined, "completion_tokens_details") or not combined.completion_tokens_details: + combined.completion_tokens_details = CompletionTokensDetailsWrapper() # Check what keys exist in the model's completion_tokens_details # Access model_fields on the class, not the instance, to avoid Pydantic 2.11+ deprecation warnings for attr in type(usage.completion_tokens_details).model_fields: - if not attr.startswith("_") and not callable( - getattr(usage.completion_tokens_details, attr) - ): - current_val = ( - getattr(combined.completion_tokens_details, attr, 0) or 0 - ) + if not attr.startswith("_") and not callable(getattr(usage.completion_tokens_details, attr)): + current_val = getattr(combined.completion_tokens_details, attr, 0) or 0 new_val = getattr(usage.completion_tokens_details, attr, 0) or 0 if isinstance(new_val, (int, float)): setattr( @@ -2481,10 +2262,8 @@ def collect_usage_from_realtime_stream_results( ) usage_objects: List[Usage] = [] for result in response_done_events: - usage_object = ( - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - result["response"].get("usage", {}) - ) + usage_object = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( + result["response"].get("usage", {}) ) usage_objects.append(usage_object) return usage_objects @@ -2496,14 +2275,8 @@ def collect_and_combine_usage_from_realtime_stream_results( """ Collect and combine usage from realtime stream results """ - collected_usage_objects = ( - RealtimeAPITokenUsageProcessor.collect_usage_from_realtime_stream_results( - results - ) - ) - combined_usage_object = RealtimeAPITokenUsageProcessor.combine_usage_objects( - collected_usage_objects - ) + collected_usage_objects = RealtimeAPITokenUsageProcessor.collect_usage_from_realtime_stream_results(results) + combined_usage_object = RealtimeAPITokenUsageProcessor.combine_usage_objects(collected_usage_objects) return combined_usage_object @staticmethod @@ -2516,9 +2289,7 @@ def create_logging_realtime_object( ) -_TRANSCRIPTION_COMPLETED_EVENT_TYPE = ( - "conversation.item.input_audio_transcription.completed" -) +_TRANSCRIPTION_COMPLETED_EVENT_TYPE = "conversation.item.input_audio_transcription.completed" def handle_realtime_stream_cost_calculation( @@ -2540,9 +2311,7 @@ def handle_realtime_stream_cost_calculation( potential_model_names = [] for result in results: if result["type"] == "session.created": - received_model = cast(OpenAIRealtimeStreamSessionEvents, result)[ - "session" - ].get("model", None) + received_model = cast(OpenAIRealtimeStreamSessionEvents, result)["session"].get("model", None) potential_model_names.append(received_model) potential_model_names.append(litellm_model_name) @@ -2591,20 +2360,14 @@ def handle_realtime_transcription_cost_calculation( - {"type": "tokens", "input_tokens": ...} → priced via input/audio token cost """ completed_events = [ - cast(dict, result) - for result in results - if result.get("type") == _TRANSCRIPTION_COMPLETED_EVENT_TYPE + cast(dict, result) for result in results if result.get("type") == _TRANSCRIPTION_COMPLETED_EVENT_TYPE ] if not completed_events: return 0.0 - model_name = ( - _get_transcription_model_name_from_results(results) or litellm_model_name - ) + model_name = _get_transcription_model_name_from_results(results) or litellm_model_name try: - model_info = litellm.get_model_info( - model=model_name, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model_name, custom_llm_provider=custom_llm_provider) except Exception: model_info = None @@ -2627,9 +2390,9 @@ def _get_transcription_model_name_from_results( "session.updated", ): session = cast(dict, result).get("session", {}) or {} - transcription = ( - (session.get("audio", {}) or {}).get("input", {}) or {} - ).get("transcription", {}) or session.get("input_audio_transcription", {}) + transcription = ((session.get("audio", {}) or {}).get("input", {}) or {}).get( + "transcription", {} + ) or session.get("input_audio_transcription", {}) model = (transcription or {}).get("model") or session.get("model") if model: return model @@ -2650,15 +2413,9 @@ def _transcription_usage_cost(usage: dict, model_info: Optional[ModelInfo]) -> f text_tokens = input_token_details.get("text_tokens") or 0 output_tokens = usage.get("output_tokens") or 0 audio_cost = float(audio_tokens) * float( - model_info.get("input_cost_per_audio_token") - or model_info.get("input_cost_per_token") - or 0.0 - ) - text_cost = float(text_tokens) * float( - model_info.get("input_cost_per_token") or 0.0 - ) - output_cost = float(output_tokens) * float( - model_info.get("output_cost_per_token") or 0.0 + model_info.get("input_cost_per_audio_token") or model_info.get("input_cost_per_token") or 0.0 ) + text_cost = float(text_tokens) * float(model_info.get("input_cost_per_token") or 0.0) + output_cost = float(output_tokens) * float(model_info.get("output_cost_per_token") or 0.0) return audio_cost + text_cost + output_cost return 0.0 diff --git a/litellm/endpoints/speech/speech_to_completion_bridge/handler.py b/litellm/endpoints/speech/speech_to_completion_bridge/handler.py index 13af0a30fe06..f2b443eb7bf4 100644 --- a/litellm/endpoints/speech/speech_to_completion_bridge/handler.py +++ b/litellm/endpoints/speech/speech_to_completion_bridge/handler.py @@ -29,9 +29,7 @@ def __init__(self): super().__init__() self.transformation_handler = SpeechToCompletionBridgeTransformationHandler() - def validate_input_kwargs( - self, kwargs: dict - ) -> SpeechToCompletionBridgeHandlerInputKwargs: + def validate_input_kwargs(self, kwargs: dict) -> SpeechToCompletionBridgeHandlerInputKwargs: from litellm import LiteLLMLoggingObj model = kwargs.get("model") diff --git a/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py b/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py index 5dce467d4436..94de4878b65e 100644 --- a/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py +++ b/litellm/endpoints/speech/speech_to_completion_bridge/transformation.py @@ -29,9 +29,7 @@ def transform_request( if isinstance(voice, str): passed_optional_params["audio"] = {"voice": voice} if "response_format" in optional_params: - passed_optional_params["audio"]["format"] = optional_params[ - "response_format" - ] + passed_optional_params["audio"]["format"] = optional_params["response_format"] return_kwargs = { "model": model, @@ -53,9 +51,7 @@ def transform_request( return_kwargs = {k: v for k, v in return_kwargs.items() if v is not None} return return_kwargs - def _convert_pcm16_to_wav( - self, pcm_data: bytes, sample_rate: int = 24000, channels: int = 1 - ) -> bytes: + def _convert_pcm16_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, channels: int = 1) -> bytes: """ Convert raw PCM16 data to WAV format. @@ -97,13 +93,9 @@ def _convert_pcm16_to_wav( def _is_gemini_tts_model(self, model: str) -> bool: """Check if the model is a Gemini TTS model that returns PCM16 data.""" - return "gemini" in model.lower() and ( - "tts" in model.lower() or "preview-tts" in model.lower() - ) + return "gemini" in model.lower() and ("tts" in model.lower() or "preview-tts" in model.lower()) - def transform_response( - self, model_response: "ModelResponse" - ) -> "HttpxBinaryResponseContent": + def transform_response(self, model_response: "ModelResponse") -> "HttpxBinaryResponseContent": import base64 import httpx diff --git a/litellm/evals/main.py b/litellm/evals/main.py index df6d3accb829..d4e9d638583c 100644 --- a/litellm/evals/main.py +++ b/litellm/evals/main.py @@ -152,10 +152,8 @@ def create_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -175,9 +173,7 @@ def create_eval( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request request_body = evals_api_provider_config.transform_create_eval_request( @@ -188,9 +184,7 @@ def create_eval( # Get API base and URL api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE - url = evals_api_provider_config.get_complete_url( - api_base=api_base, endpoint="evals" - ) + url = evals_api_provider_config.get_complete_url(api_base=api_base, endpoint="evals") # Pre-call logging litellm_logging_obj.update_from_kwargs( @@ -343,10 +337,8 @@ def list_evals( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -371,9 +363,7 @@ def list_evals( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request url, query_params = evals_api_provider_config.transform_list_evals_request( @@ -513,10 +503,8 @@ def get_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -524,9 +512,7 @@ def get_eval( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -682,10 +668,8 @@ def update_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -732,9 +716,7 @@ def update_eval( "user_agent", } # Only include user-provided metadata keys - filtered_metadata = { - k: v for k, v in metadata.items() if k not in internal_keys - } + filtered_metadata = {k: v for k, v in metadata.items() if k not in internal_keys} if filtered_metadata: # Only add if there's user metadata update_request["metadata"] = filtered_metadata @@ -744,9 +726,7 @@ def update_eval( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -893,10 +873,8 @@ def delete_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -904,9 +882,7 @@ def delete_eval( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -1047,10 +1023,8 @@ def cancel_eval( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1058,9 +1032,7 @@ def cancel_eval( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -1230,10 +1202,8 @@ def create_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1254,9 +1224,7 @@ def create_run( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -1418,10 +1386,8 @@ def list_runs( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1444,9 +1410,7 @@ def list_runs( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request url, query_params = evals_api_provider_config.transform_list_runs_request( @@ -1592,10 +1556,8 @@ def get_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1603,9 +1565,7 @@ def get_run( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -1752,10 +1712,8 @@ def cancel_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1763,9 +1721,7 @@ def cancel_run( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE @@ -1921,10 +1877,8 @@ def delete_run( custom_llm_provider = "openai" # Get provider config - evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ( - ProviderConfigManager.get_provider_evals_api_config( # type: ignore - provider=litellm.LlmProviders(custom_llm_provider), - ) + evals_api_provider_config: Optional[BaseEvalsAPIConfig] = ProviderConfigManager.get_provider_evals_api_config( # type: ignore + provider=litellm.LlmProviders(custom_llm_provider), ) if evals_api_provider_config is None: @@ -1932,9 +1886,7 @@ def delete_run( # Validate environment and get headers headers = extra_headers or {} - headers = evals_api_provider_config.validate_environment( - headers=headers, litellm_params=litellm_params - ) + headers = evals_api_provider_config.validate_environment(headers=headers, litellm_params=litellm_params) # Transform request api_base = litellm_params.api_base or DEFAULT_OPENAI_API_BASE diff --git a/litellm/exceptions.py b/litellm/exceptions.py index 1cbef6b0b49b..d97ba347b079 100644 --- a/litellm/exceptions.py +++ b/litellm/exceptions.py @@ -146,9 +146,7 @@ def __init__( self.num_retries = num_retries self.response = response or httpx.Response( status_code=self.status_code, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), # mock request object + request=httpx.Request(method="GET", url="https://litellm.ai"), # mock request object ) super().__init__( self.message, response=self.response, body=None @@ -192,9 +190,7 @@ def __init__( self.num_retries = num_retries self.response = response or httpx.Response( status_code=self.status_code, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), # mock request object + request=httpx.Request(method="GET", url="https://litellm.ai"), # mock request object ) super().__init__( self.message, response=self.response, body=None @@ -347,9 +343,7 @@ def __init__( method="POST", url="https://api.openai.com/v1", ) - super().__init__( - request=request - ) # Call the base class constructor with the parameters it needs + super().__init__(request=request) # Call the base class constructor with the parameters it needs self.status_code = exception_status_code or 408 self.message = "litellm.Timeout: {}".format(message) self.model = model @@ -438,9 +432,7 @@ def __init__( litellm_debug_info: Optional[str] = None, max_retries: Optional[int] = None, num_retries: Optional[int] = None, - category: Union[str, RateLimitErrorCategory] = ( - RateLimitErrorCategory.VENDOR_RATE_LIMIT - ), + category: Union[str, RateLimitErrorCategory] = (RateLimitErrorCategory.VENDOR_RATE_LIMIT), rate_limit_type: Optional[Union[str, RateLimitType]] = None, headers: Optional[Dict[str, str]] = None, detail: Any = None, @@ -452,16 +444,12 @@ def __init__( self.litellm_debug_info = litellm_debug_info self.max_retries = max_retries self.num_retries = num_retries - self.category = ( - category.value if isinstance(category, RateLimitErrorCategory) else category - ) + self.category = category.value if isinstance(category, RateLimitErrorCategory) else category # Which dimension was exceeded — request count, token count, parallel # requests, budget, max iterations. None when the source didn't # classify the failure (e.g. legacy vendor 429 with no header hints). self.rate_limit_type: Optional[str] = ( - rate_limit_type.value - if isinstance(rate_limit_type, RateLimitType) - else rate_limit_type + rate_limit_type.value if isinstance(rate_limit_type, RateLimitType) else rate_limit_type ) # Headers explicitly attached to the error (e.g. retry-after, # rate_limit_type, reset_at). Preserved across the proxy boundary so @@ -476,12 +464,8 @@ def __init__( # headers stay reachable on `e.response.headers` for callers that # explicitly want them; only the proxy-supplied `headers=` kwarg # makes it onto `self.headers`. - _response_headers = ( - getattr(response, "headers", None) if response is not None else None - ) - self.headers: Optional[Dict[str, str]] = ( - {k: str(v) for k, v in headers.items()} if headers else None - ) + _response_headers = getattr(response, "headers", None) if response is not None else None + self.headers: Optional[Dict[str, str]] = {k: str(v) for k, v in headers.items()} if headers else None # Mirrors FastAPI HTTPException.detail so the same instance can be # serialized through both the ProxyException and HTTPException paths. self.detail = detail if detail is not None else self.message @@ -664,9 +648,7 @@ def __init__( self.litellm_debug_info = litellm_debug_info self.max_retries = max_retries self.num_retries = num_retries - _response_headers = ( - getattr(response, "headers", None) if response is not None else None - ) + _response_headers = getattr(response, "headers", None) if response is not None else None self.response = httpx.Response( status_code=self.status_code, headers=_response_headers, @@ -714,9 +696,7 @@ def __init__( self.litellm_debug_info = litellm_debug_info self.max_retries = max_retries self.num_retries = num_retries - _response_headers = ( - getattr(response, "headers", None) if response is not None else None - ) + _response_headers = getattr(response, "headers", None) if response is not None else None self.response = httpx.Response( status_code=self.status_code, headers=_response_headers, @@ -764,9 +744,7 @@ def __init__( self.litellm_debug_info = litellm_debug_info self.max_retries = max_retries self.num_retries = num_retries - _response_headers = ( - getattr(response, "headers", None) if response is not None else None - ) + _response_headers = getattr(response, "headers", None) if response is not None else None self.response = httpx.Response( status_code=self.status_code, headers=_response_headers, @@ -915,9 +893,7 @@ def __repr__(self): class JSONSchemaValidationError(APIResponseValidationError): - def __init__( - self, model: str, llm_provider: str, raw_response: str, schema: str - ) -> None: + def __init__(self, model: str, llm_provider: str, raw_response: str, schema: str) -> None: self.raw_response = raw_response self.schema = schema self.model = model @@ -953,9 +929,7 @@ def __init__( self.litellm_debug_info = litellm_debug_info response = response or httpx.Response( status_code=self.status_code, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), # mock request object + request=httpx.Request(method="GET", url="https://litellm.ai"), # mock request object ) self.max_retries = max_retries self.num_retries = num_retries @@ -1005,10 +979,7 @@ def __init__( # to match the normalization RateLimitError.__init__ performs. self.category: str = RateLimitErrorCategory.LITELLM_RATE_LIMIT.value self.rate_limit_type: str = RateLimitType.BUDGET.value - message = ( - message - or f"Budget has been exceeded! Current cost: {current_cost}, Max budget: {max_budget}" - ) + message = message or f"Budget has been exceeded! Current cost: {current_cost}, Max budget: {max_budget}" self.message = message super().__init__(message) @@ -1022,9 +993,7 @@ def __init__(self, message, model, llm_provider): self.llm_provider = llm_provider self.response = httpx.Response( status_code=400, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), # mock request object + request=httpx.Request(method="GET", url="https://litellm.ai"), # mock request object ) super().__init__( message=self.message, response=self.response, body=None @@ -1061,9 +1030,7 @@ def __init__(self, model: str, custom_llm_provider: Optional[str] = None): self.message = LiteLLMCommonStrings.llm_provider_not_provided.value.format( model=model, custom_llm_provider=custom_llm_provider ) - super().__init__( - self.message, model=model, llm_provider=custom_llm_provider, response=None - ) + super().__init__(self.message, model=model, llm_provider=custom_llm_provider, response=None) def __str__(self): return self.message @@ -1248,8 +1215,5 @@ def __init__( self.guardrail_name = guardrail_name self.detection_info = detection_info or {} self.sticky_session_routing = sticky_session_routing - self.message = ( - message - or f"Sensitive data detected by {guardrail_name}. Routing to model: {route_to_model}" - ) + self.message = message or f"Sensitive data detected by {guardrail_name}. Routing to model: {route_to_model}" super().__init__(self.message) diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py index 5baa7cbc9c57..831e588e5bab 100644 --- a/litellm/experimental_mcp_client/client.py +++ b/litellm/experimental_mcp_client/client.py @@ -26,9 +26,7 @@ try: import mcp.client.streamable_http as streamable_http_module # type: ignore - streamable_http_client = getattr( - streamable_http_module, "streamable_http_client", None - ) + streamable_http_client = getattr(streamable_http_module, "streamable_http_client", None) except ImportError: pass from mcp.types import CallToolRequestParams as MCPCallToolRequestParams @@ -62,9 +60,7 @@ def to_basic_auth(auth_value: str) -> str: def _strip_header_whitespace(headers: Dict[str, str]) -> Dict[str, str]: return { - (key.strip() if isinstance(key, str) else key): ( - value.strip() if isinstance(value, str) else value - ) + (key.strip() if isinstance(key, str) else key): (value.strip() if isinstance(value, str) else value) for key, value in headers.items() } @@ -107,10 +103,7 @@ def __init__( try: from botocore.credentials import Credentials except ImportError: - raise ImportError( - "Missing botocore to use AWS SigV4 authentication. " - "Run 'pip install boto3'." - ) + 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 @@ -157,9 +150,7 @@ def _assume_role( import boto3 from botocore.credentials import Credentials - session_name = ( - aws_session_name or f"litellm-mcp-{int(__import__('time').time())}" - ) + 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 @@ -178,9 +169,7 @@ def _assume_role( token=sts_creds["SessionToken"], ) - def auth_flow( - self, request: httpx.Request - ) -> Generator[httpx.Request, httpx.Response, None]: + def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]: from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest @@ -282,10 +271,7 @@ def _create_transport_context( ) # HTTP transport (default) if streamable_http_client is None: - raise ImportError( - "streamable_http_client is not available. " - "Please install mcp with HTTP support." - ) + 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) @@ -299,9 +285,7 @@ def _create_transport_context( ) return transport_ctx, http_client - def _get_safe_stdio_env( - self, provided_env: Optional[Dict[str, str]] - ) -> Optional[Dict[str, str]]: + def _get_safe_stdio_env(self, provided_env: Optional[Dict[str, str]]) -> Optional[Dict[str, str]]: """ Return a safe environment for the stdio subprocess. @@ -393,18 +377,12 @@ async def _execute_session_operation( try: await transport_ctx.__aexit__(None, None, None) except BaseException as exit_error: - verbose_logger.debug( - f"Error during transport context exit: {exit_error}" - ) + verbose_logger.debug(f"Error during transport context exit: {exit_error}") root_cause = _first_non_cancelled_cause(exit_error) - if root_cause is not None and isinstance( - in_flight_error, asyncio.CancelledError - ): + if root_cause is not None and isinstance(in_flight_error, asyncio.CancelledError): raise root_cause from in_flight_error - async def run_with_session( - self, operation: Callable[[ClientSession], Awaitable[TSessionResult]] - ) -> TSessionResult: + 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: @@ -412,9 +390,7 @@ async def run_with_session( 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" - ) + verbose_logger.warning("MCP client run_with_session failed for %s", self.server_url or "stdio") raise finally: if http_client is not None: @@ -483,17 +459,11 @@ def factory( """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__}" - ) + verbose_logger.debug(f"MCP client using SSL configuration: {type(ssl_config).__name__}") # The MCP SDK's sse_client and streamable_http_client call this factory without # passing auth=, so the fallback is used: a v2-resolved auth if present, else the # SigV4 aws_auth. Both are None for the common case — no behavior change. - fallback_auth = ( - self._resolved_auth - if self._resolved_auth is not None - else self._aws_auth - ) + fallback_auth = self._resolved_auth if self._resolved_auth is not None else self._aws_auth effective_auth = auth if auth is not None else fallback_auth return httpx.AsyncClient( headers=headers, @@ -515,9 +485,7 @@ async def list_tools(self, raise_on_error: bool = False) -> List[MCPTool]: MCP client (triggering the upstream OAuth flow) rather than masking them as "connected, no tools". """ - verbose_logger.debug( - f"MCP client listing tools from {self.server_url or 'stdio'}" - ) + 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() @@ -526,9 +494,7 @@ async def _list_tools_operation(session: ClientSession): 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}" - ) + 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") @@ -562,13 +528,9 @@ async def call_tool( """ Call an MCP Tool. """ - verbose_logger.info( - f"MCP client calling tool '{call_tool_request_params.name}' with arguments: {call_tool_request_params.arguments}" - ) + verbose_logger.info(f"MCP client calling tool '{call_tool_request_params.name}'") - async def on_progress( - progress: float, total: float | None, message: str | None - ): + 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: " @@ -591,14 +553,10 @@ async def _call_tool_operation(session: ClientSession): 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" - ) + verbose_logger.info(f"MCP client tool call '{call_tool_request_params.name}' completed successfully") return tool_result except asyncio.CancelledError: - verbose_logger.warning( - f"MCP client tool call timed out after {self.timeout}s for {self.server_url}" - ) + verbose_logger.warning(f"MCP client tool call timed out after {self.timeout}s for {self.server_url}") raise except Exception as e: import traceback @@ -623,17 +581,13 @@ async def _call_tool_operation(session: ClientSession): ) # 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 + 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'}" - ) + 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() @@ -667,13 +621,9 @@ async def _list_prompts_operation(session: ClientSession): # Return empty list instead of raising to allow graceful degradation return [] - async def get_prompt( - self, get_prompt_request_params: GetPromptRequestParams - ) -> GetPromptResult: + 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}" - ) + verbose_logger.info(f"MCP client fetching prompt '{get_prompt_request_params.name}'") async def _get_prompt_operation(session: ClientSession): verbose_logger.debug("MCP client sending get_prompt request to session") @@ -684,9 +634,7 @@ async def _get_prompt_operation(session: ClientSession): 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" - ) + 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") @@ -716,9 +664,7 @@ async def _get_prompt_operation(session: ClientSession): 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'}" - ) + 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() @@ -754,9 +700,7 @@ async def _list_resources_operation(session: ClientSession): 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'}" - ) + 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() @@ -764,9 +708,7 @@ async def _list_resource_templates_operation(session: ClientSession): 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 - ] + 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}" ) @@ -802,9 +744,7 @@ async def _read_resource_operation(session: ClientSession): try: read_resource_result = await self.run_with_session(_read_resource_operation) - verbose_logger.info( - f"MCP client read_resource '{url}' completed successfully" - ) + 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") diff --git a/litellm/experimental_mcp_client/tools.py b/litellm/experimental_mcp_client/tools.py index bd42f7e71116..c65b266bd027 100644 --- a/litellm/experimental_mcp_client/tools.py +++ b/litellm/experimental_mcp_client/tools.py @@ -90,9 +90,7 @@ async def load_mcp_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 [transform_mcp_tool_to_openai_tool(mcp_tool=tool) for tool in tools.tools] return tools.tools @@ -148,10 +146,8 @@ async def call_openai_tool( 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, - ) + 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, diff --git a/litellm/files/main.py b/litellm/files/main.py index 582d9d5cdd08..3b359b55fe32 100644 --- a/litellm/files/main.py +++ b/litellm/files/main.py @@ -26,9 +26,7 @@ "manus", "anthropic", ] -FileRetrieveProvider = Literal[ - "openai", "azure", "gemini", "vertex_ai", "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 @@ -91,9 +89,7 @@ def _add_trusted_model_credentials_to_litellm_params( ) -> 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 - ) + litellm_params_dict["_litellm_internal_model_credentials"] = trusted_model_credentials @client @@ -162,9 +158,7 @@ def create_file( _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") - ) + 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") @@ -215,12 +209,7 @@ def create_file( 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 - ), + 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: @@ -264,9 +253,7 @@ def create_file( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_file", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_file", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -405,9 +392,7 @@ def file_retrieve( 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()) - ), + litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), function_id=str(kwargs.get("id") or ""), ) @@ -420,10 +405,7 @@ def file_retrieve( logging_obj=logging_obj, _is_async=_is_async, client=( - client - if client is not None - and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) - else None + client if client is not None and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) else None ), timeout=timeout, ) @@ -510,9 +492,7 @@ def file_delete( try: try: if model is not None: - _, custom_llm_provider, _, _ = get_llm_provider( - model, custom_llm_provider - ) + _, custom_llm_provider, _, _ = get_llm_provider(model, custom_llm_provider) except Exception: pass optional_params = GenericLiteLLMParams(**kwargs) @@ -592,9 +572,7 @@ def file_delete( 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()) - ), + litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), function_id=str(kwargs.get("id") or ""), ) @@ -606,10 +584,7 @@ def file_delete( logging_obj=logging_obj, _is_async=_is_async, client=( - client - if client is not None - and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) - else None + client if client is not None and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) else None ), timeout=timeout, ) @@ -731,9 +706,7 @@ def file_list( 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()) - ), + litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), function_id=str(kwargs.get("id", "")), ) @@ -745,12 +718,7 @@ def file_list( 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 - ), + client=(client if client is not None and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) else None), timeout=timeout, ) return response @@ -794,9 +762,7 @@ def file_list( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="file_list", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="file_list", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -886,9 +852,7 @@ def file_content( try: if model is not None: - _, custom_llm_provider, _, _ = get_llm_provider( - model, custom_llm_provider - ) + _, custom_llm_provider, _, _ = get_llm_provider(model, custom_llm_provider) except Exception: pass @@ -922,9 +886,7 @@ def file_content( chunk_size=chunk_size, optional_params=optional_params, timeout=timeout, - logging_obj=cast( - Optional[LiteLLMLoggingObj], kwargs.get("litellm_logging_obj") - ), + logging_obj=cast(Optional[LiteLLMLoggingObj], kwargs.get("litellm_logging_obj")), _is_async=_is_async, client=client, ) @@ -946,9 +908,7 @@ def file_content( 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()) - ), + litellm_call_id=kwargs.get("litellm_call_id", str(uuid_module.uuid4())), function_id=str(kwargs.get("id") or ""), ) @@ -959,12 +919,7 @@ def file_content( 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 - ), + client=(client if client is not None and isinstance(client, (HTTPHandler, AsyncHTTPHandler)) else None), timeout=timeout, ) return response @@ -1004,18 +959,12 @@ def file_content( 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") + 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" + 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, @@ -1047,9 +996,7 @@ def file_content( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -1095,9 +1042,9 @@ def _wrap_streaming_result( headers=response.headers, ) - response: Union[ - FileContentStreamingResult, Coroutine[Any, Any, FileContentStreamingResult] - ] = FileContentStreamingResult(stream_iterator=iter(()), 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, @@ -1130,9 +1077,7 @@ def _wrap_streaming_result( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) diff --git a/litellm/files/streaming.py b/litellm/files/streaming.py index b7095ce7e2b6..6d84f73dcfe0 100644 --- a/litellm/files/streaming.py +++ b/litellm/files/streaming.py @@ -94,9 +94,7 @@ async def aclose(self) -> None: self._close_completed = True self._logging_completed = True stream_to_close = self.stream_iterator - self.stream_iterator = cast( - Union[Iterator[bytes], AsyncIterator[bytes]], iter(()) - ) + self.stream_iterator = cast(Union[Iterator[bytes], AsyncIterator[bytes]], iter(())) # Shield cleanup from request cancellation so upstream HTTP connections # are released promptly on client disconnects. @@ -115,9 +113,7 @@ def close(self) -> None: self._close_completed = True self._logging_completed = True stream_to_close = self.stream_iterator - self.stream_iterator = cast( - Union[Iterator[bytes], AsyncIterator[bytes]], iter(()) - ) + self.stream_iterator = cast(Union[Iterator[bytes], AsyncIterator[bytes]], iter(())) if hasattr(stream_to_close, "close"): cast(Iterator[bytes], stream_to_close).close() # type: ignore[attr-defined] @@ -134,9 +130,7 @@ def _build_logging_response(self) -> Dict[str, str]: def _sync_hidden_params(self) -> None: litellm_params: dict[str, Any] = {} if self.logging_obj is not None: - litellm_params = ( - self.logging_obj.model_call_details.get("litellm_params", {}) or {} - ) + litellm_params = self.logging_obj.model_call_details.get("litellm_params", {}) or {} if "api_base" not in self._hidden_params and litellm_params.get("api_base"): self._hidden_params["api_base"] = litellm_params["api_base"] @@ -232,12 +226,8 @@ async def _log_failure_async(self, error: Exception) -> None: self._logging_completed = True end_time = datetime.datetime.now() traceback_str = traceback.format_exc() - self.logging_obj.failure_handler( - error, traceback_str, self._start_time, end_time - ) - await self.logging_obj.async_failure_handler( - error, traceback_str, self._start_time, end_time - ) + self.logging_obj.failure_handler(error, traceback_str, self._start_time, end_time) + await self.logging_obj.async_failure_handler(error, traceback_str, self._start_time, end_time) def _log_failure_sync(self, error: Exception) -> None: if self._logging_completed or self.logging_obj is None: @@ -245,6 +235,4 @@ def _log_failure_sync(self, error: Exception) -> None: self._logging_completed = True end_time = datetime.datetime.now() - self.logging_obj.failure_handler( - error, traceback.format_exc(), self._start_time, end_time - ) + self.logging_obj.failure_handler(error, traceback.format_exc(), self._start_time, end_time) diff --git a/litellm/files/types.py b/litellm/files/types.py index ba42a39f6663..6bf7b1a1cc23 100644 --- a/litellm/files/types.py +++ b/litellm/files/types.py @@ -1,8 +1,6 @@ from typing import AsyncIterator, Dict, Iterator, Literal, NamedTuple, Union -FileContentProvider = Literal[ - "openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic", "manus" -] +FileContentProvider = Literal["openai", "azure", "vertex_ai", "bedrock", "hosted_vllm", "anthropic", "manus"] class FileContentStreamingResult(NamedTuple): diff --git a/litellm/files/utils.py b/litellm/files/utils.py index a0df7a89b0f8..3ee4953bfef3 100644 --- a/litellm/files/utils.py +++ b/litellm/files/utils.py @@ -26,24 +26,18 @@ class FilesAPIUtils: """ @staticmethod - def is_batch_jsonl_file( - create_file_data: CreateFileRequest, extracted_file_data: ExtractedFileData - ) -> bool: + def is_batch_jsonl_file(create_file_data: CreateFileRequest, extracted_file_data: ExtractedFileData) -> bool: """ Check if the file is a batch jsonl file """ return ( create_file_data.get("purpose") == "batch" - and FilesAPIUtils.valid_content_type( - extracted_file_data.get("content_type") - ) + and FilesAPIUtils.valid_content_type(extracted_file_data.get("content_type")) and extracted_file_data.get("content") is not None ) @staticmethod - def is_batch_jsonl_request( - create_file_data: CreateFileRequest, content_type: Optional[str] - ) -> bool: + def is_batch_jsonl_request(create_file_data: CreateFileRequest, content_type: Optional[str]) -> bool: """ Batch-jsonl check from metadata only, so the body can stay a streamable Path/handle instead of being read into memory. diff --git a/litellm/fine_tuning/main.py b/litellm/fine_tuning/main.py index 846a8a504a89..8a8a916fa9cf 100644 --- a/litellm/fine_tuning/main.py +++ b/litellm/fine_tuning/main.py @@ -90,9 +90,7 @@ async def acreate_fine_tuning_job( 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 - ) + 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 @@ -126,9 +124,7 @@ async def acreate_fine_tuning_job( raise e -def _build_fine_tuning_job_data( - model, training_file, hyperparameters, suffix, validation_file, integrations, seed -): +def _build_fine_tuning_job_data(model, training_file, hyperparameters, suffix, validation_file, integrations, seed): return FineTuningJobCreate( model=model, training_file=training_file, @@ -245,17 +241,9 @@ def create_fine_tuning_job( ) # 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_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_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -272,9 +260,7 @@ def create_fine_tuning_job( 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 - ) + extra_body = _prepare_azure_extra_body(extra_body, kwargs, azure_specific_hyperparams) create_fine_tuning_job_data_dict = _build_fine_tuning_job_data( model, @@ -303,18 +289,12 @@ def create_fine_tuning_job( 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") + 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" + 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( @@ -344,9 +324,7 @@ def create_fine_tuning_job( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -464,17 +442,9 @@ def cancel_fine_tuning_job( ) # 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_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_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -510,9 +480,7 @@ def cancel_fine_tuning_job( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -633,17 +601,9 @@ def list_fine_tuning_jobs( ) # 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_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_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key @@ -680,9 +640,7 @@ def list_fine_tuning_jobs( response=httpx.Response( status_code=400, content="Unsupported provider", - request=httpx.Request( - method="create_thread", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="create_thread", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) return response @@ -769,17 +727,9 @@ def retrieve_fine_tuning_job( 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") + 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, @@ -794,17 +744,9 @@ def retrieve_fine_tuning_job( ) # 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_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_version = optional_params.api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") # type: ignore api_key = ( optional_params.api_key diff --git a/litellm/google_genai/adapters/handler.py b/litellm/google_genai/adapters/handler.py index 209e03d2bdab..82777fb13783 100644 --- a/litellm/google_genai/adapters/handler.py +++ b/litellm/google_genai/adapters/handler.py @@ -25,14 +25,12 @@ def _prepare_completion_kwargs( """Prepare kwargs for litellm.completion/acompletion""" # Transform generate_content request to completion format - completion_request = ( - GOOGLE_GENAI_ADAPTER.translate_generate_content_to_completion( - model=model, - contents=contents, - config=config, - litellm_params=litellm_params, - **(extra_kwargs or {}), - ) + completion_request = GOOGLE_GENAI_ADAPTER.translate_generate_content_to_completion( + model=model, + contents=contents, + config=config, + litellm_params=litellm_params, + **(extra_kwargs or {}), ) completion_kwargs: Dict[str, Any] = dict(completion_request) @@ -62,15 +60,13 @@ async def async_generate_content_handler( ) -> Union[Dict[str, Any], AsyncIterator[bytes]]: """Handle generate_content call asynchronously using completion adapter""" - completion_kwargs = ( - GenerateContentToCompletionHandler._prepare_completion_kwargs( - model=model, - contents=contents, - config=config, - stream=stream, - litellm_params=litellm_params, - extra_kwargs=kwargs, - ) + completion_kwargs = GenerateContentToCompletionHandler._prepare_completion_kwargs( + model=model, + contents=contents, + config=config, + stream=stream, + litellm_params=litellm_params, + extra_kwargs=kwargs, ) try: @@ -81,10 +77,8 @@ async def async_generate_content_handler( # This can happen in error cases or when stream is not properly supported if not hasattr(completion_response, "__aiter__"): # If it's not a stream, treat it as a regular response - generate_content_response = ( - GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( - cast(ModelResponse, completion_response) - ) + generate_content_response = GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( + cast(ModelResponse, completion_response) ) return generate_content_response else: @@ -97,17 +91,13 @@ async def async_generate_content_handler( raise ValueError("Failed to transform streaming response") else: # Transform completion response back to generate_content format - generate_content_response = ( - GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( - cast(ModelResponse, completion_response) - ) + generate_content_response = GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( + cast(ModelResponse, completion_response) ) return generate_content_response except Exception as e: - raise ValueError( - f"Error calling litellm.acompletion for generate_content: {str(e)}" - ) + raise ValueError(f"Error calling litellm.acompletion for generate_content: {str(e)}") @staticmethod def generate_content_handler( @@ -135,15 +125,13 @@ def generate_content_handler( **kwargs, ) - completion_kwargs = ( - GenerateContentToCompletionHandler._prepare_completion_kwargs( - model=model, - contents=contents, - config=config, - stream=stream, - litellm_params=litellm_params, - extra_kwargs=kwargs, - ) + completion_kwargs = GenerateContentToCompletionHandler._prepare_completion_kwargs( + model=model, + contents=contents, + config=config, + stream=stream, + litellm_params=litellm_params, + extra_kwargs=kwargs, ) try: @@ -154,10 +142,8 @@ def generate_content_handler( # This can happen in error cases or when stream is not properly supported if not hasattr(completion_response, "__iter__"): # If it's not a stream, treat it as a regular response - generate_content_response = ( - GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( - cast(ModelResponse, completion_response) - ) + generate_content_response = GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( + cast(ModelResponse, completion_response) ) return generate_content_response else: @@ -170,14 +156,10 @@ def generate_content_handler( raise ValueError("Failed to transform streaming response") else: # Transform completion response back to generate_content format - generate_content_response = ( - GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( - cast(ModelResponse, completion_response) - ) + generate_content_response = GOOGLE_GENAI_ADAPTER.translate_completion_to_generate_content( + cast(ModelResponse, completion_response) ) return generate_content_response except Exception as e: - raise ValueError( - f"Error calling litellm.completion for generate_content: {str(e)}" - ) + raise ValueError(f"Error calling litellm.completion for generate_content: {str(e)}") diff --git a/litellm/google_genai/adapters/transformation.py b/litellm/google_genai/adapters/transformation.py index d8f9f1feb0b2..02dde12a30d6 100644 --- a/litellm/google_genai/adapters/transformation.py +++ b/litellm/google_genai/adapters/transformation.py @@ -49,17 +49,13 @@ def __next__(self): if self._returned_response: raise StopIteration self._returned_response = True - return GoogleGenAIAdapter().translate_completion_to_generate_content( - self.completion_stream - ) + return GoogleGenAIAdapter().translate_completion_to_generate_content(self.completion_stream) for chunk in self.completion_stream: if chunk == "None" or chunk is None: continue - transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content( - chunk, self - ) + transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content(chunk, self) if transformed_chunk: return transformed_chunk @@ -75,17 +71,13 @@ async def __anext__(self): if self._returned_response: raise StopAsyncIteration self._returned_response = True - return GoogleGenAIAdapter().translate_completion_to_generate_content( - self.completion_stream - ) + return GoogleGenAIAdapter().translate_completion_to_generate_content(self.completion_stream) async for chunk in self.completion_stream: if chunk == "None" or chunk is None: continue - transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content( - chunk, self - ) + transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content(chunk, self) if transformed_chunk: return transformed_chunk @@ -100,13 +92,10 @@ async def __anext__(self): try: # For tool calls with no arguments, accumulated_args will be "", which is not valid JSON. # We default to an empty JSON object in this case. - parsed_args = json.loads( - tool_call_data["arguments"] or "{}" - ) + parsed_args = json.loads(tool_call_data["arguments"] or "{}") function_call_part = { "functionCall": { - "name": tool_call_data["name"] - or "undefined_tool_name", + "name": tool_call_data["name"] or "undefined_tool_name", "args": parsed_args, } } @@ -163,9 +152,7 @@ async def async_google_genai_sse_wrapper(self) -> AsyncIterator[bytes]: yield payload.encode() elif isinstance(chunk, ModelResponseStream): # Transform OpenAI streaming chunk to Google GenAI format - transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content( - chunk, self - ) + transformed_chunk = GoogleGenAIAdapter().translate_streaming_completion_to_generate_content(chunk, self) if isinstance(transformed_chunk, dict): # Only return non-empty chunks payload = f"data: {json.dumps(transformed_chunk)}\n\n" @@ -209,9 +196,7 @@ def translate_generate_content_to_completion( """ # Extract top-level fields from kwargs - system_instruction = kwargs.get("systemInstruction") or kwargs.get( - "system_instruction" - ) + system_instruction = kwargs.get("systemInstruction") or kwargs.get("system_instruction") tools = kwargs.get("tools") tool_config = kwargs.get("toolConfig") or kwargs.get("tool_config") @@ -222,9 +207,7 @@ def translate_generate_content_to_completion( contents_list = contents # Transform contents to OpenAI messages format - messages = self._transform_contents_to_messages( - contents_list, system_instruction=system_instruction - ) + messages = self._transform_contents_to_messages(contents_list, system_instruction=system_instruction) # Create base request as dict (which is compatible with ChatCompletionRequest) completion_request: ChatCompletionRequest = { @@ -271,9 +254,7 @@ def translate_generate_content_to_completion( # Handle tool_config (tool choice) if tool_config: - tool_choice = self._transform_google_genai_tool_config_to_openai( - tool_config - ) + tool_choice = self._transform_google_genai_tool_config_to_openai(tool_config) if tool_choice: completion_request["tool_choice"] = tool_choice @@ -316,9 +297,7 @@ def translate_completion_output_params_streaming( completion_stream: Any, ) -> Union[AsyncIterator[bytes], None]: """Transform streaming completion output to Google GenAI format""" - google_genai_wrapper = GoogleGenAIStreamWrapper( - completion_stream=completion_stream - ) + google_genai_wrapper = GoogleGenAIStreamWrapper(completion_stream=completion_stream) # Return the SSE-wrapped version for proper event formatting return google_genai_wrapper.async_google_genai_sse_wrapper() @@ -374,11 +353,7 @@ def _transform_contents_to_messages( if system_instruction: system_parts = system_instruction.get("parts", []) if system_parts and "text" in system_parts[0]: - messages.append( - ChatCompletionSystemMessage( - role="system", content=system_parts[0]["text"] - ) - ) + messages.append(ChatCompletionSystemMessage(role="system", content=system_parts[0]["text"])) for content in contents: role = content.get("role", "user") @@ -386,9 +361,7 @@ def _transform_contents_to_messages( if role == "user": # Handle user messages with potential function responses - content_parts: List[ - Union[ChatCompletionTextObject, ChatCompletionImageObject] - ] = [] + content_parts: List[Union[ChatCompletionTextObject, ChatCompletionImageObject]] = [] tool_messages: List[ChatCompletionToolMessage] = [] for part in parts: @@ -410,9 +383,7 @@ def _transform_contents_to_messages( ChatCompletionImageObject, { "type": "image_url", - "image_url": { - "url": f"data:{mime_type};base64,{data}" - }, + "image_url": {"url": f"data:{mime_type};base64,{data}"}, }, ) ) @@ -426,11 +397,7 @@ def _transform_contents_to_messages( ) tool_messages.append(tool_message) elif isinstance(part, str): - content_parts.append( - cast( - ChatCompletionTextObject, {"type": "text", "text": part} - ) - ) + content_parts.append(cast(ChatCompletionTextObject, {"type": "text", "text": part})) # Add user message if there's content if content_parts: @@ -441,18 +408,10 @@ def _transform_contents_to_messages( and content_parts[0].get("type") == "text" ): text_part = cast(ChatCompletionTextObject, content_parts[0]) - messages.append( - ChatCompletionUserMessage( - role="user", content=text_part["text"] - ) - ) + messages.append(ChatCompletionUserMessage(role="user", content=text_part["text"])) else: # Use multimodal format (array of content parts) - messages.append( - ChatCompletionUserMessage( - role="user", content=content_parts - ) - ) + messages.append(ChatCompletionUserMessage(role="user", content=content_parts)) # Add tool messages messages.extend(tool_messages) @@ -520,15 +479,13 @@ def translate_completion_to_generate_content( # Handle different choice types (Choices vs StreamingChoices) if isinstance(choice, Choices): if not choice.message: - raise ValueError( - "Invalid completion response: no message found in choice" - ) + raise ValueError("Invalid completion response: no message found in choice") parts = self._transform_openai_message_to_google_genai_parts(choice.message) else: # Fallback for generic choice objects - message_content = getattr(choice, "message", {}).get( + message_content = getattr(choice, "message", {}).get("content", "") or getattr(choice, "delta", {}).get( "content", "" - ) or getattr(choice, "delta", {}).get("content", "") + ) parts = [{"text": message_content}] if message_content else [] # Create Google GenAI format response @@ -536,9 +493,7 @@ def translate_completion_to_generate_content( "candidates": [ { "content": {"parts": parts, "role": "model"}, - "finishReason": self._map_finish_reason( - getattr(choice, "finish_reason", None) - ), + "finishReason": self._map_finish_reason(getattr(choice, "finish_reason", None)), "index": 0, "safetyRatings": [], } @@ -589,9 +544,7 @@ def translate_streaming_completion_to_generate_content( # Handle streaming choice if isinstance(choice, StreamingChoices): if choice.delta: - parts = self._transform_openai_delta_to_google_genai_parts_with_accumulation( - choice.delta, wrapper - ) + parts = self._transform_openai_delta_to_google_genai_parts_with_accumulation(choice.delta, wrapper) else: parts = [] finish_reason = getattr(choice, "finish_reason", None) @@ -610,11 +563,7 @@ def translate_streaming_completion_to_generate_content( "candidates": [ { "content": {"parts": parts, "role": "model"}, - "finishReason": ( - self._map_finish_reason(finish_reason) - if finish_reason - else None - ), + "finishReason": (self._map_finish_reason(finish_reason) if finish_reason else None), "index": 0, "safetyRatings": [], } @@ -660,11 +609,7 @@ def _transform_openai_message_to_google_genai_parts( for tool_call in message.tool_calls: if hasattr(tool_call, "function") and tool_call.function: try: - args = ( - json.loads(tool_call.function.arguments) - if tool_call.function.arguments - else {} - ) + args = json.loads(tool_call.function.arguments) if tool_call.function.arguments else {} except json.JSONDecodeError: args = {} @@ -717,18 +662,14 @@ def _transform_openai_delta_to_google_genai_parts_with_accumulation( # Optimization: Skip chunks that have no new data if not function_name and not args_chunk: - verbose_logger.debug( - f"Skipping empty tool call chunk for index: {tool_call_index}" - ) + verbose_logger.debug(f"Skipping empty tool call chunk for index: {tool_call_index}") continue if function_name: wrapper.accumulated_tool_calls[tool_call_index]["name"] = function_name if args_chunk: - wrapper.accumulated_tool_calls[tool_call_index]["arguments"] += ( - args_chunk - ) + wrapper.accumulated_tool_calls[tool_call_index]["arguments"] += args_chunk # Attempt to parse and emit a complete tool call accumulated_data = wrapper.accumulated_tool_calls[tool_call_index] @@ -744,9 +685,7 @@ def _transform_openai_delta_to_google_genai_parts_with_accumulation( # The part will be created by a later chunk that brings the name. if accumulated_name: # If successful, create the part and clean up - function_call_part = { - "functionCall": {"name": accumulated_name, "args": parsed_args} - } + function_call_part = {"functionCall": {"name": accumulated_name, "args": parsed_args}} parts.append(function_call_part) # Remove the completed tool call from the accumulator diff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.py index d35601c7e13e..8e77c5620948 100644 --- a/litellm/google_genai/main.py +++ b/litellm/google_genai/main.py @@ -103,9 +103,7 @@ def setup_generate_content_call( Returns: GenerateContentSetupResult containing all setup information """ - litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get( - "litellm_logging_obj" - ) + 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 @@ -135,11 +133,11 @@ def setup_generate_content_call( 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), + 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: @@ -163,30 +161,24 @@ def setup_generate_content_call( # 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, - ) + 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" - ) + system_instruction = kwargs.get("systemInstruction") or kwargs.get("system_instruction") # Native top-level REST fields arrive as loose kwargs and are otherwise dropped. native_request_fields: dict[str, object] = { field: kwargs[field] for field in generate_content_provider_config.get_generate_content_request_top_level_fields() if field in kwargs } - 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, - ) + 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 @@ -328,12 +320,8 @@ def generate_content( 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 - ) + 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( @@ -346,9 +334,7 @@ def generate_content( ) # Extract systemInstruction from kwargs to pass to handler - system_instruction = kwargs.get("systemInstruction") or kwargs.get( - "system_instruction" - ) + 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: @@ -375,9 +361,7 @@ def generate_content( litellm_params=setup_result.litellm_params, logging_obj=setup_result.litellm_logging_obj, extra_headers=extra_headers, - extra_body=_merge_native_request_fields( - setup_result.native_request_fields, extra_body - ), + extra_body=_merge_native_request_fields(setup_result.native_request_fields, extra_body), timeout=timeout or request_timeout, _is_async=_is_async, client=kwargs.get("client"), @@ -439,9 +423,7 @@ async def agenerate_content_stream( ) # Extract systemInstruction from kwargs to pass to handler - system_instruction = kwargs.get("systemInstruction") or kwargs.get( - "system_instruction" - ) + 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: @@ -449,17 +431,15 @@ async def agenerate_content_stream( 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, - ) + 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 @@ -474,9 +454,7 @@ async def agenerate_content_stream( litellm_params=setup_result.litellm_params, logging_obj=setup_result.litellm_logging_obj, extra_headers=extra_headers, - extra_body=_merge_native_request_fields( - setup_result.native_request_fields, extra_body - ), + extra_body=_merge_native_request_fields(setup_result.native_request_fields, extra_body), timeout=timeout or request_timeout, _is_async=True, client=kwargs.get("client"), @@ -533,9 +511,7 @@ def generate_content_stream( ) # Extract systemInstruction from kwargs to pass to handler - system_instruction = kwargs.get("systemInstruction") or kwargs.get( - "system_instruction" - ) + 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: @@ -565,9 +541,7 @@ def generate_content_stream( litellm_params=setup_result.litellm_params, logging_obj=setup_result.litellm_logging_obj, extra_headers=extra_headers, - extra_body=_merge_native_request_fields( - setup_result.native_request_fields, extra_body - ), + extra_body=_merge_native_request_fields(setup_result.native_request_fields, extra_body), timeout=timeout or request_timeout, _is_async=_is_async, client=kwargs.get("client"), diff --git a/litellm/google_genai/streaming_iterator.py b/litellm/google_genai/streaming_iterator.py index a8d0e5976f03..900a171640ba 100644 --- a/litellm/google_genai/streaming_iterator.py +++ b/litellm/google_genai/streaming_iterator.py @@ -98,9 +98,7 @@ async def _handle_async_streaming_logging( ) -class GoogleGenAIGenerateContentStreamingIterator( - BaseGoogleGenAIGenerateContentStreamingIterator -): +class GoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContentStreamingIterator): """ Streaming iterator specifically for Google GenAI generate content API. """ @@ -148,14 +146,10 @@ def __aiter__(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" - ) + raise NotImplementedError("Use AsyncGoogleGenAIGenerateContentStreamingIterator for async iteration") -class AsyncGoogleGenAIGenerateContentStreamingIterator( - BaseGoogleGenAIGenerateContentStreamingIterator -): +class AsyncGoogleGenAIGenerateContentStreamingIterator(BaseGoogleGenAIGenerateContentStreamingIterator): """ Async streaming iterator specifically for Google GenAI generate content API. """ diff --git a/litellm/images/main.py b/litellm/images/main.py index 34e77ffe8ab5..17ea9aa177bf 100644 --- a/litellm/images/main.py +++ b/litellm/images/main.py @@ -111,9 +111,7 @@ async def aimage_generation(*args, **kwargs) -> ImageResponse: ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) - _, custom_llm_provider, _, _ = get_llm_provider( - model=model, api_base=kwargs.get("api_base", None) - ) + _, custom_llm_provider, _, _ = get_llm_provider(model=model, api_base=kwargs.get("api_base", None)) # Await normally init_response = await loop.run_in_executor(None, func_with_context) @@ -127,9 +125,7 @@ async def aimage_generation(*args, **kwargs) -> ImageResponse: response = await init_response # type: ignore if response is None: - raise ValueError( - "Unable to get Image Response. Please pass a valid llm_provider." - ) + raise ValueError("Unable to get Image Response. Please pass a valid llm_provider.") return response except Exception as e: @@ -272,15 +268,10 @@ def image_generation( } # model-specific params - pass them straight to the model/provider image_generation_config: Optional[BaseImageGenerationConfig] = None - if ( - custom_llm_provider is not None - and custom_llm_provider in LlmProviders._member_map_.values() - ): - image_generation_config = ( - ProviderConfigManager.get_provider_image_generation_config( - model=base_model or model, - provider=LlmProviders(custom_llm_provider), - ) + if custom_llm_provider is not None and custom_llm_provider in LlmProviders._member_map_.values(): + image_generation_config = ProviderConfigManager.get_provider_image_generation_config( + model=base_model or model, + provider=LlmProviders(custom_llm_provider), ) optional_params = get_optional_params_image_gen( @@ -327,11 +318,7 @@ def image_generation( api_base = api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") - api_version = ( - api_version - or litellm.api_version - or get_secret_str("AZURE_API_VERSION") - ) + api_version = api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") api_key = ( api_key @@ -341,9 +328,7 @@ def image_generation( or get_secret_str("AZURE_API_KEY") ) - azure_ad_token = optional_params.pop( - "azure_ad_token", None - ) or get_secret_str("AZURE_AD_TOKEN") + azure_ad_token = optional_params.pop("azure_ad_token", None) or get_secret_str("AZURE_AD_TOKEN") # Create azure_ad_token_provider from tenant_id, client_id, client_secret if not already provided if azure_ad_token_provider is None: @@ -355,10 +340,7 @@ def image_generation( tenant_id = litellm_params_dict.get("tenant_id") client_id = litellm_params_dict.get("client_id") client_secret = litellm_params_dict.get("client_secret") - azure_scope = ( - litellm_params_dict.get("azure_scope") - or "https://cognitiveservices.azure.com/.default" - ) + azure_scope = litellm_params_dict.get("azure_scope") or "https://cognitiveservices.azure.com/.default" # Create token provider if credentials are available if tenant_id and client_id and client_secret: @@ -413,9 +395,7 @@ def image_generation( litellm.LlmProviders.DASHSCOPE, ): if image_generation_config is None: - raise ValueError( - f"image generation config is not supported for {custom_llm_provider}" - ) + raise ValueError(f"image generation config is not supported for {custom_llm_provider}") # Resolve api_base from litellm.api_base if not explicitly provided _api_base = api_base or litellm.api_base @@ -524,9 +504,7 @@ def image_generation( api_base=api_base, api_key=api_key, ) - elif ( - custom_llm_provider in litellm._custom_providers - ): # Assume custom LLM provider + elif custom_llm_provider in litellm._custom_providers: # Assume custom LLM provider # Get the Custom Handler custom_handler: Optional[CustomLLM] = None for item in litellm.custom_provider_map: @@ -534,9 +512,7 @@ def image_generation( custom_handler = item["custom_handler"] if custom_handler is None: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) ## ROUTE LLM CALL ## if aimg_generation is True: @@ -612,15 +588,11 @@ async def aimage_variation(*args, **kwargs) -> ImageResponse: func_with_context = partial(ctx.run, func) if custom_llm_provider is None and model is not None: - _, custom_llm_provider, _, _ = get_llm_provider( - model=model, api_base=kwargs.get("api_base", None) - ) + _, custom_llm_provider, _, _ = get_llm_provider(model=model, api_base=kwargs.get("api_base", None)) # Await normally init_response = await loop.run_in_executor(None, func_with_context) - if isinstance(init_response, dict) or isinstance( - init_response, ImageResponse - ): ## CACHING SCENARIO + if isinstance(init_response, dict) or isinstance(init_response, ImageResponse): ## CACHING SCENARIO if isinstance(init_response, dict): init_response = ImageResponse(**init_response) response = init_response @@ -793,9 +765,7 @@ def image_edit( _is_async = kwargs.pop("async_call", False) is True # add images / or return a single image - images = ( - image if isinstance(image, list) else ([image] if image is not None else []) - ) + images = image if isinstance(image, list) else ([image] if image is not None else []) headers_from_kwargs = kwargs.get("headers") merged_extra_headers: Dict[str, Any] = {} @@ -822,17 +792,13 @@ def image_edit( custom_handler = item["custom_handler"] if custom_handler is None: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) model_response = ImageResponse() if _is_async: async_custom_client: Optional[AsyncHTTPHandler] = None - if kwargs.get("client") is not None and isinstance( - kwargs.get("client"), AsyncHTTPHandler - ): + if kwargs.get("client") is not None and isinstance(kwargs.get("client"), AsyncHTTPHandler): async_custom_client = kwargs.get("client") return custom_handler.aimage_edit( @@ -849,9 +815,7 @@ def image_edit( ) else: custom_client: Optional[HTTPHandler] = None - if kwargs.get("client") is not None and isinstance( - kwargs.get("client"), HTTPHandler - ): + if kwargs.get("client") is not None and isinstance(kwargs.get("client"), HTTPHandler): custom_client = kwargs.get("client") return custom_handler.image_edit( @@ -881,19 +845,15 @@ def image_edit( local_vars.update(kwargs) # Get ImageEditOptionalRequestParams with only valid parameters image_edit_optional_params: ImageEditOptionalRequestParams = ( - _get_ImageEditRequestUtils().get_requested_image_edit_optional_param( - local_vars - ) + _get_ImageEditRequestUtils().get_requested_image_edit_optional_param(local_vars) ) # Get optional parameters for the responses API - image_edit_request_params: Dict = ( - _get_ImageEditRequestUtils().get_optional_params_image_edit( - model=model, - image_edit_provider_config=image_edit_provider_config, - image_edit_optional_params=image_edit_optional_params, - drop_params=kwargs.get("drop_params"), - additional_drop_params=kwargs.get("additional_drop_params"), - ) + image_edit_request_params: Dict = _get_ImageEditRequestUtils().get_optional_params_image_edit( + model=model, + image_edit_provider_config=image_edit_provider_config, + image_edit_optional_params=image_edit_optional_params, + drop_params=kwargs.get("drop_params"), + additional_drop_params=kwargs.get("additional_drop_params"), ) # Pre Call logging diff --git a/litellm/images/utils.py b/litellm/images/utils.py index 8d3e96f1433e..f0d4c985c012 100644 --- a/litellm/images/utils.py +++ b/litellm/images/utils.py @@ -39,9 +39,7 @@ def get_optional_params_image_edit( for param in additional_drop_params: filtered_optional_params.pop(param, None) - unsupported_params = [ - param for param in filtered_optional_params if param not in supported_params - ] + unsupported_params = [param for param in filtered_optional_params if param not in supported_params] if unsupported_params: if should_drop: @@ -54,9 +52,7 @@ def get_optional_params_image_edit( ) mapped_params = image_edit_provider_config.map_openai_params( - image_edit_optional_params=cast( - ImageEditOptionalRequestParams, filtered_optional_params - ), + image_edit_optional_params=cast(ImageEditOptionalRequestParams, filtered_optional_params), model=model, drop_params=should_drop, ) @@ -77,9 +73,7 @@ def get_requested_image_edit_optional_param( ImageEditOptionalRequestParams instance with only the valid parameters """ valid_keys = get_type_hints(ImageEditOptionalRequestParams).keys() - filtered_params = { - k: v for k, v in params.items() if k in valid_keys and v is not None - } + filtered_params = {k: v for k, v in params.items() if k in valid_keys and v is not None} return cast(ImageEditOptionalRequestParams, filtered_params) @staticmethod @@ -99,9 +93,7 @@ def get_image_content_type(image_data: Any) -> str: # Save current position current_pos = image_data.tell() image_data.seek(0) - bytes_data = image_data.read( - 100 - ) # First 100 bytes are enough for detection + bytes_data = image_data.read(100) # First 100 bytes are enough for detection # Restore position image_data.seek(current_pos) elif isinstance(image_data, BufferedReader): diff --git a/litellm/integrations/SlackAlerting/batching_handler.py b/litellm/integrations/SlackAlerting/batching_handler.py index 828f3eb41758..42f4f562422f 100644 --- a/litellm/integrations/SlackAlerting/batching_handler.py +++ b/litellm/integrations/SlackAlerting/batching_handler.py @@ -40,9 +40,7 @@ def squash_payloads(queue): return squashed -def _print_alerting_payload_warning( - payload: dict, slackAlertingInstance: SlackAlertingType -): +def _print_alerting_payload_warning(payload: dict, slackAlertingInstance: SlackAlertingType): """ Print the payload to the console when slackAlertingInstance.alerting_args.log_to_console is True @@ -70,12 +68,8 @@ async def send_to_webhook(slackAlertingInstance: SlackAlertingType, item, count) data=json.dumps(payload), ) if response.status_code != 200: - verbose_proxy_logger.debug( - f"Error sending slack alert to url={item['url']}. Error={response.text}" - ) + verbose_proxy_logger.debug(f"Error sending slack alert to url={item['url']}. Error={response.text}") except Exception as e: verbose_proxy_logger.debug(f"Error sending slack alert: {str(e)}") finally: - _print_alerting_payload_warning( - payload, slackAlertingInstance=slackAlertingInstance - ) + _print_alerting_payload_warning(payload, slackAlertingInstance=slackAlertingInstance) diff --git a/litellm/integrations/SlackAlerting/hanging_request_check.py b/litellm/integrations/SlackAlerting/hanging_request_check.py index 8c0da9bb4fb6..136b6583f38c 100644 --- a/litellm/integrations/SlackAlerting/hanging_request_check.py +++ b/litellm/integrations/SlackAlerting/hanging_request_check.py @@ -41,8 +41,7 @@ def __init__( # stay cached for at least 1.5x the threshold to guarantee a check # happens after they cross it self.hanging_request_cache_ttl = int( - self.slack_alerting_object.alerting_threshold * 1.5 - + HANGING_ALERT_BUFFER_TIME_SECONDS + self.slack_alerting_object.alerting_threshold * 1.5 + HANGING_ALERT_BUFFER_TIME_SECONDS ) self.hanging_request_cache = InMemoryCache( default_ttl=self.hanging_request_cache_ttl, @@ -62,9 +61,7 @@ async def add_request_to_hanging_request_check( model = request_data.get("model", "") api_base: Optional[str] = None - if request_data.get("deployment", None) is not None and isinstance( - request_data["deployment"], dict - ): + if request_data.get("deployment", None) is not None and isinstance(request_data["deployment"], dict): api_base = litellm.get_api_base( model=model, optional_params=request_data["deployment"].get("litellm_params", {}), @@ -104,9 +101,7 @@ async def send_alerts_for_hanging_requests(self): ) for request_id in hanging_requests: - hanging_request_data: Optional[ - HangingRequestData - ] = await self.hanging_request_cache.async_get_cache( + hanging_request_data: Optional[HangingRequestData] = await self.hanging_request_cache.async_get_cache( key=request_id, ) @@ -116,12 +111,10 @@ async def send_alerts_for_hanging_requests(self): if hanging_request_data.alerted: continue - request_status = ( - await proxy_logging_obj.internal_usage_cache.async_get_cache( - key="request_status:{}".format(hanging_request_data.request_id), - litellm_parent_otel_span=None, - local_only=True, - ) + request_status = await proxy_logging_obj.internal_usage_cache.async_get_cache( + key="request_status:{}".format(hanging_request_data.request_id), + litellm_parent_otel_span=None, + local_only=True, ) # this means the request status was either success or fail # and is not hanging @@ -141,9 +134,7 @@ async def send_alerts_for_hanging_requests(self): ################ # Send the Alert on Slack ################ - await self.send_hanging_request_alert( - hanging_request_data=hanging_request_data - ) + await self.send_hanging_request_alert(hanging_request_data=hanging_request_data) # flag so the entry is skipped on later ticks; one alert per hang, # with the existing TTL still handling cleanup hanging_request_data.alerted = True diff --git a/litellm/integrations/SlackAlerting/slack_alerting.py b/litellm/integrations/SlackAlerting/slack_alerting.py index 35731306b939..e93c650ed97b 100644 --- a/litellm/integrations/SlackAlerting/slack_alerting.py +++ b/litellm/integrations/SlackAlerting/slack_alerting.py @@ -62,9 +62,7 @@ class SlackAlerting(CustomBatchLogger): def __init__( self, internal_usage_cache: Optional[DualCache] = None, - alerting_threshold: Optional[ - float - ] = None, # threshold for slow / hanging llm responses (in seconds) + alerting_threshold: Optional[float] = None, # threshold for slow / hanging llm responses (in seconds) alerting: Optional[List] = [], alert_types: List[AlertType] = DEFAULT_ALERT_TYPES, alert_to_webhook_url: Optional[ @@ -81,12 +79,8 @@ def __init__( self.alerting = alerting self.alert_types = alert_types self.internal_usage_cache = internal_usage_cache or DualCache() - self.async_http_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) - self.alert_to_webhook_url = process_slack_alerting_variables( - alert_to_webhook_url=alert_to_webhook_url - ) + self.async_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) + self.alert_to_webhook_url = process_slack_alerting_variables(alert_to_webhook_url=alert_to_webhook_url) self.is_running = False self.alerting_args = SlackAlertingArgs(**alerting_args) self.default_webhook_url = default_webhook_url @@ -98,9 +92,7 @@ def __init__( self.alert_type_config: Dict[str, AlertTypeConfig] = {} if alert_type_config: for key, val in alert_type_config.items(): - self.alert_type_config[key] = ( - AlertTypeConfig(**val) if isinstance(val, dict) else val - ) + self.alert_type_config[key] = AlertTypeConfig(**val) if isinstance(val, dict) else val self.digest_buckets: Dict[str, DigestEntry] = {} self.digest_lock = asyncio.Lock() super().__init__(**kwargs, flush_lock=self.flush_lock) @@ -130,23 +122,14 @@ def update_values( self.periodic_started = True if alert_type_config is not None: for key, val in alert_type_config.items(): - self.alert_type_config[key] = ( - AlertTypeConfig(**val) if isinstance(val, dict) else val - ) + self.alert_type_config[key] = AlertTypeConfig(**val) if isinstance(val, dict) else val if alert_to_webhook_url is not None: # update the dict if self.alert_to_webhook_url is None: - self.alert_to_webhook_url = process_slack_alerting_variables( - alert_to_webhook_url=alert_to_webhook_url - ) + self.alert_to_webhook_url = process_slack_alerting_variables(alert_to_webhook_url=alert_to_webhook_url) else: - _new_values = ( - process_slack_alerting_variables( - alert_to_webhook_url=alert_to_webhook_url - ) - or {} - ) + _new_values = process_slack_alerting_variables(alert_to_webhook_url=alert_to_webhook_url) or {} self.alert_to_webhook_url.update(_new_values) if llm_router is not None: self.llm_router = llm_router @@ -161,15 +144,11 @@ def _prepare_outage_value_for_cache( # Convert to dict for processing cache_value = dict(outage_value) - if "deployment_ids" in cache_value and isinstance( - cache_value["deployment_ids"], set - ): + if "deployment_ids" in cache_value and isinstance(cache_value["deployment_ids"], set): cache_value["deployment_ids"] = list(cache_value["deployment_ids"]) return cache_value - def _restore_outage_value_from_cache( - self, outage_value: Optional[dict] - ) -> Optional[dict]: + def _restore_outage_value_from_cache(self, outage_value: Optional[dict]) -> Optional[dict]: """ Helper method to restore outage value after retrieving from cache. Converts list objects back to sets for proper handling. @@ -234,9 +213,7 @@ def _get_deployment_latencies_to_alert(self, metadata=None): _deployment_latency_map: Optional[dict] = None try: # try sorting deployments by latency - _deployment_latencies = sorted( - _deployment_latencies.items(), key=lambda x: x[1] - ) + _deployment_latencies = sorted(_deployment_latencies.items(), key=lambda x: x[1]) _deployment_latency_map = dict(_deployment_latencies) except Exception: pass @@ -276,23 +253,13 @@ async def response_taking_too_long_callback( alerting_metadata: dict = {} if time_difference_float > self.alerting_threshold: # add deployment latencies to alert - if ( - kwargs is not None - and "litellm_params" in kwargs - and "metadata" in kwargs["litellm_params"] - ): + if kwargs is not None and "litellm_params" in kwargs and "metadata" in kwargs["litellm_params"]: _metadata: dict = kwargs["litellm_params"]["metadata"] - request_info = _add_key_name_and_team_to_alert( - request_info=request_info, metadata=_metadata - ) + request_info = _add_key_name_and_team_to_alert(request_info=request_info, metadata=_metadata) - _deployment_latency_map = self._get_deployment_latencies_to_alert( - metadata=_metadata - ) + _deployment_latency_map = self._get_deployment_latencies_to_alert(metadata=_metadata) if _deployment_latency_map is not None: - request_info += ( - f"\nAvailable Deployment Latencies\n{_deployment_latency_map}" - ) + request_info += f"\nAvailable Deployment Latencies\n{_deployment_latency_map}" if "alerting_metadata" in _metadata: alerting_metadata = _metadata["alerting_metadata"] @@ -305,9 +272,7 @@ async def response_taking_too_long_callback( api_base=api_base, ) - async def async_update_daily_reports( - self, deployment_metrics: DeploymentMetrics - ) -> int: + async def async_update_daily_reports(self, deployment_metrics: DeploymentMetrics) -> int: """ Store the perf by deployment in cache - Number of failed requests per deployment @@ -338,9 +303,7 @@ async def async_update_daily_reports( ## LATENCY ## if deployment_metrics.latency_per_output_token is not None: await self.internal_usage_cache.async_increment_cache( - key="{}:{}".format( - deployment_metrics.id, SlackAlertingCacheKeys.latency_key.value - ), + key="{}:{}".format(deployment_metrics.id, SlackAlertingCacheKeys.latency_key.value), value=deployment_metrics.latency_per_output_token, parent_otel_span=None, # no attached request, this is a background operation ) @@ -370,13 +333,8 @@ async def send_daily_reports(self, router) -> bool: ids = router.get_model_ids() # get keys - failed_request_keys = [ - "{}:{}".format(id, SlackAlertingCacheKeys.failed_requests_key.value) - for id in ids - ] - latency_keys = [ - "{}:{}".format(id, SlackAlertingCacheKeys.latency_key.value) for id in ids - ] + failed_request_keys = ["{}:{}".format(id, SlackAlertingCacheKeys.failed_requests_key.value) for id in ids] + latency_keys = ["{}:{}".format(id, SlackAlertingCacheKeys.latency_key.value) for id in ids] combined_metrics_keys = failed_request_keys + latency_keys # reduce cache calls @@ -396,18 +354,13 @@ async def send_daily_reports(self, router) -> bool: if all_none: return False - failed_request_values = combined_metrics_values[ - : len(failed_request_keys) - ] # # [1, 2, None, ..] + failed_request_values = combined_metrics_values[: len(failed_request_keys)] # # [1, 2, None, ..] latency_values = combined_metrics_values[len(failed_request_keys) :] # find top 5 failed ## Replace None values with a placeholder value (-1 in this case) placeholder_value = 0 - replaced_failed_values = [ - value if value is not None else placeholder_value - for value in failed_request_values - ] + replaced_failed_values = [value if value is not None else placeholder_value for value in failed_request_values] ## Get the indices of top 5 keys with the highest numerical values (ignoring None and 0 values) top_5_failed = sorted( @@ -415,17 +368,12 @@ async def send_daily_reports(self, router) -> bool: key=lambda i: replaced_failed_values[i], reverse=True, )[:5] - top_5_failed = [ - index for index in top_5_failed if replaced_failed_values[index] > 0 - ] + top_5_failed = [index for index in top_5_failed if replaced_failed_values[index] > 0] # find top 5 slowest # Replace None values with a placeholder value (-1 in this case) placeholder_value = 0 - replaced_slowest_values = [ - value if value is not None else placeholder_value - for value in latency_values - ] + replaced_slowest_values = [value if value is not None else placeholder_value for value in latency_values] # Get the indices of top 5 values with the highest numerical values (ignoring None and 0 values) top_5_slowest = sorted( @@ -433,9 +381,7 @@ async def send_daily_reports(self, router) -> bool: key=lambda i: replaced_slowest_values[i], reverse=True, )[:5] - top_5_slowest = [ - index for index in top_5_slowest if replaced_slowest_values[index] > 0 - ] + top_5_slowest = [index for index in top_5_slowest if replaced_slowest_values[index] > 0] # format alert -> return the litellm model name + api base message = f"\n\nTime: `{time.time()}`s\nHere are today's key metrics 📈: \n\n" @@ -453,14 +399,14 @@ async def send_daily_reports(self, router) -> bool: api_base = litellm.get_api_base( model=deployment_name, - optional_params=( - _deployment["litellm_params"] if _deployment is not None else {} - ), + optional_params=(_deployment["litellm_params"] if _deployment is not None else {}), ) if api_base is None: api_base = "" value = replaced_failed_values[top_5_failed[i]] - message += f"\t{i + 1}. Deployment: `{deployment_name}`, Failed Requests: `{value}`, API Base: `{api_base}`\n" + message += ( + f"\t{i + 1}. Deployment: `{deployment_name}`, Failed Requests: `{value}`, API Base: `{api_base}`\n" + ) message += "\n\n*😅 Top Slowest Deployments:*\n\n" if not top_5_slowest: @@ -474,9 +420,7 @@ async def send_daily_reports(self, router) -> bool: deployment_name = "" api_base = litellm.get_api_base( model=deployment_name, - optional_params=( - _deployment["litellm_params"] if _deployment is not None else {} - ), + optional_params=(_deployment["litellm_params"] if _deployment is not None else {}), ) value = round(replaced_slowest_values[top_5_slowest[i]], 3) message += f"\t{i + 1}. Deployment: `{deployment_name}`, Latency per output token: `{value}s/token`, API Base: `{api_base}`\n\n" @@ -485,9 +429,7 @@ async def send_daily_reports(self, router) -> bool: latency_cache_keys = [(key, 0) for key in latency_keys] failed_request_cache_keys = [(key, 0) for key in failed_request_keys] combined_metrics_cache_keys = latency_cache_keys + failed_request_cache_keys - await self.internal_usage_cache.async_set_cache_pipeline( - cache_list=combined_metrics_cache_keys - ) + await self.internal_usage_cache.async_set_cache_pipeline(cache_list=combined_metrics_cache_keys) message += f"\n\nNext Run is at: `{time.time() + self.alerting_args.daily_report_frequency}`s" @@ -511,9 +453,7 @@ async def response_taking_too_long( if AlertType.llm_requests_hanging not in self.alert_types: return - await self.hanging_request_check.add_request_to_hanging_request_check( - request_data=request_data - ) + await self.hanging_request_check.add_request_to_hanging_request_check(request_data=request_data) async def failed_tracking_alert(self, error_message: str, failing_model: str): """ @@ -686,9 +626,7 @@ def _get_event_and_event_message( if user_info.max_budget is not None: if user_info.spend >= user_info.max_budget: event = "budget_crossed" - event_message += ( - f"Budget Crossed\n Total Budget:`{user_info.max_budget}`" - ) + event_message += f"Budget Crossed\n Total Budget:`{user_info.max_budget}`" elif percent_left <= SLACK_ALERTING_THRESHOLD_5_PERCENT: event = "threshold_crossed" event_message += "5% Threshold Crossed " @@ -755,9 +693,7 @@ async def customer_spend_alert( projected_spend=None, event="spend_tracked", event_group=Litellm_EntityType.END_USER, - event_message="Customer spend tracked. Customer={}, spend={}".format( - end_user_id, response_cost - ), + event_message="Customer spend tracked. Customer={}, spend={}".format(end_user_id, response_cost), ) await self.send_webhook_alert(webhook_event=event) @@ -852,9 +788,9 @@ async def region_outage_alerts( ### UNIQUE CACHE KEY ### cache_key = provider + region_name - outage_value: Optional[ - ProviderRegionOutageModel - ] = await self.internal_usage_cache.async_get_cache(key=cache_key) + outage_value: Optional[ProviderRegionOutageModel] = await self.internal_usage_cache.async_get_cache( + key=cache_key + ) # Convert deployment_ids back to set if it was stored as a list if outage_value is not None: @@ -904,8 +840,7 @@ async def region_outage_alerts( ## MINOR OUTAGE ALERT SENT ## if ( outage_value["minor_alert_sent"] is False - and len(outage_value["alerts"]) - >= self.alerting_args.minor_outage_alert_threshold + and len(outage_value["alerts"]) >= self.alerting_args.minor_outage_alert_threshold and len(_deployment_set) > 1 # make sure it's not just 1 bad deployment ): msg = self._outage_alert_msg_factory( @@ -929,8 +864,7 @@ async def region_outage_alerts( ## MAJOR OUTAGE ALERT SENT ## elif ( outage_value["major_alert_sent"] is False - and len(outage_value["alerts"]) - >= self.alerting_args.major_outage_alert_threshold + and len(outage_value["alerts"]) >= self.alerting_args.major_outage_alert_threshold and len(_deployment_set) > 1 # make sure it's not just 1 bad deployment ): msg = self._outage_alert_msg_factory( @@ -955,9 +889,7 @@ async def region_outage_alerts( ## update cache ## # Convert set to list for JSON serialization cache_value = self._prepare_outage_value_for_cache(outage_value) - await self.internal_usage_cache.async_set_cache( - key=cache_key, value=cache_value - ) + await self.internal_usage_cache.async_set_cache(key=cache_key, value=cache_value) async def outage_alerts( self, @@ -979,9 +911,7 @@ async def outage_alerts( max_alerts_size = 10 """ try: - outage_value: Optional[ - OutageModel - ] = await self.internal_usage_cache.async_get_cache(key=deployment_id) # type: ignore + outage_value: Optional[OutageModel] = await self.internal_usage_cache.async_get_cache(key=deployment_id) # type: ignore if ( getattr(exception, "status_code", None) is None or ( @@ -1004,9 +934,7 @@ async def outage_alerts( model, provider, _, _ = litellm.get_llm_provider(model=model) except Exception: provider = "" - api_base = litellm.get_api_base( - model=model, optional_params=deployment.litellm_params - ) + api_base = litellm.get_api_base(model=model, optional_params=deployment.litellm_params) if outage_value is None: outage_value = OutageModel( @@ -1025,10 +953,7 @@ async def outage_alerts( ) return - if ( - len(outage_value["alerts"]) - < self.alerting_args.max_outage_alert_list_size - ): + if len(outage_value["alerts"]) < self.alerting_args.max_outage_alert_list_size: outage_value["alerts"].append(exception.status_code) # type: ignore else: # prevent memory leaks pass @@ -1038,8 +963,7 @@ async def outage_alerts( ## MINOR OUTAGE ALERT SENT ## if ( outage_value["minor_alert_sent"] is False - and len(outage_value["alerts"]) - >= self.alerting_args.minor_outage_alert_threshold + and len(outage_value["alerts"]) >= self.alerting_args.minor_outage_alert_threshold ): msg = self._outage_alert_msg_factory( alert_type="Minor", @@ -1060,8 +984,7 @@ async def outage_alerts( outage_value["minor_alert_sent"] = True elif ( outage_value["major_alert_sent"] is False - and len(outage_value["alerts"]) - >= self.alerting_args.major_outage_alert_threshold + and len(outage_value["alerts"]) >= self.alerting_args.major_outage_alert_threshold ): msg = self._outage_alert_msg_factory( alert_type="Major", @@ -1084,15 +1007,11 @@ async def outage_alerts( ## update cache ## # Convert set to list for JSON serialization cache_value = self._prepare_outage_value_for_cache(outage_value) - await self.internal_usage_cache.async_set_cache( - key=deployment_id, value=cache_value - ) + await self.internal_usage_cache.async_set_cache(key=deployment_id, value=cache_value) except Exception: pass - async def model_added_alert( - self, model_name: str, litellm_model_name: str, passed_model_info: Any - ): + async def model_added_alert(self, model_name: str, litellm_model_name: str, passed_model_info: Any): base_model_from_user = getattr(passed_model_info, "base_model", None) model_info = {} base_model = "" @@ -1193,14 +1112,10 @@ async def _check_if_using_premium_email_feature( if premium_user is not True: if email_logo_url is not None or email_support_contact is not None: - raise ValueError( - f"Trying to Customize Email Alerting\n {CommonProxyErrors.not_premium_user.value}" - ) + raise ValueError(f"Trying to Customize Email Alerting\n {CommonProxyErrors.not_premium_user.value}") return - async def send_key_created_or_user_invited_email( - self, webhook_event: WebhookEvent - ) -> bool: + async def send_key_created_or_user_invited_email(self, webhook_event: WebhookEvent) -> bool: try: from litellm.proxy.utils import send_email @@ -1213,13 +1128,9 @@ async def send_key_created_or_user_invited_email( return False from litellm.proxy.proxy_server import premium_user, prisma_client - email_logo_url = os.getenv( - "SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None) - ) + email_logo_url = os.getenv("SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None)) email_support_contact = os.getenv("EMAIL_SUPPORT_CONTACT", None) - await self._check_if_using_premium_email_feature( - premium_user, email_logo_url, email_support_contact - ) + await self._check_if_using_premium_email_feature(premium_user, email_logo_url, email_support_contact) if email_logo_url is None: email_logo_url = LITELLM_LOGO_URL if email_support_contact is None: @@ -1228,14 +1139,8 @@ async def send_key_created_or_user_invited_email( event_name = webhook_event.event_message recipient_email = webhook_event.user_email recipient_user_id = webhook_event.user_id - if ( - recipient_email is None - and recipient_user_id is not None - and prisma_client is not None - ): - user_row = await UserRepository(prisma_client).table.find_unique( - where={"user_id": recipient_user_id} - ) + if recipient_email is None and recipient_user_id is not None and prisma_client is not None: + user_row = await UserRepository(prisma_client).table.find_unique(where={"user_id": recipient_user_id}) if user_row is not None: recipient_email = user_row.user_email @@ -1265,9 +1170,7 @@ async def send_key_created_or_user_invited_email( team_id = webhook_event.team_id team_name = "Default Team" if team_id is not None and prisma_client is not None: - team_row = await TeamRepository(prisma_client).table.find_unique( - where={"team_id": team_id} - ) + team_row = await TeamRepository(prisma_client).table.find_unique(where={"team_id": team_id}) if team_row is not None: team_name = team_row.team_alias or "-" email_html_content = USER_INVITED_EMAIL_TEMPLATE.format( @@ -1302,9 +1205,7 @@ async def send_key_created_or_user_invited_email( verbose_proxy_logger.error("Error sending email alert %s", str(e)) return False - async def send_email_alert_using_smtp( - self, webhook_event: WebhookEvent, alert_type: str - ) -> bool: + async def send_email_alert_using_smtp(self, webhook_event: WebhookEvent, alert_type: str) -> bool: """ Sends structured Email alert to an SMTP server @@ -1315,13 +1216,9 @@ async def send_email_alert_using_smtp( from litellm.proxy.proxy_server import premium_user from litellm.proxy.utils import send_email - email_logo_url = os.getenv( - "SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None) - ) + email_logo_url = os.getenv("SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None)) email_support_contact = os.getenv("EMAIL_SUPPORT_CONTACT", None) - await self._check_if_using_premium_email_feature( - premium_user, email_logo_url, email_support_contact - ) + await self._check_if_using_premium_email_feature(premium_user, email_logo_url, email_support_contact) if email_logo_url is None: email_logo_url = LITELLM_LOGO_URL @@ -1334,9 +1231,7 @@ async def send_email_alert_using_smtp( max_budget = webhook_event.max_budget email_html_content = "Alert from LiteLLM Server" if recipient_email is None: - verbose_proxy_logger.error( - "Trying to send email alert to no recipient", extra=webhook_event.dict() - ) + verbose_proxy_logger.error("Trying to send email alert to no recipient", extra=webhook_event.dict()) if webhook_event.event == "budget_crossed": email_html_content = f""" @@ -1404,30 +1299,16 @@ async def send_alert( return # Start periodic flush if not already started - if ( - not self.periodic_started - and self.alerting is not None - and len(self.alerting) > 0 - ): + if not self.periodic_started and self.alerting is not None and len(self.alerting) > 0: asyncio.create_task(self.periodic_flush()) self.periodic_started = True - if ( - "webhook" in self.alerting - and alert_type == "budget_alerts" - and user_info is not None - ): + if "webhook" in self.alerting and alert_type == "budget_alerts" and user_info is not None: await self.send_webhook_alert(webhook_event=user_info) - if ( - "email" in self.alerting - and alert_type == "budget_alerts" - and user_info is not None - ): + if "email" in self.alerting and alert_type == "budget_alerts" and user_info is not None: # only send budget alerts over Email - await self.send_email_alert_using_smtp( - webhook_event=user_info, alert_type=alert_type - ) + await self.send_email_alert_using_smtp(webhook_event=user_info, alert_type=alert_type) if "slack" not in self.alerting: return @@ -1441,13 +1322,8 @@ async def send_alert( _atc = self.alert_type_config.get(alert_type_name_str) if _atc is not None and _atc.digest: # Resolve webhook URL for this alert type (needed for digest entry) - if ( - self.alert_to_webhook_url is not None - and alert_type in self.alert_to_webhook_url - ): - _digest_webhook: Optional[Union[str, List[str]]] = ( - self.alert_to_webhook_url[alert_type] - ) + if self.alert_to_webhook_url is not None and alert_type in self.alert_to_webhook_url: + _digest_webhook: Optional[Union[str, List[str]]] = self.alert_to_webhook_url[alert_type] elif self.default_webhook_url is not None: _digest_webhook = self.default_webhook_url else: @@ -1485,7 +1361,9 @@ async def send_alert( if alert_type == "daily_reports" or alert_type == "new_model_added": formatted_message = alert_type_formatted + message else: - formatted_message = f"{alert_type_formatted}\nLevel: `{level}`\nTimestamp: `{current_time}`\n\nMessage: {message}" + formatted_message = ( + f"{alert_type_formatted}\nLevel: `{level}`\nTimestamp: `{current_time}`\n\nMessage: {message}" + ) if kwargs: for key, value in kwargs.items(): @@ -1497,13 +1375,8 @@ async def send_alert( formatted_message += f"\n\nProxy URL: `{_proxy_base_url}`" # check if we find the slack webhook url in self.alert_to_webhook_url - if ( - self.alert_to_webhook_url is not None - and alert_type in self.alert_to_webhook_url - ): - slack_webhook_url: Optional[Union[str, List[str]]] = ( - self.alert_to_webhook_url[alert_type] - ) + if self.alert_to_webhook_url is not None and alert_type in self.alert_to_webhook_url: + slack_webhook_url: Optional[Union[str, List[str]]] = self.alert_to_webhook_url[alert_type] elif self.default_webhook_url is not None: slack_webhook_url = self.default_webhook_url else: @@ -1543,9 +1416,7 @@ async def async_send_batch(self): squashed_queue = squash_payloads(self.log_queue) tasks = [ - send_to_webhook( - slackAlertingInstance=self, item=item["item"], count=item["count"] - ) + send_to_webhook(slackAlertingInstance=self, item=item["item"], count=item["count"]) for item in squashed_queue.values() ] await asyncio.gather(*tasks) @@ -1645,9 +1516,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti ): completion_tokens = response_obj.usage.completion_tokens # type: ignore if completion_tokens is not None and completion_tokens > 0: - final_value = float( - response_s.total_seconds() / completion_tokens - ) + final_value = float(response_s.total_seconds() / completion_tokens) if isinstance(final_value, timedelta): final_value = final_value.total_seconds() @@ -1692,9 +1561,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti ) if "region_outage_alerts" in self.alert_types: - await self.region_outage_alerts( - exception=kwargs["exception"], deployment_id=model_id - ) + await self.region_outage_alerts(exception=kwargs["exception"], deployment_id=model_id) except Exception: pass @@ -1781,7 +1648,9 @@ async def send_weekly_spend_report( todays_date = datetime.datetime.now().date() start_date = todays_date - datetime.timedelta(days=days) - _event_cache_key = f"weekly_spend_report_sent_{start_date.strftime('%Y-%m-%d')}_{todays_date.strftime('%Y-%m-%d')}" + _event_cache_key = ( + f"weekly_spend_report_sent_{start_date.strftime('%Y-%m-%d')}_{todays_date.strftime('%Y-%m-%d')}" + ) if await self.internal_usage_cache.async_get_cache(key=_event_cache_key): return @@ -1800,9 +1669,7 @@ async def send_weekly_spend_report( _spend_message += "\n*Team Spend Report:*\n" for spend in spend_per_team: _team_spend = round(float(spend["total_spend"]), 4) - _spend_message += ( - f"Team: `{spend['team_alias']}` | Spend: `${_team_spend}`\n" - ) + _spend_message += f"Team: `{spend['team_alias']}` | Spend: `${_team_spend}`\n" if spend_per_tag is not None: _spend_message += "\n*Tag Spend Report:*\n" @@ -1840,9 +1707,7 @@ async def send_monthly_spend_report(self): todays_date = datetime.datetime.now().date() first_day_of_month = todays_date.replace(day=1) _, last_day_of_month = monthrange(todays_date.year, todays_date.month) - last_day_of_month = first_day_of_month + datetime.timedelta( - days=last_day_of_month - 1 - ) + last_day_of_month = first_day_of_month + datetime.timedelta(days=last_day_of_month - 1) _event_cache_key = f"monthly_spend_report_sent_{first_day_of_month.strftime('%Y-%m-%d')}_{last_day_of_month.strftime('%Y-%m-%d')}" if await self.internal_usage_cache.async_get_cache(key=_event_cache_key): @@ -1867,9 +1732,7 @@ async def send_monthly_spend_report(self): _team_spend = float(_team_spend) # round to 4 decimal places _team_spend = round(_team_spend, 4) - _spend_message += ( - f"Team: `{spend['team_alias']}` | Spend: `${_team_spend}`\n" - ) + _spend_message += f"Team: `{spend['team_alias']}` | Spend: `${_team_spend}`\n" if monthly_spend_per_tag is not None: _spend_message += "\n*Tag Spend Report:*\n" @@ -1908,13 +1771,9 @@ async def send_fallback_stats_from_prometheus(self): ) # call prometheuslogger. - falllback_success_info_prometheus = ( - await get_fallback_metric_from_prometheus() - ) + falllback_success_info_prometheus = await get_fallback_metric_from_prometheus() - fallback_message = ( - f"*Fallback Statistics:*\n{falllback_success_info_prometheus}" - ) + fallback_message = f"*Fallback Statistics:*\n{falllback_success_info_prometheus}" await self.send_alert( message=fallback_message, @@ -1969,9 +1828,7 @@ async def send_virtual_key_event_slack( ) except Exception as e: - verbose_proxy_logger.error( - "Error sending send_virtual_key_event_slack %s", e - ) + verbose_proxy_logger.error("Error sending send_virtual_key_event_slack %s", e) return @@ -1982,10 +1839,7 @@ async def _request_is_completed(self, request_data: Optional[dict]) -> bool: if request_data is None: return False - if ( - request_data.get("litellm_status", "") != "success" - and request_data.get("litellm_status", "") != "fail" - ): + if request_data.get("litellm_status", "") != "success" and request_data.get("litellm_status", "") != "fail": ## CHECK IF CACHE IS UPDATED litellm_call_id = request_data.get("litellm_call_id", "") status: Optional[str] = await self.internal_usage_cache.async_get_cache( diff --git a/litellm/integrations/SlackAlerting/utils.py b/litellm/integrations/SlackAlerting/utils.py index e2580768178d..4424bedba81e 100644 --- a/litellm/integrations/SlackAlerting/utils.py +++ b/litellm/integrations/SlackAlerting/utils.py @@ -34,9 +34,7 @@ def process_slack_alerting_variables( if "os.environ/" in webhook_url: _env_value = get_secret(secret_name=webhook_url) if not isinstance(_env_value, str): - raise ValueError( - f"Invalid webhook url value for: {webhook_url}. Got type={type(_env_value)}" - ) + raise ValueError(f"Invalid webhook url value for: {webhook_url}. Got type={type(_env_value)}") _webhook_values.append(_env_value) else: _webhook_values.append(webhook_url) @@ -47,9 +45,7 @@ def process_slack_alerting_variables( if "os.environ/" in webhook_urls: _env_value = get_secret(secret_name=webhook_urls) if not isinstance(_env_value, str): - raise ValueError( - f"Invalid webhook url value for: {webhook_urls}. Got type={type(_env_value)}" - ) + raise ValueError(f"Invalid webhook url value for: {webhook_urls}. Got type={type(_env_value)}") _webhook_value_str = _env_value else: _webhook_value_str = webhook_urls @@ -76,10 +72,7 @@ async def _add_langfuse_trace_id_to_alert( # Only run if langfuse is added as a callback ######################################################### - if ( - request_data is not None - and request_data.get("litellm_logging_obj", None) is not None - ): + if request_data is not None and request_data.get("litellm_logging_obj", None) is not None: trace_id: Optional[str] = None litellm_logging_obj: Logging = request_data["litellm_logging_obj"] @@ -89,9 +82,7 @@ async def _add_langfuse_trace_id_to_alert( break await asyncio.sleep(3) # wait 3s before retrying for trace id ######################################################### - langfuse_object = litellm_logging_obj._get_callback_object( - service_name="langfuse" - ) + langfuse_object = litellm_logging_obj._get_callback_object(service_name="langfuse") if langfuse_object is not None: base_url = langfuse_object.Langfuse.base_url return f"{base_url}/trace/{trace_id}" diff --git a/litellm/integrations/_types/open_inference.py b/litellm/integrations/_types/open_inference.py index 3404df7495fd..8ce3ec6f4926 100644 --- a/litellm/integrations/_types/open_inference.py +++ b/litellm/integrations/_types/open_inference.py @@ -73,15 +73,11 @@ class SpanAttributes: """ Number of tokens in the prompt. """ - LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE = ( - "llm.token_count.prompt_details.cache_write" - ) + LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE = "llm.token_count.prompt_details.cache_write" """ Number of tokens in the prompt that were written to cache. """ - LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ = ( - "llm.token_count.prompt_details.cache_read" - ) + LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ = "llm.token_count.prompt_details.cache_read" """ Number of tokens in the prompt that were read from cache. """ @@ -93,15 +89,11 @@ class SpanAttributes: """ Number of tokens in the completion. """ - LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING = ( - "llm.token_count.completion_details.reasoning" - ) + LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING = "llm.token_count.completion_details.reasoning" """ Number of tokens used for reasoning steps in the completion. """ - LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO = ( - "llm.token_count.completion_details.audio" - ) + LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO = "llm.token_count.completion_details.audio" """ The number of audio input tokens generated by the model """ diff --git a/litellm/integrations/agentops/agentops.py b/litellm/integrations/agentops/agentops.py index 4f17806a6b74..c60e5cb0e2a6 100644 --- a/litellm/integrations/agentops/agentops.py +++ b/litellm/integrations/agentops/agentops.py @@ -65,9 +65,7 @@ def __init__( headers = f"Authorization=Bearer {jwt_token}" if jwt_token else None - otel_config = OpenTelemetryConfig( - exporter="otlp_http", endpoint=config.endpoint, headers=headers - ) + otel_config = OpenTelemetryConfig(exporter="otlp_http", endpoint=config.endpoint, headers=headers) # Initialize OpenTelemetry with our config super().__init__(config=otel_config, callback_name="agentops") diff --git a/litellm/integrations/anthropic_cache_control_hook.py b/litellm/integrations/anthropic_cache_control_hook.py index 296bfb6fc85a..1314fd822556 100644 --- a/litellm/integrations/anthropic_cache_control_hook.py +++ b/litellm/integrations/anthropic_cache_control_hook.py @@ -78,11 +78,7 @@ def get_chat_completion_prompt( # provider transform, where each tool_config point appends at most one # cachePoint to the tools. That block also counts toward Anthropic's # limit, so reserve a slot for it here to leave room. - reserved_blocks = ( - 1 - if any(p.get("location") == "tool_config" for p in remaining_points) - else 0 - ) + reserved_blocks = 1 if any(p.get("location") == "tool_config" for p in remaining_points) else 0 processed_messages = self._apply_message_injections( points=message_points, @@ -111,10 +107,7 @@ def _apply_message_injections( ``max_blocks`` is reached. Injection points are honored in config order, so earlier points win when slots are scarce. """ - used_blocks = sum( - AnthropicCacheControlHook._count_cache_control_blocks(msg) - for msg in messages - ) + used_blocks = sum(AnthropicCacheControlHook._count_cache_control_blocks(msg) for msg in messages) limit_reached = False for point in points: @@ -122,27 +115,21 @@ def _apply_message_injections( limit_reached = True break - control: ChatCompletionCachedContent = point.get( - "control", None - ) or ChatCompletionCachedContent(type="ephemeral") + control: ChatCompletionCachedContent = point.get("control", None) or ChatCompletionCachedContent( + type="ephemeral" + ) - for target_index in AnthropicCacheControlHook._resolve_target_indices( - point=point, messages=messages - ): + for target_index in AnthropicCacheControlHook._resolve_target_indices(point=point, messages=messages): if used_blocks >= max_blocks: limit_reached = True break - if AnthropicCacheControlHook._message_has_cache_control( - messages[target_index] - ): + if AnthropicCacheControlHook._message_has_cache_control(messages[target_index]): # Client already marked this message; don't overwrite it. continue - messages[target_index] = ( - AnthropicCacheControlHook._safe_insert_cache_control_in_message( - messages[target_index], control - ) + messages[target_index] = AnthropicCacheControlHook._safe_insert_cache_control_in_message( + messages[target_index], control ) used_blocks += 1 @@ -190,11 +177,7 @@ def _resolve_target_indices( # Case 2: Target by role targetted_role = point.get("role", None) if targetted_role is not None: - return [ - idx - for idx, msg in enumerate(messages) - if msg.get("role") == targetted_role - ] + return [idx for idx, msg in enumerate(messages) if msg.get("role") == targetted_role] return [] @@ -338,9 +321,7 @@ def get_custom_logger_for_anthropic_cache_control_hook( _init_custom_logger_compatible_class, ) - if AnthropicCacheControlHook.should_use_anthropic_cache_control_hook( - non_default_params - ): + if AnthropicCacheControlHook.should_use_anthropic_cache_control_hook(non_default_params): return _init_custom_logger_compatible_class( logging_integration="anthropic_cache_control_hook", internal_usage_cache=None, diff --git a/litellm/integrations/argilla.py b/litellm/integrations/argilla.py index a362ce7e4d7b..a86b6f9e388c 100644 --- a/litellm/integrations/argilla.py +++ b/litellm/integrations/argilla.py @@ -47,12 +47,8 @@ def __init__( **kwargs, ): if litellm.argilla_transformation_object is None: - raise Exception( - "'litellm.argilla_transformation_object' is required, to log your payload to Argilla." - ) - self.validate_argilla_transformation_object( - litellm.argilla_transformation_object - ) + raise Exception("'litellm.argilla_transformation_object' is required, to log your payload to Argilla.") + self.validate_argilla_transformation_object(litellm.argilla_transformation_object) self.argilla_transformation_object = litellm.argilla_transformation_object self.default_credentials = self.get_credentials_from_env( argilla_api_key=argilla_api_key, @@ -61,30 +57,21 @@ def __init__( ) self.sampling_rate: float = ( float(os.getenv("ARGILLA_SAMPLING_RATE")) # type: ignore - if os.getenv("ARGILLA_SAMPLING_RATE") is not None - and os.getenv("ARGILLA_SAMPLING_RATE").strip().isdigit() # type: ignore + if os.getenv("ARGILLA_SAMPLING_RATE") is not None and os.getenv("ARGILLA_SAMPLING_RATE").strip().isdigit() # type: ignore else 1.0 ) - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) - _batch_size = ( - os.getenv("ARGILLA_BATCH_SIZE", None) or litellm.argilla_batch_size - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) + _batch_size = os.getenv("ARGILLA_BATCH_SIZE", None) or litellm.argilla_batch_size if _batch_size: self.batch_size = int(_batch_size) asyncio.create_task(self.periodic_flush()) self.flush_lock = asyncio.Lock() super().__init__(**kwargs, flush_lock=self.flush_lock) - def validate_argilla_transformation_object( - self, argilla_transformation_object: Dict[str, Any] - ): + def validate_argilla_transformation_object(self, argilla_transformation_object: Dict[str, Any]): if not isinstance(argilla_transformation_object, dict): - raise Exception( - "'argilla_transformation_object' must be a dictionary, to log your payload to Argilla." - ) + raise Exception("'argilla_transformation_object' must be a dictionary, to log your payload to Argilla.") for v in argilla_transformation_object.values(): if v not in SUPPORTED_PAYLOAD_FIELDS: @@ -102,21 +89,11 @@ def get_credentials_from_env( if _credentials_api_key is None: raise Exception("Invalid Argilla API Key given. _credentials_api_key=None.") - _credentials_base_url = ( - argilla_base_url - or os.getenv("ARGILLA_BASE_URL") - or "http://localhost:6900/" - ) + _credentials_base_url = argilla_base_url or os.getenv("ARGILLA_BASE_URL") or "http://localhost:6900/" if _credentials_base_url is None: - raise Exception( - "Invalid Argilla Base URL given. _credentials_base_url=None." - ) + raise Exception("Invalid Argilla Base URL given. _credentials_base_url=None.") - _credentials_dataset_name = ( - argilla_dataset_name - or os.getenv("ARGILLA_DATASET_NAME") - or "litellm-completion" - ) + _credentials_dataset_name = argilla_dataset_name or os.getenv("ARGILLA_DATASET_NAME") or "litellm-completion" if _credentials_dataset_name is None: raise Exception("Invalid Argilla Dataset give. Value=None.") else: @@ -138,19 +115,13 @@ def get_credentials_from_env( ARGILLA_DATASET_NAME=_credentials_dataset_name, ) - def get_chat_messages( - self, payload: StandardLoggingPayload - ) -> List[Dict[str, Any]]: + def get_chat_messages(self, payload: StandardLoggingPayload) -> List[Dict[str, Any]]: payload_messages = payload.get("messages", None) if payload_messages is None: raise Exception("No chat messages found in payload.") - if ( - isinstance(payload_messages, list) - and len(payload_messages) > 0 - and isinstance(payload_messages[0], dict) - ): + if isinstance(payload_messages, list) and len(payload_messages) > 0 and isinstance(payload_messages[0], dict): return payload_messages elif isinstance(payload_messages, dict): return [payload_messages] @@ -166,20 +137,14 @@ def get_str_response(self, payload: StandardLoggingPayload) -> str: if isinstance(response, str): return response elif isinstance(response, dict): - return ( - response.get("choices", [{}])[0].get("message", {}).get("content", "") - ) + return response.get("choices", [{}])[0].get("message", {}).get("content", "") else: raise Exception(f"Invalid response format: {response}") - def _prepare_log_data( - self, kwargs, response_obj, start_time, end_time - ) -> Optional[ArgillaItem]: + def _prepare_log_data(self, kwargs, response_obj, start_time, end_time) -> Optional[ArgillaItem]: try: # Ensure everything in the payload is converted to str - payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if payload is None: raise Exception("Error logging request payload. Payload=none.") @@ -220,13 +185,9 @@ def _send_batch(self): ) if response.status_code >= 300: - verbose_logger.error( - f"Argilla Error: {response.status_code} - {response.text}" - ) + verbose_logger.error(f"Argilla Error: {response.status_code} - {response.text}") else: - verbose_logger.debug( - f"Batch of {len(self.log_queue)} runs successfully created" - ) + verbose_logger.debug(f"Batch of {len(self.log_queue)} runs successfully created") self.log_queue.clear() except Exception: @@ -258,9 +219,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): return self.log_queue.append(data) - verbose_logger.debug( - f"Langsmith, event added to queue. Will flush in {self.flush_interval} seconds..." - ) + verbose_logger.debug(f"Langsmith, event added to queue. Will flush in {self.flush_interval} seconds...") if len(self.log_queue) >= self.batch_size: self._send_batch() @@ -284,9 +243,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti kwargs, response_obj, ) - payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) data = self._prepare_log_data(kwargs, response_obj, start_time, end_time) @@ -312,18 +269,14 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception: - verbose_logger.exception( - "Argilla Layer Error - error logging async success event." - ) + verbose_logger.exception("Argilla Layer Error - error logging async success event.") async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): sampling_rate = self.sampling_rate random_sample = random.random() if random_sample > sampling_rate: verbose_logger.info( - "Skipping Langsmith logging. Sampling rate={}, random_sample={}".format( - sampling_rate, random_sample - ) + "Skipping Langsmith logging. Sampling rate={}, random_sample={}".format(sampling_rate, random_sample) ) return # Skip logging verbose_logger.info("Langsmith Failure Event Logging!") @@ -338,9 +291,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception: - verbose_logger.exception( - "Langsmith Layer Error - error logging async failure event." - ) + verbose_logger.exception("Langsmith Layer Error - error logging async failure event.") async def async_send_batch(self): """ @@ -378,13 +329,9 @@ async def async_send_batch(self): response.raise_for_status() if response.status_code >= 300: - verbose_logger.error( - f"Argilla Error: {response.status_code} - {response.text}" - ) + verbose_logger.error(f"Argilla Error: {response.status_code} - {response.text}") else: - verbose_logger.debug( - "Batch of %s runs successfully created", len(self.log_queue) - ) + verbose_logger.debug("Batch of %s runs successfully created", len(self.log_queue)) except httpx.HTTPStatusError: verbose_logger.exception("Argilla HTTP Error") except Exception: diff --git a/litellm/integrations/arize/__init__.py b/litellm/integrations/arize/__init__.py index bc06c7a51eb1..ab2627801e64 100644 --- a/litellm/integrations/arize/__init__.py +++ b/litellm/integrations/arize/__init__.py @@ -13,22 +13,16 @@ global_arize_config: Optional[dict] = None -def prompt_initializer( - litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec" -) -> "CustomPromptManagement": +def prompt_initializer(litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec") -> "CustomPromptManagement": """ Initialize a prompt from Arize Phoenix. """ - api_key = getattr(litellm_params, "api_key", None) or os.environ.get( - "PHOENIX_API_KEY" - ) + api_key = getattr(litellm_params, "api_key", None) or os.environ.get("PHOENIX_API_KEY") api_base = getattr(litellm_params, "api_base", None) prompt_id = getattr(litellm_params, "prompt_id", None) if not api_key or not api_base: - raise ValueError( - "api_key and api_base are required for Arize Phoenix prompt integration" - ) + raise ValueError("api_key and api_base are required for Arize Phoenix prompt integration") try: arize_prompt_manager = ArizePhoenixPromptManager( @@ -36,9 +30,7 @@ def prompt_initializer( "api_key": api_key, "api_base": api_base, "prompt_id": prompt_id, - **litellm_params.model_dump( - exclude={"api_key", "api_base", "prompt_id"} - ), + **litellm_params.model_dump(exclude={"api_key", "api_base", "prompt_id"}), }, ) diff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.py index 75710e104981..44fd7a0d01a3 100644 --- a/litellm/integrations/arize/_utils.py +++ b/litellm/integrations/arize/_utils.py @@ -48,9 +48,7 @@ def set_messages(span: "Span", kwargs: Dict[str, Any]): for idx, msg in enumerate(messages): prefix = f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}" # Set the role per message. - safe_set_attribute( - span, f"{prefix}.{MessageAttributes.MESSAGE_ROLE}", msg.get("role") - ) + safe_set_attribute(span, f"{prefix}.{MessageAttributes.MESSAGE_ROLE}", msg.get("role")) # Set the content per message. safe_set_attribute( span, @@ -164,9 +162,7 @@ def _set_audio_outputs(span: "Span", response_obj, audio_attrs, span_attrs): audio_transcript = audio_item.get("transcript") if audio_transcript: - safe_set_attribute( - span, f"{audio_attrs.AUDIO_TRANSCRIPT}.{i}", audio_transcript - ) + safe_set_attribute(span, f"{audio_attrs.AUDIO_TRANSCRIPT}.{i}", audio_transcript) def _set_embedding_outputs(span: "Span", response_obj, embedding_attrs, span_attrs): @@ -220,9 +216,7 @@ def _set_structured_outputs(span: "Span", response_obj, msg_attrs, span_attrs): message_content = getattr(first_content, "text", "") message_role = getattr(item, "role", "assistant") safe_set_attribute(span, span_attrs.OUTPUT_VALUE, message_content) - safe_set_attribute( - span, f"{prefix}.{msg_attrs.MESSAGE_CONTENT}", message_content - ) + safe_set_attribute(span, f"{prefix}.{msg_attrs.MESSAGE_CONTENT}", message_content) safe_set_attribute(span, f"{prefix}.{msg_attrs.MESSAGE_ROLE}", message_role) @@ -253,19 +247,11 @@ def _set_usage_outputs(span: "Span", response_obj, span_attrs): if not usage: return - safe_set_attribute( - span, span_attrs.LLM_TOKEN_COUNT_TOTAL, _safe_get(usage, "total_tokens") - ) - completion_tokens = _safe_get(usage, "completion_tokens") or _safe_get( - usage, "output_tokens" - ) + safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_TOTAL, _safe_get(usage, "total_tokens")) + completion_tokens = _safe_get(usage, "completion_tokens") or _safe_get(usage, "output_tokens") if completion_tokens: - safe_set_attribute( - span, span_attrs.LLM_TOKEN_COUNT_COMPLETION, completion_tokens - ) - prompt_tokens = _safe_get(usage, "prompt_tokens") or _safe_get( - usage, "input_tokens" - ) + safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_COMPLETION, completion_tokens) + prompt_tokens = _safe_get(usage, "prompt_tokens") or _safe_get(usage, "input_tokens") if prompt_tokens: safe_set_attribute(span, span_attrs.LLM_TOKEN_COUNT_PROMPT, prompt_tokens) @@ -273,9 +259,7 @@ def _set_usage_outputs(span: "Span", response_obj, span_attrs): # API (Usage) and in `output_tokens_details` for Responses API # (ResponseAPIUsage). Both nested objects may be plain Pydantic models # without `.get`. - token_details = _safe_get(usage, "completion_tokens_details") or _safe_get( - usage, "output_tokens_details" - ) + token_details = _safe_get(usage, "completion_tokens_details") or _safe_get(usage, "output_tokens_details") reasoning_tokens = _safe_get(token_details, "reasoning_tokens") if reasoning_tokens: safe_set_attribute( @@ -291,12 +275,8 @@ def _set_usage_outputs(span: "Span", response_obj, span_attrs): # `cache_creation_input_tokens` # All emits are conditional, so when none of these fields exist (the # situation in the existing test fixtures) no extra attributes are set. - prompt_token_details = _safe_get(usage, "prompt_tokens_details") or _safe_get( - usage, "input_tokens_details" - ) - cache_read = _safe_get(prompt_token_details, "cached_tokens") or _safe_get( - usage, "cache_read_input_tokens" - ) + prompt_token_details = _safe_get(usage, "prompt_tokens_details") or _safe_get(usage, "input_tokens_details") + cache_read = _safe_get(prompt_token_details, "cached_tokens") or _safe_get(usage, "cache_read_input_tokens") if cache_read: safe_set_attribute( span, @@ -374,33 +354,24 @@ def _infer_open_inference_span_kind(call_type: Optional[str]) -> str: ): return OpenInferenceSpanKindValues.LLM.value - if any( - keyword in lowered - for keyword in ("file", "batch", "container", "fine_tuning_job") - ): + if any(keyword in lowered for keyword in ("file", "batch", "container", "fine_tuning_job")): return OpenInferenceSpanKindValues.CHAIN.value return OpenInferenceSpanKindValues.UNKNOWN.value -def _set_tool_attributes( - span: "Span", optional_tools: Optional[list], metadata_tools: Optional[list] -): +def _set_tool_attributes(span: "Span", optional_tools: Optional[list], metadata_tools: Optional[list]): """set tool attributes on span from optional_params or tool call metadata""" if optional_tools: for idx, tool in enumerate(optional_tools): if not isinstance(tool, dict): continue - function = ( - tool.get("function") if isinstance(tool.get("function"), dict) else None - ) + function = tool.get("function") if isinstance(tool.get("function"), dict) else None if not function: continue tool_name = function.get("name") if tool_name: - safe_set_attribute( - span, f"{SpanAttributes.LLM_TOOLS}.{idx}.name", tool_name - ) + safe_set_attribute(span, f"{SpanAttributes.LLM_TOOLS}.{idx}.name", tool_name) tool_description = function.get("description") if tool_description: safe_set_attribute( @@ -437,9 +408,7 @@ def _set_tool_attributes( ) -def set_attributes( - span: "Span", kwargs, response_obj, attributes: Type[BaseLLMObsOTELAttributes] -): +def set_attributes(span: "Span", kwargs, response_obj, attributes: Type[BaseLLMObsOTELAttributes]): """ Populates span with OpenInference-compliant LLM attributes for Arize and Phoenix tracing. """ @@ -458,17 +427,11 @@ def set_attributes( try: optional_params = _sanitize_optional_params(kwargs.get("optional_params")) litellm_params = kwargs.get("litellm_params", {}) or {} - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: raise ValueError("standard_logging_object not found in kwargs") - metadata = ( - standard_logging_payload.get("metadata") - if standard_logging_payload - else None - ) + metadata = standard_logging_payload.get("metadata") if standard_logging_payload else None _set_metadata_attributes(span, metadata, SpanAttributes) metadata_tools = _extract_metadata_tools(metadata) @@ -492,19 +455,13 @@ def set_attributes( _set_tool_attributes(span, optional_tools, metadata_tools) attributes.set_messages(span, kwargs) - model_params = ( - standard_logging_payload.get("model_parameters") - if standard_logging_payload - else None - ) + model_params = standard_logging_payload.get("model_parameters") if standard_logging_payload else None _set_model_params(span, model_params, SpanAttributes) _set_response_attributes(span=span, response_obj=response_obj_for_attrs) except Exception as e: - verbose_logger.error( - f"[Arize/Phoenix] Failed to set OpenInference span attributes: {e}" - ) + verbose_logger.error(f"[Arize/Phoenix] Failed to set OpenInference span attributes: {e}") if hasattr(span, "record_exception"): span.record_exception(e) @@ -562,9 +519,7 @@ def _set_request_attributes( if kwargs.get("model"): safe_set_attribute(span, span_attrs.LLM_MODEL_NAME, kwargs.get("model")) - safe_set_attribute( - span, "llm.request.type", standard_logging_payload.get("call_type") - ) + safe_set_attribute(span, "llm.request.type", standard_logging_payload.get("call_type")) safe_set_attribute( span, span_attrs.LLM_PROVIDER, @@ -572,19 +527,13 @@ def _set_request_attributes( ) if optional_params.get("max_tokens"): - safe_set_attribute( - span, "llm.request.max_tokens", optional_params.get("max_tokens") - ) + safe_set_attribute(span, "llm.request.max_tokens", optional_params.get("max_tokens")) if optional_params.get("temperature"): - safe_set_attribute( - span, "llm.request.temperature", optional_params.get("temperature") - ) + safe_set_attribute(span, "llm.request.temperature", optional_params.get("temperature")) if optional_params.get("top_p"): safe_set_attribute(span, "llm.request.top_p", optional_params.get("top_p")) - safe_set_attribute( - span, "llm.is_streaming", str(optional_params.get("stream", False)) - ) + safe_set_attribute(span, "llm.is_streaming", str(optional_params.get("stream", False))) if optional_params.get("user"): safe_set_attribute(span, "llm.user", optional_params.get("user")) @@ -599,9 +548,7 @@ def _set_model_params(span: "Span", model_params: Optional[dict], span_attrs) -> if not model_params: return - safe_set_attribute( - span, span_attrs.LLM_INVOCATION_PARAMETERS, safe_dumps(model_params) - ) + safe_set_attribute(span, span_attrs.LLM_INVOCATION_PARAMETERS, safe_dumps(model_params)) if model_params.get("user"): user_id = model_params.get("user") if user_id is not None: @@ -767,9 +714,7 @@ def _emit_message_tool_calls(span: "Span", prefix: str, message) -> None: continue tc_prefix = f"{prefix}.{MessageAttributes.MESSAGE_TOOL_CALLS}.{tc_idx}" if tc["id"]: - safe_set_attribute( - span, f"{tc_prefix}.{ToolCallAttributes.TOOL_CALL_ID}", tc["id"] - ) + safe_set_attribute(span, f"{tc_prefix}.{ToolCallAttributes.TOOL_CALL_ID}", tc["id"]) fn = tc["function"] if fn["name"]: safe_set_attribute( @@ -862,9 +807,7 @@ def _emit_input_message_extras(span: "Span", prefix: str, message: dict) -> None ) -def _set_session_and_user_attrs( - span: "Span", kwargs: dict, standard_logging_payload -) -> None: +def _set_session_and_user_attrs(span: "Span", kwargs: dict, standard_logging_payload) -> None: """Emit `SESSION_ID` / `USER_ID` / team metadata when source data exists. `SESSION_ID` is emitted only when an explicit end-user identifier exists @@ -970,11 +913,7 @@ def _maybe_normalize_passthrough( passthrough I/O (with central redaction) for free and this helper's `complete_input_dict` fallback can be deleted. See follow-up issue. """ - call_type = ( - standard_logging_payload.get("call_type") - if isinstance(standard_logging_payload, dict) - else None - ) + call_type = standard_logging_payload.get("call_type") if isinstance(standard_logging_payload, dict) else None if not _is_passthrough_call_type(call_type): return @@ -989,18 +928,12 @@ def _maybe_normalize_passthrough( # --- INPUT -------------------------------------------------------------- additional_args = kwargs.get("additional_args") or {} - complete_input_dict = ( - additional_args.get("complete_input_dict") - if isinstance(additional_args, dict) - else None - ) + complete_input_dict = additional_args.get("complete_input_dict") if isinstance(additional_args, dict) else None if isinstance(complete_input_dict, dict): _set_passthrough_input_attributes(span, complete_input_dict.get("messages")) # --- OUTPUT ------------------------------------------------------------- - parsed_response = _parse_passthrough_response( - raw_response_obj, coerced_response_obj, kwargs - ) + parsed_response = _parse_passthrough_response(raw_response_obj, coerced_response_obj, kwargs) if not isinstance(parsed_response, dict): return @@ -1094,19 +1027,12 @@ def _parse_passthrough_response(raw_response_obj, coerced_response_obj, kwargs): candidates = [] if isinstance(coerced_response_obj, dict): candidates.append(coerced_response_obj) - if ( - isinstance(raw_response_obj, dict) - and raw_response_obj is not coerced_response_obj - ): + if isinstance(raw_response_obj, dict) and raw_response_obj is not coerced_response_obj: candidates.append(raw_response_obj) for candidate in candidates: # StandardPassThroughResponseObject wrapper: {"response": "..."}. - if ( - "response" in candidate - and "content" not in candidate - and "choices" not in candidate - ): + if "response" in candidate and "content" not in candidate and "choices" not in candidate: inner = candidate.get("response") if isinstance(inner, str): try: diff --git a/litellm/integrations/arize/arize.py b/litellm/integrations/arize/arize.py index fe2f9f41f1b8..e5fdb2319333 100644 --- a/litellm/integrations/arize/arize.py +++ b/litellm/integrations/arize/arize.py @@ -195,20 +195,14 @@ def construct_dynamic_otel_headers( # the suggested param is `arize_space_key` ######################################################### if standard_callback_dynamic_params.get("arize_space_id"): - dynamic_headers["arize-space-id"] = standard_callback_dynamic_params.get( - "arize_space_id" - ) + dynamic_headers["arize-space-id"] = standard_callback_dynamic_params.get("arize_space_id") if standard_callback_dynamic_params.get("arize_space_key"): - dynamic_headers["arize-space-id"] = standard_callback_dynamic_params.get( - "arize_space_key" - ) + dynamic_headers["arize-space-id"] = standard_callback_dynamic_params.get("arize_space_key") ######################################################### # `api_key` handling ######################################################### if standard_callback_dynamic_params.get("arize_api_key"): - dynamic_headers["api_key"] = standard_callback_dynamic_params.get( - "arize_api_key" - ) + dynamic_headers["api_key"] = standard_callback_dynamic_params.get("arize_api_key") return dynamic_headers diff --git a/litellm/integrations/arize/arize_phoenix.py b/litellm/integrations/arize/arize_phoenix.py index d48dba8e7bb3..db7aed1a71c2 100644 --- a/litellm/integrations/arize/arize_phoenix.py +++ b/litellm/integrations/arize/arize_phoenix.py @@ -118,9 +118,7 @@ def flush_tracer_providers(self) -> None: try: provider.force_flush() except Exception as e: - verbose_logger.debug( - "ArizePhoenixLogger: TracerProvider force_flush failed: %s", e - ) + verbose_logger.debug("ArizePhoenixLogger: TracerProvider force_flush failed: %s", e) def _get_litellm_resource_for_project(self, project_name: str): """ @@ -149,9 +147,7 @@ def _build_tracer_provider_for_project(self, project_name: str) -> TracerProvide """Create a TracerProvider for *project_name* (caller holds no cache lock).""" from opentelemetry.sdk.trace import TracerProvider - provider = TracerProvider( - resource=self._get_litellm_resource_for_project(project_name) - ) + provider = TracerProvider(resource=self._get_litellm_resource_for_project(project_name)) provider.add_span_processor(self._shared_span_processor) return provider @@ -163,9 +159,7 @@ def _get_tracer_for(self, project_name: str) -> Tracer: with self._project_providers_lock: if project_name in self._project_providers: self._project_providers.move_to_end(project_name) - return self._project_providers[project_name].get_tracer( - LITELLM_TRACER_NAME - ) + return self._project_providers[project_name].get_tracer(LITELLM_TRACER_NAME) # OTELResourceDetector().detect() is synchronous; build outside the lock so # concurrent requests for other projects are not blocked on cache misses. @@ -174,9 +168,7 @@ def _get_tracer_for(self, project_name: str) -> Tracer: with self._project_providers_lock: if project_name in self._project_providers: self._project_providers.move_to_end(project_name) - return self._project_providers[project_name].get_tracer( - LITELLM_TRACER_NAME - ) + return self._project_providers[project_name].get_tracer(LITELLM_TRACER_NAME) if len(self._project_providers) >= _MAX_PROJECT_PROVIDERS: self._project_providers.popitem(last=False) @@ -241,14 +233,10 @@ def _is_proxy_request(kwargs: dict) -> bool: detection to route their telemetry into arbitrary Arize/Phoenix projects. """ litellm_params = kwargs.get("litellm_params") - return isinstance(litellm_params, dict) and bool( - litellm_params.get("proxy_server_request") - ) + return isinstance(litellm_params, dict) and bool(litellm_params.get("proxy_server_request")) @staticmethod - def _project_from_metadata_dict( - metadata: dict, metadata_key: str, *, proxy_mode: bool - ) -> Optional[str]: + def _project_from_metadata_dict(metadata: dict, metadata_key: str, *, proxy_mode: bool) -> Optional[str]: """ Read a Phoenix project field from proxy/SDK metadata. @@ -258,25 +246,19 @@ def _project_from_metadata_dict( """ auth_metadata = metadata.get("user_api_key_auth_metadata") if isinstance(auth_metadata, dict): - project = ArizePhoenixLogger._normalize_project_name( - auth_metadata.get(metadata_key) - ) + project = ArizePhoenixLogger._normalize_project_name(auth_metadata.get(metadata_key)) if project: return project if not proxy_mode: - return ArizePhoenixLogger._normalize_project_name( - metadata.get(metadata_key) - ) + return ArizePhoenixLogger._normalize_project_name(metadata.get(metadata_key)) return None @staticmethod def _metadata_project_from_kwargs(kwargs: dict, metadata_key: str) -> Optional[str]: proxy_mode = ArizePhoenixLogger._is_proxy_request(kwargs) for metadata in ArizePhoenixLogger._iter_metadata_dicts_from_kwargs(kwargs): - project = ArizePhoenixLogger._project_from_metadata_dict( - metadata, metadata_key, proxy_mode=proxy_mode - ) + project = ArizePhoenixLogger._project_from_metadata_dict(metadata, metadata_key, proxy_mode=proxy_mode) if project: return project return None @@ -290,21 +272,16 @@ def _resolve_project_name(kwargs: dict) -> str: ``user_api_key_auth_metadata.phoenix_project_name``, env, then ``default``. SDK priority: request metadata fields, then env, then ``default``. """ - override = ArizePhoenixLogger._metadata_project_from_kwargs( - kwargs, "phoenix_project_name_override" - ) + override = ArizePhoenixLogger._metadata_project_from_kwargs(kwargs, "phoenix_project_name_override") if override: return override - phoenix_name = ArizePhoenixLogger._metadata_project_from_kwargs( - kwargs, "phoenix_project_name" - ) + phoenix_name = ArizePhoenixLogger._metadata_project_from_kwargs(kwargs, "phoenix_project_name") if phoenix_name: return phoenix_name env_name = ArizePhoenixLogger._normalize_project_name( - os.environ.get("PHOENIX_PROJECT_NAME") - or os.environ.get("ARIZE_PROJECT_NAME") + os.environ.get("PHOENIX_PROJECT_NAME") or os.environ.get("ARIZE_PROJECT_NAME") ) if env_name: return env_name @@ -335,11 +312,7 @@ def _get_phoenix_context(self, kwargs, tracer: Optional[Tracer] = None): proxy_server_request = litellm_params.get("proxy_server_request", {}) or {} headers = proxy_server_request.get("headers", {}) or {} - traceparent_ctx = ( - self.get_traceparent_from_header(headers=headers) - if headers.get("traceparent") - else None - ) + traceparent_ctx = self.get_traceparent_from_header(headers=headers) if headers.get("traceparent") else None is_proxy_mode = bool(proxy_server_request) @@ -347,9 +320,7 @@ def _get_phoenix_context(self, kwargs, tracer: Optional[Tracer] = None): start_time_val = kwargs.get("start_time", kwargs.get("api_call_start_time")) parent_span = tracer.start_span( name="litellm_proxy_request", - start_time=( - self._to_ns(start_time_val) if start_time_val is not None else None - ), + start_time=(self._to_ns(start_time_val) if start_time_val is not None else None), context=traceparent_ctx, kind=self.span_kind.SERVER, ) @@ -359,14 +330,10 @@ def _get_phoenix_context(self, kwargs, tracer: Optional[Tracer] = None): return traceparent_ctx, None def _handle_success(self, kwargs, response_obj, start_time, end_time): - self._handle_phoenix_trace( - kwargs, response_obj, start_time, end_time, success=True - ) + self._handle_phoenix_trace(kwargs, response_obj, start_time, end_time, success=True) def _handle_failure(self, kwargs, response_obj, start_time, end_time): - self._handle_phoenix_trace( - kwargs, response_obj, start_time, end_time, success=False - ) + self._handle_phoenix_trace(kwargs, response_obj, start_time, end_time, success=False) def _handle_phoenix_trace( self, @@ -402,9 +369,7 @@ def _handle_phoenix_trace( self._record_exception_on_span(span=span, kwargs=kwargs) if success: - self._maybe_log_raw_request( - kwargs, response_obj, start_time, end_time, span - ) + self._maybe_log_raw_request(kwargs, response_obj, start_time, end_time, span) span.end(end_time=self._to_ns(end_time)) self._create_guardrail_span(kwargs=kwargs, context=ctx) @@ -471,9 +436,7 @@ def get_arize_phoenix_config() -> ArizePhoenixConfig: if api_key is not None: otlp_auth_headers = f"Authorization=Bearer {api_key}" elif "app.phoenix.arize.com" in endpoint: - raise ValueError( - "PHOENIX_API_KEY must be set when using Phoenix Cloud (app.phoenix.arize.com)." - ) + raise ValueError("PHOENIX_API_KEY must be set when using Phoenix Cloud (app.phoenix.arize.com).") project_name = os.environ.get("PHOENIX_PROJECT_NAME") or "default" diff --git a/litellm/integrations/arize/arize_phoenix_client.py b/litellm/integrations/arize/arize_phoenix_client.py index 8c3c2a5ff0f5..7c0715d2e1e4 100644 --- a/litellm/integrations/arize/arize_phoenix_client.py +++ b/litellm/integrations/arize/arize_phoenix_client.py @@ -11,9 +11,7 @@ def _sanitize_id(identifier: str) -> str: """Reject path traversal characters and URL-encode the identifier.""" if any(c in identifier for c in ("/", "\\", "#", "?")): - raise ValueError( - f"Invalid identifier {identifier!r}: contains disallowed characters" - ) + raise ValueError(f"Invalid identifier {identifier!r}: contains disallowed characters") if ".." in identifier: raise ValueError(f"Invalid identifier {identifier!r}: path traversal detected") return urllib.parse.quote(identifier, safe="") @@ -87,17 +85,11 @@ def get_prompt_version(self, prompt_version_id: str) -> Optional[Dict[str, Any]] f"Access denied to prompt version '{prompt_version_id}'. Check your Arize Phoenix permissions." ) elif response.status_code == 401: - raise Exception( - "Authentication failed. Check your Arize Phoenix API key and permissions." - ) + raise Exception("Authentication failed. Check your Arize Phoenix API key and permissions.") else: - raise Exception( - f"Failed to fetch prompt version '{prompt_version_id}': {e}" - ) + raise Exception(f"Failed to fetch prompt version '{prompt_version_id}': {e}") else: - raise Exception( - f"Error fetching prompt version '{prompt_version_id}': {e}" - ) + raise Exception(f"Error fetching prompt version '{prompt_version_id}': {e}") def test_connection(self) -> bool: """ diff --git a/litellm/integrations/arize/arize_phoenix_prompt_manager.py b/litellm/integrations/arize/arize_phoenix_prompt_manager.py index df56d7bd391c..4053b725a0f9 100644 --- a/litellm/integrations/arize/arize_phoenix_prompt_manager.py +++ b/litellm/integrations/arize/arize_phoenix_prompt_manager.py @@ -44,9 +44,7 @@ def __init__( self.template_format = metadata.get("template_format", "MUSTACHE") def __repr__(self): - return ( - f"ArizePhoenixPromptTemplate(id='{self.template_id}', model='{self.model}')" - ) + return f"ArizePhoenixPromptTemplate(id='{self.template_id}', model='{self.model}')" class ArizePhoenixTemplateManager: @@ -71,9 +69,7 @@ def __init__( self.api_base = api_base self.prompt_id = prompt_id self.prompts: Dict[str, ArizePhoenixPromptTemplate] = {} - self.arize_client = ArizePhoenixClient( - api_key=self.api_key, api_base=self.api_base - ) + self.arize_client = ArizePhoenixClient(api_key=self.api_key, api_base=self.api_base) # Templates fetched from Arize Phoenix come from external workspace # users; in a plain `Environment()` a malicious template could reach @@ -109,13 +105,9 @@ def _load_prompt_from_arize(self, prompt_version_id: str) -> None: else: raise ValueError(f"Prompt version '{prompt_version_id}' not found") except Exception as e: - raise Exception( - f"Failed to load prompt version '{prompt_version_id}' from Arize Phoenix: {e}" - ) + raise Exception(f"Failed to load prompt version '{prompt_version_id}' from Arize Phoenix: {e}") - def _parse_prompt_data( - self, data: Dict[str, Any], prompt_version_id: str - ) -> ArizePhoenixPromptTemplate: + def _parse_prompt_data(self, data: Dict[str, Any], prompt_version_id: str) -> ArizePhoenixPromptTemplate: """Parse Arize Phoenix prompt data and extract messages and metadata.""" template_data = data.get("template", {}) messages = template_data.get("messages", []) @@ -154,9 +146,7 @@ def _parse_prompt_data( metadata=metadata, ) - def render_template( - self, template_id: str, variables: Optional[Dict[str, Any]] = None - ) -> List[AllMessageValues]: + def render_template(self, template_id: str, variables: Optional[Dict[str, Any]] = None) -> List[AllMessageValues]: """Render a template with the given variables and return formatted messages.""" if template_id not in self.prompts: raise ValueError(f"Template '{template_id}' not found") @@ -272,9 +262,7 @@ def get_prompt_template( raise ValueError(f"Prompt template '{prompt_id}' not found") # Render the template - rendered_messages = self.prompt_manager.render_template( - prompt_id, prompt_variables or {} - ) + rendered_messages = self.prompt_manager.render_template(prompt_id, prompt_variables or {}) # Extract metadata metadata = { @@ -317,9 +305,7 @@ def pre_call_hook( try: # Get the rendered messages and metadata - rendered_messages, prompt_metadata = self.get_prompt_template( - prompt_id, prompt_variables - ) + rendered_messages, prompt_metadata = self.get_prompt_template(prompt_id, prompt_variables) # Merge rendered messages with existing messages if rendered_messages: @@ -353,9 +339,7 @@ def pre_call_hook( # Log error but don't fail the call import litellm - litellm._logging.verbose_proxy_logger.error( - f"Error in Arize Phoenix prompt pre_call_hook: {e}" - ) + litellm._logging.verbose_proxy_logger.error(f"Error in Arize Phoenix prompt pre_call_hook: {e}") return messages, litellm_params def get_available_prompts(self) -> List[str]: @@ -408,9 +392,7 @@ def _compile_prompt_helper( self.prompt_manager._load_prompt_from_arize(prompt_id) # Get the rendered messages and metadata - rendered_messages, prompt_metadata = self.get_prompt_template( - prompt_id, prompt_variables - ) + rendered_messages, prompt_metadata = self.get_prompt_template(prompt_id, prompt_variables) # Extract model from metadata (if specified) template_model = prompt_metadata.get("model") diff --git a/litellm/integrations/athina.py b/litellm/integrations/athina.py index 49b9e9e68721..d1bf8e68624e 100644 --- a/litellm/integrations/athina.py +++ b/litellm/integrations/athina.py @@ -12,10 +12,7 @@ def __init__(self): "athina-api-key": self.athina_api_key, "Content-Type": "application/json", } - self.athina_logging_url = ( - os.getenv("ATHINA_BASE_URL", "https://log.athina.ai") - + "/api/v1/log/inference" - ) + self.athina_logging_url = os.getenv("ATHINA_BASE_URL", "https://log.athina.ai") + "/api/v1/log/inference" self.additional_keys = [ "environment", "prompt_slug", @@ -42,9 +39,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): if "complete_streaming_response" in kwargs: # Log the completion response in streaming mode completion_response = kwargs["complete_streaming_response"] - response_json = ( - completion_response.model_dump() if completion_response else {} - ) + response_json = completion_response.model_dump() if completion_response else {} else: # Skip logging if the completion response is not available return @@ -56,30 +51,19 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): "request": kwargs, "response": response_json, "prompt_tokens": response_json.get("usage", {}).get("prompt_tokens"), - "completion_tokens": response_json.get("usage", {}).get( - "completion_tokens" - ), + "completion_tokens": response_json.get("usage", {}).get("completion_tokens"), "total_tokens": response_json.get("usage", {}).get("total_tokens"), } - if ( - type(end_time) is datetime.datetime - and type(start_time) is datetime.datetime - ): - data["response_time"] = int( - (end_time - start_time).total_seconds() * 1000 - ) + if type(end_time) is datetime.datetime and type(start_time) is datetime.datetime: + data["response_time"] = int((end_time - start_time).total_seconds() * 1000) if "messages" in kwargs: data["prompt"] = kwargs.get("messages", None) # Directly add tools or functions if present optional_params = kwargs.get("optional_params", {}) - data.update( - (k, v) - for k, v in optional_params.items() - if k in ["tools", "functions"] - ) + data.update((k, v) for k, v in optional_params.items() if k in ["tools", "functions"]) # Add additional metadata keys metadata = kwargs.get("litellm_params", {}).get("metadata", {}) @@ -93,13 +77,9 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): data=json.dumps(data, default=str), ) if response.status_code != 200: - print_verbose( - f"Athina Logger Error - {response.text}, {response.status_code}" - ) + print_verbose(f"Athina Logger Error - {response.text}, {response.status_code}") else: print_verbose(f"Athina Logger Succeeded - {response.text}") except Exception as e: - print_verbose( - f"Athina Logger Error - {e}, Stack trace: {traceback.format_exc()}" - ) + print_verbose(f"Athina Logger Error - {e}, Stack trace: {traceback.format_exc()}") pass diff --git a/litellm/integrations/azure_sentinel/azure_sentinel.py b/litellm/integrations/azure_sentinel/azure_sentinel.py index 0cfd49cda370..182a2e185eff 100644 --- a/litellm/integrations/azure_sentinel/azure_sentinel.py +++ b/litellm/integrations/azure_sentinel/azure_sentinel.py @@ -63,32 +63,16 @@ def __init__( audit_stream_name (str, optional): Stream name from DCR for audit logs. If not provided, audit logs use the standard stream name. """ - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) - resolved_dcr_immutable_id = dcr_immutable_id or os.getenv( - "AZURE_SENTINEL_DCR_IMMUTABLE_ID" - ) - resolved_stream_name = ( - stream_name or os.getenv("AZURE_SENTINEL_STREAM_NAME") or "Custom-LiteLLM" - ) + resolved_dcr_immutable_id = dcr_immutable_id or os.getenv("AZURE_SENTINEL_DCR_IMMUTABLE_ID") + resolved_stream_name = stream_name or os.getenv("AZURE_SENTINEL_STREAM_NAME") or "Custom-LiteLLM" resolved_audit_stream_name = audit_stream_name or resolved_stream_name resolved_endpoint = endpoint or os.getenv("AZURE_SENTINEL_ENDPOINT") - resolved_tenant_id = ( - tenant_id - or os.getenv("AZURE_SENTINEL_TENANT_ID") - or os.getenv("AZURE_TENANT_ID") - ) - resolved_client_id = ( - client_id - or os.getenv("AZURE_SENTINEL_CLIENT_ID") - or os.getenv("AZURE_CLIENT_ID") - ) + resolved_tenant_id = tenant_id or os.getenv("AZURE_SENTINEL_TENANT_ID") or os.getenv("AZURE_TENANT_ID") + resolved_client_id = client_id or os.getenv("AZURE_SENTINEL_CLIENT_ID") or os.getenv("AZURE_CLIENT_ID") resolved_client_secret = ( - client_secret - or os.getenv("AZURE_SENTINEL_CLIENT_SECRET") - or os.getenv("AZURE_CLIENT_SECRET") + client_secret or os.getenv("AZURE_SENTINEL_CLIENT_SECRET") or os.getenv("AZURE_CLIENT_SECRET") ) if not resolved_dcr_immutable_id: @@ -144,9 +128,7 @@ def __init__( self.audit_log_queue: List[StandardAuditLogPayload] = [] @staticmethod - def _build_api_endpoint( - endpoint: str, dcr_immutable_id: str, stream_name: str - ) -> str: + def _build_api_endpoint(endpoint: str, dcr_immutable_id: str, stream_name: str) -> str: return f"{endpoint.rstrip('/')}/dataCollectionRules/{dcr_immutable_id}/streams/{stream_name}?api-version=2023-01-01" async def _get_oauth_token(self) -> str: @@ -157,9 +139,7 @@ async def _get_oauth_token(self) -> str: Bearer token string """ if ( - self.oauth_token - and self.oauth_token_expires_at - and time.time() < self.oauth_token_expires_at - 60 + self.oauth_token and self.oauth_token_expires_at and time.time() < self.oauth_token_expires_at - 60 ): # Refresh 60 seconds before expiry return self.oauth_token @@ -168,9 +148,7 @@ async def _get_oauth_token(self) -> str: assert self.client_id is not None, "client_id is required" assert self.client_secret is not None, "client_secret is required" - token_url = ( - f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token" - ) + token_url = f"https://login.microsoftonline.com/{self.tenant_id}/oauth2/v2.0/token" token_data = { "client_id": self.client_id, @@ -186,9 +164,7 @@ async def _get_oauth_token(self) -> str: ) if response.status_code != 200: - raise Exception( - f"Failed to get OAuth2 token: {response.status_code} - {response.text}" - ) + raise Exception(f"Failed to get OAuth2 token: {response.status_code} - {response.text}") token_response = response.json() self.oauth_token = token_response.get("access_token") @@ -213,15 +189,11 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti Raises a NON Blocking verbose_logger.exception if an error occurs """ try: - verbose_logger.debug( - "Azure Sentinel: Logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("Azure Sentinel: Logging - Enters logging function for model %s", kwargs) standard_logging_payload = kwargs.get("standard_logging_object", None) if standard_logging_payload is None: - verbose_logger.warning( - "Azure Sentinel: standard_logging_object not found in kwargs" - ) + verbose_logger.warning("Azure Sentinel: standard_logging_object not found in kwargs") return self.log_queue.append(standard_logging_payload) @@ -230,9 +202,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"Azure Sentinel Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Azure Sentinel Layer Error - {str(e)}\n{traceback.format_exc()}") pass async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): @@ -254,9 +224,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti standard_logging_payload = kwargs.get("standard_logging_object", None) if standard_logging_payload is None: - verbose_logger.warning( - "Azure Sentinel: standard_logging_object not found in kwargs" - ) + verbose_logger.warning("Azure Sentinel: standard_logging_object not found in kwargs") return self.log_queue.append(standard_logging_payload) @@ -265,14 +233,10 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"Azure Sentinel Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Azure Sentinel Layer Error - {str(e)}\n{traceback.format_exc()}") pass - async def async_log_audit_log_event( - self, audit_log: StandardAuditLogPayload - ) -> None: + async def async_log_audit_log_event(self, audit_log: StandardAuditLogPayload) -> None: """ Async log LiteLLM audit log events to Azure Sentinel. @@ -293,9 +257,7 @@ async def async_log_audit_log_event( await self.async_send_audit_batch() except Exception as e: - verbose_logger.exception( - f"Azure Sentinel Audit Log Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Azure Sentinel Audit Log Layer Error - {str(e)}\n{traceback.format_exc()}") pass async def async_send_batch(self): @@ -331,9 +293,7 @@ async def _async_send_batch_to_api( if not log_queue: return - verbose_logger.debug( - "Azure Sentinel - about to flush %s %s", len(log_queue), log_type - ) + verbose_logger.debug("Azure Sentinel - about to flush %s %s", len(log_queue), log_type) # Get OAuth2 token bearer_token = await self._get_oauth_token() @@ -349,9 +309,7 @@ async def _async_send_batch_to_api( } # Send the request - response = await self.async_httpx_client.post( - url=api_endpoint, data=body.encode("utf-8"), headers=headers - ) + response = await self.async_httpx_client.post(url=api_endpoint, data=body.encode("utf-8"), headers=headers) if response.status_code not in [200, 204]: verbose_logger.error( @@ -359,9 +317,7 @@ async def _async_send_batch_to_api( response.status_code, response.text, ) - raise Exception( - f"Failed to send logs to Azure Sentinel: {response.status_code} - {response.text}" - ) + raise Exception(f"Failed to send logs to Azure Sentinel: {response.status_code} - {response.text}") verbose_logger.debug( "Azure Sentinel: Response from API status_code: %s", @@ -369,9 +325,7 @@ async def _async_send_batch_to_api( ) except Exception as e: - verbose_logger.exception( - f"Azure Sentinel Error sending batch API - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Azure Sentinel Error sending batch API - {str(e)}\n{traceback.format_exc()}") finally: log_queue.clear() diff --git a/litellm/integrations/azure_storage/azure_storage.py b/litellm/integrations/azure_storage/azure_storage.py index b06fa13e9189..5ccd1a86bffb 100644 --- a/litellm/integrations/azure_storage/azure_storage.py +++ b/litellm/integrations/azure_storage/azure_storage.py @@ -24,42 +24,30 @@ def __init__( **kwargs, ): try: - verbose_logger.debug( - "AzureBlobStorageLogger: in init azure blob storage logger" - ) + verbose_logger.debug("AzureBlobStorageLogger: in init azure blob storage logger") # Env Variables used for Azure Storage Authentication self.tenant_id = os.getenv("AZURE_STORAGE_TENANT_ID") self.client_id = os.getenv("AZURE_STORAGE_CLIENT_ID") self.client_secret = os.getenv("AZURE_STORAGE_CLIENT_SECRET") - self.azure_storage_account_key: Optional[str] = os.getenv( - "AZURE_STORAGE_ACCOUNT_KEY" - ) + self.azure_storage_account_key: Optional[str] = os.getenv("AZURE_STORAGE_ACCOUNT_KEY") # Required Env Variables for Azure Storage _azure_storage_account_name = os.getenv("AZURE_STORAGE_ACCOUNT_NAME") if not _azure_storage_account_name: - raise ValueError( - "Missing required environment variable: AZURE_STORAGE_ACCOUNT_NAME" - ) + raise ValueError("Missing required environment variable: AZURE_STORAGE_ACCOUNT_NAME") self.azure_storage_account_name: str = _azure_storage_account_name _azure_storage_file_system = os.getenv("AZURE_STORAGE_FILE_SYSTEM") if not _azure_storage_file_system: - raise ValueError( - "Missing required environment variable: AZURE_STORAGE_FILE_SYSTEM" - ) + raise ValueError("Missing required environment variable: AZURE_STORAGE_FILE_SYSTEM") self.azure_storage_file_system: str = _azure_storage_file_system self._service_client = None # Time that the azure service client expires, in order to reset the connection pool and keep it fresh self._service_client_timeout: Optional[float] = None # Internal variables used for Token based authentication - self.azure_auth_token: Optional[str] = ( - None # the Azure AD token to use for Azure Storage API requests - ) - self.token_expiry: Optional[datetime] = ( - None # the expiry time of the currentAzure AD token - ) + self.azure_auth_token: Optional[str] = None # the Azure AD token to use for Azure Storage API requests + self.token_expiry: Optional[datetime] = None # the expiry time of the currentAzure AD token asyncio.create_task(self.periodic_flush()) self.flush_lock = asyncio.Lock() @@ -84,9 +72,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti "AzureBlobStorageLogger: Logging - Enters logging function for model %s", kwargs, ) - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: raise ValueError("standard_logging_payload is not set") @@ -110,9 +96,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti "AzureBlobStorageLogger: Logging - Enters logging function for model %s", kwargs, ) - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: raise ValueError("standard_logging_payload is not set") @@ -143,13 +127,9 @@ async def async_send_batch(self): await self.async_upload_payload_to_azure_blob_storage(payload=payload) except Exception as e: - verbose_logger.exception( - f"AzureBlobStorageLogger Error sending batch API - {str(e)}" - ) + verbose_logger.exception(f"AzureBlobStorageLogger Error sending batch API - {str(e)}") - async def async_upload_payload_to_azure_blob_storage( - self, payload: StandardLoggingPayload - ): + async def async_upload_payload_to_azure_blob_storage(self, payload: StandardLoggingPayload): """ Uploads the payload to Azure Blob Storage using a 3-step process: 1. Create file resource @@ -158,18 +138,12 @@ async def async_upload_payload_to_azure_blob_storage( """ try: if self.azure_storage_account_key: - await self.upload_to_azure_data_lake_with_azure_account_key( - payload=payload - ) + await self.upload_to_azure_data_lake_with_azure_account_key(payload=payload) else: # Get a valid token instead of always requesting a new one await self.set_valid_azure_ad_token() - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) - json_payload = ( - safe_dumps(payload) + "\n" - ) # Add newline for each log entry + async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) + json_payload = safe_dumps(payload) + "\n" # Add newline for each log entry payload_bytes = json_payload.encode("utf-8") filename = f"{payload.get('id') or str(uuid.uuid4())}.json" base_url = f"https://{self.azure_storage_account_name}.dfs.core.windows.net/{self.azure_storage_file_system}/{filename}" @@ -179,9 +153,7 @@ async def async_upload_payload_to_azure_blob_storage( await self._append_data(async_client, base_url, json_payload) await self._flush_data(async_client, base_url, len(payload_bytes)) - verbose_logger.debug( - f"Successfully uploaded log to Azure Blob Storage: {filename}" - ) + verbose_logger.debug(f"Successfully uploaded log to Azure Blob Storage: {filename}") except Exception as e: verbose_logger.exception(f"Error uploading to Azure Blob Storage: {str(e)}") @@ -203,9 +175,7 @@ async def _create_file(self, client: AsyncHTTPHandler, base_url: str): verbose_logger.exception(f"Error creating file resource: {str(e)}") raise - async def _append_data( - self, client: AsyncHTTPHandler, base_url: str, json_payload: str - ): + async def _append_data(self, client: AsyncHTTPHandler, base_url: str, json_payload: str): """Helper method to append data to the file""" try: verbose_logger.debug(f"Appending data to file: {base_url}") @@ -234,9 +204,7 @@ async def _flush_data(self, client: AsyncHTTPHandler, base_url: str, position: i "Content-Length": "0", "Authorization": f"Bearer {self.azure_auth_token}", } - response = await client.patch( - f"{base_url}?action=flush&position={position}", headers=headers - ) + response = await client.patch(f"{base_url}?action=flush&position={position}", headers=headers) response.raise_for_status() verbose_logger.debug("Successfully flushed data") except Exception as e: @@ -282,17 +250,11 @@ def get_azure_ad_token_from_azure_storage( client_secret is not None, ) if tenant_id is None: - raise ValueError( - "Missing required environment variable: AZURE_STORAGE_TENANT_ID" - ) + raise ValueError("Missing required environment variable: AZURE_STORAGE_TENANT_ID") if client_id is None: - raise ValueError( - "Missing required environment variable: AZURE_STORAGE_CLIENT_ID" - ) + raise ValueError("Missing required environment variable: AZURE_STORAGE_CLIENT_ID") if client_secret is None: - raise ValueError( - "Missing required environment variable: AZURE_STORAGE_CLIENT_SECRET" - ) + raise ValueError("Missing required environment variable: AZURE_STORAGE_CLIENT_SECRET") token_provider = get_azure_ad_token_from_entra_id( tenant_id=tenant_id, @@ -331,11 +293,7 @@ async def get_service_client(self): from azure.storage.filedatalake.aio import DataLakeServiceClient # expire old clients to recover from connection issues - if ( - self._service_client_timeout - and self._service_client - and self._service_client_timeout > time.time() - ): + if self._service_client_timeout and self._service_client and self._service_client_timeout > time.time(): await self._service_client.close() self._service_client = None if not self._service_client: @@ -346,9 +304,7 @@ async def get_service_client(self): self._service_client_timeout = time.time() + _DEFAULT_TTL_FOR_HTTPX_CLIENTS return self._service_client - async def upload_to_azure_data_lake_with_azure_account_key( - self, payload: StandardLoggingPayload - ): + async def upload_to_azure_data_lake_with_azure_account_key(self, payload: StandardLoggingPayload): """ Uploads the payload to Azure Data Lake using the Azure SDK @@ -359,9 +315,7 @@ async def upload_to_azure_data_lake_with_azure_account_key( service_client = await self.get_service_client() # Get file system client - file_system_client = service_client.get_file_system_client( - file_system=self.azure_storage_file_system - ) + file_system_client = service_client.get_file_system_client(file_system=self.azure_storage_file_system) try: # Create directory with today's date @@ -391,9 +345,7 @@ async def upload_to_azure_data_lake_with_azure_account_key( # Flush the content to finalize the file await file_client.flush_data(position=len(content), offset=0) - verbose_logger.debug( - f"Successfully uploaded and wrote to {today}/{file_name}" - ) + verbose_logger.debug(f"Successfully uploaded and wrote to {today}/{file_name}") except Exception as e: verbose_logger.exception(f"Error occurred: {str(e)}") diff --git a/litellm/integrations/bitbucket/__init__.py b/litellm/integrations/bitbucket/__init__.py index 111d38f78a47..2b9bd568e32f 100644 --- a/litellm/integrations/bitbucket/__init__.py +++ b/litellm/integrations/bitbucket/__init__.py @@ -29,9 +29,7 @@ def set_global_bitbucket_config(config: dict) -> None: litellm.global_bitbucket_config = config # type: ignore -def prompt_initializer( - litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec" -) -> "CustomPromptManagement": +def prompt_initializer(litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec") -> "CustomPromptManagement": """ Initialize a prompt from a BitBucket repository. """ @@ -39,9 +37,7 @@ def prompt_initializer( prompt_id = getattr(litellm_params, "prompt_id", None) if not bitbucket_config: - raise ValueError( - "bitbucket_config is required for BitBucket prompt integration" - ) + raise ValueError("bitbucket_config is required for BitBucket prompt integration") try: bitbucket_prompt_manager = BitBucketPromptManager( diff --git a/litellm/integrations/bitbucket/bitbucket_client.py b/litellm/integrations/bitbucket/bitbucket_client.py index e742cc14b7d0..c02d56811a7a 100644 --- a/litellm/integrations/bitbucket/bitbucket_client.py +++ b/litellm/integrations/bitbucket/bitbucket_client.py @@ -12,15 +12,11 @@ def _sanitize_file_path(file_path: str) -> str: """Reject path traversal and URL-encode each path segment.""" if "#" in file_path or "?" in file_path: - raise ValueError( - f"Invalid file path {file_path!r}: contains URL special characters" - ) + raise ValueError(f"Invalid file path {file_path!r}: contains URL special characters") parts = file_path.split("/") for part in parts: if part == "..": - raise ValueError( - f"Invalid file path {file_path!r}: path traversal detected" - ) + raise ValueError(f"Invalid file path {file_path!r}: path traversal detected") return "/".join(urllib.parse.quote(part, safe="") for part in parts) @@ -115,17 +111,13 @@ def get_file_content(self, file_path: str) -> Optional[str]: f"Access denied to file '{file_path}'. Check your BitBucket permissions for workspace '{self.workspace}' and repository '{self.repository}'." ) elif e.response.status_code == 401: - raise Exception( - "Authentication failed. Check your BitBucket access token and permissions." - ) + raise Exception("Authentication failed. Check your BitBucket access token and permissions.") else: raise Exception(f"Failed to fetch file '{file_path}': {e}") else: raise Exception(f"Error fetching file '{file_path}': {e}") - def list_files( - self, directory_path: str = "", file_extension: str = ".prompt" - ) -> List[str]: + def list_files(self, directory_path: str = "", file_extension: str = ".prompt") -> List[str]: """ List files in a directory with a specific extension. @@ -164,9 +156,7 @@ def list_files( f"Access denied to directory '{directory_path}'. Check your BitBucket permissions for workspace '{self.workspace}' and repository '{self.repository}'." ) elif e.response.status_code == 401: - raise Exception( - "Authentication failed. Check your BitBucket access token and permissions." - ) + raise Exception("Authentication failed. Check your BitBucket access token and permissions.") else: raise Exception(f"Failed to list files in '{directory_path}': {e}") else: diff --git a/litellm/integrations/bitbucket/bitbucket_prompt_manager.py b/litellm/integrations/bitbucket/bitbucket_prompt_manager.py index 844fa9f38cbf..6dca4d76c040 100644 --- a/litellm/integrations/bitbucket/bitbucket_prompt_manager.py +++ b/litellm/integrations/bitbucket/bitbucket_prompt_manager.py @@ -44,9 +44,7 @@ def __init__( self.temperature = metadata.get("temperature") self.max_tokens = metadata.get("max_tokens") self.input_schema = metadata.get("input", {}).get("schema", {}) - self.optional_params = { - k: v for k, v in metadata.items() if k not in ["model", "input", "content"] - } + self.optional_params = {k: v for k, v in metadata.items() if k not in ["model", "input", "content"]} def __repr__(self): return f"BitBucketPromptTemplate(id='{self.template_id}', model='{self.model}')" @@ -101,9 +99,7 @@ def _load_prompt_from_bitbucket(self, prompt_id: str) -> None: """Load a specific .prompt file from BitBucket.""" try: # Fetch the .prompt file from BitBucket - prompt_content = self.bitbucket_client.get_file_content( - f"{prompt_id}.prompt" - ) + prompt_content = self.bitbucket_client.get_file_content(f"{prompt_id}.prompt") if prompt_content: template = self._parse_prompt_file(prompt_content, prompt_id) @@ -111,9 +107,7 @@ def _load_prompt_from_bitbucket(self, prompt_id: str) -> None: except Exception as e: raise Exception(f"Failed to load prompt '{prompt_id}' from BitBucket: {e}") - def _parse_prompt_file( - self, content: str, prompt_id: str - ) -> BitBucketPromptTemplate: + def _parse_prompt_file(self, content: str, prompt_id: str) -> BitBucketPromptTemplate: """Parse a .prompt file content and extract metadata and template.""" # Split frontmatter and content if content.startswith("---"): @@ -168,9 +162,7 @@ def _parse_yaml_basic(self, yaml_str: str) -> Dict[str, Any]: result[key] = value.strip("\"'") return result - def render_template( - self, template_id: str, variables: Optional[Dict[str, Any]] = None - ) -> str: + def render_template(self, template_id: str, variables: Optional[Dict[str, Any]] = None) -> str: """Render a template with the given variables.""" if template_id not in self.prompts: raise ValueError(f"Template '{template_id}' not found") @@ -259,9 +251,7 @@ def get_prompt_template( raise ValueError(f"Prompt template '{prompt_id}' not found") # Render the template - rendered_prompt = self.prompt_manager.render_template( - prompt_id, prompt_variables or {} - ) + rendered_prompt = self.prompt_manager.render_template(prompt_id, prompt_variables or {}) # Extract metadata metadata = { @@ -291,9 +281,7 @@ def pre_call_hook( try: # Get the rendered prompt and metadata - rendered_prompt, prompt_metadata = self.get_prompt_template( - prompt_id, prompt_variables - ) + rendered_prompt, prompt_metadata = self.get_prompt_template(prompt_id, prompt_variables) # Parse the rendered prompt into messages parsed_messages = self._parse_prompt_to_messages(rendered_prompt) @@ -332,9 +320,7 @@ def pre_call_hook( # Log error but don't fail the call import litellm - litellm._logging.verbose_proxy_logger.error( - f"Error in BitBucket prompt pre_call_hook: {e}" - ) + litellm._logging.verbose_proxy_logger.error(f"Error in BitBucket prompt pre_call_hook: {e}") return messages, litellm_params def _parse_prompt_to_messages(self, prompt_content: str) -> List[AllMessageValues]: @@ -389,9 +375,7 @@ def _parse_prompt_to_messages(self, prompt_content: str) -> List[AllMessageValue # Add the last message if current_role and current_content: - messages.append( - {"role": current_role, "content": "\n".join(current_content).strip()} - ) + messages.append({"role": current_role, "content": "\n".join(current_content).strip()}) # If no role indicators found, treat as a single user message if not messages and prompt_content.strip(): @@ -466,9 +450,7 @@ def _compile_prompt_helper( self.prompt_manager._load_prompt_from_bitbucket(prompt_id) # Get the rendered prompt and metadata - rendered_prompt, prompt_metadata = self.get_prompt_template( - prompt_id, prompt_variables - ) + rendered_prompt, prompt_metadata = self.get_prompt_template(prompt_id, prompt_variables) # Convert rendered content to chat messages messages = self._parse_prompt_to_messages(rendered_prompt) diff --git a/litellm/integrations/braintrust_logging.py b/litellm/integrations/braintrust_logging.py index a69785ba2e35..686c37d3e175 100644 --- a/litellm/integrations/braintrust_logging.py +++ b/litellm/integrations/braintrust_logging.py @@ -34,16 +34,12 @@ def get_utc_datetime(): class BraintrustLogger(CustomLogger): - def __init__( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> None: + def __init__(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> None: super().__init__() self.is_mock_mode = should_use_braintrust_mock() if self.is_mock_mode: create_mock_braintrust_client() - verbose_logger.info( - "[BRAINTRUST MOCK] Braintrust logger initialized in mock mode" - ) + verbose_logger.info("[BRAINTRUST MOCK] Braintrust logger initialized in mock mode") self.validate_environment(api_key=api_key) self.api_base = api_base or os.getenv("BRAINTRUST_API_BASE") or API_BASE self.default_project_id = None @@ -52,12 +48,8 @@ def __init__( "Authorization": "Bearer " + self.api_key, "Content-Type": "application/json", } - self._project_id_cache: Dict[ - str, str - ] = {} # Cache mapping project names to IDs - self.global_braintrust_http_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self._project_id_cache: Dict[str, str] = {} # Cache mapping project names to IDs + self.global_braintrust_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.global_braintrust_sync_http_handler = HTTPHandler() def validate_environment(self, api_key: Optional[str]): @@ -143,23 +135,16 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): output = None choices = [] if response_obj is not None and ( - kwargs.get("call_type", None) == "embedding" - or isinstance(response_obj, litellm.EmbeddingResponse) + kwargs.get("call_type", None) == "embedding" or isinstance(response_obj, litellm.EmbeddingResponse) ): output = None - elif response_obj is not None and isinstance( - response_obj, litellm.ModelResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ModelResponse): output = response_obj["choices"][0]["message"].json() choices = response_obj["choices"] - elif response_obj is not None and isinstance( - response_obj, litellm.TextCompletionResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.TextCompletionResponse): output = response_obj.choices[0].text choices = response_obj.choices - elif response_obj is not None and isinstance( - response_obj, litellm.ImageResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ImageResponse): output = response_obj["data"] litellm_params = kwargs.get("litellm_params", {}) or {} @@ -169,9 +154,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): project_id = dynamic_metadata.get("project_id") if project_id is None: project_name = dynamic_metadata.get("project_name") - project_id = ( - self.get_project_id_sync(project_name) if project_name else None - ) + project_id = self.get_project_id_sync(project_name) if project_name else None if project_id is None: if self.default_project_id is None: @@ -206,8 +189,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): "completion_tokens": usage_obj.completion_tokens, "total_tokens": usage_obj.total_tokens, "total_cost": cost, - "time_to_first_token": end_time.timestamp() - - start_time.timestamp(), + "time_to_first_token": end_time.timestamp() - start_time.timestamp(), "start": start_time.timestamp(), "end": end_time.timestamp(), } @@ -278,23 +260,16 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti output = None choices = [] if response_obj is not None and ( - kwargs.get("call_type", None) == "embedding" - or isinstance(response_obj, litellm.EmbeddingResponse) + kwargs.get("call_type", None) == "embedding" or isinstance(response_obj, litellm.EmbeddingResponse) ): output = None - elif response_obj is not None and isinstance( - response_obj, litellm.ModelResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ModelResponse): output = response_obj["choices"][0]["message"].json() choices = response_obj["choices"] - elif response_obj is not None and isinstance( - response_obj, litellm.TextCompletionResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.TextCompletionResponse): output = response_obj.choices[0].text choices = response_obj.choices - elif response_obj is not None and isinstance( - response_obj, litellm.ImageResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ImageResponse): output = response_obj["data"] litellm_params = kwargs.get("litellm_params", {}) @@ -304,11 +279,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti project_id = dynamic_metadata.get("project_id") if project_id is None: project_name = dynamic_metadata.get("project_name") - project_id = ( - await self.get_project_id_async(project_name) - if project_name - else None - ) + project_id = await self.get_project_id_async(project_name) if project_name else None if project_id is None: if self.default_project_id is None: @@ -350,14 +321,8 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti api_call_start_time = kwargs.get("api_call_start_time") completion_start_time = kwargs.get("completion_start_time") - if ( - api_call_start_time is not None - and completion_start_time is not None - ): - metrics["time_to_first_token"] = ( - completion_start_time.timestamp() - - api_call_start_time.timestamp() - ) + if api_call_start_time is not None and completion_start_time is not None: + metrics["time_to_first_token"] = completion_start_time.timestamp() - api_call_start_time.timestamp() # Allow metadata override for span name span_name = dynamic_metadata.get("span_name", "Chat Completion") diff --git a/litellm/integrations/braintrust_mock_client.py b/litellm/integrations/braintrust_mock_client.py index 1af14deeab64..e2b732d6e9c0 100644 --- a/litellm/integrations/braintrust_mock_client.py +++ b/litellm/integrations/braintrust_mock_client.py @@ -156,11 +156,7 @@ def create_mock_braintrust_client(): # This is required for async calls to be mocked create_mock_braintrust_factory_client() - verbose_logger.debug( - f"[BRAINTRUST MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS * 1000:.0f}ms" - ) - verbose_logger.debug( - "[BRAINTRUST MOCK] Braintrust mock client initialization complete" - ) + verbose_logger.debug(f"[BRAINTRUST MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS * 1000:.0f}ms") + verbose_logger.debug("[BRAINTRUST MOCK] Braintrust mock client initialization complete") _mocks_initialized = True diff --git a/litellm/integrations/cloudzero/cloudzero.py b/litellm/integrations/cloudzero/cloudzero.py index 8decd4ef23f7..121b1dc6967b 100644 --- a/litellm/integrations/cloudzero/cloudzero.py +++ b/litellm/integrations/cloudzero/cloudzero.py @@ -60,15 +60,11 @@ async def initialize_cloudzero_export_job(self): # if using redis, ensure only one pod exports the data at a time if pod_lock_manager and pod_lock_manager.redis_cache: - if await pod_lock_manager.acquire_lock( - cronjob_id=CLOUDZERO_EXPORT_USAGE_DATA_JOB_NAME - ): + if await pod_lock_manager.acquire_lock(cronjob_id=CLOUDZERO_EXPORT_USAGE_DATA_JOB_NAME): try: await self._hourly_usage_data_export() finally: - await pod_lock_manager.release_lock( - cronjob_id=CLOUDZERO_EXPORT_USAGE_DATA_JOB_NAME - ) + await pod_lock_manager.release_lock(cronjob_id=CLOUDZERO_EXPORT_USAGE_DATA_JOB_NAME) else: # if not using redis, export the data directly await self._hourly_usage_data_export() @@ -86,9 +82,7 @@ async def _hourly_usage_data_export(self): current_time_utc = datetime.now(timezone.utc) # Mitigates the possibility of missing spend if an hour is skipped due to a restart in an ephemeral environment - one_hour_ago_utc = current_time_utc - timedelta( - minutes=CLOUDZERO_EXPORT_INTERVAL_MINUTES * 2 - ) + one_hour_ago_utc = current_time_utc - timedelta(minutes=CLOUDZERO_EXPORT_INTERVAL_MINUTES * 2) await self.export_usage_data( limit=CLOUDZERO_MAX_FETCHED_DATA_RECORDS, operation="replace_hourly", @@ -130,9 +124,7 @@ async def export_usage_data( # Initialize database connection and load data database = LiteLLMDatabase() verbose_logger.debug("CloudZero Logger: Loading usage data from database") - data = await database.get_usage_data( - limit=limit, start_time_utc=start_time_utc, end_time_utc=end_time_utc - ) + data = await database.get_usage_data(limit=limit, start_time_utc=start_time_utc, end_time_utc=end_time_utc) if data.is_empty(): verbose_logger.debug("CloudZero Logger: No usage data found to export") @@ -145,9 +137,7 @@ async def export_usage_data( cbf_data = transformer.transform(data) if cbf_data.is_empty(): - verbose_logger.warning( - "CloudZero Logger: No valid data after transformation" - ) + verbose_logger.warning("CloudZero Logger: No valid data after transformation") return # Send data to CloudZero @@ -157,19 +147,13 @@ async def export_usage_data( user_timezone=self.timezone, ) - verbose_logger.debug( - f"CloudZero Logger: Transmitting {len(cbf_data)} records to CloudZero" - ) + verbose_logger.debug(f"CloudZero Logger: Transmitting {len(cbf_data)} records to CloudZero") streamer.send_batched(cbf_data, operation=operation) - verbose_logger.debug( - f"CloudZero Logger: Successfully exported {len(cbf_data)} records to CloudZero" - ) + verbose_logger.debug(f"CloudZero Logger: Successfully exported {len(cbf_data)} records to CloudZero") except Exception as e: - verbose_logger.error( - f"CloudZero Logger: Error exporting usage data: {str(e)}" - ) + verbose_logger.error(f"CloudZero Logger: Error exporting usage data: {str(e)}") raise async def dry_run_export_usage_data(self, limit: Optional[int] = 10000): @@ -207,9 +191,7 @@ async def dry_run_export_usage_data(self, limit: Optional[int] = 10000): }, } - verbose_logger.debug( - f"CloudZero Dry Run: Processing {len(data)} records..." - ) + verbose_logger.debug(f"CloudZero Dry Run: Processing {len(data)} records...") # Convert usage data to dict format for response usage_data_sample = data.head(50).to_dicts() # Return first 50 rows @@ -219,21 +201,15 @@ async def dry_run_export_usage_data(self, limit: Optional[int] = 10000): cbf_data = transformer.transform(data) if cbf_data.is_empty(): - verbose_logger.warning( - "CloudZero Dry Run: No valid data after transformation" - ) + verbose_logger.warning("CloudZero Dry Run: No valid data after transformation") return { "usage_data": usage_data_sample, "cbf_data": [], "summary": { "total_records": len(usage_data_sample), - "total_cost": sum( - row.get("spend", 0) for row in usage_data_sample - ), + "total_cost": sum(row.get("spend", 0) for row in usage_data_sample), "total_tokens": sum( - row.get("prompt_tokens", 0) - + row.get("completion_tokens", 0) - for row in usage_data_sample + row.get("prompt_tokens", 0) + row.get("completion_tokens", 0) for row in usage_data_sample ), "unique_accounts": 0, "unique_services": 0, @@ -246,26 +222,14 @@ async def dry_run_export_usage_data(self, limit: Optional[int] = 10000): # Calculate summary statistics total_cost = sum(record.get("cost/cost", 0) for record in cbf_data_dict) unique_accounts = len( - set( - record.get("resource/account", "") - for record in cbf_data_dict - if record.get("resource/account") - ) + set(record.get("resource/account", "") for record in cbf_data_dict if record.get("resource/account")) ) unique_services = len( - set( - record.get("resource/service", "") - for record in cbf_data_dict - if record.get("resource/service") - ) - ) - total_tokens = sum( - record.get("usage/amount", 0) for record in cbf_data_dict + set(record.get("resource/service", "") for record in cbf_data_dict if record.get("resource/service")) ) + total_tokens = sum(record.get("usage/amount", 0) for record in cbf_data_dict) - verbose_logger.debug( - f"CloudZero Logger: Dry run completed for {len(cbf_data)} records" - ) + verbose_logger.debug(f"CloudZero Logger: Dry run completed for {len(cbf_data)} records") return { "usage_data": usage_data_sample, @@ -296,32 +260,22 @@ def _display_cbf_data_on_screen(self, cbf_data): console.print("[yellow]No CBF data to display[/yellow]") return - console.print( - f"\n[bold green]💰 CloudZero CBF Transformed Data ({len(cbf_data)} records)[/bold green]" - ) + console.print(f"\n[bold green]💰 CloudZero CBF Transformed Data ({len(cbf_data)} records)[/bold green]") # Convert to dicts for easier processing records = cbf_data.to_dicts() # Create main CBF table - cbf_table = Table( - show_header=True, header_style="bold cyan", box=SIMPLE, padding=(0, 1) - ) + cbf_table = Table(show_header=True, header_style="bold cyan", box=SIMPLE, padding=(0, 1)) cbf_table.add_column("time/usage_start", style="blue", no_wrap=False) cbf_table.add_column("cost/cost", style="green", justify="right", no_wrap=False) - cbf_table.add_column( - "entity_type", style="magenta", justify="right", no_wrap=False - ) - cbf_table.add_column( - "entity_id", style="magenta", justify="right", no_wrap=False - ) + cbf_table.add_column("entity_type", style="magenta", justify="right", no_wrap=False) + cbf_table.add_column("entity_id", style="magenta", justify="right", no_wrap=False) cbf_table.add_column("team_id", style="cyan", no_wrap=False) cbf_table.add_column("team_alias", style="cyan", no_wrap=False) cbf_table.add_column("user_email", style="cyan", no_wrap=False) cbf_table.add_column("api_key_alias", style="yellow", no_wrap=False) - cbf_table.add_column( - "usage/amount", style="yellow", justify="right", no_wrap=False - ) + cbf_table.add_column("usage/amount", style="yellow", justify="right", no_wrap=False) cbf_table.add_column("resource/id", style="magenta", no_wrap=False) cbf_table.add_column("resource/service", style="cyan", no_wrap=False) cbf_table.add_column("resource/account", style="white", no_wrap=False) @@ -364,18 +318,10 @@ def _display_cbf_data_on_screen(self, cbf_data): # Show summary statistics total_cost = sum(record.get("cost/cost", 0) for record in records) unique_accounts = len( - set( - record.get("resource/account", "") - for record in records - if record.get("resource/account") - ) + set(record.get("resource/account", "") for record in records if record.get("resource/account")) ) unique_services = len( - set( - record.get("resource/service", "") - for record in records - if record.get("resource/service") - ) + set(record.get("resource/service", "") for record in records if record.get("resource/service")) ) # Count total tokens from usage metrics @@ -388,9 +334,7 @@ def _display_cbf_data_on_screen(self, cbf_data): console.print(f" Unique Accounts: {unique_accounts}") console.print(f" Unique Services: {unique_services}") - console.print( - "\n[dim]💡 This is the CloudZero CBF format ready for AnyCost ingestion[/dim]" - ) + console.print("\n[dim]💡 This is the CloudZero CBF format ready for AnyCost ingestion[/dim]") @staticmethod async def init_cloudzero_background_job(scheduler: AsyncIOScheduler): @@ -402,10 +346,8 @@ async def init_cloudzero_background_job(scheduler: AsyncIOScheduler): from litellm.constants import CLOUDZERO_EXPORT_INTERVAL_MINUTES from litellm.integrations.custom_logger import CustomLogger - prometheus_loggers: List[CustomLogger] = ( - litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=CloudZeroLogger - ) + prometheus_loggers: List[CustomLogger] = litellm.logging_callback_manager.get_custom_loggers_for_type( + callback_type=CloudZeroLogger ) # we need to get the initialized prometheus logger instance(s) and call logger.initialize_remaining_budget_metrics() on them verbose_logger.debug("found %s cloudzero loggers", len(prometheus_loggers)) diff --git a/litellm/integrations/cloudzero/cz_resource_names.py b/litellm/integrations/cloudzero/cz_resource_names.py index 20862c1c7ec7..15cb66002f7a 100644 --- a/litellm/integrations/cloudzero/cz_resource_names.py +++ b/litellm/integrations/cloudzero/cz_resource_names.py @@ -30,9 +30,7 @@ class CZEntityType(str, Enum): class CZRNGenerator: """Generate CloudZero Resource Names (CZRNs) for LiteLLM resources.""" - CZRN_REGEX = re.compile( - r"^czrn:([a-z0-9-]+):([a-zA-Z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):(.+)$" - ) + CZRN_REGEX = re.compile(r"^czrn:([a-z0-9-]+):([a-zA-Z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):([a-z0-9-]+):(.+)$") def __init__(self): """Initialize CZRN generator.""" @@ -138,9 +136,7 @@ def _normalize_provider(self, provider: str) -> str: return normalized return provider_map.get(normalized, normalized) - def _normalize_component( - self, component: str, allow_uppercase: bool = False - ) -> str: + def _normalize_component(self, component: str, allow_uppercase: bool = False) -> str: """Normalize a CZRN component to meet format requirements.""" if not component: return "unknown" diff --git a/litellm/integrations/cloudzero/cz_stream_api.py b/litellm/integrations/cloudzero/cz_stream_api.py index d673536e72df..47d6f7474a22 100644 --- a/litellm/integrations/cloudzero/cz_stream_api.py +++ b/litellm/integrations/cloudzero/cz_stream_api.py @@ -30,9 +30,7 @@ class CloudZeroStreamer: """Stream CBF data to CloudZero AnyCost API with proper batching and timezone handling.""" - def __init__( - self, api_key: str, connection_id: str, user_timezone: Optional[str] = None - ): + def __init__(self, api_key: str, connection_id: str, user_timezone: Optional[str] = None): """Initialize CloudZero streamer with credentials.""" self.api_key = api_key self.connection_id = connection_id @@ -45,16 +43,12 @@ def __init__( try: self.user_timezone = zoneinfo.ZoneInfo(user_timezone) except zoneinfo.ZoneInfoNotFoundError: - self.console.print( - f"[yellow]Warning: Unknown timezone '{user_timezone}', using UTC[/yellow]" - ) + self.console.print(f"[yellow]Warning: Unknown timezone '{user_timezone}', using UTC[/yellow]") self.user_timezone = timezone.utc else: self.user_timezone = timezone.utc - def send_batched( - self, data: pl.DataFrame, operation: str = "replace_hourly" - ) -> None: + def send_batched(self, data: pl.DataFrame, operation: str = "replace_hourly") -> None: """Send CBF data in daily batches to CloudZero AnyCost API.""" if data.is_empty(): self.console.print("[yellow]No data to send to CloudZero[/yellow]") @@ -67,9 +61,7 @@ def send_batched( self.console.print("[yellow]No valid daily batches to send[/yellow]") return - self.console.print( - f"[blue]Sending {len(daily_batches)} daily batch(es) with operation '{operation}'[/blue]" - ) + self.console.print(f"[blue]Sending {len(daily_batches)} daily batch(es) with operation '{operation}'[/blue]") for batch_date, batch_data in daily_batches.items(): self._send_daily_batch(batch_date, batch_data, operation) @@ -80,9 +72,7 @@ def _group_by_date(self, data: pl.DataFrame) -> dict[str, pl.DataFrame]: # Ensure we have the required columns if "time/usage_start" not in data.columns: - self.console.print( - "[red]Error: Missing 'time/usage_start' column for date grouping[/red]" - ) + self.console.print("[red]Error: Missing 'time/usage_start' column for date grouping[/red]") return {} timestamp_str: Optional[str] = None @@ -103,17 +93,11 @@ def _group_by_date(self, data: pl.DataFrame) -> dict[str, pl.DataFrame]: daily_batches[batch_date].append(row) except Exception as e: - self.console.print( - f"[yellow]Warning: Could not process timestamp '{timestamp_str}': {e}[/yellow]" - ) + self.console.print(f"[yellow]Warning: Could not process timestamp '{timestamp_str}': {e}[/yellow]") continue # Convert lists back to DataFrames - return { - date_key: pl.DataFrame(records) - for date_key, records in daily_batches.items() - if records - } + return {date_key: pl.DataFrame(records) for date_key, records in daily_batches.items() if records} def _parse_and_convert_timestamp(self, timestamp_str: str) -> datetime: """Parse timestamp string and convert to UTC.""" @@ -164,9 +148,7 @@ def _parse_and_convert_timestamp(self, timestamp_str: str) -> datetime: except ValueError as e: raise ValueError(f"Could not parse timestamp '{timestamp_str}': {e}") - def _send_daily_batch( - self, batch_date: str, batch_data: pl.DataFrame, operation: str - ) -> None: + def _send_daily_batch(self, batch_date: str, batch_data: pl.DataFrame, operation: str) -> None: """Send a single daily batch to CloudZero API.""" if batch_data.is_empty(): return @@ -184,9 +166,7 @@ def _send_daily_batch( try: with httpx.Client(timeout=30.0) as client: - self.console.print( - f"[blue]Sending batch for {batch_date} ({len(batch_data)} records)[/blue]" - ) + self.console.print(f"[blue]Sending batch for {batch_date} ({len(batch_data)} records)[/blue]") response = client.post(url, headers=headers, json=payload) response.raise_for_status() @@ -196,9 +176,7 @@ def _send_daily_batch( ) except httpx.RequestError as e: - self.console.print( - f"[red]✗ Network error sending batch for {batch_date}: {e}[/red]" - ) + self.console.print(f"[red]✗ Network error sending batch for {batch_date}: {e}[/red]") raise except httpx.HTTPStatusError as e: self.console.print( @@ -206,9 +184,7 @@ def _send_daily_batch( ) raise - def _prepare_batch_payload( - self, batch_date: str, batch_data: pl.DataFrame, operation: str - ) -> dict[str, Any]: + def _prepare_batch_payload(self, batch_date: str, batch_data: pl.DataFrame, operation: str) -> dict[str, Any]: """Prepare batch payload according to CloudZero AnyCost API format.""" # Convert batch_date to month for the API (YYYY-MM format) try: @@ -229,9 +205,7 @@ def _prepare_batch_payload( return payload - def _convert_cbf_to_api_format( - self, row: dict[str, Any] - ) -> Optional[dict[str, Any]]: + def _convert_cbf_to_api_format(self, row: dict[str, Any]) -> Optional[dict[str, Any]]: """Convert CBF row to CloudZero API format - keeping CBF field names as CloudZero expects them.""" try: # CloudZero expects CBF format field names directly, not converted names @@ -253,16 +227,12 @@ def _convert_cbf_to_api_format( # Ensure timestamp is in UTC format if "time/usage_start" in api_record: - api_record["time/usage_start"] = self._ensure_utc_timestamp( - api_record["time/usage_start"] - ) + api_record["time/usage_start"] = self._ensure_utc_timestamp(api_record["time/usage_start"]) return api_record except Exception as e: - self.console.print( - f"[yellow]Warning: Could not convert record to API format: {e}[/yellow]" - ) + self.console.print(f"[yellow]Warning: Could not convert record to API format: {e}[/yellow]") return None def _ensure_utc_timestamp(self, timestamp_str: str) -> str: diff --git a/litellm/integrations/cloudzero/transform.py b/litellm/integrations/cloudzero/transform.py index 2d84796150ae..c72001aee1a9 100644 --- a/litellm/integrations/cloudzero/transform.py +++ b/litellm/integrations/cloudzero/transform.py @@ -78,9 +78,7 @@ def transform(self, data: pl.DataFrame) -> pl.DataFrame: ) if len(cbf_data) > 0: - console.print( - f"[green]✓ Successfully transformed {len(cbf_data):,} records[/green]" - ) + console.print(f"[green]✓ Successfully transformed {len(cbf_data):,} records[/green]") return pl.DataFrame(cbf_data) @@ -100,9 +98,7 @@ def _create_cbf_record(self, row: dict[str, Any]) -> CBFRecord: # Build dimensions for CloudZero model = str(row.get("model", "")) - api_key_hash = str(row.get("api_key", ""))[ - :8 - ] # First 8 chars for identification + api_key_hash = str(row.get("api_key", ""))[:8] # First 8 chars for identification # Handle team information with fallbacks team_id = row.get("team_id") @@ -110,9 +106,7 @@ def _create_cbf_record(self, row: dict[str, Any]) -> CBFRecord: user_email = row.get("user_email") # Use team_alias if available, otherwise team_id, otherwise fallback to 'unknown' - entity_id = ( - str(team_alias) if team_alias else (str(team_id) if team_id else "unknown") - ) + entity_id = str(team_alias) if team_alias else (str(team_id) if team_id else "unknown") # Get alias fields if they exist api_key_alias = row.get("api_key_alias") @@ -152,9 +146,7 @@ def _create_cbf_record(self, row: dict[str, Any]) -> CBFRecord: ) = czrn_components # Build resource/account as concat of api_key_alias and api_key_prefix - resource_account = ( - f"{api_key_alias}|{api_key_hash}" if api_key_alias else api_key_hash - ) + resource_account = f"{api_key_alias}|{api_key_hash}" if api_key_alias else api_key_hash # CloudZero CBF format with proper column names cbf_record = { @@ -171,9 +163,7 @@ def _create_cbf_record(self, row: dict[str, Any]) -> CBFRecord: "resource/service": str(row.get("model_group", "")), # Send model_group "resource/account": resource_account, # Send api_key_alias|api_key_prefix "resource/region": region, # Maps to CZRN region (cross-region) - "resource/usage_family": str( - row.get("custom_llm_provider", "") - ), # Send provider + "resource/usage_family": str(row.get("custom_llm_provider", "")), # Send provider # Action field "action/operation": str(team_id) if team_id else "", # Send team_id # Line item details @@ -182,15 +172,11 @@ def _create_cbf_record(self, row: dict[str, Any]) -> CBFRecord: # Add CZRN components that don't have direct CBF column mappings as resource tags cbf_record["resource/tag:provider"] = provider # CZRN provider component - cbf_record["resource/tag:model"] = ( - cloud_local_id # CZRN cloud-local-id component (model) - ) + cbf_record["resource/tag:model"] = cloud_local_id # CZRN cloud-local-id component (model) # Add resource tags for all dimensions (using resource/tag: format) for key, value in dimensions.items(): - if ( - value and value != "N/A" and value != "unknown" - ): # Only add meaningful tags + if value and value != "N/A" and value != "unknown": # Only add meaningful tags cbf_record[f"resource/tag:{key}"] = str(value) # Add token breakdown as resource tags for analysis (excluding total_tokens per LIT-1907) diff --git a/litellm/integrations/code_interpreter_interception/handler.py b/litellm/integrations/code_interpreter_interception/handler.py index 362581937d72..cd7b211f1a5d 100644 --- a/litellm/integrations/code_interpreter_interception/handler.py +++ b/litellm/integrations/code_interpreter_interception/handler.py @@ -104,9 +104,7 @@ class ChatCompletionFunctionToolChoice(TypedDict): function: dict[str, str] -CodeExecutionFunctionToolChoice = ( - ResponsesFunctionToolChoice | ChatCompletionFunctionToolChoice -) +CodeExecutionFunctionToolChoice = ResponsesFunctionToolChoice | ChatCompletionFunctionToolChoice def _resolve_sandbox_tool(sandbox_tool_name: str | None) -> dict[str, Any] | None: @@ -145,9 +143,7 @@ def __init__( self._container_cache: dict[str, tuple[Any, dict[str, Any] | None, float]] = {} @classmethod - def from_config_yaml( - cls, config: CodeInterpreterInterceptionConfig - ) -> "CodeInterpreterInterceptionLogger": + def from_config_yaml(cls, config: CodeInterpreterInterceptionConfig) -> "CodeInterpreterInterceptionLogger": return cls( enabled=bool(config.get("enabled", True)), enabled_providers=config.get("enabled_providers"), @@ -171,9 +167,7 @@ def initialize_from_proxy_config( ) return CodeInterpreterInterceptionLogger.from_config_yaml(params) - async def async_pre_call_deployment_hook( - self, kwargs: dict[str, Any], call_type: CallTypes | None - ) -> dict | None: + async def async_pre_call_deployment_hook(self, kwargs: dict[str, Any], call_type: CallTypes | None) -> dict | None: if not kwargs.get("_agentic_loop_depth"): kwargs.pop(_INTERCEPTION_ACTIVE_KEY, None) kwargs.pop(_SANDBOX_KEY, None) @@ -187,19 +181,13 @@ async def async_pre_call_deployment_hook( CallTypes.acompletion, ): return None - if ( - self.enabled_providers is not None - and self._resolve_provider(kwargs) not in self.enabled_providers - ): + if self.enabled_providers is not None and self._resolve_provider(kwargs) not in self.enabled_providers: return None tools = kwargs.get("tools") if not isinstance(tools, list): return None - if not any( - isinstance(tool, dict) and tool.get("type") == "code_interpreter" - for tool in tools - ): + if not any(isinstance(tool, dict) and tool.get("type") == "code_interpreter" for tool in tools): return None kwargs[_INTERCEPTION_ACTIVE_KEY] = True @@ -211,11 +199,7 @@ async def async_pre_call_deployment_hook( function_tool = self._get_function_tool(call_type=call_type) kwargs["tools"] = [ - ( - function_tool - if isinstance(tool, dict) and tool.get("type") == "code_interpreter" - else tool - ) + (function_tool if isinstance(tool, dict) and tool.get("type") == "code_interpreter" else tool) for tool in tools ] if self._tool_choice_targets_code_interpreter(kwargs.get("tool_choice")): @@ -256,9 +240,7 @@ def _get_function_parameters() -> CodeExecutionFunctionParameters: "required": ["code"], } - def _get_function_tool( - self, call_type: CallTypes | None - ) -> CodeExecutionFunctionTool: + def _get_function_tool(self, call_type: CallTypes | None) -> CodeExecutionFunctionTool: description = "Execute python code in a sandbox and return stdout." if call_type in (CallTypes.completion, CallTypes.acompletion): return { @@ -299,10 +281,7 @@ def _tool_choice_targets_code_interpreter(tool_choice: Any) -> bool: tool_choice.get("type") == "code_interpreter" or tool_choice.get("name") == "code_interpreter" or tool_choice.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME - or ( - isinstance(function, dict) - and function.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME - ) + or (isinstance(function, dict) and function.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME) ) def _resolve_provider(self, kwargs: dict[str, Any]) -> str | None: @@ -331,16 +310,12 @@ async def async_should_run_agentic_loop( return False, {} if not kwargs.get(_INTERCEPTION_ACTIVE_KEY): return False, {} - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: return False, {} tool_calls = ( self._extract_chat_completion_code_execution_tool_calls(response=response) - if kwargs.get("_agentic_loop_api_surface") - == CHAT_COMPLETION_AGENTIC_SURFACE + if kwargs.get("_agentic_loop_api_surface") == CHAT_COMPLETION_AGENTIC_SURFACE else self._extract_code_execution_tool_calls(response=response) ) if not tool_calls: @@ -381,9 +356,7 @@ async def async_build_agentic_loop_plan( for tool_call in tool_calls: arguments = tool_call.get("arguments", "") code = self._parse_code(arguments) - stdout = await self._run_tool_call( - container=container, params=params, arguments=arguments - ) + stdout = await self._run_tool_call(container=container, params=params, arguments=arguments) input_list.append( { "type": "function_call", @@ -406,9 +379,7 @@ async def async_build_agentic_loop_plan( "status": "completed", "code": code, "container_id": container_id, - "outputs": ( - [{"type": "logs", "logs": stdout}] if stdout else [] - ), + "outputs": ([{"type": "logs", "logs": stdout}] if stdout else []), } ) except Exception: @@ -469,9 +440,7 @@ async def _build_chat_completion_agentic_loop_plan( request_patch = AgenticLoopRequestPatch( model=model, - messages=list(messages) - + [self._build_chat_completion_assistant_message(tool_calls)] - + tool_messages, + messages=list(messages) + [self._build_chat_completion_assistant_message(tool_calls)] + tool_messages, tools=self._get_followup_tools( tools=optional_params.get("tools"), call_type=CallTypes.completion, @@ -500,12 +469,8 @@ async def _build_chat_completion_tool_result( ) -> tuple[ChatCompletionToolMessage, CodeInterpreterCall]: arguments = tool_call.get("arguments", "") code = self._parse_code(arguments) - stdout = await self._run_tool_call( - container=container, params=params, arguments=arguments - ) - tool_call_id = ( - tool_call.get("id") or tool_call.get("call_id") or uuid.uuid4().hex - ) + stdout = await self._run_tool_call(container=container, params=params, arguments=arguments) + tool_call_id = tool_call.get("id") or tool_call.get("call_id") or uuid.uuid4().hex return ( { "role": "tool", @@ -522,9 +487,7 @@ async def _build_chat_completion_tool_result( }, ) - async def async_agentic_loop_cleanup_hook( - self, plan: AgenticLoopPlan, kwargs: dict - ) -> None: + async def async_agentic_loop_cleanup_hook(self, plan: AgenticLoopPlan, kwargs: dict) -> None: metadata = plan.metadata or {} if plan else {} await self._delete_container_for_cache_key(metadata.get("sandbox_key")) @@ -534,14 +497,10 @@ def _filter_agentic_loop_kwargs(kwargs: dict[str, object]) -> dict[str, object]: k: v for k, v in kwargs.items() if k not in {"litellm_logging_obj", "acompletion"} - and not is_interception_internal_key( - k, prefixes=NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES - ) + and not is_interception_internal_key(k, prefixes=NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES) } - def _get_followup_tools( - self, tools: object, call_type: CallTypes | None - ) -> list[dict[str, Any]] | None: + def _get_followup_tools(self, tools: object, call_type: CallTypes | None) -> list[dict[str, Any]] | None: if not isinstance(tools, list): return None return [ @@ -553,21 +512,13 @@ def _get_followup_tools( for tool in tools ] - def _get_followup_optional_params( - self, optional_params: dict[str, object] - ) -> dict[str, object]: - drop_tool_choice = self._tool_choice_targets_code_interpreter( - optional_params.get("tool_choice") - ) + def _get_followup_optional_params(self, optional_params: dict[str, object]) -> dict[str, object]: + drop_tool_choice = self._tool_choice_targets_code_interpreter(optional_params.get("tool_choice")) return { - k: v - for k, v in optional_params.items() - if k != "tools" and not (k == "tool_choice" and drop_tool_choice) + k: v for k, v in optional_params.items() if k != "tools" and not (k == "tool_choice" and drop_tool_choice) } - async def async_post_agentic_loop_response_hook( - self, response: Any, plan: AgenticLoopPlan, kwargs: dict - ) -> Any: + async def async_post_agentic_loop_response_hook(self, response: Any, plan: AgenticLoopPlan, kwargs: dict) -> Any: metadata = plan.metadata or {} if plan else {} await self._delete_container_for_cache_key(metadata.get("sandbox_key")) @@ -576,18 +527,12 @@ async def async_post_agentic_loop_response_hook( return response is_dict = isinstance(response, dict) - output = ( - response.get("output") if is_dict else getattr(response, "output", None) - ) + output = response.get("output") if is_dict else getattr(response, "output", None) if not isinstance(output, list): return response def _item_type(item: Any) -> Any: - return ( - item.get("type") - if isinstance(item, dict) - else getattr(item, "type", None) - ) + return item.get("type") if isinstance(item, dict) else getattr(item, "type", None) insert_at = next( (i for i, item in enumerate(output) if _item_type(item) == "message"), @@ -607,9 +552,7 @@ def _parse_code(arguments: str) -> str: except (json.JSONDecodeError, TypeError, AttributeError): return "" - async def _run_tool_call( - self, container: Any, params: dict[str, Any] | None, arguments: str - ) -> str: + async def _run_tool_call(self, container: Any, params: dict[str, Any] | None, arguments: str) -> str: try: code = json.loads(arguments).get("code", "") if arguments else "" except (json.JSONDecodeError, TypeError): @@ -618,17 +561,11 @@ async def _run_tool_call( result = await self._run_code(container=container, params=params, code=code) if getattr(result, "error", None): error = result.error - message = ( - error.get("value") or error.get("name") - if isinstance(error, dict) - else str(error) - ) + message = error.get("value") or error.get("name") if isinstance(error, dict) else str(error) return f"[execution error] {message}" return getattr(result, "stdout", "") or "" - async def _get_or_create_container( - self, cache_key: str | None - ) -> tuple[Any, dict[str, Any] | None]: + async def _get_or_create_container(self, cache_key: str | None) -> tuple[Any, dict[str, Any] | None]: if cache_key: cached = self._container_cache.get(cache_key) if cached is not None: @@ -657,15 +594,11 @@ async def _create_container(self) -> tuple[Any, dict[str, Any] | None]: ) return container, params - async def _run_code( - self, container: Any, params: dict[str, Any] | None, code: str - ) -> Any: + async def _run_code(self, container: Any, params: dict[str, Any] | None, code: str) -> Any: if self.sandbox_config is not None: return await self.sandbox_config.arun_code(container=container, code=code) if params is None: - raise ValueError( - "CodeInterpreterInterception: no sandbox available to run code." - ) + raise ValueError("CodeInterpreterInterception: no sandbox available to run code.") return await litellm.arun_code( provider=params["sandbox_provider"], container=container, @@ -673,9 +606,7 @@ async def _run_code( api_key=params.get("api_key"), ) - async def _delete_container( - self, container: Any, params: dict[str, Any] | None - ) -> None: + async def _delete_container(self, container: Any, params: dict[str, Any] | None) -> None: try: if self.sandbox_config is not None: await self.sandbox_config.adelete_sandbox(container=container) @@ -689,9 +620,7 @@ async def _delete_container( api_base=params.get("api_base"), ) except Exception: - verbose_logger.exception( - "CodeInterpreterInterception: failed to delete sandbox container" - ) + verbose_logger.exception("CodeInterpreterInterception: failed to delete sandbox container") async def _delete_container_for_cache_key(self, cache_key: str | None) -> None: if not cache_key: @@ -708,9 +637,7 @@ def _normalize_messages(self, messages: Any) -> list[dict[str, Any]]: return list(messages) return [] - def _extract_code_execution_tool_calls( - self, response: object - ) -> list[CodeExecutionToolCall]: + def _extract_code_execution_tool_calls(self, response: object) -> list[CodeExecutionToolCall]: if isinstance(response, dict): output = response.get("output", []) else: @@ -720,17 +647,9 @@ def _extract_code_execution_tool_calls( return [ { - "call_id": ( - item.get("call_id") - if isinstance(item, dict) - else getattr(item, "call_id", None) - ), + "call_id": (item.get("call_id") if isinstance(item, dict) else getattr(item, "call_id", None)), "name": LITELLM_CODE_EXECUTION_TOOL_NAME, - "arguments": ( - item.get("arguments") - if isinstance(item, dict) - else getattr(item, "arguments", "") - ), + "arguments": (item.get("arguments") if isinstance(item, dict) else getattr(item, "arguments", "")), } for item in output if self._is_code_execution_call(item) @@ -751,18 +670,14 @@ def _extract_chat_completion_code_execution_tool_calls( return [ normalized for tool_call in tool_calls - if (normalized := self._normalize_chat_completion_tool_call(tool_call)) - is not None + if (normalized := self._normalize_chat_completion_tool_call(tool_call)) is not None ] @staticmethod def _normalize_chat_completion_tool_call( tool_call: ChatCompletionMessageToolCall, ) -> CodeExecutionToolCall | None: - if ( - tool_call.type != "function" - or tool_call.function.name != LITELLM_CODE_EXECUTION_TOOL_NAME - ): + if tool_call.type != "function" or tool_call.function.name != LITELLM_CODE_EXECUTION_TOOL_NAME: return None arguments = tool_call.function.arguments @@ -814,10 +729,7 @@ def _to_model_response( def _is_code_execution_call(self, item: Any) -> bool: if isinstance(item, dict): - return ( - item.get("type") == "function_call" - and item.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME - ) + return item.get("type") == "function_call" and item.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME return ( getattr(item, "type", None) == "function_call" and getattr(item, "name", None) == LITELLM_CODE_EXECUTION_TOOL_NAME diff --git a/litellm/integrations/compression_interception/handler.py b/litellm/integrations/compression_interception/handler.py index 8899089500dc..c82f9ff477f4 100644 --- a/litellm/integrations/compression_interception/handler.py +++ b/litellm/integrations/compression_interception/handler.py @@ -53,9 +53,7 @@ def __init__( self._compression_cache_by_call_id: Dict[str, Tuple[Dict[str, str], float]] = {} @classmethod - def from_config_yaml( - cls, config: CompressionInterceptionConfig - ) -> "CompressionInterceptionLogger": + def from_config_yaml(cls, config: CompressionInterceptionConfig) -> "CompressionInterceptionLogger": return cls( enabled=bool(config.get("enabled", True)), compression_trigger=int(config.get("compression_trigger", 200_000)), @@ -124,9 +122,7 @@ async def async_pre_call_deployment_hook( kwargs["messages"] = compressed["messages"] if compressed_tools: kwargs["tools"] = self._merge_tools( - existing_tools=cast( - Optional[List[Dict[str, Any]]], kwargs.get("tools") - ), + existing_tools=cast(Optional[List[Dict[str, Any]]], kwargs.get("tools")), compressed_tools=compressed_tools, ) call_id = cast(Optional[str], kwargs.get("litellm_call_id")) @@ -166,9 +162,7 @@ async def async_should_run_agentic_loop( if not self._has_retrieval_tool(tools): return False, {} - tool_calls, thinking_blocks = self._extract_retrieval_tool_calls( - response=response - ) + tool_calls, thinking_blocks = self._extract_retrieval_tool_calls(response=response) if not tool_calls: return False, {} @@ -196,9 +190,7 @@ async def async_build_agentic_loop_plan( call_id = self._resolve_call_id(logging_obj=logging_obj, kwargs=kwargs) cache = self._get_cache(call_id=call_id) - retrieval_results = [ - self._resolve_retrieval_content(tc, cache) for tc in tool_calls - ] + retrieval_results = [self._resolve_retrieval_content(tc, cache) for tc in tool_calls] assistant_message = { "role": "assistant", @@ -228,20 +220,15 @@ async def async_build_agentic_loop_plan( max_tokens = cast( Optional[int], - anthropic_messages_optional_request_params.get("max_tokens") - or kwargs.get("max_tokens"), + anthropic_messages_optional_request_params.get("max_tokens") or kwargs.get("max_tokens"), ) optional_params_without_max_tokens = { - k: v - for k, v in anthropic_messages_optional_request_params.items() - if k != "max_tokens" + k: v for k, v in anthropic_messages_optional_request_params.items() if k != "max_tokens" } full_model_name = model if logging_obj is not None: - agentic_params = logging_obj.model_call_details.get( - "agentic_loop_params", {} - ) + agentic_params = logging_obj.model_call_details.get("agentic_loop_params", {}) full_model_name = cast(str, agentic_params.get("model", model)) request_patch = AgenticLoopRequestPatch( @@ -277,21 +264,15 @@ def _get_cache(self, call_id: Optional[str]) -> Dict[str, str]: return {} return cache_entry[0] - def _resolve_call_id( - self, logging_obj: Any, kwargs: Dict[str, Any] - ) -> Optional[str]: + def _resolve_call_id(self, logging_obj: Any, kwargs: Dict[str, Any]) -> Optional[str]: if logging_obj is not None: logging_call_id = getattr(logging_obj, "litellm_call_id", None) if isinstance(logging_call_id, str) and logging_call_id: return logging_call_id kwargs_call_id = kwargs.get("litellm_call_id") - return cast( - Optional[str], kwargs_call_id if isinstance(kwargs_call_id, str) else None - ) + return cast(Optional[str], kwargs_call_id if isinstance(kwargs_call_id, str) else None) - def _resolve_retrieval_content( - self, tool_call: Dict[str, Any], cache: Dict[str, str] - ) -> str: + def _resolve_retrieval_content(self, tool_call: Dict[str, Any], cache: Dict[str, str]) -> str: raw_input = tool_call.get("input", {}) key = "" if isinstance(raw_input, dict): @@ -302,9 +283,7 @@ def _resolve_retrieval_content( return cache[key] return f"[compressed content key '{key}' not found]" - def _extract_retrieval_tool_calls( - self, response: Any - ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: + def _extract_retrieval_tool_calls(self, response: Any) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: if isinstance(response, dict): content = response.get("content", []) else: @@ -322,10 +301,7 @@ def _extract_retrieval_tool_calls( block_name = block.get("name") if block_type in ("thinking", "redacted_thinking"): thinking_blocks.append(block) - if ( - block_type == "tool_use" - and block_name == LITELLM_CONTENT_RETRIEVE_TOOL_NAME - ): + if block_type == "tool_use" and block_name == LITELLM_CONTENT_RETRIEVE_TOOL_NAME: tool_calls.append( { "id": block.get("id"), @@ -352,10 +328,7 @@ def _extract_retrieval_tool_calls( "data": getattr(block, "data", ""), } ) - if ( - block_type == "tool_use" - and block_name == LITELLM_CONTENT_RETRIEVE_TOOL_NAME - ): + if block_type == "tool_use" and block_name == LITELLM_CONTENT_RETRIEVE_TOOL_NAME: tool_calls.append( { "id": getattr(block, "id", None), @@ -370,9 +343,7 @@ def _extract_retrieval_tool_calls( def _prepare_followup_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: internal_keys = {"litellm_logging_obj"} return { - k: v - for k, v in kwargs.items() - if not k.startswith("_compression_interception") and k not in internal_keys + k: v for k, v in kwargs.items() if not k.startswith("_compression_interception") and k not in internal_keys } def _has_retrieval_tool(self, tools: Any) -> bool: @@ -385,10 +356,7 @@ def _has_retrieval_tool(self, tools: Any) -> bool: if tool.get("type") == "function" and isinstance(function, dict): if function.get("name") == LITELLM_CONTENT_RETRIEVE_TOOL_NAME: return True - if ( - tool.get("type") == "custom" - and tool.get("name") == LITELLM_CONTENT_RETRIEVE_TOOL_NAME - ): + if tool.get("type") == "custom" and tool.get("name") == LITELLM_CONTENT_RETRIEVE_TOOL_NAME: return True return False diff --git a/litellm/integrations/custom_batch_logger.py b/litellm/integrations/custom_batch_logger.py index 8f4844501c37..aded12fa399b 100644 --- a/litellm/integrations/custom_batch_logger.py +++ b/litellm/integrations/custom_batch_logger.py @@ -41,20 +41,14 @@ def __init__( self.batch_size: int = batch_size or litellm.DEFAULT_BATCH_SIZE self.last_flush_time = time.time() self.flush_lock = flush_lock - self.max_queue_size: int = ( - max_queue_size - if max_queue_size is not None - else self.DEFAULT_MAX_QUEUE_SIZE - ) + self.max_queue_size: int = max_queue_size if max_queue_size is not None else self.DEFAULT_MAX_QUEUE_SIZE super().__init__(**kwargs) async def periodic_flush(self): while True: await asyncio.sleep(self.flush_interval) - verbose_logger.debug( - f"CustomLogger periodic flush after {self.flush_interval} seconds" - ) + verbose_logger.debug(f"CustomLogger periodic flush after {self.flush_interval} seconds") await self.flush_queue() async def flush_queue(self): @@ -64,9 +58,7 @@ async def flush_queue(self): async with self.flush_lock: if self.log_queue: log_queue_length = len(self.log_queue) - verbose_logger.debug( - "CustomLogger: Flushing batch of %s events", len(self.log_queue) - ) + verbose_logger.debug("CustomLogger: Flushing batch of %s events", len(self.log_queue)) try: await self.async_send_batch() except Exception: @@ -76,8 +68,7 @@ async def flush_queue(self): # their own errors, so this only affects loggers that opt # in to surfacing failures (e.g. Rubrik). verbose_logger.exception( - "CustomLogger: async_send_batch raised; preserving " - "%s events in queue for retry", + "CustomLogger: async_send_batch raised; preserving %s events in queue for retry", log_queue_length, ) # Guard against unbounded queue growth if the destination @@ -87,8 +78,7 @@ async def flush_queue(self): if overflow > 0: del self.log_queue[:overflow] verbose_logger.warning( - "CustomLogger: log queue exceeded max_queue_size=%s; " - "dropped %s oldest events.", + "CustomLogger: log queue exceeded max_queue_size=%s; dropped %s oldest events.", self.max_queue_size, overflow, ) diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py index 38245a2e5baa..59d37639098d 100644 --- a/litellm/integrations/custom_guardrail.py +++ b/litellm/integrations/custom_guardrail.py @@ -86,9 +86,7 @@ def __init__( self, guardrail_name: Optional[str] = None, supported_event_hooks: Optional[List[GuardrailEventHooks]] = None, - event_hook: Optional[ - Union[GuardrailEventHooks, List[GuardrailEventHooks], Mode] - ] = None, + event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks], Mode]] = None, default_on: bool = False, mask_request_content: bool = False, mask_response_content: bool = False, @@ -120,9 +118,7 @@ def __init__( """ self.guardrail_name = guardrail_name self.supported_event_hooks = supported_event_hooks - self.event_hook: Optional[ - Union[GuardrailEventHooks, List[GuardrailEventHooks], Mode] - ] = event_hook + self.event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks], Mode]] = event_hook self.default_on: bool = default_on self.mask_request_content: bool = mask_request_content self.mask_response_content: bool = mask_response_content @@ -131,9 +127,7 @@ def __init__( self.on_violation: Optional[str] = on_violation self.realtime_violation_message: Optional[str] = realtime_violation_message self.on_sensitive_data: Optional[str] = on_sensitive_data - self.sensitive_data_route_to_model: Optional[str] = ( - sensitive_data_route_to_model - ) + self.sensitive_data_route_to_model: Optional[str] = sensitive_data_route_to_model self.sticky_session_routing: bool = sticky_session_routing if supported_event_hooks: @@ -141,9 +135,7 @@ def __init__( self._validate_event_hook(event_hook, supported_event_hooks) super().__init__(**kwargs) - def render_violation_message( - self, default: str, context: Optional[Dict[str, Any]] = None - ) -> str: + def render_violation_message(self, default: str, context: Optional[Dict[str, Any]] = None) -> str: """Return a custom violation message if template is configured.""" if not self.violation_message_template: @@ -247,9 +239,7 @@ def raise_sensitive_data_route_exception( sticky_session_routing=self.sticky_session_routing, ) - def _get_session_id_from_request_data( - self, request_data: Dict[str, Any] - ) -> Optional[str]: + def _get_session_id_from_request_data(self, request_data: Dict[str, Any]) -> Optional[str]: """Extract session_id from request data.""" return get_session_id_from_request_data(request_data) @@ -258,10 +248,7 @@ def should_route_on_sensitive_data(self) -> bool: Returns True if this guardrail is configured to route requests to a different model when sensitive data is detected. """ - return ( - self.on_sensitive_data == "route" - and self.sensitive_data_route_to_model is not None - ) + return self.on_sensitive_data == "route" and self.sensitive_data_route_to_model is not None def handle_sensitive_data_detection( self, @@ -297,8 +284,7 @@ def handle_sensitive_data_detection( except ValueError: raise GuardrailRaisedException( message=( - f"Sensitive data detected by {self.guardrail_name} " - "(routing skipped: request has no session_id)" + f"Sensitive data detected by {self.guardrail_name} (routing skipped: request has no session_id)" ), guardrail_name=self.guardrail_name, ) @@ -319,9 +305,7 @@ def get_config_model() -> Optional[Type["GuardrailConfigModel"]]: def _validate_event_hook( self, - event_hook: Optional[ - Union[GuardrailEventHooks, List[GuardrailEventHooks], Mode] - ], + event_hook: Optional[Union[GuardrailEventHooks, List[GuardrailEventHooks], Mode]], supported_event_hooks: List[GuardrailEventHooks], ) -> None: def _validate_event_hook_list_is_in_supported_event_hooks( @@ -332,18 +316,14 @@ def _validate_event_hook_list_is_in_supported_event_hooks( if isinstance(hook, str): hook = GuardrailEventHooks(hook) if hook not in supported_event_hooks: - raise ValueError( - f"Event hook {hook} is not in the supported event hooks {supported_event_hooks}" - ) + raise ValueError(f"Event hook {hook} is not in the supported event hooks {supported_event_hooks}") if event_hook is None: return if isinstance(event_hook, str): event_hook = GuardrailEventHooks(event_hook) if isinstance(event_hook, list): - _validate_event_hook_list_is_in_supported_event_hooks( - event_hook, supported_event_hooks - ) + _validate_event_hook_list_is_in_supported_event_hooks(event_hook, supported_event_hooks) elif isinstance(event_hook, Mode): tag_values_flat: list = [] for v in event_hook.tags.values(): @@ -351,23 +331,13 @@ def _validate_event_hook_list_is_in_supported_event_hooks( tag_values_flat.extend(v) else: tag_values_flat.append(v) - _validate_event_hook_list_is_in_supported_event_hooks( - tag_values_flat, supported_event_hooks - ) + _validate_event_hook_list_is_in_supported_event_hooks(tag_values_flat, supported_event_hooks) if event_hook.default: - default_list = ( - event_hook.default - if isinstance(event_hook.default, list) - else [event_hook.default] - ) - _validate_event_hook_list_is_in_supported_event_hooks( - default_list, supported_event_hooks - ) + default_list = event_hook.default if isinstance(event_hook.default, list) else [event_hook.default] + _validate_event_hook_list_is_in_supported_event_hooks(default_list, supported_event_hooks) elif isinstance(event_hook, GuardrailEventHooks): if event_hook not in supported_event_hooks: - raise ValueError( - f"Event hook {event_hook} is not in the supported event hooks {supported_event_hooks}" - ) + raise ValueError(f"Event hook {event_hook} is not in the supported event hooks {supported_event_hooks}") @staticmethod def _get_admin_metadata(data: dict) -> dict: @@ -431,9 +401,7 @@ def _is_valid_response_type(self, result: Any) -> bool: return True raise - def get_guardrail_from_metadata( - self, data: dict - ) -> Union[List[str], List[Dict[str, DynamicGuardrailParams]]]: + def get_guardrail_from_metadata(self, data: dict) -> Union[List[str], List[Dict[str, DynamicGuardrailParams]]]: """ Returns the guardrail(s) to be run from the metadata or root """ @@ -522,12 +490,7 @@ async def async_pre_call_deployment_hook( if self._pre_call_hook_already_ran(kwargs): return kwargs - if ( - self.should_run_guardrail( - data=kwargs, event_type=GuardrailEventHooks.pre_call - ) - is not True - ): + if self.should_run_guardrail(data=kwargs, event_type=GuardrailEventHooks.pre_call) is not True: return kwargs # CHECK IF GUARDRAIL REJECTS THE REQUEST @@ -568,12 +531,7 @@ async def async_post_call_success_deployment_hook( if litellm_guardrails is None or not isinstance(litellm_guardrails, list): return response - if ( - self.should_run_guardrail( - data=request_data, event_type=GuardrailEventHooks.post_call - ) - is not True - ): + if self.should_run_guardrail(data=request_data, event_type=GuardrailEventHooks.post_call) is not True: return response # CHECK IF GUARDRAIL REJECTS THE REQUEST @@ -604,9 +562,7 @@ def should_run_guardrail( """ requested_guardrails = self.get_guardrail_from_metadata(data) disable_global_guardrail = self.get_disable_global_guardrail(data) - opted_out_global_guardrails = ( - self.get_opted_out_global_guardrails_from_metadata(data) - ) + opted_out_global_guardrails = self.get_opted_out_global_guardrails_from_metadata(data) verbose_logger.debug( "inside should_run_guardrail for guardrail=%s event_type= %s guardrail_supported_event_hooks= %s requested_guardrails= %s self.default_on= %s", self.guardrail_name, @@ -615,10 +571,7 @@ def should_run_guardrail( requested_guardrails, self.default_on, ) - if ( - self.default_on is True - and self.guardrail_name in opted_out_global_guardrails - ): + if self.default_on is True and self.guardrail_name in opted_out_global_guardrails: return False if self.default_on is True and disable_global_guardrail is True: @@ -662,9 +615,7 @@ def should_run_guardrail( raise ImportError( "Setting tag-based guardrails is only available in litellm-enterprise. You must be a premium user to use this feature." ) - result = EnterpriseCustomGuardrailHelper._should_run_if_mode_by_tag( - data, self.event_hook, event_type - ) + result = EnterpriseCustomGuardrailHelper._should_run_if_mode_by_tag(data, self.event_hook, event_type) if result is not None: return result return True @@ -690,9 +641,7 @@ def _event_hook_is_event_type(self, event_type: GuardrailEventHooks) -> bool: return True if self.event_hook.default: default_list = ( - self.event_hook.default - if isinstance(self.event_hook.default, list) - else [self.event_hook.default] + self.event_hook.default if isinstance(self.event_hook.default, list) else [self.event_hook.default] ) return event_type.value in default_list return False @@ -722,9 +671,7 @@ def get_guardrail_dynamic_request_body_params(self, request_data: dict) -> dict: for guardrail in requested_guardrails: if isinstance(guardrail, dict) and self.guardrail_name in guardrail: # Get the configuration for this guardrail - guardrail_config: DynamicGuardrailParams = DynamicGuardrailParams( - **guardrail[self.guardrail_name] - ) + guardrail_config: DynamicGuardrailParams = DynamicGuardrailParams(**guardrail[self.guardrail_name]) extra_body = guardrail_config.get("extra_body", {}) if self._validate_premium_user() is not True: if isinstance(extra_body, dict) and extra_body: @@ -779,9 +726,7 @@ def add_standard_logging_guardrail_information_to_request_data( from litellm.types.utils import GuardrailMode # Use event_type if provided, otherwise fall back to self.event_hook - guardrail_mode: Union[ - GuardrailEventHooks, GuardrailMode, List[GuardrailEventHooks] - ] + guardrail_mode: Union[GuardrailEventHooks, GuardrailMode, List[GuardrailEventHooks]] if event_type is not None: guardrail_mode = event_type elif isinstance(self.event_hook, Mode): @@ -795,9 +740,7 @@ def add_standard_logging_guardrail_information_to_request_data( # Sanitize the response to ensure it's JSON serializable and free of circular refs # This prevents RecursionErrors in downstream loggers (Langfuse, Datadog, etc.) - clean_guardrail_response = filter_exceptions_from_params( - guardrail_json_response - ) + clean_guardrail_response = filter_exceptions_from_params(guardrail_json_response) # Strip secret_fields to prevent plaintext Authorization headers from # being persisted to spend logs, OTEL traces, or other logging backends. @@ -812,9 +755,7 @@ def add_standard_logging_guardrail_information_to_request_data( # Default-safe behavior: never persist raw matched spans in standard # guardrail logging payloads (single shared implementation; Bedrock hooks pass # raw provider JSON so redaction is not duplicated upstream). - clean_guardrail_response = redact_nested_match_and_regex_keys( - clean_guardrail_response - ) + clean_guardrail_response = redact_nested_match_and_regex_keys(clean_guardrail_response) slg = StandardLoggingGuardrailInformation( guardrail_name=self.guardrail_name, @@ -908,9 +849,7 @@ def _process_response( This gets logged on downsteam Langfuse, DataDog, etc. """ # Convert None to empty dict to satisfy type requirements - guardrail_response: Union[Dict[str, Any], str] = ( - {} if response is None else response - ) + guardrail_response: Union[Dict[str, Any], str] = {} if response is None else response # For apply_guardrail functions in custom_code_guardrail scenario, # simplify the logged response to "allow", "deny", or "mask" @@ -958,11 +897,7 @@ def _is_guardrail_intervention(e: Exception) -> bool: ), ): return True - if ( - HTTPException is not None - and isinstance(e, HTTPException) - and e.status_code == 400 - ): + if HTTPException is not None and isinstance(e, HTTPException) and e.status_code == 400: return True return False @@ -981,9 +916,7 @@ def _process_error( This gets logged on downsteam Langfuse, DataDog, etc. """ guardrail_status: GuardrailStatus = ( - "guardrail_intervened" - if self._is_guardrail_intervention(e) - else "guardrail_failed_to_respond" + "guardrail_intervened" if self._is_guardrail_intervention(e) else "guardrail_failed_to_respond" ) # For custom_code_guardrail scenario, log as "deny" instead of full exception # Check if this is from custom_code_guardrail by checking the class name @@ -1071,10 +1004,7 @@ def get_guardrails_messages_for_call_type( # /responses # User/System messages are stored in the "input" key, use litellm transformation to get the messages ######################################################### - if ( - call_type == CallTypes.responses.value - or call_type == CallTypes.aresponses.value - ): + if call_type == CallTypes.responses.value or call_type == CallTypes.aresponses.value: from typing import cast from litellm.responses.litellm_completion_transformation.transformation import ( @@ -1093,6 +1023,41 @@ def get_guardrails_messages_for_call_type( return None +def _append_slg_to_litellm_params(lp: object, entries: list) -> None: + """Merge guardrail entries into a single litellm_params dict.""" + if not isinstance(lp, dict): + return + if lp.get("metadata") is None: + lp["metadata"] = {} + existing = lp["metadata"].setdefault("standard_logging_guardrail_information", []) + for entry in entries: + if entry not in existing: + existing.append(entry) + + +def _sync_guardrail_info_to_logging_obj(request_data: dict, logging_obj: object) -> None: + """Copy standard_logging_guardrail_information from request_data into logging_obj. + + The @log_guardrail_information decorator writes guardrail info to + request_data["metadata"] or request_data["litellm_metadata"]. For + passthrough routes (/v1/messages, /v1/responses) the spend-log payload is + built from logging_obj.litellm_params["metadata"], which is a separate dict + that does not share identity with the one in request_data. This helper + bridges that gap so guardrail_information is non-null in spend logs for all + routes, not just /v1/chat/completions. + """ + if logging_obj is None: + return + meta_src = request_data.get("metadata") or request_data.get("litellm_metadata") or {} + slg_info = meta_src.get("standard_logging_guardrail_information") + if not slg_info: + return + entries: list = slg_info if isinstance(slg_info, list) else [slg_info] + mcd = getattr(logging_obj, "model_call_details", None) or {} + _append_slg_to_litellm_params(getattr(logging_obj, "litellm_params", None), entries) + _append_slg_to_litellm_params(mcd.get("litellm_params"), entries) + + def log_guardrail_information(func): """ Decorator to add standard logging guardrail information to any function @@ -1153,6 +1118,7 @@ async def async_wrapper(*args, **kwargs): if func.__name__ == "apply_guardrail" and "inputs" in kwargs: original_inputs = kwargs.get("inputs") + logging_obj = kwargs.get("logging_obj") entries_before = _count_recorded_guardrail_entries(request_data) try: response = await func(*args, **kwargs) @@ -1178,6 +1144,8 @@ async def async_wrapper(*args, **kwargs): duration=(datetime.now() - start_time).total_seconds(), event_type=event_type, ) + finally: + _sync_guardrail_info_to_logging_obj(request_data, logging_obj) @functools.wraps(func) def sync_wrapper(*args, **kwargs): @@ -1191,6 +1159,7 @@ def sync_wrapper(*args, **kwargs): if func.__name__ == "apply_guardrail" and "inputs" in kwargs: original_inputs = kwargs.get("inputs") + logging_obj = kwargs.get("logging_obj") entries_before = _count_recorded_guardrail_entries(request_data) try: response = func(*args, **kwargs) @@ -1212,6 +1181,8 @@ def sync_wrapper(*args, **kwargs): duration=(datetime.now() - start_time).total_seconds(), event_type=event_type, ) + finally: + _sync_guardrail_info_to_logging_obj(request_data, logging_obj) @functools.wraps(func) def wrapper(*args, **kwargs): diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.py index 6d65b4ec0d26..108928871b0c 100644 --- a/litellm/integrations/custom_logger.py +++ b/litellm/integrations/custom_logger.py @@ -145,9 +145,7 @@ async def async_log_stream_event(self, kwargs, response_obj, start_time, end_tim async def async_log_pre_api_call(self, model, messages, kwargs): pass - async def async_pre_request_hook( - self, model: str, messages: List, kwargs: Dict - ) -> Optional[Dict]: + async def async_pre_request_hook(self, model: str, messages: List, kwargs: Dict) -> Optional[Dict]: """ Hook called before making the API request to allow modifying request parameters. @@ -273,9 +271,7 @@ async def async_pre_call_deployment_hook( """ pass - async def async_pre_call_check( - self, deployment: dict, parent_otel_span: Optional[Span] - ) -> Optional[dict]: + async def async_pre_call_check(self, deployment: dict, parent_otel_span: Optional[Span]) -> Optional[dict]: pass def pre_call_check(self, deployment: dict) -> Optional[dict]: @@ -311,29 +307,21 @@ async def log_model_group_rate_limit_error( ): pass - async def log_success_fallback_event( - self, original_model_group: str, kwargs: dict, original_exception: Exception - ): + async def log_success_fallback_event(self, original_model_group: str, kwargs: dict, original_exception: Exception): pass - async def log_failure_fallback_event( - self, original_model_group: str, kwargs: dict, original_exception: Exception - ): + async def log_failure_fallback_event(self, original_model_group: str, kwargs: dict, original_exception: Exception): pass #### ADAPTERS #### Allow calling 100+ LLMs in custom format - https://github.com/BerriAI/litellm/pulls - def translate_completion_input_params( - self, kwargs - ) -> Optional[ChatCompletionRequest]: + def translate_completion_input_params(self, kwargs) -> Optional[ChatCompletionRequest]: """ Translates the input params, from the provider's native format to the litellm.completion() format. """ pass - def translate_completion_output_params( - self, response: ModelResponse - ) -> Optional[BaseModel]: + def translate_completion_output_params(self, response: ModelResponse) -> Optional[BaseModel]: """ Translates the output params, from the OpenAI format to the custom format. """ @@ -435,15 +423,11 @@ async def async_post_call_success_hook( ) -> Any: pass - async def async_logging_hook( - self, kwargs: dict, result: Any, call_type: str - ) -> Tuple[dict, Any]: + async def async_logging_hook(self, kwargs: dict, result: Any, call_type: str) -> Tuple[dict, Any]: """For masking logged request/response. Return a modified version of the request/result.""" return kwargs, result - def logging_hook( - self, kwargs: dict, result: Any, call_type: str - ) -> Tuple[dict, Any]: + def logging_hook(self, kwargs: dict, result: Any, call_type: str) -> Tuple[dict, Any]: """For masking logged request/response. Return a modified version of the request/result.""" return kwargs, result @@ -485,9 +469,7 @@ def log_input_event(self, model, messages, kwargs, print_verbose, callback_func) except Exception: print_verbose(f"Custom Logger Error - {traceback.format_exc()}") - async def async_log_input_event( - self, model, messages, kwargs, print_verbose, callback_func - ): + async def async_log_input_event(self, model, messages, kwargs, print_verbose, callback_func): try: kwargs["model"] = model kwargs["messages"] = messages @@ -499,9 +481,7 @@ async def async_log_input_event( except Exception: print_verbose(f"Custom Logger Error - {traceback.format_exc()}") - def log_event( - self, kwargs, response_obj, start_time, end_time, print_verbose, callback_func - ): + def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose, callback_func): # Method definition try: kwargs["log_event_type"] = "post_api_call" @@ -515,9 +495,7 @@ def log_event( print_verbose(f"Custom Logger Error - {traceback.format_exc()}") pass - async def async_log_event( - self, kwargs, response_obj, start_time, end_time, print_verbose, callback_func - ): + async def async_log_event(self, kwargs, response_obj, start_time, end_time, print_verbose, callback_func): # Method definition try: kwargs["log_event_type"] = "post_api_call" @@ -834,15 +812,12 @@ def _truncate_field( def _truncate_text(self, text: str, max_length: int) -> str: """Truncate text if it exceeds max_length""" return ( - text[:max_length] - + "...truncated by litellm, this logger does not support large content" + text[:max_length] + "...truncated by litellm, this logger does not support large content" if len(text) > max_length else text ) - def _select_metadata_field( - self, request_kwargs: Optional[Dict] = None - ) -> Optional[str]: + def _select_metadata_field(self, request_kwargs: Optional[Dict] = None) -> Optional[str]: """ Select the metadata field to use for logging @@ -857,9 +832,7 @@ def _select_metadata_field( return LITELLM_METADATA_FIELD return OLD_LITELLM_METADATA_FIELD - def redact_standard_logging_payload_from_model_call_details( - self, model_call_details: Dict - ) -> Dict: + def redact_standard_logging_payload_from_model_call_details(self, model_call_details: Dict) -> Dict: """ Redacts or excludes fields from StandardLoggingPayload before callbacks receive it. @@ -876,12 +849,8 @@ def redact_standard_logging_payload_from_model_call_details( from litellm import Choices, Message, ModelResponse - turn_off_message_logging: bool = getattr( - self, "turn_off_message_logging", False - ) - excluded_fields: Optional[List[str]] = getattr( - litellm, "standard_logging_payload_excluded_fields", None - ) + turn_off_message_logging: bool = getattr(self, "turn_off_message_logging", False) + excluded_fields: Optional[List[str]] = getattr(litellm, "standard_logging_payload_excluded_fields", None) # Early return if no processing needed if turn_off_message_logging is False and not excluded_fields: @@ -907,18 +876,10 @@ def redact_standard_logging_payload_from_model_call_details( if turn_off_message_logging: redacted_str = "redacted-by-litellm" - if ( - "messages" not in (excluded_fields or []) - and standard_logging_object_copy.get("messages") is not None - ): - standard_logging_object_copy["messages"] = [ - Message(content=redacted_str).model_dump() - ] - - if ( - "response" not in (excluded_fields or []) - and standard_logging_object_copy.get("response") is not None - ): + if "messages" not in (excluded_fields or []) and standard_logging_object_copy.get("messages") is not None: + standard_logging_object_copy["messages"] = [Message(content=redacted_str).model_dump()] + + if "response" not in (excluded_fields or []) and standard_logging_object_copy.get("response") is not None: response = standard_logging_object_copy["response"] # Check if this is a ResponsesAPIResponse (has "output" field) if isinstance(response, dict) and "output" in response: @@ -929,30 +890,20 @@ def redact_standard_logging_payload_from_model_call_details( # Redact content in output array if isinstance(response_copy.get("output"), list): for output_item in response_copy["output"]: - if ( - isinstance(output_item, dict) - and "content" in output_item - ): + if isinstance(output_item, dict) and "content" in output_item: if isinstance(output_item["content"], list): # Redact text in content items for content_item in output_item["content"]: - if ( - isinstance(content_item, dict) - and "text" in content_item - ): + if isinstance(content_item, dict) and "text" in content_item: content_item["text"] = redacted_str standard_logging_object_copy["response"] = response_copy else: # Standard ModelResponse format - model_response = ModelResponse( - choices=[Choices(message=Message(content=redacted_str))] - ) + model_response = ModelResponse(choices=[Choices(message=Message(content=redacted_str))]) model_response_dict = model_response.model_dump() standard_logging_object_copy["response"] = model_response_dict - model_call_details_copy["standard_logging_object"] = ( - standard_logging_object_copy - ) + model_call_details_copy["standard_logging_object"] = standard_logging_object_copy return model_call_details_copy async def get_proxy_server_request_from_cold_storage_with_object_key( @@ -978,12 +929,8 @@ def handle_callback_failure(self, callback_name: str): for callback_obj in all_callbacks: if hasattr(callback_obj, "increment_callback_logging_failure"): - verbose_logger.debug( - f"Incrementing callback failure metric for {callback_name}" - ) - callback_obj.increment_callback_logging_failure( - callback_name=callback_name - ) # type: ignore + verbose_logger.debug(f"Incrementing callback failure metric for {callback_name}") + callback_obj.increment_callback_logging_failure(callback_name=callback_name) # type: ignore return verbose_logger.debug( @@ -994,9 +941,7 @@ def handle_callback_failure(self, callback_name: str): except Exception as e: from litellm._logging import verbose_logger - verbose_logger.debug( - f"Error in handle_callback_failure for {callback_name}: {str(e)}" - ) + verbose_logger.debug(f"Error in handle_callback_failure for {callback_name}: {str(e)}") async def _strip_base64_from_messages( self, @@ -1015,14 +960,10 @@ async def _strip_base64_from_messages( """ raw_messages: Any = payload.get("messages", []) messages: List[Any] = raw_messages if isinstance(raw_messages, list) else [] - verbose_logger.debug( - f"[CustomLogger] Stripping base64 from {len(messages)} messages" - ) + verbose_logger.debug(f"[CustomLogger] Stripping base64 from {len(messages)} messages") if messages: - payload["messages"] = self._process_messages( - messages=messages, max_depth=max_depth - ) + payload["messages"] = self._process_messages(messages=messages, max_depth=max_depth) total_items = 0 for m in payload.get("messages", []) or []: @@ -1031,9 +972,7 @@ async def _strip_base64_from_messages( if isinstance(content, list): total_items += len(content) - verbose_logger.debug( - f"[CustomLogger] Completed base64 strip; retained {total_items} content items" - ) + verbose_logger.debug(f"[CustomLogger] Completed base64 strip; retained {total_items} content items") return payload def _strip_base64_from_messages_sync( @@ -1053,14 +992,10 @@ def _strip_base64_from_messages_sync( """ raw_messages: Any = payload.get("messages", []) messages: List[Any] = raw_messages if isinstance(raw_messages, list) else [] - verbose_logger.debug( - f"[CustomLogger] Stripping base64 from {len(messages)} messages" - ) + verbose_logger.debug(f"[CustomLogger] Stripping base64 from {len(messages)} messages") if messages: - payload["messages"] = self._process_messages( - messages=messages, max_depth=max_depth - ) + payload["messages"] = self._process_messages(messages=messages, max_depth=max_depth) total_items = 0 for m in payload.get("messages", []) or []: @@ -1069,9 +1004,7 @@ def _strip_base64_from_messages_sync( if isinstance(content, list): total_items += len(content) - verbose_logger.debug( - f"[CustomLogger] Completed base64 strip; retained {total_items} content items" - ) + verbose_logger.debug(f"[CustomLogger] Completed base64 strip; retained {total_items} content items") return payload def _redact_base64( @@ -1082,30 +1015,20 @@ def _redact_base64( ) -> Any: """Recursively redact inline base64 from any nested structure with a max recursion depth limit.""" if depth > max_depth: - verbose_logger.warning( - f"[CustomLogger] Max recursion depth {max_depth} reached while redacting base64" - ) + verbose_logger.warning(f"[CustomLogger] Max recursion depth {max_depth} reached while redacting base64") return "[MAX_DEPTH_REACHED]" if isinstance(value, str): if _BASE64_INLINE_PATTERN.search(value): - verbose_logger.debug( - f"[CustomLogger] Redacted inline base64 string: {value[:40]}..." - ) + verbose_logger.debug(f"[CustomLogger] Redacted inline base64 string: {value[:40]}...") return _BASE64_INLINE_PATTERN.sub("[BASE64_REDACTED]", value) return value if isinstance(value, list): - return [ - self._redact_base64(value=v, depth=depth + 1, max_depth=max_depth) - for v in value - ] + return [self._redact_base64(value=v, depth=depth + 1, max_depth=max_depth) for v in value] if isinstance(value, dict): - return { - k: self._redact_base64(value=v, depth=depth + 1, max_depth=max_depth) - for k, v in value.items() - } + return {k: self._redact_base64(value=v, depth=depth + 1, max_depth=max_depth) for k, v in value.items()} return value @@ -1132,14 +1055,10 @@ def _process_messages( cleaned: List[Any] = [] for c in contents: if self._should_keep_content(content=c): - cleaned.append( - self._redact_base64(value=c, max_depth=max_depth) - ) + cleaned.append(self._redact_base64(value=c, max_depth=max_depth)) msg["content"] = cleaned else: - msg["content"] = self._redact_base64( - value=contents, max_depth=max_depth - ) + msg["content"] = self._redact_base64(value=contents, max_depth=max_depth) for key, val in list(msg.items()): if key != "content": diff --git a/litellm/integrations/custom_prompt_management.py b/litellm/integrations/custom_prompt_management.py index 61e619aba651..fbca1867793c 100644 --- a/litellm/integrations/custom_prompt_management.py +++ b/litellm/integrations/custom_prompt_management.py @@ -18,9 +18,7 @@ def __init__( **kwargs, ): self.ignore_prompt_manager_model = ignore_prompt_manager_model - self.ignore_prompt_manager_optional_params = ( - ignore_prompt_manager_optional_params - ) + self.ignore_prompt_manager_optional_params = ignore_prompt_manager_optional_params def get_chat_completion_prompt( self, @@ -65,9 +63,7 @@ def _compile_prompt_helper( prompt_label: Optional[str] = None, prompt_version: Optional[int] = None, ) -> PromptManagementClient: - raise NotImplementedError( - "Custom prompt management does not support compile prompt helper" - ) + raise NotImplementedError("Custom prompt management does not support compile prompt helper") async def async_compile_prompt_helper( self, @@ -78,6 +74,4 @@ async def async_compile_prompt_helper( prompt_label: Optional[str] = None, prompt_version: Optional[int] = None, ) -> PromptManagementClient: - raise NotImplementedError( - "Custom prompt management does not support async compile prompt helper" - ) + raise NotImplementedError("Custom prompt management does not support async compile prompt helper") diff --git a/litellm/integrations/custom_secret_manager.py b/litellm/integrations/custom_secret_manager.py index 45ffa2e08cf1..a1bb7b00d92b 100644 --- a/litellm/integrations/custom_secret_manager.py +++ b/litellm/integrations/custom_secret_manager.py @@ -224,14 +224,10 @@ def validate_environment(self) -> bool: Raises: ValueError: If required configuration is missing """ - verbose_logger.debug( - "No environment validation configured for custom secret manager" - ) + verbose_logger.debug("No environment validation configured for custom secret manager") return True - async def async_health_check( - self, timeout: Optional[Union[float, httpx.Timeout]] = None - ) -> bool: + async def async_health_check(self, timeout: Optional[Union[float, httpx.Timeout]] = None) -> bool: """ Perform a health check on your secret manager. @@ -243,9 +239,7 @@ async def async_health_check( Returns: True if the secret manager is healthy, False otherwise """ - verbose_logger.debug( - f"Health check not implemented for {self.secret_manager_name}" - ) + verbose_logger.debug(f"Health check not implemented for {self.secret_manager_name}") return True def __repr__(self) -> str: diff --git a/litellm/integrations/datadog/datadog.py b/litellm/integrations/datadog/datadog.py index b0cd0eb11727..6775858c1242 100644 --- a/litellm/integrations/datadog/datadog.py +++ b/litellm/integrations/datadog/datadog.py @@ -129,9 +129,7 @@ def __init__( if self.is_mock_mode: create_mock_datadog_client() - verbose_logger.debug( - "[DATADOG MOCK] Datadog logger initialized in mock mode" - ) + verbose_logger.debug("[DATADOG MOCK] Datadog logger initialized in mock mode") ######################################################### # Handle datadog_params set as litellm.datadog_params @@ -139,9 +137,7 @@ def __init__( dict_datadog_params = self._get_datadog_params() kwargs.update(dict_datadog_params) - self.async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) # Configure DataDog endpoint (Agent or Direct API) # Prefer explicit kwargs, then fall back to env vars @@ -173,9 +169,7 @@ def __init__( batch_size=_resolve_dd_batch_size(), ) except Exception as e: - verbose_logger.exception( - f"Datadog: Got exception on init Datadog client {str(e)}" - ) + verbose_logger.exception(f"Datadog: Got exception on init Datadog client {str(e)}") raise e def _get_datadog_params(self) -> Dict: @@ -190,9 +184,7 @@ def _get_datadog_params(self) -> Dict: dict_datadog_params = litellm.datadog_params.model_dump() elif isinstance(litellm.datadog_params, Dict): # only allow params that are of DatadogInitParams - dict_datadog_params = DatadogInitParams( - **litellm.datadog_params - ).model_dump() + dict_datadog_params = DatadogInitParams(**litellm.datadog_params).model_dump() return dict_datadog_params def _configure_dd_agent( @@ -211,9 +203,7 @@ def _configure_dd_agent( dd_api_key: Datadog API key. Falls back to DD_API_KEY env var when allow_env_credentials is True. Optional when using agent. allow_env_credentials: When False, never read the API key from DD_API_KEY env var. """ - resolved_port = dd_agent_port or os.getenv( - "LITELLM_DD_AGENT_PORT", "10518" - ) # default port for logs + resolved_port = dd_agent_port or os.getenv("LITELLM_DD_AGENT_PORT", "10518") # default port for logs self.intake_url = f"http://{dd_agent_host}:{resolved_port}/api/v2/logs" self.DD_API_KEY = dd_api_key or ( os.getenv("DD_API_KEY") if allow_env_credentials else None @@ -237,9 +227,7 @@ def _configure_dd_direct_api( Raises: Exception: If required credentials are not provided via args or env vars """ - resolved_api_key = dd_api_key or ( - os.getenv("DD_API_KEY") if allow_env_credentials else None - ) + resolved_api_key = dd_api_key or (os.getenv("DD_API_KEY") if allow_env_credentials else None) resolved_site = dd_site or os.getenv("DD_SITE") if resolved_api_key is None: @@ -263,28 +251,20 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti Raises a NON Blocking verbose_logger.exception if an error occurs """ try: - verbose_logger.debug( - "Datadog: Logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("Datadog: Logging - Enters logging function for model %s", kwargs) await self._log_async_event(kwargs, response_obj, start_time, end_time) except Exception as e: - verbose_logger.exception( - f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}") pass async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - "Datadog: Logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("Datadog: Logging - Enters logging function for model %s", kwargs) await self._log_async_event(kwargs, response_obj, start_time, end_time) except Exception as e: - verbose_logger.exception( - f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}") pass async def async_post_call_failure_hook( @@ -323,36 +303,24 @@ async def async_post_call_failure_hook( LiteLLMProxyRequestSetup, ) - _meta = ( - LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key( - user_api_key_dict=user_api_key_dict - ) + _meta = LiteLLMProxyRequestSetup.get_sanitized_user_information_from_key( + user_api_key_dict=user_api_key_dict ) user_context = dict(_meta) if isinstance(_meta, dict) else _meta except Exception: # Fallback if proxy not available (e.g. SDK-only): minimal safe fields if hasattr(user_api_key_dict, "request_route"): - user_context["request_route"] = getattr( - user_api_key_dict, "request_route", None - ) + user_context["request_route"] = getattr(user_api_key_dict, "request_route", None) if hasattr(user_api_key_dict, "team_id"): - user_context["team_id"] = getattr( - user_api_key_dict, "team_id", None - ) + user_context["team_id"] = getattr(user_api_key_dict, "team_id", None) if hasattr(user_api_key_dict, "user_id"): - user_context["user_id"] = getattr( - user_api_key_dict, "user_id", None - ) + user_context["user_id"] = getattr(user_api_key_dict, "user_id", None) if hasattr(user_api_key_dict, "end_user_id"): - user_context["end_user_id"] = getattr( - user_api_key_dict, "end_user_id", None - ) + user_context["end_user_id"] = getattr(user_api_key_dict, "end_user_id", None) message_payload: DatadogProxyFailureHookJsonMessage = { - "exception": error_information.get("error_message") - or str(original_exception), - "error_class": error_information.get("error_class") - or original_exception.__class__.__name__, + "exception": error_information.get("error_message") or str(original_exception), + "error_class": error_information.get("error_class") or original_exception.__class__.__name__, "status_code": status_code, "traceback": error_information.get("traceback") or "", "user_api_key_dict": user_context, @@ -372,9 +340,7 @@ async def async_post_call_failure_hook( if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception as e: - verbose_logger.exception( - f"Datadog: async_post_call_failure_hook - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Datadog: async_post_call_failure_hook - {str(e)}\n{traceback.format_exc()}") return None async def async_send_batch(self): @@ -403,24 +369,18 @@ async def async_send_batch(self): ) if self.is_mock_mode: - verbose_logger.debug( - "[DATADOG MOCK] Mock mode enabled - API calls will be intercepted" - ) + verbose_logger.debug("[DATADOG MOCK] Mock mode enabled - API calls will be intercepted") undelivered = await self._send_with_413_split(batch_to_send) if undelivered: self.log_queue = undelivered + self.log_queue if self.is_mock_mode: - verbose_logger.debug( - f"[DATADOG MOCK] Batch of {len(batch_to_send)} events successfully mocked" - ) + verbose_logger.debug(f"[DATADOG MOCK] Batch of {len(batch_to_send)} events successfully mocked") except Exception as e: self.log_queue = batch_to_send + self.log_queue - verbose_logger.exception( - f"Datadog Error sending batch API - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Datadog Error sending batch API - {str(e)}\n{traceback.format_exc()}") async def _send_with_413_split(self, batch: List) -> List: """ @@ -444,9 +404,7 @@ async def _send_with_413_split(self, batch: List) -> List: if isinstance(e, MaskedHTTPStatusError) and e.status_code == 413: response = e.response else: - verbose_logger.exception( - f"Datadog Error sending batch API - {str(e)}" - ) + verbose_logger.exception(f"Datadog Error sending batch API - {str(e)}") return self._undelivered(chunk, pending) if response.status_code == 413: @@ -484,9 +442,7 @@ async def flush_queue(self): async with self.flush_lock: if self.log_queue: - verbose_logger.debug( - "Datadog: Flushing batch of %s events", len(self.log_queue) - ) + verbose_logger.debug("Datadog: Flushing batch of %s events", len(self.log_queue)) await self.async_send_batch() if not self.log_queue: self.last_flush_time = time.time() @@ -528,9 +484,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): response.raise_for_status() if response.status_code != 202: - raise Exception( - f"Response from datadog API status_code: {response.status_code}, text: {response.text}" - ) + raise Exception(f"Response from datadog API status_code: {response.status_code}, text: {response.text}") verbose_logger.debug( "Datadog: Response from datadog API status_code: %s, text: %s", @@ -539,9 +493,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): ) except Exception as e: - verbose_logger.exception( - f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}") pass pass @@ -554,9 +506,7 @@ async def _log_async_event(self, kwargs, response_obj, start_time, end_time): ) self.log_queue.append(dd_payload) - verbose_logger.debug( - f"Datadog, event added to queue. Will flush in {self.flush_interval} seconds..." - ) + verbose_logger.debug(f"Datadog, event added to queue. Will flush in {self.flush_interval} seconds...") if len(self.log_queue) >= self.batch_size: await self.flush_queue() @@ -572,9 +522,7 @@ def _create_datadog_logging_payload_helper( verbose_logger.debug("Datadog: Logger - Logging payload = %s", json_payload) dd_payload = DatadogPayload( ddsource=get_datadog_source(), - ddtags=",".join( - get_datadog_tags(standard_logging_object=standard_logging_object) - ), + ddtags=",".join(get_datadog_tags(standard_logging_object=standard_logging_object)), hostname=get_datadog_hostname(), message=json_payload, service=get_datadog_service(), @@ -603,9 +551,7 @@ def create_datadog_logging_payload( DatadogPayload: defined in types.py """ - standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if standard_logging_object is None: raise ValueError("standard_logging_object not found in kwargs") @@ -687,9 +633,7 @@ async def async_service_failure_hook( self.log_queue.append(_dd_payload) except Exception as e: - verbose_logger.exception( - f"Datadog: Logger - Exception in async_service_failure_hook: {e}" - ) + verbose_logger.exception(f"Datadog: Logger - Exception in async_service_failure_hook: {e}") pass async def async_service_success_hook( @@ -729,9 +673,7 @@ async def async_service_success_hook( self.log_queue.append(_dd_payload) except Exception as e: - verbose_logger.exception( - f"Datadog: Logger - Exception in async_service_failure_hook: {e}" - ) + verbose_logger.exception(f"Datadog: Logger - Exception in async_service_failure_hook: {e}") def _create_v0_logging_payload( self, @@ -748,9 +690,7 @@ def _create_v0_logging_payload( """ litellm_params = kwargs.get("litellm_params", {}) - metadata = ( - litellm_params.get("metadata", {}) or {} - ) # if litellm_params['metadata'] == None + metadata = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None messages = kwargs.get("messages") optional_params = kwargs.get("optional_params", {}) call_type = kwargs.get("call_type", "litellm.completion") @@ -834,9 +774,7 @@ def _add_trace_context_to_payload( if span_id is not None: dd_payload["dd.span_id"] = span_id except Exception: - verbose_logger.exception( - "Datadog: Failed to attach trace context to payload" - ) + verbose_logger.exception("Datadog: Failed to attach trace context to payload") def _get_active_trace_context(self) -> Optional[Dict[str, str]]: try: @@ -863,9 +801,7 @@ def _get_active_trace_context(self) -> Optional[Dict[str, str]]: trace_context["span_id"] = str(span_id) return trace_context except Exception: - verbose_logger.exception( - "Datadog: Failed to retrieve active trace context from tracer" - ) + verbose_logger.exception("Datadog: Failed to retrieve active trace context from tracer") return None async def async_health_check(self) -> IntegrationHealthCheckStatus: diff --git a/litellm/integrations/datadog/datadog_cost_management.py b/litellm/integrations/datadog/datadog_cost_management.py index 0f954eb1ce02..714a50eb2f21 100644 --- a/litellm/integrations/datadog/datadog_cost_management.py +++ b/litellm/integrations/datadog/datadog_cost_management.py @@ -57,9 +57,7 @@ def __init__(self, cost_tag_keys: Optional[List[str]] = None, **kwargs): self.upload_url = f"https://api.{self.dd_site}/api/v2/cost/custom_costs" - self.async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) # Initialize lock and start periodic flush task self.flush_lock = asyncio.Lock() @@ -73,9 +71,7 @@ def __init__(self, cost_tag_keys: Optional[List[str]] = None, **kwargs): async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): try: - standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if standard_logging_object is None: return @@ -88,9 +84,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"Datadog Cost Management: Error in async_log_success_event: {str(e)}" - ) + verbose_logger.exception(f"Datadog Cost Management: Error in async_log_success_event: {str(e)}") async def async_send_batch(self): if not self.log_queue: @@ -103,28 +97,21 @@ async def async_send_batch(self): aggregated_entries = self._aggregate_costs(batch_to_send) if not aggregated_entries: verbose_logger.debug( - "Datadog Cost Management: batch produced no aggregable entries; " - "dropping %d log(s) from queue.", + "Datadog Cost Management: batch produced no aggregable entries; dropping %d log(s) from queue.", len(batch_to_send), ) return await self._upload_to_datadog(aggregated_entries) except Exception as e: self.log_queue = batch_to_send + self.log_queue - verbose_logger.exception( - f"Datadog Cost Management: Error in async_send_batch: {str(e)}" - ) + verbose_logger.exception(f"Datadog Cost Management: Error in async_send_batch: {str(e)}") - def _aggregate_costs( - self, logs: List[StandardLoggingPayload] - ) -> List[DatadogFOCUSCostEntry]: + def _aggregate_costs(self, logs: List[StandardLoggingPayload]) -> List[DatadogFOCUSCostEntry]: """ Aggregates costs by Provider, Model, and Date. Returns a list of DatadogFOCUSCostEntry. """ - aggregator: Dict[ - Tuple[str, str, str, Tuple[Tuple[str, str], ...]], DatadogFOCUSCostEntry - ] = {} + aggregator: Dict[Tuple[str, str, str, Tuple[Tuple[str, str], ...]], DatadogFOCUSCostEntry] = {} for log in logs: try: @@ -172,9 +159,7 @@ def _aggregate_costs( aggregator[key]["BilledCost"] += cost except Exception as e: - verbose_logger.warning( - f"Error processing log for cost aggregation: {e}" - ) + verbose_logger.warning(f"Error processing log for cost aggregation: {e}") continue return list(aggregator.values()) @@ -229,11 +214,7 @@ def _extract_tags(self, log: StandardLoggingPayload) -> Dict[str, str]: nested = metadata.get(nested_key) if isinstance(nested, dict): for k, v in nested.items(): - if ( - k in allow - and v is not None - and not isinstance(v, (dict, list)) - ): + if k in allow and v is not None and not isinstance(v, (dict, list)): self._set_custom_tag(tags, k, str(v)) return tags @@ -268,9 +249,7 @@ async def _upload_to_datadog(self, payload: List[Dict]): # The API endpoint expects a list of objects directly in the body (file content behavior) data_json = safe_dumps(payload) - response = await self.async_client.put( - self.upload_url, content=data_json, headers=headers - ) + response = await self.async_client.put(self.upload_url, content=data_json, headers=headers) response.raise_for_status() diff --git a/litellm/integrations/datadog/datadog_llm_obs.py b/litellm/integrations/datadog/datadog_llm_obs.py index 201d3fb0a41f..1078f05165a9 100644 --- a/litellm/integrations/datadog/datadog_llm_obs.py +++ b/litellm/integrations/datadog/datadog_llm_obs.py @@ -53,18 +53,14 @@ def __init__(self, **kwargs): if self.is_mock_mode: create_mock_datadog_client() - verbose_logger.debug( - "[DATADOG MOCK] DataDogLLMObs logger initialized in mock mode" - ) + verbose_logger.debug("[DATADOG MOCK] DataDogLLMObs logger initialized in mock mode") # Configure DataDog endpoint (Agent or Direct API) # Use LITELLM_DD_AGENT_HOST to avoid conflicts with ddtrace's DD_AGENT_HOST # Check for agent mode FIRST - agent mode doesn't require DD_API_KEY or DD_SITE dd_agent_host = os.getenv("LITELLM_DD_AGENT_HOST") - self.async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.DD_API_KEY = os.getenv("DD_API_KEY") if dd_agent_host: @@ -74,9 +70,7 @@ def __init__(self, **kwargs): if os.getenv("DD_API_KEY", None) is None: raise Exception("DD_API_KEY is not set, set 'DD_API_KEY=<>'") if os.getenv("DD_SITE", None) is None: - raise Exception( - "DD_SITE is not set, set 'DD_SITE=<>', example sit = `us5.datadoghq.com`" - ) + raise Exception("DD_SITE is not set, set 'DD_SITE=<>', example sit = `us5.datadoghq.com`") self._configure_dd_direct_api() # Optional override for testing @@ -108,9 +102,7 @@ def _configure_dd_agent(self, dd_agent_host: str): # Use specific port for LLM Obs (Trace Agent) to avoid conflict with Logs Agent (10518) agent_port = os.getenv("LITELLM_DD_LLM_OBS_PORT", "8126") self.DD_SITE = "localhost" # Not used for URL construction in agent mode - self.intake_url = ( - f"http://{dd_agent_host}:{agent_port}/api/intake/llm-obs/v1/trace/spans" - ) + self.intake_url = f"http://{dd_agent_host}:{agent_port}/api/intake/llm-obs/v1/trace/spans" verbose_logger.debug(f"DataDogLLMObs: Using DD Agent at {self.intake_url}") def _configure_dd_direct_api(self): @@ -122,13 +114,9 @@ def _configure_dd_direct_api(self): self.DD_SITE = os.getenv("DD_SITE") if not self.DD_SITE: - raise Exception( - "DD_SITE is not set, set 'DD_SITE=<>', example site = `us5.datadoghq.com`" - ) + raise Exception("DD_SITE is not set, set 'DD_SITE=<>', example site = `us5.datadoghq.com`") - self.intake_url = ( - f"https://api.{self.DD_SITE}/api/intake/llm-obs/v1/trace/spans" - ) + self.intake_url = f"https://api.{self.DD_SITE}/api/intake/llm-obs/v1/trace/spans" def _get_datadog_llm_obs_params(self) -> Dict: """ @@ -138,12 +126,8 @@ def _get_datadog_llm_obs_params(self) -> Dict: """ dict_datadog_llm_obs_params: Dict = {} if litellm.datadog_llm_observability_params is not None: - if isinstance( - litellm.datadog_llm_observability_params, DatadogLLMObsInitParams - ): - dict_datadog_llm_obs_params = ( - litellm.datadog_llm_observability_params.model_dump() - ) + if isinstance(litellm.datadog_llm_observability_params, DatadogLLMObsInitParams): + dict_datadog_llm_obs_params = litellm.datadog_llm_observability_params.model_dump() elif isinstance(litellm.datadog_llm_observability_params, Dict): # only allow params that are of DatadogLLMObsInitParams dict_datadog_llm_obs_params = DatadogLLMObsInitParams( @@ -153,9 +137,7 @@ def _get_datadog_llm_obs_params(self) -> Dict: async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - f"DataDogLLMObs: Logging success event for model {kwargs.get('model', 'unknown')}" - ) + verbose_logger.debug(f"DataDogLLMObs: Logging success event for model {kwargs.get('model', 'unknown')}") payload = self.create_llm_obs_payload(kwargs, start_time, end_time) verbose_logger.debug(f"DataDogLLMObs: Payload: {payload}") self.log_queue.append(payload) @@ -163,15 +145,11 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"DataDogLLMObs: Error logging success event - {str(e)}" - ) + verbose_logger.exception(f"DataDogLLMObs: Error logging success event - {str(e)}") async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - f"DataDogLLMObs: Logging failure event for model {kwargs.get('model', 'unknown')}" - ) + verbose_logger.debug(f"DataDogLLMObs: Logging failure event for model {kwargs.get('model', 'unknown')}") payload = self.create_llm_obs_payload(kwargs, start_time, end_time) verbose_logger.debug(f"DataDogLLMObs: Payload: {payload}") self.log_queue.append(payload) @@ -179,23 +157,17 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"DataDogLLMObs: Error logging failure event - {str(e)}" - ) + verbose_logger.exception(f"DataDogLLMObs: Error logging failure event - {str(e)}") async def async_send_batch(self): try: if not self.log_queue: return - verbose_logger.debug( - f"DataDogLLMObs: Flushing {len(self.log_queue)} events" - ) + verbose_logger.debug(f"DataDogLLMObs: Flushing {len(self.log_queue)} events") if self.is_mock_mode: - verbose_logger.debug( - "[DATADOG MOCK] Mock mode enabled - API calls will be intercepted" - ) + verbose_logger.debug("[DATADOG MOCK] Mock mode enabled - API calls will be intercepted") # Prepare the payload payload = { @@ -215,9 +187,7 @@ async def async_send_batch(self): try: verbose_logger.debug("payload %s", safe_dumps(payload)) except Exception as debug_error: - verbose_logger.debug( - "payload serialization failed: %s", str(debug_error) - ) + verbose_logger.debug("payload serialization failed: %s", str(debug_error)) json_payload = safe_dumps(payload) @@ -237,27 +207,17 @@ async def async_send_batch(self): ) if self.is_mock_mode: - verbose_logger.debug( - f"[DATADOG MOCK] Batch of {len(self.log_queue)} events successfully mocked" - ) + verbose_logger.debug(f"[DATADOG MOCK] Batch of {len(self.log_queue)} events successfully mocked") else: - verbose_logger.debug( - f"DataDogLLMObs: Successfully sent batch - status_code: {response.status_code}" - ) + verbose_logger.debug(f"DataDogLLMObs: Successfully sent batch - status_code: {response.status_code}") self.log_queue.clear() except httpx.HTTPStatusError as e: - verbose_logger.exception( - f"DataDogLLMObs: Error sending batch - {e.response.text}" - ) + verbose_logger.exception(f"DataDogLLMObs: Error sending batch - {e.response.text}") except Exception as e: verbose_logger.exception(f"DataDogLLMObs: Error sending batch - {str(e)}") - def create_llm_obs_payload( - self, kwargs: Dict, start_time: datetime, end_time: datetime - ) -> LLMObsPayload: - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + def create_llm_obs_payload(self, kwargs: Dict, start_time: datetime, end_time: datetime) -> LLMObsPayload: + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: raise Exception("DataDogLLMObs: standard_logging_object is not set") @@ -266,11 +226,7 @@ def create_llm_obs_payload( metadata = kwargs.get("litellm_params", {}).get("metadata", {}) - input_meta = InputMeta( - messages=handle_any_messages_to_chat_completion_str_messages_conversion( - messages - ) - ) + input_meta = InputMeta(messages=handle_any_messages_to_chat_completion_str_messages_conversion(messages)) output_meta = OutputMeta( messages=self._get_response_messages( standard_logging_payload=standard_logging_payload, @@ -285,9 +241,7 @@ def create_llm_obs_payload( metadata_parent_id = metadata.get("parent_id") meta = Meta( - kind=self._get_datadog_span_kind( - standard_logging_payload.get("call_type"), metadata_parent_id - ), + kind=self._get_datadog_span_kind(standard_logging_payload.get("call_type"), metadata_parent_id), input=input_meta, output=output_meta, metadata=self._get_dd_llm_obs_payload_metadata(standard_logging_payload), @@ -300,9 +254,7 @@ def create_llm_obs_payload( output_tokens=float(standard_logging_payload.get("completion_tokens", 0)), total_tokens=float(standard_logging_payload.get("total_tokens", 0)), total_cost=float(standard_logging_payload.get("response_cost", 0)), - time_to_first_token=self._get_time_to_first_token_seconds( - standard_logging_payload - ), + time_to_first_token=self._get_time_to_first_token_seconds(standard_logging_payload), ) payload: LLMObsPayload = LLMObsPayload( @@ -338,9 +290,7 @@ def _get_apm_trace_id(self) -> Optional[str]: pass return None - def _assemble_error_info( - self, standard_logging_payload: StandardLoggingPayload - ) -> Optional[DDLLMObsError]: + def _assemble_error_info(self, standard_logging_payload: StandardLoggingPayload) -> Optional[DDLLMObsError]: """ Assemble error information for failure cases according to DD LLM Obs API spec """ @@ -349,8 +299,8 @@ def _assemble_error_info( if standard_logging_payload.get("status") == "failure": # Try to get structured error information first - error_information: Optional[StandardLoggingPayloadErrorInformation] = ( - standard_logging_payload.get("error_information") + error_information: Optional[StandardLoggingPayloadErrorInformation] = standard_logging_payload.get( + "error_information" ) if error_information: @@ -363,9 +313,7 @@ def _assemble_error_info( ) return error_info - def _get_time_to_first_token_seconds( - self, standard_logging_payload: StandardLoggingPayload - ) -> float: + def _get_time_to_first_token_seconds(self, standard_logging_payload: StandardLoggingPayload) -> float: """ Get the time to first token in seconds @@ -374,9 +322,7 @@ def _get_time_to_first_token_seconds( For non streaming calls, CompletionStartTime is time we get the response back """ start_time: Optional[float] = standard_logging_payload.get("startTime") - completion_start_time: Optional[float] = standard_logging_payload.get( - "completionStartTime" - ) + completion_start_time: Optional[float] = standard_logging_payload.get("completionStartTime") end_time: Optional[float] = standard_logging_payload.get("endTime") if completion_start_time is not None and start_time is not None: @@ -538,9 +484,7 @@ def _get_datadog_span_kind( # Default fallback for unknown or passthrough operations return "llm" - def _ensure_string_content( - self, messages: Optional[Union[str, List[Any], Dict[Any, Any]]] - ) -> List[Any]: + def _ensure_string_content(self, messages: Optional[Union[str, List[Any], Dict[Any, Any]]]) -> List[Any]: if messages is None: return [] if isinstance(messages, str): @@ -551,28 +495,20 @@ def _ensure_string_content( return [str(messages.get("content", ""))] return [] - def _get_dd_llm_obs_payload_metadata( - self, standard_logging_payload: StandardLoggingPayload - ) -> Dict[str, Any]: + def _get_dd_llm_obs_payload_metadata(self, standard_logging_payload: StandardLoggingPayload) -> Dict[str, Any]: """ Fields to track in DD LLM Observability metadata from litellm standard logging payload """ _metadata: Dict[str, Any] = { "model_name": standard_logging_payload.get("model", "unknown"), - "model_provider": standard_logging_payload.get( - "custom_llm_provider", "unknown" - ), + "model_provider": standard_logging_payload.get("custom_llm_provider", "unknown"), "id": standard_logging_payload.get("id", "unknown"), "trace_id": standard_logging_payload.get("trace_id", "unknown"), "cache_hit": standard_logging_payload.get("cache_hit", "unknown"), "cache_key": standard_logging_payload.get("cache_key", "unknown"), "saved_cache_cost": standard_logging_payload.get("saved_cache_cost", 0), - "guardrail_information": standard_logging_payload.get( - "guardrail_information", None - ), - "is_streamed_request": self._get_stream_value_from_payload( - standard_logging_payload - ), + "guardrail_information": standard_logging_payload.get("guardrail_information", None), + "is_streamed_request": self._get_stream_value_from_payload(standard_logging_payload), } ######################################################### @@ -591,28 +527,20 @@ def _get_dd_llm_obs_payload_metadata( tool_call_metadata = self._extract_tool_call_metadata(standard_logging_payload) _metadata.update(tool_call_metadata) - _standard_logging_metadata: dict = ( - dict(standard_logging_payload.get("metadata", {})) or {} - ) + _standard_logging_metadata: dict = dict(standard_logging_payload.get("metadata", {})) or {} _metadata.update(_standard_logging_metadata) return _metadata - def _get_latency_metrics( - self, standard_logging_payload: StandardLoggingPayload - ) -> DDLLMObsLatencyMetrics: + def _get_latency_metrics(self, standard_logging_payload: StandardLoggingPayload) -> DDLLMObsLatencyMetrics: """ Get the latency metrics from the standard logging payload """ latency_metrics: DDLLMObsLatencyMetrics = DDLLMObsLatencyMetrics() # Add latency metrics to metadata # Time to first token (convert from seconds to milliseconds for consistency) - time_to_first_token_seconds = self._get_time_to_first_token_seconds( - standard_logging_payload - ) + time_to_first_token_seconds = self._get_time_to_first_token_seconds(standard_logging_payload) if time_to_first_token_seconds > 0: - latency_metrics["time_to_first_token_ms"] = ( - time_to_first_token_seconds * 1000 - ) + latency_metrics["time_to_first_token_ms"] = time_to_first_token_seconds * 1000 # LiteLLM overhead time hidden_params = standard_logging_payload.get("hidden_params", {}) @@ -621,8 +549,8 @@ def _get_latency_metrics( latency_metrics["litellm_overhead_time_ms"] = litellm_overhead_ms # Guardrail overhead latency - guardrail_info: Optional[list[StandardLoggingGuardrailInformation]] = ( - standard_logging_payload.get("guardrail_information") + guardrail_info: Optional[list[StandardLoggingGuardrailInformation]] = standard_logging_payload.get( + "guardrail_information" ) if guardrail_info is not None: total_duration = 0.0 @@ -637,9 +565,7 @@ def _get_latency_metrics( return latency_metrics - def _get_stream_value_from_payload( - self, standard_logging_payload: StandardLoggingPayload - ) -> bool: + def _get_stream_value_from_payload(self, standard_logging_payload: StandardLoggingPayload) -> bool: """ Extract the stream value from standard logging payload. @@ -664,18 +590,14 @@ def _get_stream_value_from_payload( # Default to False for non-streaming requests return False - def _get_spend_metrics( - self, standard_logging_payload: StandardLoggingPayload - ) -> DDLLMObsSpendMetrics: + def _get_spend_metrics(self, standard_logging_payload: StandardLoggingPayload) -> DDLLMObsSpendMetrics: """ Get the spend metrics from the standard logging payload """ spend_metrics: DDLLMObsSpendMetrics = DDLLMObsSpendMetrics() # send response cost - spend_metrics["response_cost"] = standard_logging_payload.get( - "response_cost", 0.0 - ) + spend_metrics["response_cost"] = standard_logging_payload.get("response_cost", 0.0) # Get budget information from metadata metadata = standard_logging_payload.get("metadata", {}) @@ -691,9 +613,7 @@ def _get_spend_metrics( try: spend_metrics["user_api_key_spend"] = float(user_api_key_spend) except (ValueError, TypeError): - verbose_logger.debug( - f"Invalid user_api_key_spend value: {user_api_key_spend}" - ) + verbose_logger.debug(f"Invalid user_api_key_spend value: {user_api_key_spend}") # API key budget reset datetime user_api_key_budget_reset_at = metadata.get("user_api_key_budget_reset_at") @@ -720,18 +640,14 @@ def _get_spend_metrics( spend_metrics["user_api_key_budget_reset_at"] = iso_string # Debug logging to verify the conversion - verbose_logger.debug( - f"Converted budget_reset_at to ISO format: {iso_string}" - ) + verbose_logger.debug(f"Converted budget_reset_at to ISO format: {iso_string}") except Exception as e: verbose_logger.debug(f"Error processing budget reset datetime: {e}") verbose_logger.debug(f"Original value: {user_api_key_budget_reset_at}") return spend_metrics - def _process_input_messages_preserving_tool_calls( - self, messages: List[Any] - ) -> List[Dict[str, Any]]: + def _process_input_messages_preserving_tool_calls(self, messages: List[Any]) -> List[Dict[str, Any]]: """ Process input messages while preserving tool_calls and tool message types. @@ -746,19 +662,11 @@ def _process_input_messages_preserving_tool_calls( processed.append(msg) else: # For regular messages, still apply string conversion - converted = ( - handle_any_messages_to_chat_completion_str_messages_conversion( - [msg] - ) - ) + converted = handle_any_messages_to_chat_completion_str_messages_conversion([msg]) processed.extend(converted) else: # For non-dict messages, apply string conversion - converted = ( - handle_any_messages_to_chat_completion_str_messages_conversion( - [msg] - ) - ) + converted = handle_any_messages_to_chat_completion_str_messages_conversion([msg]) processed.extend(converted) return processed @@ -793,26 +701,18 @@ def _tool_calls_kv_pair(tool_calls: List[Dict[str, Any]]) -> Dict[str, Any]: if function_arguments: # Store arguments as JSON string for Datadog if isinstance(function_arguments, str): - kv_pairs[f"tool_calls.{idx}.function.arguments"] = ( - function_arguments - ) + kv_pairs[f"tool_calls.{idx}.function.arguments"] = function_arguments else: import json - kv_pairs[f"tool_calls.{idx}.function.arguments"] = ( - json.dumps(function_arguments) - ) + kv_pairs[f"tool_calls.{idx}.function.arguments"] = json.dumps(function_arguments) except (KeyError, TypeError, ValueError) as e: - verbose_logger.debug( - f"DataDogLLMObs: Error processing tool call {idx}: {str(e)}" - ) + verbose_logger.debug(f"DataDogLLMObs: Error processing tool call {idx}: {str(e)}") continue return kv_pairs - def _extract_tool_call_metadata( - self, standard_logging_payload: StandardLoggingPayload - ) -> Dict[str, Any]: + def _extract_tool_call_metadata(self, standard_logging_payload: StandardLoggingPayload) -> Dict[str, Any]: """ Extract tool call information from both input messages and response for Datadog metadata. """ @@ -841,16 +741,12 @@ def _extract_tool_call_metadata( if message and isinstance(message, dict): tool_calls = message.get("tool_calls") if tool_calls: - response_tool_calls_kv = self._tool_calls_kv_pair( - tool_calls - ) + response_tool_calls_kv = self._tool_calls_kv_pair(tool_calls) # Prefix with "output_" to distinguish from input tool calls for key, value in response_tool_calls_kv.items(): tool_call_metadata[f"output_{key}"] = value except Exception as e: - verbose_logger.debug( - f"DataDogLLMObs: Error extracting tool call metadata: {str(e)}" - ) + verbose_logger.debug(f"DataDogLLMObs: Error extracting tool call metadata: {str(e)}") return tool_call_metadata diff --git a/litellm/integrations/datadog/datadog_metrics.py b/litellm/integrations/datadog/datadog_metrics.py index bd5c165cba23..b1e4bc73e77e 100644 --- a/litellm/integrations/datadog/datadog_metrics.py +++ b/litellm/integrations/datadog/datadog_metrics.py @@ -34,15 +34,11 @@ def __init__(self, start_periodic_flush: bool = True, **kwargs): self.dd_site = os.getenv("DD_SITE", "datadoghq.com") if not self.dd_api_key: - verbose_logger.warning( - "Datadog Metrics: DD_API_KEY is required. Integration will not work." - ) + verbose_logger.warning("Datadog Metrics: DD_API_KEY is required. Integration will not work.") self.upload_url = f"https://api.{self.dd_site}/api/v2/series" - self.async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) # Initialize lock self.flush_lock = asyncio.Lock() @@ -155,8 +151,7 @@ def _add_metrics_from_log( "points": [ { "timestamp": timestamp, - "value": litellm_overhead_time_ms - / 1000, # convert ms → seconds + "value": litellm_overhead_time_ms / 1000, # convert ms → seconds } ], "tags": overhead_tags, @@ -175,54 +170,40 @@ def _add_metrics_from_log( async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): try: - standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if standard_logging_object is None: return - self._add_metrics_from_log( - log=standard_logging_object, kwargs=kwargs, status_code="200" - ) + self._add_metrics_from_log(log=standard_logging_object, kwargs=kwargs, status_code="200") if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception as e: - verbose_logger.exception( - f"Datadog Metrics: Error in async_log_success_event: {str(e)}" - ) + verbose_logger.exception(f"Datadog Metrics: Error in async_log_success_event: {str(e)}") async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: - standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if standard_logging_object is None: return # Extract status code from error information status_code = "500" # default - error_information = ( - standard_logging_object.get("error_information", {}) or {} - ) + error_information = standard_logging_object.get("error_information", {}) or {} error_code = error_information.get("error_code") # type: ignore if error_code is not None: status_code = str(error_code) - self._add_metrics_from_log( - log=standard_logging_object, kwargs=kwargs, status_code=status_code - ) + self._add_metrics_from_log(log=standard_logging_object, kwargs=kwargs, status_code=status_code) if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception as e: - verbose_logger.exception( - f"Datadog Metrics: Error in async_log_failure_event: {str(e)}" - ) + verbose_logger.exception(f"Datadog Metrics: Error in async_log_failure_event: {str(e)}") async def async_send_batch(self): if not self.log_queue: @@ -234,9 +215,7 @@ async def async_send_batch(self): try: await self._upload_to_datadog(payload_data) except Exception as e: - verbose_logger.exception( - f"Datadog Metrics: Error in async_send_batch: {str(e)}" - ) + verbose_logger.exception(f"Datadog Metrics: Error in async_send_batch: {str(e)}") raise async def _upload_to_datadog(self, payload: DatadogMetricsPayload): diff --git a/litellm/integrations/datadog/datadog_mock_client.py b/litellm/integrations/datadog/datadog_mock_client.py index 7f9beab72cce..c50cdc6a0191 100644 --- a/litellm/integrations/datadog/datadog_mock_client.py +++ b/litellm/integrations/datadog/datadog_mock_client.py @@ -28,6 +28,4 @@ patch_sync_client=True, ) -create_mock_datadog_client, should_use_datadog_mock = create_mock_client_factory( - _config -) +create_mock_datadog_client, should_use_datadog_mock = create_mock_client_factory(_config) diff --git a/litellm/integrations/datadog/datadog_team_handler.py b/litellm/integrations/datadog/datadog_team_handler.py index 3a5b73fc005f..cae954f753c0 100644 --- a/litellm/integrations/datadog/datadog_team_handler.py +++ b/litellm/integrations/datadog/datadog_team_handler.py @@ -54,11 +54,9 @@ def get_datadog_logger_for_request( # if not cached, create a new datadog logger and cache it if temp_datadog_logger is None: - temp_datadog_logger = ( - DataDogHandler._create_datadog_logger_from_credentials( - credentials=credentials_dict, - in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, - ) + temp_datadog_logger = DataDogHandler._create_datadog_logger_from_credentials( + credentials=credentials_dict, + in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, ) return temp_datadog_logger @@ -73,10 +71,7 @@ def _create_datadog_logger_from_credentials( """ # When the destination is caller-supplied (dd_agent_host/dd_site), never fall back to the # proxy's DD_API_KEY env var, otherwise it would be sent to a team-controlled host. - allow_env_credentials = ( - credentials.get("dd_agent_host") is None - and credentials.get("dd_site") is None - ) + allow_env_credentials = credentials.get("dd_agent_host") is None and credentials.get("dd_site") is None datadog_logger = DataDogLogger( dd_api_key=credentials.get("dd_api_key"), dd_site=credentials.get("dd_site"), @@ -89,9 +84,7 @@ def _create_datadog_logger_from_credentials( service_name="datadog", logging_obj=datadog_logger, ) - verbose_logger.debug( - "Datadog: Created and cached new DataDogLogger for team-scoped credentials" - ) + verbose_logger.debug("Datadog: Created and cached new DataDogLogger for team-scoped credentials") return datadog_logger @staticmethod diff --git a/litellm/integrations/deepeval/api.py b/litellm/integrations/deepeval/api.py index 5e446e26feb7..fccc59704335 100644 --- a/litellm/integrations/deepeval/api.py +++ b/litellm/integrations/deepeval/api.py @@ -58,13 +58,9 @@ def __init__(self, api_key: str, base_url=None): # using the global non-eu variable for base url self.base_api_url = base_url or API_BASE_URL self.sync_http_handler = HTTPHandler() - self.async_http_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) - def _http_request( - self, method: str, url: str, headers=None, json=None, params=None - ): + def _http_request(self, method: str, url: str, headers=None, json=None, params=None): if method != "POST": raise Exception("Only POST requests are supported") try: @@ -79,9 +75,7 @@ def _http_request( except Exception as e: raise e - def send_request( - self, method: HttpMethods, endpoint: Endpoints, body=None, params=None - ): + def send_request(self, method: HttpMethods, endpoint: Endpoints, body=None, params=None): url = f"{self.base_api_url}{endpoint.value}" res = self._http_request( method=method.value, @@ -100,9 +94,7 @@ def send_request( verbose_logger.debug(res.json()) raise Exception(res.json().get("error", res.text)) - async def a_send_request( - self, method: HttpMethods, endpoint: Endpoints, body=None, params=None - ): + async def a_send_request(self, method: HttpMethods, endpoint: Endpoints, body=None, params=None): if method != HttpMethods.POST: raise Exception("Only POST requests are supported") diff --git a/litellm/integrations/deepeval/deepeval.py b/litellm/integrations/deepeval/deepeval.py index 972843e120a0..90c1d8eedce0 100644 --- a/litellm/integrations/deepeval/deepeval.py +++ b/litellm/integrations/deepeval/deepeval.py @@ -25,39 +25,27 @@ def __init__(self, *args, **kwargs): self.litellm_environment = os.getenv("LITELM_ENVIRONMENT", "development") validate_environment(self.litellm_environment) if not api_key: - raise ValueError( - "Please set 'CONFIDENT_API_KEY=<>' in your environment variables." - ) + raise ValueError("Please set 'CONFIDENT_API_KEY=<>' in your environment variables.") self.api = Api(api_key=api_key) super().__init__(*args, **kwargs) def log_success_event(self, kwargs, response_obj, start_time, end_time): """Logs a success event to DeepEval's platform.""" - self._sync_event_handler( - kwargs, response_obj, start_time, end_time, is_success=True - ) + self._sync_event_handler(kwargs, response_obj, start_time, end_time, is_success=True) def log_failure_event(self, kwargs, response_obj, start_time, end_time): """Logs a failure event to DeepEval's platform.""" - self._sync_event_handler( - kwargs, response_obj, start_time, end_time, is_success=False - ) + self._sync_event_handler(kwargs, response_obj, start_time, end_time, is_success=False) async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): """Logs a failure event to DeepEval's platform.""" - await self._async_event_handler( - kwargs, response_obj, start_time, end_time, is_success=False - ) + await self._async_event_handler(kwargs, response_obj, start_time, end_time, is_success=False) async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): """Logs a success event to DeepEval's platform.""" - await self._async_event_handler( - kwargs, response_obj, start_time, end_time, is_success=True - ) + await self._async_event_handler(kwargs, response_obj, start_time, end_time, is_success=True) - def _prepare_trace_api( - self, kwargs, response_obj, start_time, end_time, is_success - ): + def _prepare_trace_api(self, kwargs, response_obj, start_time, end_time, is_success): _start_time = to_zod_compatible_iso(start_time) _end_time = to_zod_compatible_iso(end_time) _standard_logging_object = kwargs.get("standard_logging_object", {}) @@ -85,12 +73,8 @@ def _prepare_trace_api( body = trace_api.dict(by_alias=True, exclude_none=True) return body - def _sync_event_handler( - self, kwargs, response_obj, start_time, end_time, is_success - ): - body = self._prepare_trace_api( - kwargs, response_obj, start_time, end_time, is_success - ) + def _sync_event_handler(self, kwargs, response_obj, start_time, end_time, is_success): + body = self._prepare_trace_api(kwargs, response_obj, start_time, end_time, is_success) try: response = self.api.send_request( method=HttpMethods.POST, @@ -99,29 +83,19 @@ def _sync_event_handler( ) except Exception as e: raise e - verbose_logger.debug( - "DeepEvalLogger: sync_log_failure_event: Api response %s", response - ) + verbose_logger.debug("DeepEvalLogger: sync_log_failure_event: Api response %s", response) - async def _async_event_handler( - self, kwargs, response_obj, start_time, end_time, is_success - ): - body = self._prepare_trace_api( - kwargs, response_obj, start_time, end_time, is_success - ) + async def _async_event_handler(self, kwargs, response_obj, start_time, end_time, is_success): + body = self._prepare_trace_api(kwargs, response_obj, start_time, end_time, is_success) response = await self.api.a_send_request( method=HttpMethods.POST, endpoint=Endpoints.TRACING_ENDPOINT, body=body, ) - verbose_logger.debug( - "DeepEvalLogger: async_event_handler: Api response %s", response - ) + verbose_logger.debug("DeepEvalLogger: async_event_handler: Api response %s", response) - def _create_base_api_span( - self, kwargs, standard_logging_object, start_time, end_time, is_success - ): + def _create_base_api_span(self, kwargs, standard_logging_object, start_time, end_time, is_success): # extract usage usage = standard_logging_object.get("response", {}).get("usage", {}) if is_success: @@ -135,12 +109,8 @@ def _create_base_api_span( output = str(standard_logging_object.get("error_string", "")) return BaseApiSpan( uuid=standard_logging_object.get("id", uuid.uuid4()), - name=( - "litellm_success_callback" if is_success else "litellm_failure_callback" - ), - status=( - TraceSpanApiStatus.SUCCESS if is_success else TraceSpanApiStatus.ERRORED - ), + name=("litellm_success_callback" if is_success else "litellm_failure_callback"), + status=(TraceSpanApiStatus.SUCCESS if is_success else TraceSpanApiStatus.ERRORED), type=SpanApiType.LLM, traceUuid=standard_logging_object.get("trace_id", uuid.uuid4()), startTime=str(start_time), @@ -149,9 +119,7 @@ def _create_base_api_span( output=output, model=standard_logging_object.get("model", None), inputTokenCount=usage.get("prompt_tokens", None) if is_success else None, - outputTokenCount=( - usage.get("completion_tokens", None) if is_success else None - ), + outputTokenCount=(usage.get("completion_tokens", None) if is_success else None), ) def _create_trace_api( diff --git a/litellm/integrations/deepeval/utils.py b/litellm/integrations/deepeval/utils.py index 0beb22db9e32..3df9aceb2412 100644 --- a/litellm/integrations/deepeval/utils.py +++ b/litellm/integrations/deepeval/utils.py @@ -3,16 +3,10 @@ def to_zod_compatible_iso(dt: datetime) -> str: - return ( - dt.astimezone(timezone.utc) - .isoformat(timespec="milliseconds") - .replace("+00:00", "Z") - ) + return dt.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") def validate_environment(environment: str): if environment not in [env.value for env in Environment]: valid_values = ", ".join(f'"{env.value}"' for env in Environment) - raise ValueError( - f"Invalid environment: {environment}. Please use one of the following instead: {valid_values}" - ) + raise ValueError(f"Invalid environment: {environment}. Please use one of the following instead: {valid_values}") diff --git a/litellm/integrations/dotprompt/__init__.py b/litellm/integrations/dotprompt/__init__.py index 394929f4a25e..8432d50e32b5 100644 --- a/litellm/integrations/dotprompt/__init__.py +++ b/litellm/integrations/dotprompt/__init__.py @@ -42,9 +42,7 @@ def _get_prompt_data_from_dotprompt_content(dotprompt_content: str) -> dict: return {"content": content.strip(), "metadata": metadata} -def prompt_initializer( - litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec" -) -> "CustomPromptManagement": +def prompt_initializer(litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec") -> "CustomPromptManagement": """ Initialize a prompt from a .prompt file. """ diff --git a/litellm/integrations/dotprompt/dotprompt_manager.py b/litellm/integrations/dotprompt/dotprompt_manager.py index 37fdf7da6932..3ba9efd68b75 100644 --- a/litellm/integrations/dotprompt/dotprompt_manager.py +++ b/litellm/integrations/dotprompt/dotprompt_manager.py @@ -69,11 +69,7 @@ def integration_name(self) -> str: def prompt_manager(self) -> PromptManager: """Lazy-load the prompt manager.""" if self._prompt_manager is None: - if ( - self.prompt_directory is None - and not self.prompt_data - and not self.prompt_file - ): + if self.prompt_directory is None and not self.prompt_data and not self.prompt_file: raise ValueError( "Either prompt_directory or prompt_data must be set before using dotprompt manager. " "Set litellm.global_prompt_directory, initialize with prompt_directory parameter, or provide prompt_data." @@ -129,14 +125,10 @@ def _compile_prompt_helper( try: # Get the prompt template (versioned or base) - template = self.prompt_manager.get_prompt( - prompt_id=prompt_id, version=prompt_version - ) + template = self.prompt_manager.get_prompt(prompt_id=prompt_id, version=prompt_version) if template is None: version_str = f" (version {prompt_version})" if prompt_version else "" - raise ValueError( - f"Prompt '{prompt_id}'{version_str} not found in prompt directory" - ) + raise ValueError(f"Prompt '{prompt_id}'{version_str} not found in prompt directory") # Render the template with variables (pass version for proper lookup) rendered_content = self.prompt_manager.render( @@ -282,29 +274,17 @@ def _convert_to_messages(self, rendered_content: str) -> List[AllMessageValues]: # Check for role prefixes if line.startswith("System:"): if current_role and current_content: - messages.append( - self._create_message( - current_role, "\n".join(current_content).strip() - ) - ) + messages.append(self._create_message(current_role, "\n".join(current_content).strip())) current_role = "system" current_content = [line[7:].strip()] # Remove "System:" prefix elif line.startswith("User:"): if current_role and current_content: - messages.append( - self._create_message( - current_role, "\n".join(current_content).strip() - ) - ) + messages.append(self._create_message(current_role, "\n".join(current_content).strip())) current_role = "user" current_content = [line[5:].strip()] # Remove "User:" prefix elif line.startswith("Assistant:"): if current_role and current_content: - messages.append( - self._create_message( - current_role, "\n".join(current_content).strip() - ) - ) + messages.append(self._create_message(current_role, "\n".join(current_content).strip())) current_role = "assistant" current_content = [line[10:].strip()] # Remove "Assistant:" prefix else: diff --git a/litellm/integrations/dotprompt/prompt_manager.py b/litellm/integrations/dotprompt/prompt_manager.py index 6407a18d0b3c..dd198ba12721 100644 --- a/litellm/integrations/dotprompt/prompt_manager.py +++ b/litellm/integrations/dotprompt/prompt_manager.py @@ -93,9 +93,7 @@ def __init__( def _load_prompts(self) -> None: """Load all .prompt files from the prompt directory.""" if not self.prompt_directory or not self.prompt_directory.exists(): - raise ValueError( - f"Prompt directory does not exist: {self.prompt_directory}" - ) + raise ValueError(f"Prompt directory does not exist: {self.prompt_directory}") prompt_files = list(self.prompt_directory.glob("*.prompt")) @@ -109,9 +107,7 @@ def _load_prompts(self) -> None: # Optional: print(f"Error loading prompt file {prompt_file}") pass - def _load_prompts_from_json( - self, prompt_data: Dict[str, Dict[str, Any]], prompt_id: Optional[str] = None - ) -> None: + def _load_prompts_from_json(self, prompt_data: Dict[str, Dict[str, Any]], prompt_id: Optional[str] = None) -> None: """Load prompts from JSON data structure. Expected format: @@ -147,9 +143,7 @@ def _load_prompts_from_json( # Optional: print(f"Error loading prompt from JSON: {prompt_id}") pass - def _load_prompt_file( - self, file_path: Union[str, Path], prompt_id: str - ) -> PromptTemplate: + def _load_prompt_file(self, file_path: Union[str, Path], prompt_id: str) -> PromptTemplate: """Load and parse a single .prompt file.""" if isinstance(file_path, str): file_path = Path(file_path) @@ -213,9 +207,7 @@ def render( if template is None: available_prompts = list(self.prompts.keys()) version_str = f" (version {version})" if version else "" - raise KeyError( - f"Prompt '{prompt_id}'{version_str} not found. Available prompts: {available_prompts}" - ) + raise KeyError(f"Prompt '{prompt_id}'{version_str} not found. Available prompts: {available_prompts}") variables = prompt_variables or {} @@ -231,9 +223,7 @@ def render( except Exception as e: raise ValueError(f"Error rendering template '{prompt_id}': {e}") - def _validate_input( - self, variables: Dict[str, Any], schema: Dict[str, Any] - ) -> None: + def _validate_input(self, variables: Dict[str, Any], schema: Dict[str, Any]) -> None: """Basic validation of input variables against schema.""" for field_name, field_type in schema.items(): if field_name in variables: @@ -265,9 +255,7 @@ def _get_python_type(self, schema_type: str) -> Union[type, tuple]: return type_mapping.get(schema_type.lower(), str) # type: ignore - def get_prompt( - self, prompt_id: str, version: Optional[int] = None - ) -> Optional[PromptTemplate]: + def get_prompt(self, prompt_id: str, version: Optional[int] = None) -> Optional[PromptTemplate]: """ Get a prompt template by ID and optional version. @@ -302,13 +290,9 @@ def reload_prompts(self) -> None: if self.prompt_directory: self._load_prompts() - def add_prompt( - self, prompt_id: str, content: str, metadata: Optional[Dict[str, Any]] = None - ) -> None: + def add_prompt(self, prompt_id: str, content: str, metadata: Optional[Dict[str, Any]] = None) -> None: """Add a prompt template programmatically.""" - template = PromptTemplate( - content=content, metadata=metadata or {}, template_id=prompt_id - ) + template = PromptTemplate(content=content, metadata=metadata or {}, template_id=prompt_id) self.prompts[prompt_id] = template def prompt_file_to_json(self, file_path: Union[str, Path]) -> Dict[str, Any]: @@ -365,8 +349,6 @@ def get_all_prompts_as_json(self) -> Dict[str, Dict[str, Any]]: } return result - def load_prompts_from_json_data( - self, prompt_data: Dict[str, Dict[str, Any]] - ) -> None: + def load_prompts_from_json_data(self, prompt_data: Dict[str, Dict[str, Any]]) -> None: """Load additional prompts from JSON data (merges with existing prompts).""" self._load_prompts_from_json(prompt_data) diff --git a/litellm/integrations/dynamodb.py b/litellm/integrations/dynamodb.py index dfc05ae1f322..ab76fa3c8bd9 100644 --- a/litellm/integrations/dynamodb.py +++ b/litellm/integrations/dynamodb.py @@ -16,32 +16,24 @@ def __init__(self): # Instance variables import boto3 - self.dynamodb: Any = boto3.resource( - "dynamodb", region_name=os.environ["AWS_REGION_NAME"] - ) + self.dynamodb: Any = boto3.resource("dynamodb", region_name=os.environ["AWS_REGION_NAME"]) if litellm.dynamodb_table_name is None: raise ValueError( "LiteLLM Error, trying to use DynamoDB but not table name passed. Create a table and set `litellm.dynamodb_table_name=`" ) self.table_name = litellm.dynamodb_table_name - async def _async_log_event( - self, kwargs, response_obj, start_time, end_time, print_verbose - ): + async def _async_log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): self.log_event(kwargs, response_obj, start_time, end_time, print_verbose) def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): try: - print_verbose( - f"DynamoDB Logging - Enters logging function for model {kwargs}" - ) + print_verbose(f"DynamoDB Logging - Enters logging function for model {kwargs}") # construct payload to send to DynamoDB # follows the same params as langfuse.py litellm_params = kwargs.get("litellm_params", {}) - metadata = ( - litellm_params.get("metadata", {}) or {} - ) # if litellm_params['metadata'] == None + metadata = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None messages = kwargs.get("messages") optional_params = kwargs.get("optional_params", {}) call_type = kwargs.get("call_type", "litellm.completion") @@ -80,9 +72,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): print_verbose(f"Response from DynamoDB:{str(response)}") - print_verbose( - f"DynamoDB Layer Logging - final response object: {response_obj}" - ) + print_verbose(f"DynamoDB Layer Logging - final response object: {response_obj}") return response except Exception: print_verbose(f"DynamoDB Layer Error - {traceback.format_exc()}") diff --git a/litellm/integrations/email_alerting.py b/litellm/integrations/email_alerting.py index b721dc504643..35d63a691f93 100644 --- a/litellm/integrations/email_alerting.py +++ b/litellm/integrations/email_alerting.py @@ -15,9 +15,7 @@ async def get_all_team_member_emails(team_id: Optional[str] = None) -> list: - verbose_logger.debug( - "Email Alerting: Getting all team members for team_id=%s", team_id - ) + verbose_logger.debug("Email Alerting: Getting all team members for team_id=%s", team_id) if team_id is None: return [] from litellm.proxy.proxy_server import prisma_client @@ -76,9 +74,7 @@ async def send_team_budget_alert(webhook_event: WebhookEvent) -> bool: _team_id = webhook_event.team_id team_alias = webhook_event.team_alias - verbose_logger.debug( - "Email Alerting: Sending Team Budget Alert for team=%s", team_alias - ) + verbose_logger.debug("Email Alerting: Sending Team Budget Alert for team=%s", team_alias) email_logo_url = os.getenv("SMTP_SENDER_LOGO", os.getenv("EMAIL_LOGO_URL", None)) email_support_contact = os.getenv("EMAIL_SUPPORT_CONTACT", None) @@ -93,9 +89,7 @@ async def send_team_budget_alert(webhook_event: WebhookEvent) -> bool: email_support_contact = LITELLM_SUPPORT_CONTACT recipient_emails = await get_all_team_member_emails(_team_id) recipient_emails_str: str = ",".join(recipient_emails) - verbose_logger.debug( - "Email Alerting: Sending team budget alert to %s", recipient_emails_str - ) + verbose_logger.debug("Email Alerting: Sending team budget alert to %s", recipient_emails_str) event_name = webhook_event.event_message max_budget = webhook_event.max_budget diff --git a/litellm/integrations/focus/destinations/factory.py b/litellm/integrations/focus/destinations/factory.py index cd25a87729f9..3d79046bf6cb 100644 --- a/litellm/integrations/focus/destinations/factory.py +++ b/litellm/integrations/focus/destinations/factory.py @@ -24,9 +24,7 @@ def create( ) -> FocusDestination: """Return a destination implementation for the requested provider.""" provider_lower = provider.lower() - normalized_config = FocusDestinationFactory._resolve_config( - provider=provider_lower, overrides=config or {} - ) + normalized_config = FocusDestinationFactory._resolve_config(provider=provider_lower, overrides=config or {}) if provider_lower == "s3": return FocusS3Destination(prefix=prefix, config=normalized_config) if provider_lower == "vantage": @@ -35,9 +33,7 @@ def create( return FocusGCSDestination(prefix=prefix, config=normalized_config) if provider_lower == "mavvrik": return FocusMavvrikDestination(prefix=prefix, config=normalized_config) - raise NotImplementedError( - f"Provider '{provider}' not supported for Focus export" - ) + raise NotImplementedError(f"Provider '{provider}' not supported for Focus export") @staticmethod def _resolve_config( @@ -47,18 +43,12 @@ def _resolve_config( ) -> Dict[str, Any]: if provider == "s3": resolved = { - "bucket_name": overrides.get("bucket_name") - or os.getenv("FOCUS_S3_BUCKET_NAME"), - "region_name": overrides.get("region_name") - or os.getenv("FOCUS_S3_REGION_NAME"), - "endpoint_url": overrides.get("endpoint_url") - or os.getenv("FOCUS_S3_ENDPOINT_URL"), - "aws_access_key_id": overrides.get("aws_access_key_id") - or os.getenv("FOCUS_S3_ACCESS_KEY"), - "aws_secret_access_key": overrides.get("aws_secret_access_key") - or os.getenv("FOCUS_S3_SECRET_KEY"), - "aws_session_token": overrides.get("aws_session_token") - or os.getenv("FOCUS_S3_SESSION_TOKEN"), + "bucket_name": overrides.get("bucket_name") or os.getenv("FOCUS_S3_BUCKET_NAME"), + "region_name": overrides.get("region_name") or os.getenv("FOCUS_S3_REGION_NAME"), + "endpoint_url": overrides.get("endpoint_url") or os.getenv("FOCUS_S3_ENDPOINT_URL"), + "aws_access_key_id": overrides.get("aws_access_key_id") or os.getenv("FOCUS_S3_ACCESS_KEY"), + "aws_secret_access_key": overrides.get("aws_secret_access_key") or os.getenv("FOCUS_S3_SECRET_KEY"), + "aws_session_token": overrides.get("aws_session_token") or os.getenv("FOCUS_S3_SESSION_TOKEN"), } if not resolved.get("bucket_name"): raise ValueError("FOCUS_S3_BUCKET_NAME must be provided for S3 exports") @@ -66,39 +56,28 @@ def _resolve_config( if provider == "vantage": resolved = { "api_key": overrides.get("api_key") or os.getenv("VANTAGE_API_KEY"), - "integration_token": overrides.get("integration_token") - or os.getenv("VANTAGE_INTEGRATION_TOKEN"), - "base_url": overrides.get("base_url") - or os.getenv("VANTAGE_BASE_URL", "https://api.vantage.sh"), + "integration_token": overrides.get("integration_token") or os.getenv("VANTAGE_INTEGRATION_TOKEN"), + "base_url": overrides.get("base_url") or os.getenv("VANTAGE_BASE_URL", "https://api.vantage.sh"), } if not resolved.get("api_key"): raise ValueError("VANTAGE_API_KEY must be provided for Vantage exports") if not resolved.get("integration_token"): - raise ValueError( - "VANTAGE_INTEGRATION_TOKEN must be provided for Vantage exports" - ) + raise ValueError("VANTAGE_INTEGRATION_TOKEN must be provided for Vantage exports") return {k: v for k, v in resolved.items() if v is not None} if provider == "gcs": resolved = { - "bucket_name": overrides.get("bucket_name") - or os.getenv("FOCUS_GCS_BUCKET_NAME"), + "bucket_name": overrides.get("bucket_name") or os.getenv("FOCUS_GCS_BUCKET_NAME"), "service_account_json": overrides.get("service_account_json") or os.getenv("FOCUS_GCS_PATH_SERVICE_ACCOUNT"), } if not resolved.get("bucket_name"): - raise ValueError( - "FOCUS_GCS_BUCKET_NAME must be provided for GCS exports" - ) + raise ValueError("FOCUS_GCS_BUCKET_NAME must be provided for GCS exports") return {k: v for k, v in resolved.items() if v is not None} if provider == "mavvrik": resolved = { "api_key": overrides.get("api_key") or os.getenv("MAVVRIK_API_KEY"), - "api_endpoint": overrides.get("api_endpoint") - or os.getenv("MAVVRIK_API_ENDPOINT"), - "connection_id": overrides.get("connection_id") - or os.getenv("MAVVRIK_CONNECTION_ID"), + "api_endpoint": overrides.get("api_endpoint") or os.getenv("MAVVRIK_API_ENDPOINT"), + "connection_id": overrides.get("connection_id") or os.getenv("MAVVRIK_CONNECTION_ID"), } return {k: v for k, v in resolved.items() if v is not None} - raise NotImplementedError( - f"Provider '{provider}' not supported for Focus export configuration" - ) + raise NotImplementedError(f"Provider '{provider}' not supported for Focus export configuration") diff --git a/litellm/integrations/focus/destinations/gcs_destination.py b/litellm/integrations/focus/destinations/gcs_destination.py index b04c16c9d327..e4525ccd2676 100644 --- a/litellm/integrations/focus/destinations/gcs_destination.py +++ b/litellm/integrations/focus/destinations/gcs_destination.py @@ -41,22 +41,16 @@ async def deliver( filename: str, ) -> None: object_name = self._build_object_key(time_window=time_window, filename=filename) - headers = await self.construct_request_headers( - service_account_json=self.path_service_account_json - ) + headers = await self.construct_request_headers(service_account_json=self.path_service_account_json) headers["Content-Type"] = "application/octet-stream" encoded_name = encode_gcs_object_name_for_url(object_name) url = ( f"https://storage.googleapis.com/upload/storage/v1/b/" f"{self.BUCKET_NAME}/o?uploadType=media&name={encoded_name}" ) - response = await self.async_httpx_client.post( - url=url, headers=headers, data=content - ) + response = await self.async_httpx_client.post(url=url, headers=headers, data=content) if response.status_code != 200: - raise RuntimeError( - f"GCS upload failed: status={response.status_code} body={response.text}" - ) + raise RuntimeError(f"GCS upload failed: status={response.status_code} body={response.text}") verbose_logger.debug( "Focus GCS: uploaded %d bytes to gs://%s/%s", len(content), diff --git a/litellm/integrations/focus/destinations/mavvrik_destination.py b/litellm/integrations/focus/destinations/mavvrik_destination.py index 81944ba69e23..cf500a71b527 100644 --- a/litellm/integrations/focus/destinations/mavvrik_destination.py +++ b/litellm/integrations/focus/destinations/mavvrik_destination.py @@ -41,14 +41,9 @@ def _validate_api_endpoint(api_endpoint: str) -> None: def _validate_gcs_url(url: str, label: str) -> None: parsed = urlparse(url) if parsed.scheme != "https": - raise ValueError( - f"Mavvrik FOCUS destination: {label} must be HTTPS, got scheme '{parsed.scheme}'" - ) + raise ValueError(f"Mavvrik FOCUS destination: {label} must be HTTPS, got scheme '{parsed.scheme}'") hostname = (parsed.hostname or "").lower() - if not ( - hostname == "storage.googleapis.com" - or hostname.endswith(".storage.googleapis.com") - ): + if not (hostname == "storage.googleapis.com" or hostname.endswith(".storage.googleapis.com")): raise ValueError( f"Mavvrik FOCUS destination: {label} must be a GCS endpoint (storage.googleapis.com), got '{hostname}'" ) @@ -90,9 +85,7 @@ def __init__( self.api_endpoint = api_endpoint.rstrip("/") self.connection_id = connection_id self.prefix = prefix - self._http: AsyncHTTPHandler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self._http: AsyncHTTPHandler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self._registered = False @property @@ -132,9 +125,7 @@ async def _ensure_registered(self) -> Optional[int]: "Re-enable the connection in the Mavvrik dashboard." ) if resp.status_code >= 400: - raise RuntimeError( - f"Mavvrik FOCUS destination: register failed ({resp.status_code}): {resp.text[:200]}" - ) + raise RuntimeError(f"Mavvrik FOCUS destination: register failed ({resp.status_code}): {resp.text[:200]}") self._registered = True metrics_marker = resp.json().get("metricsMarker", 0) verbose_logger.debug( @@ -159,13 +150,9 @@ async def _get_signed_url(self, date_str: str) -> str: ) signed_url = resp.json().get("url") if not signed_url: - raise RuntimeError( - f"Mavvrik FOCUS destination: response missing 'url' field: {resp.json()}" - ) + raise RuntimeError(f"Mavvrik FOCUS destination: response missing 'url' field: {resp.json()}") _validate_gcs_url(signed_url, "signed URL") - verbose_logger.debug( - "Mavvrik FOCUS destination: got signed URL for date %s", date_str - ) + verbose_logger.debug("Mavvrik FOCUS destination: got signed URL for date %s", date_str) return signed_url async def _upload_to_gcs(self, signed_url: str, content: bytes) -> None: @@ -205,9 +192,7 @@ async def _upload_to_gcs(self, signed_url: str, content: bytes) -> None: session_uri = init_resp.headers.get("Location") if not session_uri: - raise RuntimeError( - "Mavvrik FOCUS destination: GCS session init missing Location header" - ) + raise RuntimeError("Mavvrik FOCUS destination: GCS session init missing Location header") _validate_gcs_url(session_uri, "session URI") verbose_logger.debug( @@ -224,11 +209,7 @@ async def _upload_to_gcs(self, signed_url: str, content: bytes) -> None: chunk = gzip_bytes[offset : offset + _GCS_CHUNK_SIZE] chunk_end = offset + len(chunk) - 1 is_final = (offset + len(chunk)) >= total - content_range = ( - f"bytes {offset}-{chunk_end}/{total}" - if is_final - else f"bytes {offset}-{chunk_end}/*" - ) + content_range = f"bytes {offset}-{chunk_end}/{total}" if is_final else f"bytes {offset}-{chunk_end}/*" expected_statuses = {200, 201} if is_final else {308} resp = await self._http.client.request( @@ -256,12 +237,8 @@ async def _upload_to_gcs(self, signed_url: str, content: bytes) -> None: except Exception: # Cancel the open GCS session so it doesn't linger for up to 1 week. try: - await self._http.client.request( - method="DELETE", url=session_uri, timeout=10.0 - ) - verbose_logger.debug( - "Mavvrik FOCUS destination: cancelled GCS session after error" - ) + await self._http.client.request(method="DELETE", url=session_uri, timeout=10.0) + verbose_logger.debug("Mavvrik FOCUS destination: cancelled GCS session after error") except Exception: pass raise @@ -283,12 +260,9 @@ async def _update_metrics_marker(self, date_epoch: int) -> None: ) if resp.status_code >= 400: raise RuntimeError( - f"Mavvrik FOCUS destination: failed to update metricsMarker " - f"({resp.status_code}): {resp.text[:200]}" + f"Mavvrik FOCUS destination: failed to update metricsMarker ({resp.status_code}): {resp.text[:200]}" ) - verbose_logger.debug( - "Mavvrik FOCUS destination: metricsMarker advanced to %s", date_epoch - ) + verbose_logger.debug("Mavvrik FOCUS destination: metricsMarker advanced to %s", date_epoch) async def get_metrics_marker(self) -> Optional[int]: """Register with Mavvrik and return the current metricsMarker. @@ -311,14 +285,10 @@ async def get_metrics_marker(self) -> Optional[int]: "Re-enable the connection in the Mavvrik dashboard." ) if resp.status_code >= 400: - raise RuntimeError( - f"Mavvrik FOCUS destination: register failed ({resp.status_code}): {resp.text[:200]}" - ) + raise RuntimeError(f"Mavvrik FOCUS destination: register failed ({resp.status_code}): {resp.text[:200]}") self._registered = True metrics_marker = resp.json().get("metricsMarker", 0) - verbose_logger.debug( - "Mavvrik FOCUS destination: got metricsMarker=%s", metrics_marker - ) + verbose_logger.debug("Mavvrik FOCUS destination: got metricsMarker=%s", metrics_marker) return metrics_marker async def deliver( @@ -356,6 +326,4 @@ async def deliver( await self._upload_to_gcs(signed_url, content) await self._update_metrics_marker(date_epoch) - verbose_logger.debug( - "Mavvrik FOCUS destination: upload complete for date=%s", date_str - ) + verbose_logger.debug("Mavvrik FOCUS destination: upload complete for date=%s", date_str) diff --git a/litellm/integrations/focus/destinations/vantage_destination.py b/litellm/integrations/focus/destinations/vantage_destination.py index 4e3dd2b6d8ba..ffd37aa195b8 100644 --- a/litellm/integrations/focus/destinations/vantage_destination.py +++ b/litellm/integrations/focus/destinations/vantage_destination.py @@ -67,20 +67,14 @@ def _strip_unsupported_columns(csv_bytes: bytes) -> bytes: return csv_bytes header_cols = lines[0].decode("utf-8").split(",") - keep_indices = [ - i - for i, col in enumerate(header_cols) - if col.strip('"') in VANTAGE_SUPPORTED_COLUMNS - ] + keep_indices = [i for i, col in enumerate(header_cols) if col.strip('"') in VANTAGE_SUPPORTED_COLUMNS] # If all columns are supported, return as-is if len(keep_indices) == len(header_cols): return csv_bytes dropped = [col for i, col in enumerate(header_cols) if i not in keep_indices] - verbose_logger.debug( - "Vantage destination: dropping unsupported columns: %s", dropped - ) + verbose_logger.debug("Vantage destination: dropping unsupported columns: %s", dropped) output = io.StringIO() writer = csv.writer(output) @@ -143,10 +137,7 @@ async def deliver( # Check both size and row-count limits before single-shot upload lines = content.split(b"\n") data_line_count = sum(1 for line in lines[1:] if line.strip()) - within_limits = ( - len(content) <= VANTAGE_MAX_BYTES_PER_UPLOAD - and data_line_count <= VANTAGE_MAX_ROWS_PER_UPLOAD - ) + within_limits = len(content) <= VANTAGE_MAX_BYTES_PER_UPLOAD and data_line_count <= VANTAGE_MAX_ROWS_PER_UPLOAD if within_limits: await self._upload_csv(client, content, filename) return @@ -154,9 +145,7 @@ async def deliver( # Otherwise split into batches respecting both limits await self._upload_batched(client, content, filename) - async def _upload_csv( - self, client: AsyncHTTPHandler, csv_bytes: bytes, filename: str - ) -> None: + async def _upload_csv(self, client: AsyncHTTPHandler, csv_bytes: bytes, filename: str) -> None: url = f"{self.base_url}/v2/integrations/{self.integration_token}/costs.csv" headers = { "Authorization": f"Bearer {self.api_key}", @@ -174,9 +163,7 @@ async def _upload_csv( filename, ) - async def _upload_batched( - self, client: AsyncHTTPHandler, csv_bytes: bytes, filename: str - ) -> None: + async def _upload_batched(self, client: AsyncHTTPHandler, csv_bytes: bytes, filename: str) -> None: """Split the CSV into batches and upload each. Continues uploading remaining batches even if one fails, then raises @@ -195,16 +182,12 @@ async def _upload_batched( try: # If a single batch still exceeds 2 MB, split further by size if len(batch_csv) > VANTAGE_MAX_BYTES_PER_UPLOAD: - await self._upload_size_limited( - client, header, batch_lines, filename, batch_num - ) + await self._upload_size_limited(client, header, batch_lines, filename, batch_num) else: batch_filename = f"{filename}.part{batch_num}" await self._upload_csv(client, batch_csv, batch_filename) except Exception as e: - verbose_logger.error( - "Vantage destination: batch %d failed: %s", batch_num, e - ) + verbose_logger.error("Vantage destination: batch %d failed: %s", batch_num, e) if first_error is None: first_error = e batch_num += 1 @@ -244,10 +227,7 @@ async def _upload_size_limited( ) continue - if ( - current_size + line_size > VANTAGE_MAX_BYTES_PER_UPLOAD - and current_chunk - ): + if current_size + line_size > VANTAGE_MAX_BYTES_PER_UPLOAD and current_chunk: batch_csv = header + b"\n" + b"\n".join(current_chunk) + b"\n" batch_filename = f"{filename}.part{batch_offset}_{sub_batch}" try: diff --git a/litellm/integrations/focus/export_engine.py b/litellm/integrations/focus/export_engine.py index 37da18a0eb7a..67ae6bcc3d04 100644 --- a/litellm/integrations/focus/export_engine.py +++ b/litellm/integrations/focus/export_engine.py @@ -42,9 +42,7 @@ def _init_serializer(self) -> FocusSerializer: return FocusCsvSerializer() if self.export_format == "parquet": return FocusParquetSerializer() - raise NotImplementedError( - f"Export format '{self.export_format}' not supported. Use 'parquet' or 'csv'." - ) + raise NotImplementedError(f"Export format '{self.export_format}' not supported. Use 'parquet' or 'csv'.") async def dry_run_export_usage_data(self, limit: Optional[int]) -> Dict[str, Any]: data = await self._database.get_usage_data(limit=limit) @@ -111,16 +109,12 @@ async def export_window( normalized = self._transformer.transform(data) if normalized.is_empty(): - verbose_logger.debug( - "Focus export: normalized data empty for window %s", window - ) + verbose_logger.debug("Focus export: normalized data empty for window %s", window) return await self._serialize_and_upload(normalized, window) - async def _serialize_and_upload( - self, frame: pl.DataFrame, window: FocusTimeWindow - ) -> None: + async def _serialize_and_upload(self, frame: pl.DataFrame, window: FocusTimeWindow) -> None: payload = self._serializer.serialize(frame) if not payload: verbose_logger.debug("Focus export: serializer returned empty payload") diff --git a/litellm/integrations/focus/focus_logger.py b/litellm/integrations/focus/focus_logger.py index 083b0e1463ab..ac6f1f7af1f6 100644 --- a/litellm/integrations/focus/focus_logger.py +++ b/litellm/integrations/focus/focus_logger.py @@ -39,20 +39,12 @@ def __init__( ) -> None: super().__init__(**kwargs) self.provider = (provider or os.getenv("FOCUS_PROVIDER") or "s3").lower() - self.export_format = ( - export_format or os.getenv("FOCUS_FORMAT") or "parquet" - ).lower() + self.export_format = (export_format or os.getenv("FOCUS_FORMAT") or "parquet").lower() self.frequency = (frequency or os.getenv("FOCUS_FREQUENCY") or "hourly").lower() self.cron_offset_minute = ( - cron_offset_minute - if cron_offset_minute is not None - else int(os.getenv("FOCUS_CRON_OFFSET", "5")) - ) - raw_interval = ( - interval_seconds - if interval_seconds is not None - else os.getenv("FOCUS_INTERVAL_SECONDS") + cron_offset_minute if cron_offset_minute is not None else int(os.getenv("FOCUS_CRON_OFFSET", "5")) ) + raw_interval = interval_seconds if interval_seconds is not None else os.getenv("FOCUS_INTERVAL_SECONDS") self.interval_seconds: Optional[int] = None if raw_interval is not None: try: @@ -63,11 +55,7 @@ def __init__( raw_interval, ) env_prefix = os.getenv("FOCUS_PREFIX") - self.prefix: str = ( - prefix - if prefix is not None - else (env_prefix if env_prefix else "focus_exports") - ) + self.prefix: str = prefix if prefix is not None else (env_prefix if env_prefix else "focus_exports") self._destination_config = destination_config self._engine: Optional["FocusExportEngine"] = None @@ -100,9 +88,7 @@ async def export_usage_data( automatic scheduler runs. """ if bool(start_time_utc) ^ bool(end_time_utc): - raise ValueError( - "start_time_utc and end_time_utc must be provided together" - ) + raise ValueError("start_time_utc and end_time_utc must be provided together") if start_time_utc and end_time_utc: window = FocusTimeWindow( @@ -115,9 +101,7 @@ async def export_usage_data( # No time bounds → export all available data await self._export_all(limit=limit) - async def dry_run_export_usage_data( - self, limit: Optional[int] = DEFAULT_DRY_RUN_LIMIT - ) -> dict[str, Any]: + async def dry_run_export_usage_data(self, limit: Optional[int] = DEFAULT_DRY_RUN_LIMIT) -> dict[str, Any]: """Return transformed data without uploading.""" engine = self._ensure_engine() return await engine.dry_run_export_usage_data(limit=limit) @@ -133,18 +117,14 @@ async def initialize_focus_export_job(self) -> None: pod_lock_manager = getattr(writer, "pod_lock_manager", None) if pod_lock_manager and pod_lock_manager.redis_cache: - acquired = await pod_lock_manager.acquire_lock( - cronjob_id=FOCUS_USAGE_DATA_JOB_NAME - ) + acquired = await pod_lock_manager.acquire_lock(cronjob_id=FOCUS_USAGE_DATA_JOB_NAME) if not acquired: verbose_logger.debug("Focus export: unable to acquire pod lock") return try: await self._run_scheduled_export() finally: - await pod_lock_manager.release_lock( - cronjob_id=FOCUS_USAGE_DATA_JOB_NAME - ) + await pod_lock_manager.release_lock(cronjob_id=FOCUS_USAGE_DATA_JOB_NAME) else: await self._run_scheduled_export() @@ -158,15 +138,11 @@ async def init_focus_export_background_job( # which have their own dedicated scheduling method. focus_loggers: List[CustomLogger] = [ cb - for cb in litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=FocusLogger - ) + for cb in litellm.logging_callback_manager.get_custom_loggers_for_type(callback_type=FocusLogger) if type(cb) is FocusLogger ] if not focus_loggers: - verbose_logger.debug( - "No Focus export logger registered; skipping scheduler" - ) + verbose_logger.debug("No Focus export logger registered; skipping scheduler") return focus_logger = cast(FocusLogger, focus_loggers[0]) diff --git a/litellm/integrations/focus/serializers/csv.py b/litellm/integrations/focus/serializers/csv.py index 8e33c557be26..c07903581792 100644 --- a/litellm/integrations/focus/serializers/csv.py +++ b/litellm/integrations/focus/serializers/csv.py @@ -19,15 +19,9 @@ def serialize(self, frame: pl.DataFrame) -> bytes: # Cast Decimal columns to Float64 so CSV output uses standard # floating-point notation (e.g. "1.5") instead of fixed-point # strings (e.g. "1.500000") that some parsers may reject. - decimal_cols = [ - col - for col, dtype in zip(frame.columns, frame.dtypes) - if isinstance(dtype, pl.Decimal) - ] + decimal_cols = [col for col, dtype in zip(frame.columns, frame.dtypes) if isinstance(dtype, pl.Decimal)] if decimal_cols: - frame = frame.with_columns( - [pl.col(c).cast(pl.Float64) for c in decimal_cols] - ) + frame = frame.with_columns([pl.col(c).cast(pl.Float64) for c in decimal_cols]) buffer = io.BytesIO() frame.write_csv(buffer) return buffer.getvalue() diff --git a/litellm/integrations/focus/transformer.py b/litellm/integrations/focus/transformer.py index a17df29b912e..0fbefee75de7 100644 --- a/litellm/integrations/focus/transformer.py +++ b/litellm/integrations/focus/transformer.py @@ -36,11 +36,7 @@ def _struct_to_json(row: dict) -> str: tags = {k: str(v) for k, v in row.items() if v is not None} return json.dumps(tags) if tags else "{}" - return ( - pl.struct(available_keys) - .map_elements(_struct_to_json, return_dtype=pl.String) - .alias("Tags") - ) + return pl.struct(available_keys).map_elements(_struct_to_json, return_dtype=pl.String).alias("Tags") class FocusTransformer: @@ -97,9 +93,7 @@ def dec(col): pl.lit("Usage-Based").alias("ChargeFrequency"), fmt(pl.col("ChargePeriodEnd")).alias("ChargePeriodEnd"), fmt(pl.col("ChargePeriodStart")).alias("ChargePeriodStart"), - dec( - pl.col("api_requests").cast(pl.Int64).cast(pl.Float64).fill_null(0.0) - ).alias("ConsumedQuantity"), + dec(pl.col("api_requests").cast(pl.Int64).cast(pl.Float64).fill_null(0.0)).alias("ConsumedQuantity"), pl.lit("Requests").alias("ConsumedUnit"), dec(pl.col("spend").fill_null(0.0)).alias("ContractedCost"), none_str.alias("ContractedUnitPrice"), @@ -111,9 +105,7 @@ def dec(col): none_str.alias("AvailabilityZone"), pl.lit("USD").alias("PricingCurrency"), none_str.alias("PricingCategory"), - dec( - pl.col("api_requests").cast(pl.Int64).cast(pl.Float64).fill_null(0.0) - ).alias("PricingQuantity"), + dec(pl.col("api_requests").cast(pl.Int64).cast(pl.Float64).fill_null(0.0)).alias("PricingQuantity"), none_dec.alias("PricingCurrencyContractedUnitPrice"), dec(pl.col("spend").fill_null(0.0)).alias("PricingCurrencyEffectiveCost"), none_dec.alias("PricingCurrencyListUnitPrice"), diff --git a/litellm/integrations/galileo.py b/litellm/integrations/galileo.py index f9ff7e8c7a1b..0ec6d496689b 100644 --- a/litellm/integrations/galileo.py +++ b/litellm/integrations/galileo.py @@ -52,9 +52,7 @@ class LLMResponse(BaseModel): default=None, description="Optional. When available, logprobs are used to compute Uncertainty.", ) - created_at: str = Field( - ..., description='timestamp constructed in "%Y-%m-%dT%H:%M:%S" format' - ) + created_at: str = Field(..., description='timestamp constructed in "%Y-%m-%dT%H:%M:%S" format') tags: Optional[List[str]] = None user_metadata: Optional[Dict[str, Any]] = None @@ -73,9 +71,7 @@ def __init__(self) -> None: self.base_url = GALILEO_CLOUD_API_BASE_URL self.use_v2_api = bool(self.api_key) self.headers: Optional[Dict[str, str]] = None - self.async_httpx_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) @staticmethod def _normalize_base_url(base_url: Optional[str]) -> Optional[str]: @@ -108,8 +104,7 @@ async def async_health_check(self) -> IntegrationHealthCheckStatus: return IntegrationHealthCheckStatus( status="unhealthy", error_message=( - "GALILEO_API_KEY or GALILEO_USERNAME and GALILEO_PASSWORD " - "environment variables must be set" + "GALILEO_API_KEY or GALILEO_USERNAME and GALILEO_PASSWORD environment variables must be set" ), ) @@ -181,9 +176,7 @@ async def _ensure_headers(self) -> bool: return False @staticmethod - def _galileo_input_messages( - messages: Optional[Any], input_text: str - ) -> List[Dict[str, str]]: + def _galileo_input_messages(messages: Optional[Any], input_text: str) -> List[Dict[str, str]]: if isinstance(messages, dict): messages = messages.get("messages") if not messages: @@ -201,9 +194,7 @@ def _galileo_input_messages( galileo_messages.append( { "role": str(role), - "content": convert_content_list_to_str( - message=cast(AllMessageValues, message) - ), + "content": convert_content_list_to_str(message=cast(AllMessageValues, message)), } ) @@ -267,9 +258,7 @@ def _record_to_v2_span( "parent_id": trace_id, "name": record.get("node_type", "litellm"), "created_at": created_at, - "input": GalileoObserve._galileo_input_messages( - record.get("messages"), record.get("input_text", "") - ), + "input": GalileoObserve._galileo_input_messages(record.get("messages"), record.get("input_text", "")), "output": { "role": "assistant", "content": record.get("output_text", ""), @@ -303,11 +292,7 @@ def _record_to_v2_trace(record: Dict[str, Any]) -> Dict[str, Any]: "duration_ns": int(record.get("latency_ms", 0)) * 1_000_000, **GalileoObserve._token_metrics_from_record(record), }, - "spans": [ - GalileoObserve._record_to_v2_span( - record, trace_id=trace_id, span_id=span_id - ) - ], + "spans": [GalileoObserve._record_to_v2_span(record, trace_id=trace_id, span_id=span_id)], } def _build_traces_payload(self, records: List[dict]) -> Dict[str, Any]: @@ -351,9 +336,7 @@ def _redact_headers(headers: Optional[Dict[str, str]]) -> Dict[str, str]: redacted: Dict[str, str] = {} for key, value in headers.items(): if key.lower() in {"authorization", "galileo-api-key"} and value: - redacted[key] = ( - f"{value[:8]}...{value[-4:]}" if len(value) > 12 else "***" - ) + redacted[key] = f"{value[:8]}...{value[-4:]}" if len(value) > 12 else "***" else: redacted[key] = value return redacted @@ -391,13 +374,9 @@ def _log_v2_payload_validation(payload: Dict[str, Any]) -> None: continue for field in ("id", "trace_id", "parent_id"): if field not in span: - missing_fields.append( - f"traces[{trace_index}].spans[{span_index}].{field}" - ) + missing_fields.append(f"traces[{trace_index}].spans[{span_index}].{field}") if trace_id and span.get("trace_id") != trace_id: - missing_fields.append( - f"traces[{trace_index}].spans[{span_index}].trace_id mismatch" - ) + missing_fields.append(f"traces[{trace_index}].spans[{span_index}].trace_id mismatch") if missing_fields: verbose_logger.debug( @@ -516,16 +495,11 @@ def _get_galileo_input_output_content( call_type = kwargs.get("call_type") prompt = self._build_prompt(kwargs) - if ( - level == "ERROR" - and status_message is not None - and isinstance(status_message, str) - ): + if level == "ERROR" and status_message is not None and isinstance(status_message, str): return self._prompt_to_input_text(prompt), status_message, prompt if response_obj is not None and ( - call_type in ("embedding", "aembedding") - or isinstance(response_obj, litellm.EmbeddingResponse) + call_type in ("embedding", "aembedding") or isinstance(response_obj, litellm.EmbeddingResponse) ): # Match Langfuse OTEL: log embeddings without serializing vectors. return self._prompt_to_input_text(prompt), "embedding-output", prompt @@ -538,14 +512,10 @@ def _get_galileo_input_output_content( kwargs.get("messages") or [], ) - if response_obj is not None and isinstance( - response_obj, HttpxBinaryResponseContent - ): + if response_obj is not None and isinstance(response_obj, HttpxBinaryResponseContent): return self._prompt_to_input_text(prompt), "speech-output", prompt - if response_obj is not None and isinstance( - response_obj, litellm.TextCompletionResponse - ): + if response_obj is not None and isinstance(response_obj, litellm.TextCompletionResponse): output = self._get_text_completion_content_for_galileo(response_obj) return ( self._prompt_to_input_text(prompt), @@ -561,9 +531,7 @@ def _get_galileo_input_output_content( prompt, ) - if response_obj is not None and isinstance( - response_obj, litellm.TranscriptionResponse - ): + if response_obj is not None and isinstance(response_obj, litellm.TranscriptionResponse): output = response_obj.get("text", None) return ( self._prompt_to_input_text(prompt), @@ -571,9 +539,7 @@ def _get_galileo_input_output_content( prompt, ) - if response_obj is not None and isinstance( - response_obj, litellm.RerankResponse - ): + if response_obj is not None and isinstance(response_obj, litellm.RerankResponse): output = response_obj.results rerank_prompt = self._langfuse_style_rerank_prompt(kwargs) return ( @@ -590,11 +556,7 @@ def _get_galileo_input_output_content( kwargs.get("messages") or [], ) - if ( - call_type == "_arealtime" - and response_obj is not None - and isinstance(response_obj, list) - ): + if call_type == "_arealtime" and response_obj is not None and isinstance(response_obj, list): input_val = kwargs.get("input") return ( self._serialize_galileo_output(input_val), @@ -602,11 +564,7 @@ def _get_galileo_input_output_content( input_val, ) - if ( - call_type == "pass_through_endpoint" - and response_obj is not None - and isinstance(response_obj, dict) - ): + if call_type == "pass_through_endpoint" and response_obj is not None and isinstance(response_obj, dict): output = response_obj.get("response", "") return ( self._prompt_to_input_text(prompt), @@ -624,12 +582,8 @@ def _get_galileo_input_output_content( return self._prompt_to_input_text(prompt), "", kwargs.get("messages") or [] - def get_output_str_from_response( - self, response_obj: Any, kwargs: Dict[str, Any] - ) -> str: - _, output_text, _ = self._get_galileo_input_output_content( - kwargs=kwargs, response_obj=response_obj - ) + def get_output_str_from_response(self, response_obj: Any, kwargs: Dict[str, Any]) -> str: + _, output_text, _ = self._get_galileo_input_output_content(kwargs=kwargs, response_obj=response_obj) return output_text @staticmethod @@ -646,10 +600,7 @@ def _input_text_from_messages(messages: Any) -> str: if str(msg.get("role", "")).lower() in ("user", "human"): content = msg.get("content") or "" if isinstance(content, list): - content = " ".join( - b.get("text", "") if isinstance(b, dict) else str(b) - for b in content - ) + content = " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in content) if content: return str(content) # Fallback: first non-empty content of any role @@ -657,17 +608,12 @@ def _input_text_from_messages(messages: Any) -> str: if isinstance(msg, dict): content = msg.get("content") or "" if isinstance(content, list): - content = " ".join( - b.get("text", "") if isinstance(b, dict) else str(b) - for b in content - ) + content = " ".join(b.get("text", "") if isinstance(b, dict) else str(b) for b in content) if content: return str(content) return "" - async def async_log_success_event( - self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any - ): + async def async_log_success_event(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any): verbose_logger.debug("On Async Success") try: await self._async_log_success_event_impl( @@ -677,13 +623,9 @@ async def async_log_success_event( end_time=end_time, ) except Exception: - verbose_logger.exception( - "Galileo Logger: unexpected error in async_log_success_event" - ) + verbose_logger.exception("Galileo Logger: unexpected error in async_log_success_event") - async def _async_log_success_event_impl( - self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any - ): + async def _async_log_success_event_impl(self, kwargs: Any, response_obj: Any, start_time: Any, end_time: Any): if not self._is_configured(): verbose_logger.debug( "Galileo Logger: skipping — GALILEO_PROJECT_ID=%s GALILEO_API_KEY=%s GALILEO_BASE_URL=%s", @@ -695,14 +637,10 @@ async def _async_log_success_event_impl( slo: Optional[Dict[str, Any]] = kwargs.get("standard_logging_object") if slo is None: - verbose_logger.debug( - "Galileo Logger: no standard_logging_object in kwargs, skipping" - ) + verbose_logger.debug("Galileo Logger: no standard_logging_object in kwargs, skipping") return - _call_type: str = str( - slo.get("call_type") or kwargs.get("call_type") or "litellm" - ) + _call_type: str = str(slo.get("call_type") or kwargs.get("call_type") or "litellm") input_text, output_text, messages = self._get_galileo_input_output_content( kwargs=kwargs, response_obj=response_obj @@ -715,9 +653,7 @@ async def _async_log_success_event_impl( "Galileo Logger: standard_logging_object missing startTime/endTime, " "falling back to start_time/end_time params" ) - if not isinstance(start_time, datetime) or not isinstance( - end_time, datetime - ): + if not isinstance(start_time, datetime) or not isinstance(end_time, datetime): return start_ts = start_time end_ts = end_time @@ -757,17 +693,13 @@ async def _async_log_success_event_impl( if isinstance(messages, list) and messages: request_dict["messages"] = messages self.in_memory_records.append(request_dict) - verbose_logger.debug( - "Galileo Logger: queued record, in_memory=%d", len(self.in_memory_records) - ) + verbose_logger.debug("Galileo Logger: queued record, in_memory=%d", len(self.in_memory_records)) # Bound the buffer so persistent flush failures cannot grow it # without limit. Drop the oldest records once we exceed the cap. if len(self.in_memory_records) > GALILEO_MAX_IN_MEMORY_RECORDS: dropped = len(self.in_memory_records) - GALILEO_MAX_IN_MEMORY_RECORDS - self.in_memory_records = self.in_memory_records[ - -GALILEO_MAX_IN_MEMORY_RECORDS: - ] + self.in_memory_records = self.in_memory_records[-GALILEO_MAX_IN_MEMORY_RECORDS:] verbose_logger.warning( "Galileo Logger: in-memory buffer exceeded %s records; " "dropped %s oldest record(s). Check Galileo connectivity/credentials.", @@ -789,15 +721,11 @@ async def flush_in_memory_records(self): ingest_request = self._get_ingest_request() if ingest_request is None: - verbose_logger.debug( - "Galileo Logger: missing GALILEO_BASE_URL or GALILEO_PROJECT_ID — skipping flush" - ) + verbose_logger.debug("Galileo Logger: missing GALILEO_BASE_URL or GALILEO_PROJECT_ID — skipping flush") return if not await self._ensure_headers(): - verbose_logger.debug( - "Galileo Logger: could not set request headers — skipping flush" - ) + verbose_logger.debug("Galileo Logger: could not set request headers — skipping flush") return url, payload = ingest_request @@ -817,20 +745,14 @@ async def flush_in_memory_records(self): ) except httpx.HTTPStatusError as e: self._log_http_status_error(error=e, url=url) - verbose_logger.debug( - "Galileo Logger: failed to flush in memory records: %s", e - ) + verbose_logger.debug("Galileo Logger: failed to flush in memory records: %s", e) return except Exception as e: - verbose_logger.debug( - "Galileo Logger: failed to flush in memory records: %s", e - ) + verbose_logger.debug("Galileo Logger: failed to flush in memory records: %s", e) return if response.is_success: - verbose_logger.debug( - "Galileo Logger: successfully flushed in memory records" - ) + verbose_logger.debug("Galileo Logger: successfully flushed in memory records") verbose_logger.debug( "Galileo Logger flush response: status=%s body=%s", response.status_code, diff --git a/litellm/integrations/gcs_bucket/gcs_bucket.py b/litellm/integrations/gcs_bucket/gcs_bucket.py index 90057984235f..c2e0ad64586d 100644 --- a/litellm/integrations/gcs_bucket/gcs_bucket.py +++ b/litellm/integrations/gcs_bucket/gcs_bucket.py @@ -32,14 +32,9 @@ def __init__(self, bucket_name: Optional[str] = None) -> None: super().__init__(bucket_name=bucket_name) self.batch_size = int(os.getenv("GCS_BATCH_SIZE", GCS_DEFAULT_BATCH_SIZE)) - self.flush_interval = int( - os.getenv("GCS_FLUSH_INTERVAL", GCS_DEFAULT_FLUSH_INTERVAL_SECONDS) - ) + self.flush_interval = int(os.getenv("GCS_FLUSH_INTERVAL", GCS_DEFAULT_FLUSH_INTERVAL_SECONDS)) self.use_batched_logging = ( - os.getenv( - "GCS_USE_BATCHED_LOGGING", str(GCS_DEFAULT_USE_BATCHED_LOGGING).lower() - ).lower() - == "true" + os.getenv("GCS_USE_BATCHED_LOGGING", str(GCS_DEFAULT_USE_BATCHED_LOGGING).lower()).lower() == "true" ) self.flush_lock = asyncio.Lock() super().__init__( @@ -72,19 +67,13 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti kwargs, response_obj, ) - logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if logging_payload is None: raise ValueError("standard_logging_object not found in kwargs") # When queue is at maxsize, flush immediately to make room (no blocking, no data dropped) if self.log_queue.full(): await self.flush_queue() - await self.log_queue.put( - GCSLogQueueItem( - payload=logging_payload, kwargs=kwargs, response_obj=response_obj - ) - ) + await self.log_queue.put(GCSLogQueueItem(payload=logging_payload, kwargs=kwargs, response_obj=response_obj)) except Exception as e: verbose_logger.exception(f"GCS Bucket logging error: {str(e)}") @@ -97,19 +86,13 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti response_obj, ) - logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if logging_payload is None: raise ValueError("standard_logging_object not found in kwargs") # When queue is at maxsize, flush immediately to make room (no blocking, no data dropped) if self.log_queue.full(): await self.flush_queue() - await self.log_queue.put( - GCSLogQueueItem( - payload=logging_payload, kwargs=kwargs, response_obj=response_obj - ) - ) + await self.log_queue.put(GCSLogQueueItem(payload=logging_payload, kwargs=kwargs, response_obj=response_obj)) except Exception as e: verbose_logger.exception(f"GCS Bucket logging error: {str(e)}") @@ -147,15 +130,9 @@ def _get_config_key(self, kwargs: Dict[str, Any]) -> str: This key may contain sensitive information (bucket names, paths) - use _sanitize_config_key() for logging purposes. """ - standard_callback_dynamic_params = ( - kwargs.get("standard_callback_dynamic_params", None) or {} - ) + standard_callback_dynamic_params = kwargs.get("standard_callback_dynamic_params", None) or {} - bucket_name = ( - standard_callback_dynamic_params.get("gcs_bucket_name", None) - or self.BUCKET_NAME - or "default" - ) + bucket_name = standard_callback_dynamic_params.get("gcs_bucket_name", None) or self.BUCKET_NAME or "default" path_service_account = ( standard_callback_dynamic_params.get("gcs_path_service_account", None) or self.path_service_account_json @@ -174,9 +151,7 @@ def _sanitize_config_key(self, config_key: str) -> str: hash_obj = hashlib.sha256(config_key.encode("utf-8")) return f"config-{hash_obj.hexdigest()[:8]}" - def _group_items_by_config( - self, items: List[GCSLogQueueItem] - ) -> Dict[str, List[GCSLogQueueItem]]: + def _group_items_by_config(self, items: List[GCSLogQueueItem]) -> Dict[str, List[GCSLogQueueItem]]: """ Group items by their GCS config (bucket + credentials). This ensures items with different configs are processed separately. @@ -203,9 +178,7 @@ def _combine_payloads_to_ndjson(self, items: List[GCSLogQueueItem]) -> str: lines.append(json_line) return "\n".join(lines) - async def _send_grouped_batch( - self, items: List[GCSLogQueueItem], config_key: str - ) -> Tuple[int, int]: + async def _send_grouped_batch(self, items: List[GCSLogQueueItem], config_key: str) -> Tuple[int, int]: """ Send a batch of items that share the same GCS config. @@ -218,9 +191,7 @@ async def _send_grouped_batch( first_kwargs = items[0]["kwargs"] try: - gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config( - first_kwargs - ) + gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config(first_kwargs) headers = await self.construct_request_headers( vertex_instance=gcs_logging_config["vertex_instance"], @@ -228,9 +199,7 @@ async def _send_grouped_batch( ) bucket_name = gcs_logging_config["bucket_name"] - current_date = self._get_object_date_from_datetime( - datetime.now(timezone.utc) - ) + current_date = self._get_object_date_from_datetime(datetime.now(timezone.utc)) batch_id = f"{int(time.time() * 1000)}-{uuid.uuid4().hex[:8]}" object_name = self._generate_batch_object_name(current_date, batch_id) combined_payload = self._combine_payloads_to_ndjson(items) @@ -249,9 +218,7 @@ async def _send_grouped_batch( except Exception as e: success_count = 0 error_count = len(items) - verbose_logger.exception( - f"GCS Bucket error logging batch payload to GCS bucket: {str(e)}" - ) + verbose_logger.exception(f"GCS Bucket error logging batch payload to GCS bucket: {str(e)}") return (success_count, error_count) async def _send_individual_logs(self, items: List[GCSLogQueueItem]) -> None: @@ -267,9 +234,7 @@ async def _send_single_log_item(self, item: GCSLogQueueItem) -> None: Send a single log item to GCS as an individual object. """ try: - gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config( - item["kwargs"] - ) + gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config(item["kwargs"]) headers = await self.construct_request_headers( vertex_instance=gcs_logging_config["vertex_instance"], @@ -290,9 +255,7 @@ async def _send_single_log_item(self, item: GCSLogQueueItem) -> None: logging_payload=item["payload"], ) except Exception as e: - verbose_logger.exception( - f"GCS Bucket error logging individual payload to GCS bucket: {str(e)}" - ) + verbose_logger.exception(f"GCS Bucket error logging individual payload to GCS bucket: {str(e)}") async def async_send_batch(self): """ @@ -316,9 +279,7 @@ async def async_send_batch(self): else: await self._send_individual_logs(items_to_process) - def _get_object_name( - self, kwargs: Dict, logging_payload: StandardLoggingPayload, response_obj: Any - ) -> str: + def _get_object_name(self, kwargs: Dict, logging_payload: StandardLoggingPayload, response_obj: Any) -> str: """ Get the object name to use for the current payload """ @@ -337,9 +298,7 @@ def _get_object_name( _litellm_params = kwargs.get("litellm_params", None) or {} _metadata = _litellm_params.get("metadata", None) or {} if "gcs_log_id" in _metadata: - safe_log_id = sanitize_cloud_object_component( - _metadata.get("gcs_log_id"), fallback="" - ) + safe_log_id = sanitize_cloud_object_component(_metadata.get("gcs_log_id"), fallback="") if safe_log_id: object_name = f"{current_date}/custom-{uuid.uuid4().hex}-{safe_log_id}" @@ -356,9 +315,7 @@ async def get_request_response_payload( Tries current day, next day, and previous day until it finds the payload """ if start_time_utc is None: - raise ValueError( - "start_time_utc is required for getting a payload from GCS Bucket" - ) + raise ValueError("start_time_utc is required for getting a payload from GCS Bucket") dates_to_try = [ start_time_utc, @@ -379,9 +336,7 @@ async def get_request_response_payload( loaded_response = json.loads(response) return loaded_response except Exception as e: - verbose_logger.debug( - f"Failed to fetch payload for date {date_str}: {str(e)}" - ) + verbose_logger.debug(f"Failed to fetch payload for date {date_str}: {str(e)}") continue return None @@ -415,9 +370,7 @@ async def periodic_flush(self): """ while True: await asyncio.sleep(self.flush_interval) - verbose_logger.debug( - f"GCS Bucket periodic flush after {self.flush_interval} seconds" - ) + verbose_logger.debug(f"GCS Bucket periodic flush after {self.flush_interval} seconds") await self.flush_queue() async def async_health_check(self) -> IntegrationHealthCheckStatus: diff --git a/litellm/integrations/gcs_bucket/gcs_bucket_base.py b/litellm/integrations/gcs_bucket/gcs_bucket_base.py index 1c5e30777a2d..0eabf16cff9e 100644 --- a/litellm/integrations/gcs_bucket/gcs_bucket_base.py +++ b/litellm/integrations/gcs_bucket/gcs_bucket_base.py @@ -37,9 +37,7 @@ def __init__(self, bucket_name: Optional[str] = None, **kwargs) -> None: mock_vertex_auth_methods() create_mock_gcs_client() - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) _path_service_account = os.getenv("GCS_PATH_SERVICE_ACCOUNT") _bucket_name = bucket_name or os.getenv("GCS_BUCKET_NAME") self.path_service_account_json: Optional[str] = _path_service_account @@ -74,9 +72,7 @@ async def construct_request_headers( custom_llm_provider="vertex_ai", api_base=None, ) - verbose_logger.debug( - "constructed auth_header [set=%s]", auth_header is not None - ) + verbose_logger.debug("constructed auth_header [set=%s]", auth_header is not None) headers = { "Authorization": f"Bearer {auth_header}", # auth_header "Content-Type": "application/json", @@ -112,9 +108,7 @@ def sync_construct_request_headers(self) -> Dict[str, str]: custom_llm_provider="vertex_ai", api_base=None, ) - verbose_logger.debug( - "constructed auth_header [set=%s]", auth_header is not None - ) + verbose_logger.debug("constructed auth_header [set=%s]", auth_header is not None) headers = { "Authorization": f"Bearer {auth_header}", # auth_header "Content-Type": "application/json", @@ -143,9 +137,7 @@ def _handle_folders_in_bucket_name( return bucket_name, object_name return bucket_name, object_name - async def get_gcs_logging_config( - self, kwargs: Optional[Dict[str, Any]] = {} - ) -> GCSLoggingConfig: + async def get_gcs_logging_config(self, kwargs: Optional[Dict[str, Any]] = {}) -> GCSLoggingConfig: """ This function is used to get the GCS logging config for the GCS Bucket Logger. It checks if the dynamic parameters are provided in the kwargs and uses them to get the GCS logging config. @@ -154,25 +146,21 @@ async def get_gcs_logging_config( if kwargs is None: kwargs = {} - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params", None) + standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = kwargs.get( + "standard_callback_dynamic_params", None ) bucket_name: str path_service_account: Optional[str] if standard_callback_dynamic_params is not None: verbose_logger.debug("Using dynamic GCS logging") - verbose_logger.debug( - "standard_callback_dynamic_params: %s", standard_callback_dynamic_params - ) + verbose_logger.debug("standard_callback_dynamic_params: %s", standard_callback_dynamic_params) _bucket_name: Optional[str] = ( - standard_callback_dynamic_params.get("gcs_bucket_name", None) - or self.BUCKET_NAME + standard_callback_dynamic_params.get("gcs_bucket_name", None) or self.BUCKET_NAME ) _path_service_account: Optional[str] = ( - standard_callback_dynamic_params.get("gcs_path_service_account", None) - or self.path_service_account_json + standard_callback_dynamic_params.get("gcs_path_service_account", None) or self.path_service_account_json ) if _bucket_name is None: @@ -181,9 +169,7 @@ async def get_gcs_logging_config( ) bucket_name = _bucket_name path_service_account = _path_service_account - vertex_instance = await self.get_or_create_vertex_instance( - credentials=path_service_account - ) + vertex_instance = await self.get_or_create_vertex_instance(credentials=path_service_account) else: # If no dynamic parameters, use the default instance if self.BUCKET_NAME is None: @@ -192,9 +178,7 @@ async def get_gcs_logging_config( ) bucket_name = self.BUCKET_NAME path_service_account = self.path_service_account_json - vertex_instance = await self.get_or_create_vertex_instance( - credentials=path_service_account - ) + vertex_instance = await self.get_or_create_vertex_instance(credentials=path_service_account) return GCSLoggingConfig( bucket_name=bucket_name, @@ -202,9 +186,7 @@ async def get_gcs_logging_config( path_service_account=path_service_account, ) - async def get_or_create_vertex_instance( - self, credentials: Optional[str] - ) -> VertexBase: + async def get_or_create_vertex_instance(self, credentials: Optional[str]) -> VertexBase: """ This function is used to get the Vertex instance for the GCS Bucket Logger. It checks if the Vertex instance is already created and cached, if not it creates a new instance and caches it. @@ -240,9 +222,7 @@ async def download_gcs_object(self, object_name: str, **kwargs): https://cloud.google.com/storage/docs/downloading-objects#download-object-json """ try: - gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config( - kwargs=kwargs - ) + gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config(kwargs=kwargs) headers = await self.construct_request_headers( vertex_instance=gcs_logging_config["vertex_instance"], service_account_json=gcs_logging_config["path_service_account"], @@ -260,14 +240,10 @@ async def download_gcs_object(self, object_name: str, **kwargs): response = await self.async_httpx_client.get(url=url, headers=headers) if response.status_code != 200: - verbose_logger.error( - "GCS object download error: %s", str(response.text) - ) + verbose_logger.error("GCS object download error: %s", str(response.text)) return None - verbose_logger.debug( - "GCS object download response status code: %s", response.status_code - ) + verbose_logger.debug("GCS object download response status code: %s", response.status_code) # Return the content of the downloaded object return response.content @@ -281,9 +257,7 @@ async def delete_gcs_object(self, object_name: str, **kwargs): Delete an object from GCS. """ try: - gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config( - kwargs=kwargs - ) + gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config(kwargs=kwargs) headers = await self.construct_request_headers( vertex_instance=gcs_logging_config["vertex_instance"], service_account_json=gcs_logging_config["path_service_account"], diff --git a/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py b/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py index 9161455a2461..fae7ddaf5361 100644 --- a/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py +++ b/litellm/integrations/gcs_bucket/gcs_bucket_mock_client.py @@ -38,14 +38,10 @@ # Default mock latency in seconds (simulates network round-trip) # Typical GCS API calls take 100-300ms for uploads, 50-150ms for GET/DELETE -_MOCK_LATENCY_SECONDS = ( - float(__import__("os").getenv("GCS_MOCK_LATENCY_MS", "150")) / 1000.0 -) +_MOCK_LATENCY_SECONDS = float(__import__("os").getenv("GCS_MOCK_LATENCY_MS", "150")) / 1000.0 -async def _mock_async_handler_get( - self, url, params=None, headers=None, follow_redirects=None -): +async def _mock_async_handler_get(self, url, params=None, headers=None, follow_redirects=None): """Monkey-patched AsyncHTTPHandler.get that intercepts GCS calls.""" # Only mock GCS API calls if isinstance(url, str) and "storage.googleapis.com" in url: @@ -154,10 +150,7 @@ def create_mock_gcs_client(): This function is idempotent - it only initializes mocks once, even if called multiple times. """ - global \ - _original_async_handler_get, \ - _original_async_handler_delete, \ - _mocks_initialized + global _original_async_handler_get, _original_async_handler_delete, _mocks_initialized # Use factory for POST handler _create_mock_gcs_post() @@ -181,9 +174,7 @@ def create_mock_gcs_client(): AsyncHTTPHandler.delete = _mock_async_handler_delete # type: ignore verbose_logger.debug("[GCS MOCK] Patched AsyncHTTPHandler.delete") - verbose_logger.debug( - f"[GCS MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS * 1000:.0f}ms" - ) + verbose_logger.debug(f"[GCS MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS * 1000:.0f}ms") verbose_logger.debug("[GCS MOCK] GCS mock client initialization complete") _mocks_initialized = True @@ -205,29 +196,17 @@ def mock_vertex_auth_methods(): "_original_ensure_access_token_async", VertexBase._ensure_access_token_async, ) - setattr( - VertexBase, "_original_ensure_access_token", VertexBase._ensure_access_token - ) - setattr( - VertexBase, "_original_get_token_and_url", VertexBase._get_token_and_url - ) + setattr(VertexBase, "_original_ensure_access_token", VertexBase._ensure_access_token) + setattr(VertexBase, "_original_get_token_and_url", VertexBase._get_token_and_url) - async def _mock_ensure_access_token_async( - self, credentials, project_id, custom_llm_provider - ): + async def _mock_ensure_access_token_async(self, credentials, project_id, custom_llm_provider): """Mock async auth method - returns fake token.""" - verbose_logger.debug( - "[GCS MOCK] Vertex AI auth: _ensure_access_token_async called" - ) + verbose_logger.debug("[GCS MOCK] Vertex AI auth: _ensure_access_token_async called") return ("mock-gcs-token", "mock-project-id") - def _mock_ensure_access_token( - self, credentials, project_id, custom_llm_provider - ): + def _mock_ensure_access_token(self, credentials, project_id, custom_llm_provider): """Mock sync auth method - returns fake token.""" - verbose_logger.debug( - "[GCS MOCK] Vertex AI auth: _ensure_access_token called" - ) + verbose_logger.debug("[GCS MOCK] Vertex AI auth: _ensure_access_token called") return ("mock-gcs-token", "mock-project-id") def _mock_get_token_and_url( diff --git a/litellm/integrations/gcs_pubsub/pub_sub.py b/litellm/integrations/gcs_pubsub/pub_sub.py index db7f9bb4d0b5..c1bccb0b3906 100644 --- a/litellm/integrations/gcs_pubsub/pub_sub.py +++ b/litellm/integrations/gcs_pubsub/pub_sub.py @@ -48,15 +48,11 @@ def __init__( _premium_user_check() - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.project_id = project_id or os.getenv("GCS_PUBSUB_PROJECT_ID") self.topic_id = topic_id or os.getenv("GCS_PUBSUB_TOPIC_ID") - self.path_service_account_json = credentials_path or os.getenv( - "GCS_PATH_SERVICE_ACCOUNT" - ) + self.path_service_account_json = credentials_path or os.getenv("GCS_PATH_SERVICE_ACCOUNT") if not self.project_id or not self.topic_id: raise ValueError("Both project_id and topic_id must be provided") @@ -116,9 +112,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti _premium_user_check() try: - verbose_logger.debug( - "PubSub: Logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("PubSub: Logging - Enters logging function for model %s", kwargs) standard_logging_payload = kwargs.get("standard_logging_object", None) # Backwards compatibility with old logging payload @@ -138,9 +132,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"PubSub Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"PubSub Layer Error - {str(e)}\n{traceback.format_exc()}") pass async def async_send_batch(self): @@ -151,17 +143,13 @@ async def async_send_batch(self): if not self.log_queue: return - verbose_logger.debug( - f"PubSub - about to flush {len(self.log_queue)} events" - ) + verbose_logger.debug(f"PubSub - about to flush {len(self.log_queue)} events") for message in self.log_queue: await self.publish_message(message) except Exception as e: - verbose_logger.exception( - f"PubSub Error sending batch - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"PubSub Error sending batch - {str(e)}\n{traceback.format_exc()}") finally: self.log_queue.clear() @@ -189,18 +177,14 @@ async def publish_message( # Base64 encode the message import base64 - encoded_message = base64.b64encode(message_data.encode("utf-8")).decode( - "utf-8" - ) + encoded_message = base64.b64encode(message_data.encode("utf-8")).decode("utf-8") # Construct request body request_body = {"messages": [{"data": encoded_message}]} url = f"https://pubsub.googleapis.com/v1/projects/{self.project_id}/topics/{self.topic_id}:publish" - response = await self.async_httpx_client.post( - url=url, headers=headers, json=request_body - ) + response = await self.async_httpx_client.post(url=url, headers=headers, json=request_body) if response.status_code not in [200, 202]: verbose_logger.error("Pub/Sub publish error: %s", str(response.text)) diff --git a/litellm/integrations/generic_api/generic_api_callback.py b/litellm/integrations/generic_api/generic_api_callback.py index 2982df8fda23..da6009c3a942 100644 --- a/litellm/integrations/generic_api/generic_api_callback.py +++ b/litellm/integrations/generic_api/generic_api_callback.py @@ -37,15 +37,11 @@ def load_compatible_callbacks() -> Dict: Dict: Dictionary of compatible callbacks configuration """ try: - json_path = os.path.join( - os.path.dirname(__file__), "generic_api_compatible_callbacks.json" - ) + json_path = os.path.join(os.path.dirname(__file__), "generic_api_compatible_callbacks.json") with open(json_path, "r") as f: return json.load(f) except Exception as e: - verbose_logger.warning( - f"Error loading generic_api_compatible_callbacks.json: {str(e)}" - ) + verbose_logger.warning(f"Error loading generic_api_compatible_callbacks.json: {str(e)}") return {} @@ -127,9 +123,7 @@ def __init__( ######################################################### if callback_name: if is_callback_compatible(callback_name): - verbose_logger.debug( - f"Loading configuration for callback: {callback_name}" - ) + verbose_logger.debug(f"Loading configuration for callback: {callback_name}") callback_config = get_callback_config(callback_name) # Use config from JSON if not explicitly provided @@ -156,9 +150,7 @@ def __init__( ######################################################### # Init httpx client ######################################################### - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) endpoint = endpoint or os.getenv("GENERIC_LOGGER_ENDPOINT") if endpoint is None: raise ValueError( @@ -180,9 +172,7 @@ def __init__( "ndjson", "single", ]: - raise ValueError( - f"Invalid log_format: {log_format}. Must be one of: 'json_array', 'ndjson', 'single'" - ) + raise ValueError(f"Invalid log_format: {log_format}. Must be one of: 'json_array', 'ndjson', 'single'") self.log_format: LOG_FORMAT_TYPES = log_format or "json_array" verbose_logger.debug( @@ -223,9 +213,7 @@ def _get_headers(self, headers: Optional[dict] = None): key, value = item.split("=", 1) headers_dict[key.strip()] = value.strip() except Exception as e: - verbose_logger.warning( - f"Error parsing headers from environment variables: {str(e)}" - ) + verbose_logger.warning(f"Error parsing headers from environment variables: {str(e)}") # 2. Update with litellm generic headers if available if litellm.generic_logger_headers: @@ -273,8 +261,7 @@ async def _post_with_retries(self, data: str) -> httpx.Response: raise verbose_logger.warning( - "Generic API Logger - retrying request to %s after error: %s " - "(attempt %s/%s)", + "Generic API Logger - retrying request to %s after error: %s (attempt %s/%s)", self.endpoint, str(e), attempt + 1, @@ -300,9 +287,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti return try: - verbose_logger.debug( - "Generic API Logger - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("Generic API Logger - Enters logging function for model %s", kwargs) standard_logging_payload = kwargs.get("standard_logging_object", None) # Backwards compatibility with old logging payload @@ -322,9 +307,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"Generic API Logger Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Generic API Logger Error - {str(e)}\n{traceback.format_exc()}") pass async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): @@ -338,9 +321,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti return try: - verbose_logger.debug( - "Generic API Logger - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("Generic API Logger - Enters logging function for model %s", kwargs) standard_logging_payload = kwargs.get("standard_logging_object", None) if litellm.generic_api_use_v1 is True: @@ -358,9 +339,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti await self.async_send_batch() except Exception as e: - verbose_logger.exception( - f"Generic API Logger Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Generic API Logger Error - {str(e)}\n{traceback.format_exc()}") async def async_send_batch(self): """ @@ -392,9 +371,7 @@ async def async_send_batch(self): # Log results for idx, result in enumerate(responses): if isinstance(result, Exception): - verbose_logger.exception( - f"Generic API Logger - Error sending log {idx}: {result}" - ) + verbose_logger.exception(f"Generic API Logger - Error sending log {idx}: {result}") else: # result is a Response object verbose_logger.debug( @@ -418,30 +395,22 @@ async def async_send_batch(self): ) except Exception as e: - verbose_logger.exception( - f"Generic API Logger Error sending batch - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Generic API Logger Error sending batch - {str(e)}\n{traceback.format_exc()}") finally: self.log_queue.clear() - def _get_v1_logging_payload( - self, kwargs, response_obj, start_time, end_time - ) -> dict: + def _get_v1_logging_payload(self, kwargs, response_obj, start_time, end_time) -> dict: """ Maintained for backwards compatibility with old logging payload Returns a dict of the payload to send to the Generic API Endpoint """ - verbose_logger.debug( - f"GenericAPILogger Logging - Enters logging function for model {kwargs}" - ) + verbose_logger.debug(f"GenericAPILogger Logging - Enters logging function for model {kwargs}") # construct payload to send custom logger # follows the same params as langfuse.py litellm_params = kwargs.get("litellm_params", {}) - metadata = ( - litellm_params.get("metadata", {}) or {} - ) # if litellm_params['metadata'] == None + metadata = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None messages = kwargs.get("messages") cost = kwargs.get("response_cost", 0.0) optional_params = kwargs.get("optional_params", {}) diff --git a/litellm/integrations/generic_prompt_management/__init__.py b/litellm/integrations/generic_prompt_management/__init__.py index 7466dc9c68de..44c61aa5f502 100644 --- a/litellm/integrations/generic_prompt_management/__init__.py +++ b/litellm/integrations/generic_prompt_management/__init__.py @@ -30,9 +30,7 @@ def set_global_generic_prompt_config(config: dict) -> None: litellm.global_generic_prompt_config = config # type: ignore -def prompt_initializer( - litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec" -) -> "CustomPromptManagement": +def prompt_initializer(litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec") -> "CustomPromptManagement": """ Initialize a prompt from a generic prompt management API. """ diff --git a/litellm/integrations/generic_prompt_management/generic_prompt_manager.py b/litellm/integrations/generic_prompt_management/generic_prompt_manager.py index 858bfd458b65..f9837efdde2e 100644 --- a/litellm/integrations/generic_prompt_management/generic_prompt_manager.py +++ b/litellm/integrations/generic_prompt_management/generic_prompt_manager.py @@ -74,9 +74,7 @@ def __init__( self.api_key = api_key self.timeout = timeout self.prompt_id = prompt_id - self.additional_provider_specific_query_params = ( - additional_provider_specific_query_params - ) + self.additional_provider_specific_query_params = additional_provider_specific_query_params self._prompt_cache: Dict[str, PromptManagementClient] = {} @property @@ -94,9 +92,7 @@ def _get_headers(self) -> Dict[str, str]: headers["Authorization"] = f"Bearer {self.api_key}" return headers - def _fetch_prompt_from_api( - self, prompt_id: Optional[str], prompt_spec: Optional[PromptSpec] - ) -> Dict[str, Any]: + def _fetch_prompt_from_api(self, prompt_id: Optional[str], prompt_spec: Optional[PromptSpec]) -> Dict[str, Any]: """ Fetch a prompt from the API. @@ -147,8 +143,7 @@ async def async_fetch_prompt_from_api( "prompt_id": prompt_id, **( prompt_spec.litellm_params.provider_specific_query_params - if prompt_spec - and prompt_spec.litellm_params.provider_specific_query_params + if prompt_spec and prompt_spec.litellm_params.provider_specific_query_params else {} ), } @@ -204,9 +199,7 @@ def _parse_api_response( prompt_id=prompt_id, prompt_template=api_response.get("prompt_template", []), prompt_template_model=api_response.get("prompt_template_model"), - prompt_template_optional_params=api_response.get( - "prompt_template_optional_params" - ), + prompt_template_optional_params=api_response.get("prompt_template_optional_params"), completed_messages=None, ) @@ -223,8 +216,7 @@ def should_run_prompt_management( in the _compile_prompt_helper method. """ if prompt_id is not None or ( - prompt_spec is not None - and prompt_spec.litellm_params.provider_specific_query_params is not None + prompt_spec is not None and prompt_spec.litellm_params.provider_specific_query_params is not None ): return True return False @@ -299,9 +291,7 @@ def _compile_prompt_helper( api_response = self._fetch_prompt_from_api(prompt_id, prompt_spec) # Parse the response - prompt_client = self._parse_api_response( - prompt_id, prompt_spec, api_response - ) + prompt_client = self._parse_api_response(prompt_id, prompt_spec, api_response) # Cache the result self._prompt_cache[cache_key] = prompt_client @@ -339,14 +329,10 @@ async def async_compile_prompt_helper( try: # Fetch from API - api_response = await self.async_fetch_prompt_from_api( - prompt_id=prompt_id, prompt_spec=prompt_spec - ) + api_response = await self.async_fetch_prompt_from_api(prompt_id=prompt_id, prompt_spec=prompt_spec) # Parse the response - prompt_client = self._parse_api_response( - prompt_id, prompt_spec, api_response - ) + prompt_client = self._parse_api_response(prompt_id, prompt_spec, api_response) # Cache the result self._prompt_cache[cache_key] = prompt_client @@ -358,9 +344,7 @@ async def async_compile_prompt_helper( return prompt_client except Exception as e: - raise ValueError( - f"Error compiling prompt '{prompt_id}': {e}, prompt_spec: {prompt_spec}" - ) + raise ValueError(f"Error compiling prompt '{prompt_id}': {e}, prompt_spec: {prompt_spec}") def _apply_variables( self, @@ -383,15 +367,11 @@ def _apply_variables( updated_messages: List[AllMessageValues] = [] for message in prompt_client["prompt_template"]: updated_message = dict(message) # type: ignore - if "content" in updated_message and isinstance( - updated_message["content"], str - ): + if "content" in updated_message and isinstance(updated_message["content"], str): content = updated_message["content"] for key, value in variables.items(): content = content.replace(f"{{{key}}}", str(value)) - content = content.replace( - f"{{{{{key}}}}}", str(value) - ) # Also support {{key}} + content = content.replace(f"{{{{{key}}}}}", str(value)) # Also support {{key}} updated_message["content"] = content updated_messages.append(updated_message) # type: ignore @@ -399,9 +379,7 @@ def _apply_variables( prompt_id=prompt_client["prompt_id"], prompt_template=updated_messages, prompt_template_model=prompt_client["prompt_template_model"], - prompt_template_optional_params=prompt_client[ - "prompt_template_optional_params" - ], + prompt_template_optional_params=prompt_client["prompt_template_optional_params"], completed_messages=None, ) @@ -439,8 +417,7 @@ async def async_get_chat_completion_prompt( prompt_label=prompt_label, prompt_version=prompt_version, ignore_prompt_manager_model=( - ignore_prompt_manager_model - or prompt_spec.litellm_params.ignore_prompt_manager_model + ignore_prompt_manager_model or prompt_spec.litellm_params.ignore_prompt_manager_model if prompt_spec else False ), @@ -481,8 +458,7 @@ def get_chat_completion_prompt( prompt_label=prompt_label, prompt_version=prompt_version, ignore_prompt_manager_model=( - ignore_prompt_manager_model - or prompt_spec.litellm_params.ignore_prompt_manager_model + ignore_prompt_manager_model or prompt_spec.litellm_params.ignore_prompt_manager_model if prompt_spec else False ), diff --git a/litellm/integrations/gitlab/__init__.py b/litellm/integrations/gitlab/__init__.py index 24e7ddea9e8a..f06c28c50017 100644 --- a/litellm/integrations/gitlab/__init__.py +++ b/litellm/integrations/gitlab/__init__.py @@ -30,9 +30,7 @@ def set_global_gitlab_config(config: dict) -> None: litellm.global_gitlab_config = config # type: ignore -def prompt_initializer( - litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec" -) -> "CustomPromptManagement": +def prompt_initializer(litellm_params: "PromptLiteLLMParams", prompt_spec: "PromptSpec") -> "CustomPromptManagement": """ Initialize a prompt from a Gitlab repository. """ diff --git a/litellm/integrations/gitlab/gitlab_client.py b/litellm/integrations/gitlab/gitlab_client.py index 60f73256185d..ca366274ccdd 100644 --- a/litellm/integrations/gitlab/gitlab_client.py +++ b/litellm/integrations/gitlab/gitlab_client.py @@ -108,9 +108,7 @@ def set_ref(self, ref: str) -> None: raise ValueError("ref must be a non-empty string") self.ref = ref - def get_file_content( - self, file_path: str, *, ref: Optional[str] = None - ) -> Optional[str]: + def get_file_content(self, file_path: str, *, ref: Optional[str] = None) -> Optional[str]: """ Fetch the content of a file from the GitLab repository at the given ref (tag, branch, or commit SHA). If `ref` is None, uses self.ref. @@ -132,11 +130,7 @@ def get_file_content( resp.raise_for_status() ctype = (resp.headers.get("content-type") or "").lower() - if ( - ctype.startswith("text/") - or "charset=" in ctype - or ctype.startswith("application/json") - ): + if ctype.startswith("text/") or "charset=" in ctype or ctype.startswith("application/json"): return resp.text try: return resp.content.decode("utf-8") @@ -152,14 +146,10 @@ def get_file_content( f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'." ) if status == 401: - raise Exception( - "Authentication failed. Check your GitLab token and auth_method." - ) + raise Exception("Authentication failed. Check your GitLab token and auth_method.") raise Exception(f"Failed to fetch file '{file_path}': {e}") - def _get_file_content_via_json( - self, file_path: str, *, ref: Optional[str] = None - ) -> Optional[str]: + def _get_file_content_via_json(self, file_path: str, *, ref: Optional[str] = None) -> Optional[str]: """ Fallback for get_file_content(): use the JSON file API which returns base64 content. """ @@ -187,12 +177,8 @@ def _get_file_content_via_json( f"Access denied to file '{file_path}'. Check your GitLab permissions for project '{self.project}'." ) if status == 401: - raise Exception( - "Authentication failed. Check your GitLab token and auth_method." - ) - raise Exception( - f"Failed to fetch file '{file_path}' via JSON endpoint: {e}" - ) + raise Exception("Authentication failed. Check your GitLab token and auth_method.") + raise Exception(f"Failed to fetch file '{file_path}' via JSON endpoint: {e}") def list_files( self, @@ -240,9 +226,7 @@ def list_files( f"Access denied to directory '{directory_path}'. Check your GitLab permissions for project '{self.project}'." ) if status == 401: - raise Exception( - "Authentication failed. Check your GitLab token and auth_method." - ) + raise Exception("Authentication failed. Check your GitLab token and auth_method.") raise Exception(f"Failed to list files in '{directory_path}': {e}") def get_repository_info(self) -> Dict[str, Any]: @@ -274,9 +258,7 @@ def get_branches(self) -> List[Dict[str, Any]]: except Exception as e: raise Exception(f"Failed to get branches: {e}") - def get_file_metadata( - self, file_path: str, *, ref: Optional[str] = None - ) -> Optional[Dict[str, Any]]: + def get_file_metadata(self, file_path: str, *, ref: Optional[str] = None) -> Optional[Dict[str, Any]]: """ Get minimal metadata about a file via RAW endpoint headers at a given ref. diff --git a/litellm/integrations/gitlab/gitlab_prompt_manager.py b/litellm/integrations/gitlab/gitlab_prompt_manager.py index 99d9d9b285b4..4896f95f398e 100644 --- a/litellm/integrations/gitlab/gitlab_prompt_manager.py +++ b/litellm/integrations/gitlab/gitlab_prompt_manager.py @@ -54,9 +54,7 @@ def __init__( self.temperature = metadata.get("temperature") self.max_tokens = metadata.get("max_tokens") self.input_schema = metadata.get("input", {}).get("schema", {}) - self.optional_params = { - k: v for k, v in metadata.items() if k not in ["model", "input", "content"] - } + self.optional_params = {k: v for k, v in metadata.items() if k not in ["model", "input", "content"]} def __repr__(self): return f"GitLabPromptTemplate(id='{self.template_id}', model='{self.model}')" @@ -86,9 +84,7 @@ def __init__( # Folder inside repo to look for prompts (e.g., "prompts" or "prompts/chat") self.prompts_path: str = ( - self.gitlab_config.get("prompts_path") - or self.gitlab_config.get("folder") - or "" + self.gitlab_config.get("prompts_path") or self.gitlab_config.get("folder") or "" ).strip("/") # Templates fetched from a GitLab repo are not trustworthy: @@ -134,9 +130,7 @@ def _repo_path_to_id(self, repo_path: str) -> str: # ---------- loading ---------- - def _load_prompt_from_gitlab( - self, prompt_id: str, *, ref: Optional[str] = None - ) -> None: + def _load_prompt_from_gitlab(self, prompt_id: str, *, ref: Optional[str] = None) -> None: """Load a specific .prompt file from GitLab (scoped under prompts_path if set).""" try: # prompt_id = decode_prompt_id(prompt_id) @@ -146,9 +140,7 @@ def _load_prompt_from_gitlab( template = self._parse_prompt_file(prompt_content, prompt_id) self.prompts[prompt_id] = template except Exception as e: - raise Exception( - f"Failed to load prompt '{encode_prompt_id(prompt_id)}' from GitLab: {e}" - ) + raise Exception(f"Failed to load prompt '{encode_prompt_id(prompt_id)}' from GitLab: {e}") def load_all_prompts(self, *, recursive: bool = True) -> List[str]: """ @@ -215,9 +207,7 @@ def _parse_yaml_basic(self, yaml_str: str) -> Dict[str, Any]: result[key] = value.strip("\"'") return result - def render_template( - self, template_id: str, variables: Optional[Dict[str, Any]] = None - ) -> str: + def render_template(self, template_id: str, variables: Optional[Dict[str, Any]] = None) -> str: if template_id not in self.prompts: raise ValueError(f"Template '{template_id}' not found") template = self.prompts[template_id] @@ -335,9 +325,7 @@ def get_prompt_template( if not template: raise ValueError(f"Prompt template '{prompt_id}' not found") - rendered_prompt = self.prompt_manager.render_template( - prompt_id, prompt_variables or {} - ) + rendered_prompt = self.prompt_manager.render_template(prompt_id, prompt_variables or {}) metadata = { "model": template.model, @@ -364,17 +352,13 @@ def pre_call_hook( # Precedence: explicit prompt_version → per-call git_ref kwarg → manager override → config default git_ref = prompt_version or kwargs.get("git_ref") or self._ref_override - rendered_prompt, prompt_metadata = self.get_prompt_template( - prompt_id, prompt_variables, ref=git_ref - ) + rendered_prompt, prompt_metadata = self.get_prompt_template(prompt_id, prompt_variables, ref=git_ref) parsed_messages = self._parse_prompt_to_messages(rendered_prompt) if parsed_messages: final_messages: List[AllMessageValues] = parsed_messages else: - final_messages = [ - {"role": "user", "content": rendered_prompt} - ] + messages # type: ignore + final_messages = [{"role": "user", "content": rendered_prompt}] + messages # type: ignore if litellm_params is None: litellm_params = {} @@ -396,9 +380,7 @@ def pre_call_hook( except Exception as e: import litellm - litellm._logging.verbose_proxy_logger.error( - f"Error in GitLab prompt pre_call_hook: {e}" - ) + litellm._logging.verbose_proxy_logger.error(f"Error in GitLab prompt pre_call_hook: {e}") return messages, litellm_params def _parse_prompt_to_messages(self, prompt_content: str) -> List[AllMessageValues]: @@ -446,9 +428,7 @@ def _parse_prompt_to_messages(self, prompt_content: str) -> List[AllMessageValue current_content.append(line) if current_role and current_content: - messages.append( - {"role": current_role, "content": "\n".join(current_content).strip()} - ) # type: ignore + messages.append({"role": current_role, "content": "\n".join(current_content).strip()}) # type: ignore if not messages and prompt_content.strip(): messages = [{"role": "user", "content": prompt_content.strip()}] # type: ignore return messages @@ -514,9 +494,7 @@ def _compile_prompt_helper( ) self.prompt_manager._load_prompt_from_gitlab(decoded_id, ref=git_ref) - rendered_prompt, prompt_metadata = self.get_prompt_template( - prompt_id, prompt_variables - ) + rendered_prompt, prompt_metadata = self.get_prompt_template(prompt_id, prompt_variables) messages = self._parse_prompt_to_messages(rendered_prompt) template_model = prompt_metadata.get("model") @@ -678,9 +656,7 @@ def __init__( ref=ref, gitlab_client=gitlab_client, ) - self.template_manager: GitLabTemplateManager = ( - self.prompt_manager.prompt_manager - ) + self.template_manager: GitLabTemplateManager = self.prompt_manager.prompt_manager # In-memory stores self._by_file: Dict[str, Dict[str, Any]] = {} @@ -695,9 +671,7 @@ def load_all(self, *, recursive: bool = True) -> Dict[str, Dict[str, Any]]: Scan GitLab for all .prompt files under prompts_path, load and parse each, and return the mapping of repo file path -> JSON-like dict. """ - ids = self.template_manager.list_templates( - recursive=recursive - ) # IDs relative to prompts_path + ids = self.template_manager.list_templates(recursive=recursive) # IDs relative to prompts_path for pid in ids: # Ensure template is loaded into TemplateManager if pid not in self.template_manager.prompts: @@ -711,9 +685,7 @@ def load_all(self, *, recursive: bool = True) -> Dict[str, Dict[str, Any]]: if tmpl is None: continue - file_path = self.template_manager._id_to_repo_path( - pid - ) # "prompts/chat/..../file.prompt" + file_path = self.template_manager._id_to_repo_path(pid) # "prompts/chat/..../file.prompt" entry = self._template_to_json(pid, tmpl) self._by_file[file_path] = entry @@ -757,9 +729,7 @@ def get_by_id(self, prompt_id: str) -> Optional[Dict[str, Any]]: # Internals # ------------------------- - def _template_to_json( - self, prompt_id: str, tmpl: GitLabPromptTemplate - ) -> Dict[str, Any]: + def _template_to_json(self, prompt_id: str, tmpl: GitLabPromptTemplate) -> Dict[str, Any]: """ Normalize a GitLabPromptTemplate into a JSON-like dict that is easy to serialize. """ @@ -774,9 +744,7 @@ def _template_to_json( return { "id": prompt_id, # e.g. "greet/hi" - "path": self.template_manager._id_to_repo_path( - prompt_id - ), # e.g. "prompts/chat/greet/hi.prompt" + "path": self.template_manager._id_to_repo_path(prompt_id), # e.g. "prompts/chat/greet/hi.prompt" "content": tmpl.content, # rendered content (without frontmatter) "metadata": md, # parsed frontmatter "model": model, diff --git a/litellm/integrations/greenscale.py b/litellm/integrations/greenscale.py index 430c3d0abf22..e2aca3610108 100644 --- a/litellm/integrations/greenscale.py +++ b/litellm/integrations/greenscale.py @@ -22,18 +22,12 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): data = { "modelId": kwargs.get("model"), "inputTokenCount": response_json.get("usage", {}).get("prompt_tokens"), - "outputTokenCount": response_json.get("usage", {}).get( - "completion_tokens" - ), + "outputTokenCount": response_json.get("usage", {}).get("completion_tokens"), } - data["timestamp"] = datetime.now(timezone.utc).strftime( - "%Y-%m-%dT%H:%M:%SZ" - ) + data["timestamp"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if type(end_time) is datetime and type(start_time) is datetime: - data["invocationLatency"] = int( - (end_time - start_time).total_seconds() * 1000 - ) + data["invocationLatency"] = int((end_time - start_time).total_seconds() * 1000) # Add additional metadata keys to tags tags = [] @@ -45,9 +39,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): elif key == "greenscale_application": data["application"] = value else: - tags.append( - {"key": key.replace("greenscale_", ""), "value": str(value)} - ) + tags.append({"key": key.replace("greenscale_", ""), "value": str(value)}) data["tags"] = tags @@ -60,13 +52,9 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): data=json.dumps(data, default=str), ) if response.status_code != 200: - print_verbose( - f"Greenscale Logger Error - {response.text}, {response.status_code}" - ) + print_verbose(f"Greenscale Logger Error - {response.text}, {response.status_code}") else: print_verbose(f"Greenscale Logger Succeeded - {response.text}") except Exception as e: - print_verbose( - f"Greenscale Logger Error - {e}, Stack trace: {traceback.format_exc()}" - ) + print_verbose(f"Greenscale Logger Error - {e}, Stack trace: {traceback.format_exc()}") pass diff --git a/litellm/integrations/helicone.py b/litellm/integrations/helicone.py index 376952033a0a..21e9479491e4 100644 --- a/litellm/integrations/helicone.py +++ b/litellm/integrations/helicone.py @@ -31,9 +31,7 @@ def __init__(self): self.is_mock_mode = should_use_helicone_mock() if self.is_mock_mode: create_mock_helicone_client() - verbose_logger.info( - "[HELICONE MOCK] Helicone logger initialized in mock mode" - ) + verbose_logger.info("[HELICONE MOCK] Helicone logger initialized in mock mode") self.provider_url = "https://api.openai.com/v1" self.key = os.getenv("HELICONE_API_KEY") @@ -106,9 +104,7 @@ def add_metadata_from_header(litellm_params: dict, metadata: dict) -> dict: if metadata is None: metadata = {} - proxy_headers = ( - litellm_params.get("proxy_server_request", {}).get("headers", {}) or {} - ) + proxy_headers = litellm_params.get("proxy_server_request", {}).get("headers", {}) or {} for header_key in proxy_headers: if header_key.startswith("helicone_"): @@ -121,14 +117,10 @@ def add_metadata_from_header(litellm_params: dict, metadata: dict) -> dict: return metadata - def log_success( - self, model, messages, response_obj, start_time, end_time, print_verbose, kwargs - ): + def log_success(self, model, messages, response_obj, start_time, end_time, print_verbose, kwargs): # Method definition try: - print_verbose( - f"Helicone Logging - Enters logging function for model {model}" - ) + print_verbose(f"Helicone Logging - Enters logging function for model {model}") litellm_params = kwargs.get("litellm_params", {}) custom_llm_provider = litellm_params.get("custom_llm_provider", "") kwargs.get("litellm_call_id", None) @@ -136,29 +128,19 @@ def log_success( metadata = self.add_metadata_from_header(litellm_params, metadata) # Check if model is a vertex_ai model - is_vertex_ai = custom_llm_provider == "vertex_ai" or model.startswith( - "vertex_ai/" - ) + is_vertex_ai = custom_llm_provider == "vertex_ai" or model.startswith("vertex_ai/") model = ( model - if any( - accepted_model in model - for accepted_model in self.helicone_model_list - ) - or is_vertex_ai + if any(accepted_model in model for accepted_model in self.helicone_model_list) or is_vertex_ai else "gpt-3.5-turbo" ) provider_request = {"model": model, "messages": messages} - if isinstance(response_obj, litellm.EmbeddingResponse) or isinstance( - response_obj, litellm.ModelResponse - ): + if isinstance(response_obj, litellm.EmbeddingResponse) or isinstance(response_obj, litellm.ModelResponse): response_obj = response_obj.json() if "claude" in model and not is_vertex_ai: - response_obj = self.claude_mapping( - model=model, messages=messages, response_obj=response_obj - ) + response_obj = self.claude_mapping(model=model, messages=messages, response_obj=response_obj) providerResponse = { "json": response_obj, @@ -183,13 +165,9 @@ def log_success( "Content-Type": "application/json", } start_time_seconds = int(start_time.timestamp()) - start_time_milliseconds = int( - (start_time.timestamp() - start_time_seconds) * 1000 - ) + start_time_milliseconds = int((start_time.timestamp() - start_time_seconds) * 1000) end_time_seconds = int(end_time.timestamp()) - end_time_milliseconds = int( - (end_time.timestamp() - end_time_seconds) * 1000 - ) + end_time_milliseconds = int((end_time.timestamp() - end_time_seconds) * 1000) meta = {"Helicone-Auth": f"Bearer {self.key}"} meta.update(metadata) data = { @@ -213,9 +191,7 @@ def log_success( response = litellm.module_level_client.post(url, headers=headers, json=data) if response.status_code == 200: if self.is_mock_mode: - print_verbose( - "[HELICONE MOCK] Helicone Logging - Successfully mocked!" - ) + print_verbose("[HELICONE MOCK] Helicone Logging - Successfully mocked!") else: print_verbose("Helicone Logging - Success!") else: diff --git a/litellm/integrations/helicone_mock_client.py b/litellm/integrations/helicone_mock_client.py index c2d3dfdf5bc6..02530692d430 100644 --- a/litellm/integrations/helicone_mock_client.py +++ b/litellm/integrations/helicone_mock_client.py @@ -32,6 +32,4 @@ patch_http_handler=True, # Patch HTTPHandler.post directly ) -create_mock_helicone_client, should_use_helicone_mock = create_mock_client_factory( - _config -) +create_mock_helicone_client, should_use_helicone_mock = create_mock_client_factory(_config) diff --git a/litellm/integrations/humanloop.py b/litellm/integrations/humanloop.py index 369df5ee0bd8..2a5cb70baee4 100644 --- a/litellm/integrations/humanloop.py +++ b/litellm/integrations/humanloop.py @@ -32,12 +32,8 @@ class HumanLoopPromptManager(DualCache): def integration_name(self): return "humanloop" - def _get_prompt_from_id_cache( - self, humanloop_prompt_id: str - ) -> Optional[PromptManagementClient]: - return cast( - Optional[PromptManagementClient], self.get_cache(key=humanloop_prompt_id) - ) + def _get_prompt_from_id_cache(self, humanloop_prompt_id: str) -> Optional[PromptManagementClient]: + return cast(Optional[PromptManagementClient], self.get_cache(key=humanloop_prompt_id)) def _compile_prompt_helper( self, prompt_template: List[AllMessageValues], prompt_variables: Dict[str, Any] @@ -64,9 +60,7 @@ def _compile_prompt_helper( return compiled_prompts - def _get_prompt_from_id_api( - self, humanloop_prompt_id: str, humanloop_api_key: str - ) -> PromptManagementClient: + def _get_prompt_from_id_api(self, humanloop_prompt_id: str, humanloop_api_key: str) -> PromptManagementClient: client = _get_httpx_client() base_url = "https://api.humanloop.com/v5/prompts/{}".format(humanloop_prompt_id) @@ -104,14 +98,10 @@ def _get_prompt_from_id_api( optional_params=optional_params, ) - def _get_prompt_from_id( - self, humanloop_prompt_id: str, humanloop_api_key: str - ) -> PromptManagementClient: + def _get_prompt_from_id(self, humanloop_prompt_id: str, humanloop_api_key: str) -> PromptManagementClient: prompt = self._get_prompt_from_id_cache(humanloop_prompt_id) if prompt is None: - prompt = self._get_prompt_from_id_api( - humanloop_prompt_id, humanloop_api_key - ) + prompt = self._get_prompt_from_id_api(humanloop_prompt_id, humanloop_api_key) self.set_cache( key=humanloop_prompt_id, value=prompt, @@ -136,9 +126,7 @@ def compile_prompt( return compiled_prompt - def _get_model_from_prompt( - self, prompt_management_client: PromptManagementClient, model: str - ) -> str: + def _get_model_from_prompt(self, prompt_management_client: PromptManagementClient, model: str) -> str: if prompt_management_client["model"] is not None: return prompt_management_client["model"] else: @@ -167,9 +155,7 @@ def get_chat_completion_prompt( List[AllMessageValues], dict, ]: - humanloop_api_key = dynamic_callback_params.get( - "humanloop_api_key" - ) or get_secret_str("HUMANLOOP_API_KEY") + humanloop_api_key = dynamic_callback_params.get("humanloop_api_key") or get_secret_str("HUMANLOOP_API_KEY") if prompt_id is None: raise ValueError("prompt_id is required for Humanloop integration") @@ -201,8 +187,6 @@ def get_chat_completion_prompt( **prompt_template_optional_params, } - model = prompt_manager._get_model_from_prompt( - prompt_management_client=prompt_template, model=model - ) + model = prompt_manager._get_model_from_prompt(prompt_management_client=prompt_template, model=model) return model, updated_messages, updated_non_default_params diff --git a/litellm/integrations/lago.py b/litellm/integrations/lago.py index c7c010f99767..0052e04644d2 100644 --- a/litellm/integrations/lago.py +++ b/litellm/integrations/lago.py @@ -32,9 +32,7 @@ class LagoLogger(CustomLogger): def __init__(self) -> None: super().__init__() self.validate_environment() - self.async_http_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.sync_http_handler = HTTPHandler() def validate_environment(self): @@ -70,8 +68,7 @@ def _common_logic(self, kwargs: dict, response_obj) -> dict: usage = {} if ( - isinstance(response_obj, litellm.ModelResponse) - or isinstance(response_obj, litellm.EmbeddingResponse) + isinstance(response_obj, litellm.ModelResponse) or isinstance(response_obj, litellm.EmbeddingResponse) ) and hasattr(response_obj, "usage"): usage = { "prompt_tokens": response_obj["usage"].get("prompt_tokens", 0), @@ -89,9 +86,7 @@ def _common_logic(self, kwargs: dict, response_obj) -> dict: charge_by: Literal["end_user_id", "team_id", "user_id"] = "end_user_id" external_customer_id: Optional[str] = None - if os.getenv("LAGO_API_CHARGE_BY", None) is not None and isinstance( - os.environ["LAGO_API_CHARGE_BY"], str - ): + if os.getenv("LAGO_API_CHARGE_BY", None) is not None and isinstance(os.environ["LAGO_API_CHARGE_BY"], str): if os.environ["LAGO_API_CHARGE_BY"] in [ "end_user_id", "user_id", @@ -124,9 +119,7 @@ def _common_logic(self, kwargs: dict, response_obj) -> dict: } } - verbose_logger.debug( - "\033[91mLogged Lago Object:\n{}\033[0m\n".format(returned_val) - ) + verbose_logger.debug("\033[91mLogged Lago Object:\n{}\033[0m\n".format(returned_val)) return returned_val def log_success_event(self, kwargs, response_obj, start_time, end_time): @@ -166,9 +159,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti verbose_logger.debug("ENTERS LAGO CALLBACK") _url = os.getenv("LAGO_API_BASE") assert _url is not None and isinstance(_url, str), ( - "LAGO_API_BASE missing or not set correctly. LAGO_API_BASE={}".format( - _url - ) + "LAGO_API_BASE missing or not set correctly. LAGO_API_BASE={}".format(_url) ) if _url.endswith("/"): _url += "api/v1/events" diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.py index b1c6956a16c1..8068a8c0b0c2 100644 --- a/litellm/integrations/langfuse/langfuse.py +++ b/litellm/integrations/langfuse/langfuse.py @@ -76,15 +76,9 @@ def _extract_cache_read_input_tokens(usage_obj) -> int: # Check prompt_tokens_details.cached_tokens (used by Gemini and other providers) if hasattr(usage_obj, "prompt_tokens_details"): prompt_tokens_details = getattr(usage_obj, "prompt_tokens_details", None) - if prompt_tokens_details is not None and hasattr( - prompt_tokens_details, "cached_tokens" - ): + if prompt_tokens_details is not None and hasattr(prompt_tokens_details, "cached_tokens"): cached_tokens = getattr(prompt_tokens_details, "cached_tokens", None) - if ( - cached_tokens is not None - and isinstance(cached_tokens, (int, float)) - and cached_tokens > 0 - ): + if cached_tokens is not None and isinstance(cached_tokens, (int, float)) and cached_tokens > 0: cache_read_input_tokens = cached_tokens return cache_read_input_tokens @@ -101,14 +95,10 @@ def resolve_langfuse_credentials( secret_key = langfuse_secret or langfuse_secret_key public_key = langfuse_public_key else: - secret_key = ( - langfuse_secret or langfuse_secret_key or os.getenv("LANGFUSE_SECRET_KEY") - ) + secret_key = langfuse_secret or langfuse_secret_key or os.getenv("LANGFUSE_SECRET_KEY") public_key = langfuse_public_key or os.getenv("LANGFUSE_PUBLIC_KEY") - resolved_host = langfuse_host or os.getenv( - "LANGFUSE_HOST", "https://cloud.langfuse.com" - ) + resolved_host = langfuse_host or os.getenv("LANGFUSE_HOST", "https://cloud.langfuse.com") return public_key, secret_key, resolved_host @@ -130,25 +120,18 @@ def __init__( raise Exception( f"\033[91mLangfuse not installed, try running 'pip install langfuse' to fix this error: {e}\n{traceback.format_exc()}\033[0m" ) - self.public_key, self.secret_key, self.langfuse_host = ( - resolve_langfuse_credentials( - langfuse_public_key=langfuse_public_key, - langfuse_secret=langfuse_secret, - langfuse_host=langfuse_host, - allow_env_credentials=allow_env_credentials, - ) + self.public_key, self.secret_key, self.langfuse_host = resolve_langfuse_credentials( + langfuse_public_key=langfuse_public_key, + langfuse_secret=langfuse_secret, + langfuse_host=langfuse_host, + allow_env_credentials=allow_env_credentials, ) - if not ( - self.langfuse_host.startswith("http://") - or self.langfuse_host.startswith("https://") - ): + if not (self.langfuse_host.startswith("http://") or self.langfuse_host.startswith("https://")): # add http:// if unset, assume communicating over private network - e.g. render self.langfuse_host = "http://" + self.langfuse_host self.langfuse_release = os.getenv("LANGFUSE_RELEASE") self.langfuse_debug = os.getenv("LANGFUSE_DEBUG") - self.langfuse_flush_interval = LangFuseLogger._get_langfuse_flush_interval( - flush_interval - ) + self.langfuse_flush_interval = LangFuseLogger._get_langfuse_flush_interval(flush_interval) if should_use_langfuse_mock(): self.langfuse_client = create_mock_langfuse_client() @@ -188,16 +171,10 @@ def __init__( if os.getenv("UPSTREAM_LANGFUSE_SECRET_KEY") is not None: upstream_langfuse_debug_env = os.getenv("UPSTREAM_LANGFUSE_DEBUG") upstream_langfuse_debug = ( - str_to_bool(upstream_langfuse_debug_env) - if upstream_langfuse_debug_env is not None - else None - ) - self.upstream_langfuse_secret_key = os.getenv( - "UPSTREAM_LANGFUSE_SECRET_KEY" - ) - self.upstream_langfuse_public_key = os.getenv( - "UPSTREAM_LANGFUSE_PUBLIC_KEY" + str_to_bool(upstream_langfuse_debug_env) if upstream_langfuse_debug_env is not None else None ) + self.upstream_langfuse_secret_key = os.getenv("UPSTREAM_LANGFUSE_SECRET_KEY") + self.upstream_langfuse_public_key = os.getenv("UPSTREAM_LANGFUSE_PUBLIC_KEY") self.upstream_langfuse_host = os.getenv("UPSTREAM_LANGFUSE_HOST") self.upstream_langfuse_release = os.getenv("UPSTREAM_LANGFUSE_RELEASE") self.upstream_langfuse_debug = upstream_langfuse_debug_env @@ -206,11 +183,7 @@ def __init__( secret_key=self.upstream_langfuse_secret_key, host=self.upstream_langfuse_host, release=self.upstream_langfuse_release, - debug=( - upstream_langfuse_debug - if upstream_langfuse_debug is not None - else False - ), + debug=(upstream_langfuse_debug if upstream_langfuse_debug is not None else False), ) else: self.upstream_langfuse = None @@ -231,9 +204,7 @@ def safe_init_langfuse_client(self, parameters: dict) -> Langfuse: ) langfuse_client = Langfuse(**parameters) litellm.initialized_langfuse_clients += 1 - verbose_logger.debug( - f"Created langfuse client number {litellm.initialized_langfuse_clients}" - ) + verbose_logger.debug(f"Created langfuse client number {litellm.initialized_langfuse_clients}") return langfuse_client @staticmethod @@ -254,21 +225,15 @@ def add_metadata_from_header(litellm_params: dict, metadata: dict) -> dict: if metadata is None: metadata = {} - proxy_headers = ( - litellm_params.get("proxy_server_request", {}).get("headers", {}) or {} - ) + proxy_headers = litellm_params.get("proxy_server_request", {}).get("headers", {}) or {} for metadata_param_key in proxy_headers: if metadata_param_key.startswith("langfuse_"): trace_param_key = metadata_param_key.replace("langfuse_", "", 1) if trace_param_key in metadata: - verbose_logger.warning( - f"Overwriting Langfuse `{trace_param_key}` from request header" - ) + verbose_logger.warning(f"Overwriting Langfuse `{trace_param_key}` from request header") else: - verbose_logger.debug( - f"Found Langfuse `{trace_param_key}` in request header" - ) + verbose_logger.debug(f"Found Langfuse `{trace_param_key}` in request header") metadata[trace_param_key] = proxy_headers.get(metadata_param_key) return metadata @@ -298,9 +263,7 @@ def log_event_on_langfuse( Logs a success or error event on Langfuse """ try: - verbose_logger.debug( - f"Langfuse Logging - Enters logging function for model {kwargs}" - ) + verbose_logger.debug(f"Langfuse Logging - Enters logging function for model {kwargs}") # set default values for input/output for langfuse logging input = None @@ -308,9 +271,7 @@ def log_event_on_langfuse( litellm_params = kwargs.get("litellm_params", {}) litellm_call_id = kwargs.get("litellm_call_id", None) - metadata = ( - litellm_params.get("metadata", {}) or {} - ) # if litellm_params['metadata'] == None + metadata = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None metadata = self.add_metadata_from_header(litellm_params, metadata) optional_params = safe_deep_copy(kwargs.get("optional_params", {})) @@ -341,9 +302,7 @@ def log_event_on_langfuse( level=level, status_message=status_message, ) - verbose_logger.debug( - f"OUTPUT IN LANGFUSE: {output}; original: {response_obj}" - ) + verbose_logger.debug(f"OUTPUT IN LANGFUSE: {output}; original: {response_obj}") trace_id = None generation_id = None if self._is_langfuse_v2(): @@ -373,16 +332,12 @@ def log_event_on_langfuse( input=input, response_obj=response_obj, ) - verbose_logger.debug( - f"Langfuse Layer Logging - final response object: {response_obj}" - ) + verbose_logger.debug(f"Langfuse Layer Logging - final response object: {response_obj}") verbose_logger.info("Langfuse Layer Logging - logging success") return {"trace_id": trace_id, "generation_id": generation_id} except Exception as e: - verbose_logger.exception( - "Langfuse Layer Error(): Exception occured - {}".format(str(e)) - ) + verbose_logger.exception("Langfuse Layer Error(): Exception occured - {}".format(str(e))) return {"trace_id": None, "generation_id": None} def _get_langfuse_input_output_content( @@ -420,52 +375,33 @@ def _get_langfuse_input_output_content( """ input = None output: Optional[Union[str, dict, List[Any]]] = None - if ( - level == "ERROR" - and status_message is not None - and isinstance(status_message, str) - ): + if level == "ERROR" and status_message is not None and isinstance(status_message, str): input = prompt output = status_message elif response_obj is not None and ( - kwargs.get("call_type", None) == "embedding" - or isinstance(response_obj, litellm.EmbeddingResponse) + kwargs.get("call_type", None) == "embedding" or isinstance(response_obj, litellm.EmbeddingResponse) ): input = prompt output = None - elif response_obj is not None and isinstance( - response_obj, litellm.ModelResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ModelResponse): input = prompt output = self._get_chat_content_for_langfuse(response_obj) - elif response_obj is not None and isinstance( - response_obj, litellm.HttpxBinaryResponseContent - ): + elif response_obj is not None and isinstance(response_obj, litellm.HttpxBinaryResponseContent): input = prompt output = "speech-output" - elif response_obj is not None and isinstance( - response_obj, litellm.TextCompletionResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.TextCompletionResponse): input = prompt output = self._get_text_completion_content_for_langfuse(response_obj) - elif response_obj is not None and isinstance( - response_obj, litellm.ImageResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ImageResponse): input = prompt output = response_obj.get("data", None) - elif response_obj is not None and isinstance( - response_obj, litellm.TranscriptionResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.TranscriptionResponse): input = prompt output = response_obj.get("text", None) - elif response_obj is not None and isinstance( - response_obj, litellm.RerankResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.RerankResponse): input = prompt output = response_obj.results - elif response_obj is not None and isinstance( - response_obj, litellm.ResponsesAPIResponse - ): + elif response_obj is not None and isinstance(response_obj, litellm.ResponsesAPIResponse): input = prompt output = self._get_responses_api_content_for_langfuse(response_obj) elif ( @@ -486,9 +422,7 @@ def _get_langfuse_input_output_content( output = response_obj.get("response", "") return input, output - async def _async_log_event( - self, kwargs, response_obj, start_time, end_time, user_id - ): + async def _async_log_event(self, kwargs, response_obj, start_time, end_time, user_id): """ Langfuse SDK uses a background thread to log events @@ -528,9 +462,7 @@ def _log_langfuse_v1( ) custom_llm_provider = cast(Optional[str], kwargs.get("custom_llm_provider")) - model_name = reconstruct_model_name( - kwargs.get("model", ""), custom_llm_provider, metadata - ) + model_name = reconstruct_model_name(kwargs.get("model", ""), custom_llm_provider, metadata) trace.generation( CreateGeneration( @@ -579,19 +511,13 @@ def _log_langfuse_v2( if standard_logging_object is None: end_user_id = None - prompt_management_metadata: Optional[ - StandardLoggingPromptManagementMetadata - ] = None + prompt_management_metadata: Optional[StandardLoggingPromptManagementMetadata] = None else: - end_user_id = standard_logging_object["metadata"].get( - "user_api_key_end_user_id", None - ) + end_user_id = standard_logging_object["metadata"].get("user_api_key_end_user_id", None) prompt_management_metadata = cast( Optional[StandardLoggingPromptManagementMetadata], - standard_logging_object["metadata"].get( - "prompt_management_metadata", None - ), + standard_logging_object["metadata"].get("prompt_management_metadata", None), ) # Clean Metadata before logging - never log raw metadata @@ -599,9 +525,7 @@ def _log_langfuse_v2( # we clean out all extra litellm metadata params before logging clean_metadata: Dict[str, Any] = {} if prompt_management_metadata is not None: - clean_metadata["prompt_management_metadata"] = ( - prompt_management_metadata - ) + clean_metadata["prompt_management_metadata"] = prompt_management_metadata if isinstance(metadata, dict): for key, value in metadata.items(): # generate langfuse tags - Default Tags sent to Langfuse from LiteLLM Proxy @@ -624,9 +548,7 @@ def _log_langfuse_v2( clean_metadata[key] = value # Add default langfuse tags - tags = self.add_default_langfuse_tags( - tags=tags, kwargs=kwargs, metadata=metadata - ) + tags = self.add_default_langfuse_tags(tags=tags, kwargs=kwargs, metadata=metadata) session_id = clean_metadata.pop("session_id", None) trace_name = cast(Optional[str], clean_metadata.pop("trace_name", None)) @@ -649,9 +571,9 @@ def _log_langfuse_v2( mask_output = clean_metadata.pop("mask_output", False) # Look for masking function in the dedicated location first (set by scrub_sensitive_keys_in_metadata) # Fall back to metadata for backwards compatibility - masking_function = litellm_params.get( - "_langfuse_masking_function" - ) or clean_metadata.pop("langfuse_masking_function", None) + masking_function = litellm_params.get("_langfuse_masking_function") or clean_metadata.pop( + "langfuse_masking_function", None + ) # Apply custom masking function if provided if masking_function is not None and callable(masking_function): @@ -672,27 +594,19 @@ def _log_langfuse_v2( for metadata_param_key in update_trace_keys: trace_param_key = metadata_param_key.replace("trace_", "") if trace_param_key not in trace_params: - updated_trace_value = clean_metadata.pop( - metadata_param_key, None - ) + updated_trace_value = clean_metadata.pop(metadata_param_key, None) if updated_trace_value is not None: trace_params[trace_param_key] = updated_trace_value # Pop the trace specific keys that would have been popped if there were a new trace - for key in list( - filter(lambda key: key.startswith("trace_"), clean_metadata.keys()) - ): + for key in list(filter(lambda key: key.startswith("trace_"), clean_metadata.keys())): clean_metadata.pop(key, None) # Special keys that are found in the function arguments and not the metadata if "input" in update_trace_keys: - trace_params["input"] = ( - input if not mask_input else "redacted-by-litellm" - ) + trace_params["input"] = input if not mask_input else "redacted-by-litellm" if "output" in update_trace_keys: - trace_params["output"] = ( - output if not mask_output else "redacted-by-litellm" - ) + trace_params["output"] = output if not mask_output else "redacted-by-litellm" else: # don't overwrite an existing trace trace_params = { "id": trace_id, @@ -704,19 +618,13 @@ def _log_langfuse_v2( ), # If provided just version, it will applied to the trace as well, if applied a trace version it will take precedence "user_id": end_user_id, } - for key in list( - filter(lambda key: key.startswith("trace_"), clean_metadata.keys()) - ): - trace_params[key.replace("trace_", "")] = clean_metadata.pop( - key, None - ) + for key in list(filter(lambda key: key.startswith("trace_"), clean_metadata.keys())): + trace_params[key.replace("trace_", "")] = clean_metadata.pop(key, None) if level == "ERROR": trace_params["status_message"] = output else: - trace_params["output"] = ( - output if not mask_output else "redacted-by-litellm" - ) + trace_params["output"] = output if not mask_output else "redacted-by-litellm" if debug is True or (isinstance(debug, str) and debug.lower() == "true"): if "metadata" in trace_params: @@ -731,9 +639,7 @@ def _log_langfuse_v2( clean_metadata["litellm_response_cost"] = cost if standard_logging_object is not None: hidden_params = standard_logging_object.get("hidden_params", {}) - clean_metadata["hidden_params"] = filter_exceptions_from_params( - hidden_params - ) + clean_metadata["hidden_params"] = filter_exceptions_from_params(hidden_params) if ( litellm.langfuse_default_tags is not None @@ -791,30 +697,19 @@ def _log_langfuse_v2( usage = None usage_details = None if response_obj is not None: - if ( - hasattr(response_obj, "id") - and response_obj.get("id", None) is not None - ): - generation_id = litellm.utils.get_logging_id( - start_time, response_obj - ) + if hasattr(response_obj, "id") and response_obj.get("id", None) is not None: + generation_id = litellm.utils.get_logging_id(start_time, response_obj) _usage_obj = getattr(response_obj, "usage", None) if _usage_obj: # Safely get usage values, defaulting None to 0 for Langfuse compatibility. # Some providers may return null for token counts. prompt_tokens = getattr(_usage_obj, "prompt_tokens", None) or 0 - completion_tokens = ( - getattr(_usage_obj, "completion_tokens", None) or 0 - ) + completion_tokens = getattr(_usage_obj, "completion_tokens", None) or 0 total_tokens = getattr(_usage_obj, "total_tokens", None) or 0 - cache_creation_input_tokens = ( - _usage_obj.get("cache_creation_input_tokens") or 0 - ) - cache_read_input_tokens = _extract_cache_read_input_tokens( - _usage_obj - ) + cache_creation_input_tokens = _usage_obj.get("cache_creation_input_tokens") or 0 + cache_read_input_tokens = _extract_cache_read_input_tokens(_usage_obj) usage = { "prompt_tokens": prompt_tokens, @@ -836,12 +731,8 @@ def _log_langfuse_v2( # if `generation_name` is None, use sensible default values # If using litellm proxy user `key_alias` if not None # If `key_alias` is None, just log `litellm-{call_type}` as the generation name - _user_api_key_alias = cast( - Optional[str], clean_metadata.get("user_api_key_alias", None) - ) - generation_name = ( - f"litellm-{cast(str, kwargs.get('call_type', 'completion'))}" - ) + _user_api_key_alias = cast(Optional[str], clean_metadata.get("user_api_key_alias", None)) + generation_name = f"litellm-{cast(str, kwargs.get('call_type', 'completion'))}" if _user_api_key_alias is not None: generation_name = f"litellm:{_user_api_key_alias}" @@ -854,9 +745,7 @@ def _log_langfuse_v2( optional_params["system_fingerprint"] = system_fingerprint custom_llm_provider = cast(Optional[str], kwargs.get("custom_llm_provider")) - model_name = reconstruct_model_name( - kwargs.get("model", ""), custom_llm_provider, metadata - ) + model_name = reconstruct_model_name(kwargs.get("model", ""), custom_llm_provider, metadata) generation_params = { "name": generation_name, @@ -889,9 +778,7 @@ def _log_langfuse_v2( generation_params["status_message"] = output if self._supports_completion_start_time(): - generation_params["completion_start_time"] = kwargs.get( - "completion_start_time", None - ) + generation_params["completion_start_time"] = kwargs.get("completion_start_time", None) generation_client = trace.generation(**generation_params) @@ -965,9 +852,7 @@ def add_default_langfuse_tags(self, tags, kwargs, metadata): - cache_key """ - if litellm.langfuse_default_tags is not None and isinstance( - litellm.langfuse_default_tags, list - ): + if litellm.langfuse_default_tags is not None and isinstance(litellm.langfuse_default_tags, list): if "cache_hit" in litellm.langfuse_default_tags: _cache_hit_value = kwargs.get("cache_hit", False) tags.append(f"cache_hit:{_cache_hit_value}") @@ -976,9 +861,7 @@ def add_default_langfuse_tags(self, tags, kwargs, metadata): _cache_key = _hidden_params.get("cache_key", None) if _cache_key is None and litellm.cache is not None: # fallback to using "preset_cache_key" - _preset_cache_key = litellm.cache._get_preset_cache_key_from_kwargs( - **kwargs - ) + _preset_cache_key = litellm.cache._get_preset_cache_key_from_kwargs(**kwargs) _cache_key = _preset_cache_key tags.append(f"cache_key:{_cache_key}") return tags @@ -1000,9 +883,7 @@ def _supports_completion_start_time(self): return Version(self.langfuse_sdk_version) >= Version("2.7.3") @staticmethod - def _apply_masking_function( - data: Any, masking_function: Callable[[Any], Any] - ) -> Any: + def _apply_masking_function(data: Any, masking_function: Callable[[Any], Any]) -> Any: """ Apply a masking function to data, handling different data types. @@ -1022,22 +903,15 @@ def _apply_masking_function( elif isinstance(data, dict): masked_dict = {} for key, value in data.items(): - masked_dict[key] = LangFuseLogger._apply_masking_function( - value, masking_function - ) + masked_dict[key] = LangFuseLogger._apply_masking_function(value, masking_function) return masked_dict elif isinstance(data, list): - return [ - LangFuseLogger._apply_masking_function(item, masking_function) - for item in data - ] + return [LangFuseLogger._apply_masking_function(item, masking_function) for item in data] else: # For other types, try to apply the function directly return masking_function(data) except Exception as e: - verbose_logger.warning( - f"Failed to apply masking function: {e}. Returning original data." - ) + verbose_logger.warning(f"Failed to apply masking function: {e}. Returning original data.") return data @staticmethod @@ -1065,18 +939,12 @@ def _log_guardrail_information_as_span( Log guardrail information as a span """ if standard_logging_object is None: - verbose_logger.debug( - "Not logging guardrail information as span because standard_logging_object is None" - ) + verbose_logger.debug("Not logging guardrail information as span because standard_logging_object is None") return - guardrail_information = standard_logging_object.get( - "guardrail_information", None - ) + guardrail_information = standard_logging_object.get("guardrail_information", None) if not guardrail_information: - verbose_logger.debug( - "Not logging guardrail information as span because guardrail_information is empty" - ) + verbose_logger.debug("Not logging guardrail information as span because guardrail_information is empty") return if not isinstance(guardrail_information, list): @@ -1101,9 +969,7 @@ def _log_guardrail_information_as_span( metadata={ "guardrail_name": guardrail_entry.get("guardrail_name", None), "guardrail_mode": guardrail_entry.get("guardrail_mode", None), - "guardrail_masked_entity_count": guardrail_entry.get( - "masked_entity_count", None - ), + "guardrail_masked_entity_count": guardrail_entry.get("masked_entity_count", None), }, start_time=guardrail_entry.get("start_time", None), # type: ignore end_time=guardrail_entry.get("end_time", None), # type: ignore @@ -1142,9 +1008,7 @@ def _add_prompt_to_generation_params( elif "version" in user_prompt and "prompt" in user_prompt: # prompts if isinstance(user_prompt["prompt"], str): - prompt_text_params = getattr( - Prompt_Text, "model_fields", Prompt_Text.__fields__ - ) + prompt_text_params = getattr(Prompt_Text, "model_fields", Prompt_Text.__fields__) _data = { "name": user_prompt["name"], "prompt": user_prompt["prompt"], @@ -1158,9 +1022,7 @@ def _add_prompt_to_generation_params( generation_params["prompt"] = TextPromptClient(prompt=_prompt_obj) elif isinstance(user_prompt["prompt"], list): - prompt_chat_params = getattr( - Prompt_Chat, "model_fields", Prompt_Chat.__fields__ - ) + prompt_chat_params = getattr(Prompt_Chat, "model_fields", Prompt_Chat.__fields__) _data = { "name": user_prompt["name"], "prompt": user_prompt["prompt"], @@ -1175,25 +1037,14 @@ def _add_prompt_to_generation_params( generation_params["prompt"] = ChatPromptClient(prompt=_prompt_obj) else: - verbose_logger.error( - "[Non-blocking] Langfuse Logger: Invalid prompt format" - ) + verbose_logger.error("[Non-blocking] Langfuse Logger: Invalid prompt format") else: - verbose_logger.error( - "[Non-blocking] Langfuse Logger: Invalid prompt format. No prompt logged to Langfuse" - ) - elif ( - prompt_management_metadata is not None - and prompt_management_metadata["prompt_integration"] == "langfuse" - ): + verbose_logger.error("[Non-blocking] Langfuse Logger: Invalid prompt format. No prompt logged to Langfuse") + elif prompt_management_metadata is not None and prompt_management_metadata["prompt_integration"] == "langfuse": try: - generation_params["prompt"] = langfuse_client.get_prompt( - prompt_management_metadata["prompt_id"] - ) + generation_params["prompt"] = langfuse_client.get_prompt(prompt_management_metadata["prompt_id"]) except Exception as e: - verbose_logger.debug( - f"[Non-blocking] Langfuse Logger: Error getting prompt client for logging: {e}" - ) + verbose_logger.debug(f"[Non-blocking] Langfuse Logger: Error getting prompt client for logging: {e}") pass else: @@ -1221,9 +1072,7 @@ def log_provider_specific_information_as_span( if _hidden_params is None: return - vertex_ai_grounding_metadata = _hidden_params.get( - "vertex_ai_grounding_metadata", None - ) + vertex_ai_grounding_metadata = _hidden_params.get("vertex_ai_grounding_metadata", None) if vertex_ai_grounding_metadata is not None: if isinstance(vertex_ai_grounding_metadata, list): diff --git a/litellm/integrations/langfuse/langfuse_handler.py b/litellm/integrations/langfuse/langfuse_handler.py index 797c1609f806..b1d083bd7d45 100644 --- a/litellm/integrations/langfuse/langfuse_handler.py +++ b/litellm/integrations/langfuse/langfuse_handler.py @@ -36,12 +36,7 @@ def get_langfuse_logger_for_request( """ temp_langfuse_logger: Optional[LangFuseLogger] = globalLangfuseLogger - if ( - LangFuseHandler._dynamic_langfuse_credentials_are_passed( - standard_callback_dynamic_params - ) - is False - ): + if LangFuseHandler._dynamic_langfuse_credentials_are_passed(standard_callback_dynamic_params) is False: return LangFuseHandler._return_global_langfuse_logger( globalLangfuseLogger=globalLangfuseLogger, in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, @@ -61,11 +56,9 @@ def get_langfuse_logger_for_request( # if not cached, create a new langfuse logger and cache it if temp_langfuse_logger is None: - temp_langfuse_logger = ( - LangFuseHandler._create_langfuse_logger_from_credentials( - credentials=credentials_dict, - in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, - ) + temp_langfuse_logger = LangFuseHandler._create_langfuse_logger_from_credentials( + credentials=credentials_dict, + in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, ) return temp_langfuse_logger @@ -94,11 +87,9 @@ def _return_global_langfuse_logger( service_name="langfuse", ) if globalLangfuseLogger is None: - globalLangfuseLogger = ( - LangFuseHandler._create_langfuse_logger_from_credentials( - credentials=credentials_dict, - in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, - ) + globalLangfuseLogger = LangFuseHandler._create_langfuse_logger_from_credentials( + credentials=credentials_dict, + in_memory_dynamic_logger_cache=in_memory_dynamic_logger_cache, ) return globalLangfuseLogger @@ -115,8 +106,7 @@ def _create_langfuse_logger_from_credentials( langfuse_logger = LangFuseLogger( langfuse_public_key=credentials.get("langfuse_public_key"), - langfuse_secret=credentials.get("langfuse_secret") - or credentials.get("langfuse_secret_key"), + langfuse_secret=credentials.get("langfuse_secret") or credentials.get("langfuse_secret_key"), langfuse_host=credentials.get("langfuse_host"), allow_env_credentials=credentials.get("langfuse_host") is None, ) @@ -143,9 +133,7 @@ def get_dynamic_langfuse_logging_config( return LangfuseLoggingConfig( langfuse_secret=standard_callback_dynamic_params.get("langfuse_secret") or standard_callback_dynamic_params.get("langfuse_secret_key"), - langfuse_public_key=standard_callback_dynamic_params.get( - "langfuse_public_key" - ), + langfuse_public_key=standard_callback_dynamic_params.get("langfuse_public_key"), langfuse_host=standard_callback_dynamic_params.get("langfuse_host"), ) diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.py index 7370bcdf9345..fc7c1b211c06 100644 --- a/litellm/integrations/langfuse/langfuse_otel.py +++ b/litellm/integrations/langfuse/langfuse_otel.py @@ -48,9 +48,7 @@ def set_langfuse_otel_attributes(span: Span, kwargs, response_obj): ######################################################### # Set Langfuse specific attributes ######################################################### - LangfuseOtelLogger._set_langfuse_specific_attributes( - span=span, kwargs=kwargs, response_obj=response_obj - ) + LangfuseOtelLogger._set_langfuse_specific_attributes(span=span, kwargs=kwargs, response_obj=response_obj) return @staticmethod @@ -141,11 +139,7 @@ def _set_observation_output(span: Span, response_obj): function = tool_call.get("function", {}) arguments_str = function.get("arguments", "{}") try: - arguments_obj = ( - json.loads(arguments_str) - if isinstance(arguments_str, str) - else arguments_str - ) + arguments_obj = json.loads(arguments_str) if isinstance(arguments_str, str) else arguments_str except json.JSONDecodeError: arguments_obj = {} langfuse_tool_call = { @@ -193,18 +187,12 @@ def _set_observation_output(span: Span, response_obj): output_items_data.append( { "role": getattr(item, "role", "assistant"), - "content": getattr( - getattr(item, "content", [{}])[0], "text", "" - ), + "content": getattr(getattr(item, "content", [{}])[0], "text", ""), } ) elif item_type == "function_call": arguments_str = getattr(item, "arguments", "{}") - arguments_obj = ( - json.loads(arguments_str) - if isinstance(arguments_str, str) - else arguments_str - ) + arguments_obj = json.loads(arguments_str) if isinstance(arguments_str, str) else arguments_str langfuse_tool_call = { "id": getattr(item, "id", ""), "name": getattr(item, "name", ""), @@ -379,12 +367,8 @@ def construct_dynamic_otel_headers( """ dynamic_headers = {} - dynamic_langfuse_public_key = standard_callback_dynamic_params.get( - "langfuse_public_key" - ) - dynamic_langfuse_secret_key = standard_callback_dynamic_params.get( - "langfuse_secret_key" - ) + dynamic_langfuse_public_key = standard_callback_dynamic_params.get("langfuse_public_key") + dynamic_langfuse_secret_key = standard_callback_dynamic_params.get("langfuse_secret_key") if dynamic_langfuse_public_key and dynamic_langfuse_secret_key: auth_header = LangfuseOtelLogger._get_langfuse_authorization_header( public_key=dynamic_langfuse_public_key, diff --git a/litellm/integrations/langfuse/langfuse_otel_attributes.py b/litellm/integrations/langfuse/langfuse_otel_attributes.py index fb4a0a6a36ce..46bfc21968f6 100644 --- a/litellm/integrations/langfuse/langfuse_otel_attributes.py +++ b/litellm/integrations/langfuse/langfuse_otel_attributes.py @@ -74,9 +74,7 @@ def get_output_content_by_type( if isinstance(response_obj, BaseModel): return response_obj.model_dump_json() - if response_obj and ( - isinstance(response_obj, dict) or isinstance(response_obj, list) - ): + if response_obj and (isinstance(response_obj, dict) or isinstance(response_obj, list)): return json.dumps(response_obj) else: return "" diff --git a/litellm/integrations/langfuse/langfuse_prompt_management.py b/litellm/integrations/langfuse/langfuse_prompt_management.py index cae592956349..0e06f516ecd3 100644 --- a/litellm/integrations/langfuse/langfuse_prompt_management.py +++ b/litellm/integrations/langfuse/langfuse_prompt_management.py @@ -79,9 +79,7 @@ def langfuse_client_init( allow_env_credentials=allow_env_credentials, ) - if not ( - langfuse_host.startswith("http://") or langfuse_host.startswith("https://") - ): + if not (langfuse_host.startswith("http://") or langfuse_host.startswith("https://")): # add http:// if unset, assume communicating over private network - e.g. render langfuse_host = "http://" + langfuse_host @@ -94,9 +92,7 @@ def langfuse_client_init( "host": langfuse_host, "release": langfuse_release, "debug": langfuse_debug, - "flush_interval": LangFuseLogger._get_langfuse_flush_interval( - flush_interval - ), # flush interval in seconds + "flush_interval": LangFuseLogger._get_langfuse_flush_interval(flush_interval), # flush interval in seconds } if Version(langfuse.version.__version__) >= Version("2.6.0"): @@ -148,9 +144,7 @@ def _get_prompt_from_id( prompt_label: Optional[str] = None, prompt_version: Optional[int] = None, ) -> PROMPT_CLIENT: - prompt_client = langfuse_client.get_prompt( - langfuse_prompt_id, label=prompt_label, version=prompt_version - ) + prompt_client = langfuse_client.get_prompt(langfuse_prompt_id, label=prompt_label, version=prompt_version) return prompt_client @@ -168,17 +162,13 @@ def _compile_prompt( compiled_prompt = langfuse_prompt_client.compile(**langfuse_prompt_variables) if isinstance(compiled_prompt, str): - compiled_prompt = [ - ChatCompletionSystemMessage(role="system", content=compiled_prompt) - ] + compiled_prompt = [ChatCompletionSystemMessage(role="system", content=compiled_prompt)] else: compiled_prompt = cast(List[AllMessageValues], compiled_prompt) return compiled_prompt - def _get_optional_params_from_langfuse( - self, langfuse_prompt_client: PROMPT_CLIENT - ) -> dict: + def _get_optional_params_from_langfuse(self, langfuse_prompt_client: PROMPT_CLIENT) -> dict: config = langfuse_prompt_client.config optional_params = {} for k, v in config.items(): @@ -276,9 +266,7 @@ def _compile_prompt_helper( template_model = langfuse_prompt_client.config.get("model") - template_optional_params = self._get_optional_params_from_langfuse( - langfuse_prompt_client - ) + template_optional_params = self._get_optional_params_from_langfuse(langfuse_prompt_client) return PromptManagementClient( prompt_id=prompt_id, @@ -307,20 +295,14 @@ async def async_compile_prompt_helper( ) def log_success_event(self, kwargs, response_obj, start_time, end_time): - return run_async_function( - self.async_log_success_event, kwargs, response_obj, start_time, end_time - ) + return run_async_function(self.async_log_success_event, kwargs, response_obj, start_time, end_time) def log_failure_event(self, kwargs, response_obj, start_time, end_time): - return run_async_function( - self.async_log_failure_event, kwargs, response_obj, start_time, end_time - ) + return run_async_function(self.async_log_failure_event, kwargs, response_obj, start_time, end_time) async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): try: - standard_callback_dynamic_params = kwargs.get( - "standard_callback_dynamic_params" - ) + standard_callback_dynamic_params = kwargs.get("standard_callback_dynamic_params") langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request( globalLangfuseLogger=self, standard_callback_dynamic_params=standard_callback_dynamic_params, @@ -336,16 +318,12 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti except Exception as e: from litellm._logging import verbose_logger - verbose_logger.exception( - f"Langfuse Layer Error - Exception occurred while logging success event: {str(e)}" - ) + verbose_logger.exception(f"Langfuse Layer Error - Exception occurred while logging success event: {str(e)}") self.handle_callback_failure(callback_name="langfuse") async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: - standard_callback_dynamic_params = kwargs.get( - "standard_callback_dynamic_params" - ) + standard_callback_dynamic_params = kwargs.get("standard_callback_dynamic_params") langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request( globalLangfuseLogger=self, standard_callback_dynamic_params=standard_callback_dynamic_params, @@ -357,9 +335,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti ) status_message = str(kwargs.get("exception", "Unknown error")) if standard_logging_object is not None: - status_message = ( - standard_logging_object.get("error_str", None) or status_message - ) + status_message = standard_logging_object.get("error_str", None) or status_message langfuse_logger_to_use.log_event_on_langfuse( start_time=start_time, end_time=end_time, @@ -372,7 +348,5 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti except Exception as e: from litellm._logging import verbose_logger - verbose_logger.exception( - f"Langfuse Layer Error - Exception occurred while logging failure event: {str(e)}" - ) + verbose_logger.exception(f"Langfuse Layer Error - Exception occurred while logging failure event: {str(e)}") self.handle_callback_failure(callback_name="langfuse") diff --git a/litellm/integrations/langsmith.py b/litellm/integrations/langsmith.py index 15f92e8b3222..18c4baccd51c 100644 --- a/litellm/integrations/langsmith.py +++ b/litellm/integrations/langsmith.py @@ -54,9 +54,7 @@ def __init__( if self.is_mock_mode: create_mock_langsmith_client() - verbose_logger.debug( - "[LANGSMITH MOCK] LangSmith logger initialized in mock mode" - ) + verbose_logger.debug("[LANGSMITH MOCK] LangSmith logger initialized in mock mode") self.default_credentials = self.get_credentials_from_env( langsmith_api_key=langsmith_api_key, @@ -70,31 +68,21 @@ def __init__( and os.getenv("LANGSMITH_SAMPLING_RATE").strip().isdigit() # type: ignore else 1.0 ) - self.langsmith_default_run_name = os.getenv( - "LANGSMITH_DEFAULT_RUN_NAME", "LLMRun" - ) - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) - _batch_size = ( - os.getenv("LANGSMITH_BATCH_SIZE", None) or litellm.langsmith_batch_size - ) + self.langsmith_default_run_name = os.getenv("LANGSMITH_DEFAULT_RUN_NAME", "LLMRun") + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) + _batch_size = os.getenv("LANGSMITH_BATCH_SIZE", None) or litellm.langsmith_batch_size if _batch_size: self.batch_size = int(_batch_size) self.log_queue: List[LangsmithQueueObject] = [] - self._flush_task: Optional[asyncio.Task[Any]] = ( - self._start_periodic_flush_task() - ) + self._flush_task: Optional[asyncio.Task[Any]] = self._start_periodic_flush_task() def _start_periodic_flush_task(self) -> Optional[asyncio.Task[Any]]: """Start the periodic flush task only when an event loop is already running.""" try: loop = asyncio.get_running_loop() except RuntimeError: - verbose_logger.debug( - "Langsmith logger init: no running event loop, skipping periodic flush task startup" - ) + verbose_logger.debug("Langsmith logger init: no running event loop, skipping periodic flush task startup") return None return loop.create_task(self.periodic_flush()) @@ -121,19 +109,11 @@ def get_credentials_from_env( _credentials_tenant_id = langsmith_tenant_id else: _credentials_api_key = langsmith_api_key or os.getenv("LANGSMITH_API_KEY") - _credentials_project = ( - langsmith_project - or os.getenv("LANGSMITH_PROJECT") - or "litellm-completion" - ) + _credentials_project = langsmith_project or os.getenv("LANGSMITH_PROJECT") or "litellm-completion" _credentials_base_url = ( - langsmith_base_url - or os.getenv("LANGSMITH_BASE_URL") - or "https://api.smith.langchain.com" - ) - _credentials_tenant_id = langsmith_tenant_id or os.getenv( - "LANGSMITH_TENANT_ID" + langsmith_base_url or os.getenv("LANGSMITH_BASE_URL") or "https://api.smith.langchain.com" ) + _credentials_tenant_id = langsmith_tenant_id or os.getenv("LANGSMITH_TENANT_ID") return LangsmithCredentialsObject( LANGSMITH_API_KEY=_credentials_api_key, @@ -142,13 +122,9 @@ def get_credentials_from_env( LANGSMITH_TENANT_ID=_credentials_tenant_id, ) - def _extract_metadata_fields( - self, metadata: dict, credentials: LangsmithCredentialsObject - ): + def _extract_metadata_fields(self, metadata: dict, credentials: LangsmithCredentialsObject): return { - "project_name": metadata.get( - "project_name", credentials["LANGSMITH_PROJECT"] - ), + "project_name": metadata.get("project_name", credentials["LANGSMITH_PROJECT"]), "run_name": metadata.get("run_name", self.langsmith_default_run_name), "run_id": metadata.get("id", metadata.get("run_id", None)), "parent_run_id": metadata.get("parent_run_id", None), @@ -170,14 +146,10 @@ def _build_extra_metadata(self, metadata: Dict): extra_metadata = redact_user_api_key_info(metadata=extra_metadata) nested = extra_metadata.get("requester_metadata") if isinstance(nested, dict): - extra_metadata["requester_metadata"] = redact_user_api_key_info( - metadata=nested - ) + extra_metadata["requester_metadata"] = redact_user_api_key_info(metadata=nested) return extra_metadata - def _build_outputs_with_usage( - self, payload: StandardLoggingPayload - ) -> Dict[str, Any]: + def _build_outputs_with_usage(self, payload: StandardLoggingPayload) -> Dict[str, Any]: response = payload["response"] outputs: Dict[str, Any] if isinstance(response, dict): @@ -222,9 +194,7 @@ def _prepare_log_data( f"Langsmith Logging - project_name: {fields['project_name']}, run_name {fields['run_name']}" ) - payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if payload is None: raise Exception("Error logging request payload. Payload=none.") @@ -295,9 +265,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): credentials=credentials, ) ) - verbose_logger.debug( - f"Langsmith, event added to queue. Will flush in {self.flush_interval} seconds..." - ) + verbose_logger.debug(f"Langsmith, event added to queue. Will flush in {self.flush_interval} seconds...") if len(self.log_queue) >= self.batch_size: self._send_batch() @@ -344,9 +312,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception: - verbose_logger.exception( - "Langsmith Layer Error - error logging async success event." - ) + verbose_logger.exception("Langsmith Layer Error - error logging async success event.") async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: @@ -383,9 +349,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception: - verbose_logger.exception( - "Langsmith Layer Error - error logging async failure event." - ) + verbose_logger.exception("Langsmith Layer Error - error logging async failure event.") async def async_send_batch(self): """ @@ -414,9 +378,7 @@ async def async_send_batch(self): queue_objects=batch_group.queue_objects, ) - def _add_endpoint_to_url( - self, url: str, endpoint: str, api_version: str = "/api/v1" - ) -> str: + def _add_endpoint_to_url(self, url: str, endpoint: str, api_version: str = "/api/v1") -> str: if api_version not in url: url = f"{url.rstrip('/')}{api_version}" @@ -451,13 +413,9 @@ async def _log_batch_on_langsmith( elements_to_log = [queue_object["data"] for queue_object in queue_objects] try: - verbose_logger.debug( - "Sending batch of %s runs to Langsmith", len(elements_to_log) - ) + verbose_logger.debug("Sending batch of %s runs to Langsmith", len(elements_to_log)) if self.is_mock_mode: - verbose_logger.debug( - "[LANGSMITH MOCK] Mock mode enabled - API calls will be intercepted" - ) + verbose_logger.debug("[LANGSMITH MOCK] Mock mode enabled - API calls will be intercepted") response = await self.async_httpx_client.post( url=url, json={"post": elements_to_log}, @@ -466,26 +424,16 @@ async def _log_batch_on_langsmith( response.raise_for_status() if response.status_code >= 300: - verbose_logger.error( - f"Langsmith Error: {response.status_code} - {response.text}" - ) + verbose_logger.error(f"Langsmith Error: {response.status_code} - {response.text}") else: if self.is_mock_mode: - verbose_logger.debug( - f"[LANGSMITH MOCK] Batch of {len(elements_to_log)} runs successfully mocked" - ) + verbose_logger.debug(f"[LANGSMITH MOCK] Batch of {len(elements_to_log)} runs successfully mocked") else: - verbose_logger.debug( - f"Batch of {len(self.log_queue)} runs successfully created" - ) + verbose_logger.debug(f"Batch of {len(self.log_queue)} runs successfully created") except httpx.HTTPStatusError as e: - verbose_logger.exception( - f"Langsmith HTTP Error: {e.response.status_code} - {e.response.text}" - ) + verbose_logger.exception(f"Langsmith HTTP Error: {e.response.status_code} - {e.response.text}") except Exception: - verbose_logger.exception( - f"Langsmith Layer Error - {traceback.format_exc()}" - ) + verbose_logger.exception(f"Langsmith Layer Error - {traceback.format_exc()}") def _group_batches_by_credentials(self) -> Dict[CredentialsKey, BatchGroup]: """Groups queue objects by credentials using a proper key structure""" @@ -494,10 +442,7 @@ def _group_batches_by_credentials(self) -> Dict[CredentialsKey, BatchGroup]: for queue_object in self.log_queue: credentials = queue_object["credentials"] # if credential missing, skip - log warning - if ( - credentials["LANGSMITH_API_KEY"] is None - or credentials["LANGSMITH_PROJECT"] is None - ): + if credentials["LANGSMITH_API_KEY"] is None or credentials["LANGSMITH_PROJECT"] is None: verbose_logger.warning( "Langsmith Logging - credentials missing - api_key: %s, project: %s", credentials["LANGSMITH_API_KEY"], @@ -512,30 +457,24 @@ def _group_batches_by_credentials(self) -> Dict[CredentialsKey, BatchGroup]: ) if key not in log_queue_by_credentials: - log_queue_by_credentials[key] = BatchGroup( - credentials=credentials, queue_objects=[] - ) + log_queue_by_credentials[key] = BatchGroup(credentials=credentials, queue_objects=[]) log_queue_by_credentials[key].queue_objects.append(queue_object) return log_queue_by_credentials def _get_sampling_rate_to_use_for_request(self, kwargs: Dict[str, Any]) -> float: - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params", None) + standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = kwargs.get( + "standard_callback_dynamic_params", None ) sampling_rate: float = self.sampling_rate if standard_callback_dynamic_params is not None: - _sampling_rate = standard_callback_dynamic_params.get( - "langsmith_sampling_rate" - ) + _sampling_rate = standard_callback_dynamic_params.get("langsmith_sampling_rate") if _sampling_rate is not None: sampling_rate = float(_sampling_rate) return sampling_rate - def _get_credentials_to_use_for_request( - self, kwargs: Dict[str, Any] - ) -> LangsmithCredentialsObject: + def _get_credentials_to_use_for_request(self, kwargs: Dict[str, Any]) -> LangsmithCredentialsObject: """ Handles key/team based logging @@ -543,27 +482,16 @@ def _get_credentials_to_use_for_request( Otherwise, use the default credentials. """ - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params", None) + standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = kwargs.get( + "standard_callback_dynamic_params", None ) if standard_callback_dynamic_params is not None: credentials = self.get_credentials_from_env( - langsmith_api_key=standard_callback_dynamic_params.get( - "langsmith_api_key", None - ), - langsmith_project=standard_callback_dynamic_params.get( - "langsmith_project", None - ), - langsmith_base_url=standard_callback_dynamic_params.get( - "langsmith_base_url", None - ), - langsmith_tenant_id=standard_callback_dynamic_params.get( - "langsmith_tenant_id", None - ), - allow_env_credentials=standard_callback_dynamic_params.get( - "langsmith_base_url", None - ) - is None, + langsmith_api_key=standard_callback_dynamic_params.get("langsmith_api_key", None), + langsmith_project=standard_callback_dynamic_params.get("langsmith_project", None), + langsmith_base_url=standard_callback_dynamic_params.get("langsmith_base_url", None), + langsmith_tenant_id=standard_callback_dynamic_params.get("langsmith_tenant_id", None), + allow_env_credentials=standard_callback_dynamic_params.get("langsmith_base_url", None) is None, ) else: credentials = self.default_credentials diff --git a/litellm/integrations/langsmith_mock_client.py b/litellm/integrations/langsmith_mock_client.py index 0226bdecc272..1e20e1b5ce53 100644 --- a/litellm/integrations/langsmith_mock_client.py +++ b/litellm/integrations/langsmith_mock_client.py @@ -29,6 +29,4 @@ patch_sync_client=False, ) -create_mock_langsmith_client, should_use_langsmith_mock = create_mock_client_factory( - _config -) +create_mock_langsmith_client, should_use_langsmith_mock = create_mock_client_factory(_config) diff --git a/litellm/integrations/langtrace.py b/litellm/integrations/langtrace.py index ac1069f440e6..a9e580a83b26 100644 --- a/litellm/integrations/langtrace.py +++ b/litellm/integrations/langtrace.py @@ -86,12 +86,8 @@ def set_usage_attributes(self, span: Span, response_obj): usage = response_obj.get("usage") if usage: usage_attributes = { - SpanAttributes.LLM_USAGE_PROMPT_TOKENS.value: usage.get( - "prompt_tokens" - ), - SpanAttributes.LLM_USAGE_COMPLETION_TOKENS.value: usage.get( - "completion_tokens" - ), + SpanAttributes.LLM_USAGE_PROMPT_TOKENS.value: usage.get("prompt_tokens"), + SpanAttributes.LLM_USAGE_COMPLETION_TOKENS.value: usage.get("completion_tokens"), SpanAttributes.LLM_USAGE_TOTAL_TOKENS.value: usage.get("total_tokens"), } self.set_span_attributes(span, usage_attributes) diff --git a/litellm/integrations/levo/levo.py b/litellm/integrations/levo/levo.py index 4b08ce50f740..a865944485c7 100644 --- a/litellm/integrations/levo/levo.py +++ b/litellm/integrations/levo/levo.py @@ -56,17 +56,11 @@ def get_levo_config() -> LevoConfig: # Validate required env vars if not api_key: - raise ValueError( - "LEVOAI_API_KEY environment variable is required for Levo integration." - ) + raise ValueError("LEVOAI_API_KEY environment variable is required for Levo integration.") if not org_id: - raise ValueError( - "LEVOAI_ORG_ID environment variable is required for Levo integration." - ) + raise ValueError("LEVOAI_ORG_ID environment variable is required for Levo integration.") if not workspace_id: - raise ValueError( - "LEVOAI_WORKSPACE_ID environment variable is required for Levo integration." - ) + raise ValueError("LEVOAI_WORKSPACE_ID environment variable is required for Levo integration.") if not collector_url: raise ValueError( "LEVOAI_COLLECTOR_URL environment variable is required for Levo integration. " diff --git a/litellm/integrations/literal_ai.py b/litellm/integrations/literal_ai.py index 042779ba844d..c8c931eb6679 100644 --- a/litellm/integrations/literal_ai.py +++ b/litellm/integrations/literal_ai.py @@ -33,9 +33,7 @@ def __init__( } if env: self.headers["x-env"] = env - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.sync_http_handler = HTTPHandler() batch_size = os.getenv("LITERAL_BATCH_SIZE", None) self.flush_lock = asyncio.Lock() @@ -62,9 +60,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): if len(self.log_queue) >= self.batch_size: self._send_batch() except Exception: - verbose_logger.exception( - "Literal AI Layer Error - error logging success event." - ) + verbose_logger.exception("Literal AI Layer Error - error logging success event.") def log_failure_event(self, kwargs, response_obj, start_time, end_time): verbose_logger.info("Literal AI Failure Event Logging!") @@ -79,9 +75,7 @@ def log_failure_event(self, kwargs, response_obj, start_time, end_time): if len(self.log_queue) >= self.batch_size: self._send_batch() except Exception: - verbose_logger.exception( - "Literal AI Layer Error - error logging failure event." - ) + verbose_logger.exception("Literal AI Layer Error - error logging failure event.") def _send_batch(self): if not self.log_queue: @@ -101,13 +95,9 @@ def _send_batch(self): ) if response.status_code >= 300: - verbose_logger.error( - f"Literal AI Error: {response.status_code} - {response.text}" - ) + verbose_logger.error(f"Literal AI Error: {response.status_code} - {response.text}") else: - verbose_logger.debug( - f"Batch of {len(self.log_queue)} runs successfully created" - ) + verbose_logger.debug(f"Batch of {len(self.log_queue)} runs successfully created") except Exception: verbose_logger.exception("Literal AI Layer Error") @@ -128,9 +118,7 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception: - verbose_logger.exception( - "Literal AI Layer Error - error logging async success event." - ) + verbose_logger.exception("Literal AI Layer Error - error logging async success event.") async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): verbose_logger.info("Literal AI Failure Event Logging!") @@ -145,9 +133,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti if len(self.log_queue) >= self.batch_size: await self.flush_queue() except Exception: - verbose_logger.exception( - "Literal AI Layer Error - error logging async failure event." - ) + verbose_logger.exception("Literal AI Layer Error - error logging async failure event.") async def async_send_batch(self): if not self.log_queue: @@ -167,24 +153,16 @@ async def async_send_batch(self): headers=self.headers, ) if response.status_code >= 300: - verbose_logger.error( - f"Literal AI Error: {response.status_code} - {response.text}" - ) + verbose_logger.error(f"Literal AI Error: {response.status_code} - {response.text}") else: - verbose_logger.debug( - f"Batch of {len(self.log_queue)} runs successfully created" - ) + verbose_logger.debug(f"Batch of {len(self.log_queue)} runs successfully created") except httpx.HTTPStatusError as e: - verbose_logger.exception( - f"Literal AI HTTP Error: {e.response.status_code} - {e.response.text}" - ) + verbose_logger.exception(f"Literal AI HTTP Error: {e.response.status_code} - {e.response.text}") except Exception: verbose_logger.exception("Literal AI Layer Error") def _prepare_log_data(self, kwargs, response_obj, start_time, end_time) -> dict: - logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if logging_payload is None: raise ValueError("standard_logging_object not found in kwargs") diff --git a/litellm/integrations/logfire_logger.py b/litellm/integrations/logfire_logger.py index 2345dc869c6b..c92dfff29340 100644 --- a/litellm/integrations/logfire_logger.py +++ b/litellm/integrations/logfire_logger.py @@ -39,25 +39,17 @@ def __init__(self): raise e def _get_span_config(self, payload) -> SpanConfig: - if ( - payload["call_type"] == "completion" - or payload["call_type"] == "acompletion" - ): + if payload["call_type"] == "completion" or payload["call_type"] == "acompletion": return SpanConfig( message_template="Chat Completion with {request_data[model]!r}", span_data={"request_data": payload}, ) - elif ( - payload["call_type"] == "embedding" or payload["call_type"] == "aembedding" - ): + elif payload["call_type"] == "embedding" or payload["call_type"] == "aembedding": return SpanConfig( message_template="Embedding Creation with {request_data[model]!r}", span_data={"request_data": payload}, ) - elif ( - payload["call_type"] == "image_generation" - or payload["call_type"] == "aimage_generation" - ): + elif payload["call_type"] == "image_generation" or payload["call_type"] == "aimage_generation": return SpanConfig( message_template="Image Generation with {request_data[model]!r}", span_data={"request_data": payload}, @@ -98,16 +90,12 @@ def log_event( try: import logfire - verbose_logger.debug( - f"logfire Logging - Enters logging function for model {kwargs}" - ) + verbose_logger.debug(f"logfire Logging - Enters logging function for model {kwargs}") if not response_obj: response_obj = {} litellm_params = kwargs.get("litellm_params", {}) - metadata = ( - litellm_params.get("metadata", {}) or {} - ) # if litellm_params['metadata'] == None + metadata = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None messages = kwargs.get("messages") optional_params = kwargs.get("optional_params", {}) call_type = kwargs.get("call_type", "completion") @@ -169,11 +157,7 @@ def log_event( ) print_verbose(f"\ndd Logger - Logging payload = {payload}") - print_verbose( - f"Logfire Layer Logging - final response object: {response_obj}" - ) + print_verbose(f"Logfire Layer Logging - final response object: {response_obj}") except Exception as e: - verbose_logger.debug( - f"Logfire Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.debug(f"Logfire Layer Error - {str(e)}\n{traceback.format_exc()}") pass diff --git a/litellm/integrations/lunary.py b/litellm/integrations/lunary.py index 7b1cbc32d43e..aaf5751cb79e 100644 --- a/litellm/integrations/lunary.py +++ b/litellm/integrations/lunary.py @@ -130,11 +130,7 @@ def log_event( pass if response_obj: - usage = ( - parse_usage(response_obj["usage"]) - if "usage" in response_obj - else None - ) + usage = parse_usage(response_obj["usage"]) if "usage" in response_obj else None output = response_obj["choices"] if "choices" in response_obj else None diff --git a/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py b/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py index 49030ffc2e1c..26b2f32f32f0 100644 --- a/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py +++ b/litellm/integrations/mavvrik_focus/mavvrik_focus_logger.py @@ -66,9 +66,7 @@ def _parse_metrics_marker( continue except Exception: pass - verbose_proxy_logger.warning( - "Mavvrik FOCUS: could not parse metricsMarker %r — skipping catch-up", marker - ) + verbose_proxy_logger.warning("Mavvrik FOCUS: could not parse metricsMarker %r — skipping catch-up", marker) return None @@ -134,9 +132,7 @@ async def _export_window( ) payload = b"" if data.is_empty(): - verbose_proxy_logger.debug( - "Mavvrik FOCUS export: no usage data for window %s", window - ) + verbose_proxy_logger.debug("Mavvrik FOCUS export: no usage data for window %s", window) else: normalized = engine._transformer.transform(data) if not normalized.is_empty(): @@ -179,9 +175,7 @@ async def _run_scheduled_export(self) -> None: marker = await destination.get_metrics_marker() now = datetime.now(timezone.utc) - yesterday = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta( - days=1 - ) + yesterday = now.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=1) last_ingested = _parse_metrics_marker(marker) @@ -189,15 +183,10 @@ async def _run_scheduled_export(self) -> None: earliest_catchup = yesterday - timedelta(days=self._MAX_CATCHUP_DAYS - 1) if is_empty_marker or (last_ingested is not None and last_ingested < yesterday): catch_up_date = ( - earliest_catchup - if last_ingested is None - else max(last_ingested + timedelta(days=1), earliest_catchup) + earliest_catchup if last_ingested is None else max(last_ingested + timedelta(days=1), earliest_catchup) ) - if ( - last_ingested is not None - and last_ingested + timedelta(days=1) < earliest_catchup - ): + if last_ingested is not None and last_ingested + timedelta(days=1) < earliest_catchup: verbose_proxy_logger.warning( "Mavvrik FOCUS export: metricsMarker is more than %d days behind " "(%s). Catching up from %s only; earlier data will not be re-exported.", @@ -244,20 +233,14 @@ async def initialize_mavvrik_focus_export_job(self) -> None: pod_lock_manager = getattr(writer, "pod_lock_manager", None) if pod_lock_manager and pod_lock_manager.redis_cache: - acquired = await pod_lock_manager.acquire_lock( - cronjob_id=MAVVRIK_FOCUS_EXPORT_JOB_NAME - ) + acquired = await pod_lock_manager.acquire_lock(cronjob_id=MAVVRIK_FOCUS_EXPORT_JOB_NAME) if not acquired: - verbose_proxy_logger.debug( - "Mavvrik FOCUS export: unable to acquire pod lock" - ) + verbose_proxy_logger.debug("Mavvrik FOCUS export: unable to acquire pod lock") return try: await self._run_scheduled_export() finally: - await pod_lock_manager.release_lock( - cronjob_id=MAVVRIK_FOCUS_EXPORT_JOB_NAME - ) + await pod_lock_manager.release_lock(cronjob_id=MAVVRIK_FOCUS_EXPORT_JOB_NAME) else: await self._run_scheduled_export() @@ -268,9 +251,7 @@ async def init_mavvrik_focus_background_job( """Register the Mavvrik FOCUS export job on the provided scheduler.""" loggers: List[MavvrikFocusLogger] = [ cb - for cb in litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=MavvrikFocusLogger - ) + for cb in litellm.logging_callback_manager.get_custom_loggers_for_type(callback_type=MavvrikFocusLogger) if type(cb) is MavvrikFocusLogger ] if not loggers and "mavvrik" in litellm.callbacks: @@ -289,9 +270,7 @@ async def init_mavvrik_focus_background_job( if isinstance(instance, MavvrikFocusLogger): loggers = [instance] if not loggers: - verbose_proxy_logger.debug( - "No MavvrikFocusLogger registered; skipping scheduler" - ) + verbose_proxy_logger.debug("No MavvrikFocusLogger registered; skipping scheduler") return logger = loggers[0] @@ -302,6 +281,4 @@ async def init_mavvrik_focus_background_job( replace_existing=True, **trigger_kwargs, ) - verbose_proxy_logger.info( - "mavvrik_focus: background export job scheduled (%s)", trigger_kwargs - ) + verbose_proxy_logger.info("mavvrik_focus: background export job scheduled (%s)", trigger_kwargs) diff --git a/litellm/integrations/mlflow.py b/litellm/integrations/mlflow.py index 6378e55f7e1d..1952c95eac98 100644 --- a/litellm/integrations/mlflow.py +++ b/litellm/integrations/mlflow.py @@ -60,10 +60,7 @@ def _extract_and_set_chat_attributes(self, span, kwargs, response_obj): inputs = self._construct_input(kwargs) input_messages = inputs.get("messages", []) - output_messages = [ - c.message.model_dump(exclude_none=True) - for c in getattr(response_obj, "choices", []) - ] + output_messages = [c.message.model_dump(exclude_none=True) for c in getattr(response_obj, "choices", [])] if messages := [*input_messages, *output_messages]: set_span_chat_messages(span, messages) if tools := inputs.get("tools"): @@ -130,9 +127,7 @@ def _handle_stream_event(self, kwargs, response_obj, start_time, end_time): # If this is the final chunk, end the span. The final chunk # has the assembled streaming response (key differs between sync/async paths). - final_response = kwargs.get("complete_streaming_response") or kwargs.get( - "async_complete_streaming_response" - ) + final_response = kwargs.get("complete_streaming_response") or kwargs.get("async_complete_streaming_response") if final_response: end_time_ns = int(end_time.timestamp() * 1e9) @@ -156,9 +151,7 @@ def _add_chunk_events(self, span, response_obj): span.add_event( SpanEvent( name="streaming_chunk", - attributes={ - "delta": json.dumps(choice.delta.model_dump, default=str) - }, + attributes={"delta": json.dumps(choice.delta.model_dump, default=str)}, ) ) except Exception: @@ -192,9 +185,7 @@ def _extract_attributes(self, kwargs): "call_type": kwargs.get("call_type"), "model": kwargs.get("model"), } - standard_obj: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_obj: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_obj: attributes.update( { @@ -267,9 +258,7 @@ def _start_span_or_trace(self, kwargs, start_time): span_type=span_type, inputs=inputs, attributes=attributes, - tags=self._transform_tag_list_to_dict( - attributes.get("request_tags", []) - ), + tags=self._transform_tag_list_to_dict(attributes.get("request_tags", [])), start_time_ns=start_time_ns, ) diff --git a/litellm/integrations/mock_client_factory.py b/litellm/integrations/mock_client_factory.py index 3b013f96a791..76c0ac03b7b4 100644 --- a/litellm/integrations/mock_client_factory.py +++ b/litellm/integrations/mock_client_factory.py @@ -25,14 +25,10 @@ class MockClientConfig: default_latency_ms: int = 100 # Default mock latency in milliseconds default_status_code: int = 200 # Default HTTP status code default_json_data: Optional[Dict] = None # Default JSON response data - url_matchers: Optional[List[str]] = ( - None # List of strings to match in URLs (e.g., ["storage.googleapis.com"]) - ) + url_matchers: Optional[List[str]] = None # List of strings to match in URLs (e.g., ["storage.googleapis.com"]) patch_async_handler: bool = True # Whether to patch AsyncHTTPHandler.post patch_sync_client: bool = False # Whether to patch httpx.Client.post - patch_http_handler: bool = ( - False # Whether to patch HTTPHandler.post (for sync calls that use HTTPHandler) - ) + patch_http_handler: bool = False # Whether to patch HTTPHandler.post (for sync calls that use HTTPHandler) def __post_init__(self): """Ensure url_matchers is a list.""" @@ -124,9 +120,7 @@ def create_mock_client_factory(config: MockClientConfig): import os latency_env = f"{config.name.upper()}_MOCK_LATENCY_MS" - _MOCK_LATENCY_SECONDS = ( - float(os.getenv(latency_env, str(config.default_latency_ms))) / 1000.0 - ) + _MOCK_LATENCY_SECONDS = float(os.getenv(latency_env, str(config.default_latency_ms))) / 1000.0 # Create URL matcher function def _is_mock_url(url) -> bool: @@ -241,9 +235,7 @@ def create_mock_client(): if _mocks_initialized: return - verbose_logger.debug( - f"[{config.name} MOCK] Initializing {config.name} mock client..." - ) + verbose_logger.debug(f"[{config.name} MOCK] Initializing {config.name} mock client...") if config.patch_async_handler and _original_async_handler_post is None: from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler @@ -264,12 +256,8 @@ def create_mock_client(): HTTPHandler.post = _mock_http_handler_post # type: ignore verbose_logger.debug(f"[{config.name} MOCK] Patched HTTPHandler.post") - verbose_logger.debug( - f"[{config.name} MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS * 1000:.0f}ms" - ) - verbose_logger.debug( - f"[{config.name} MOCK] {config.name} mock client initialization complete" - ) + verbose_logger.debug(f"[{config.name} MOCK] Mock latency set to {_MOCK_LATENCY_SECONDS * 1000:.0f}ms") + verbose_logger.debug(f"[{config.name} MOCK] {config.name} mock client initialization complete") _mocks_initialized = True @@ -284,9 +272,7 @@ def should_use_mock() -> bool: result = bool(result) if result is not None else False if result: - verbose_logger.info( - f"{config.name} Mock Mode: ENABLED - API calls will be mocked" - ) + verbose_logger.info(f"{config.name} Mock Mode: ENABLED - API calls will be mocked") return result diff --git a/litellm/integrations/newrelic/newrelic.py b/litellm/integrations/newrelic/newrelic.py index 753b85203377..3c2bed60ef44 100644 --- a/litellm/integrations/newrelic/newrelic.py +++ b/litellm/integrations/newrelic/newrelic.py @@ -120,10 +120,7 @@ def __init__(self, **kwargs): f"content recording: {self.record_content}" ) except Exception as e: - verbose_logger.error( - f"Failed to initialize New Relic agent: {e}. " - "Integration will be disabled." - ) + verbose_logger.error(f"Failed to initialize New Relic agent: {e}. Integration will be disabled.") self.enabled = False def _get_newrelic_params(self) -> Dict: @@ -138,9 +135,7 @@ def _get_newrelic_params(self) -> Dict: dict_newrelic_params = litellm.newrelic_params.model_dump() elif isinstance(litellm.newrelic_params, Dict): # only allow params that are of NewRelicInitParams - dict_newrelic_params = NewRelicInitParams( - **litellm.newrelic_params - ).model_dump() + dict_newrelic_params = NewRelicInitParams(**litellm.newrelic_params).model_dump() return dict_newrelic_params @property @@ -221,13 +216,9 @@ def _emit_supportability_metric(self): if app and app.enabled: app.record_custom_metric(metric_name, 1) - verbose_logger.info( - f"Emitted New Relic supportability metric: {metric_name}" - ) + verbose_logger.info(f"Emitted New Relic supportability metric: {metric_name}") else: - verbose_logger.info( - "New Relic application is not enabled; skipping metric recording." - ) + verbose_logger.info("New Relic application is not enabled; skipping metric recording.") except Exception as e: verbose_logger.warning(f"Failed to emit supportability metric: {e}") @@ -241,18 +232,14 @@ def _check_and_emit_periodic_metric(self): """ # Quick check without lock to avoid unnecessary locking current_time = time.time() - time_since_last_emission = ( - current_time - NewRelicLogger._last_metric_emission_time - ) + time_since_last_emission = current_time - NewRelicLogger._last_metric_emission_time if time_since_last_emission >= 97200: # 27 hours = 97200 seconds # Acquire lock to ensure only one thread emits with NewRelicLogger._metric_lock: # Double-check inside lock in case another thread just emitted current_time = time.time() - time_since_last_emission = ( - current_time - NewRelicLogger._last_metric_emission_time - ) + time_since_last_emission = current_time - NewRelicLogger._last_metric_emission_time if time_since_last_emission >= 97200: self._emit_supportability_metric() @@ -292,9 +279,7 @@ def _get_trace_context( metadata = litellm_params.get("metadata") or {} headers = metadata.get("headers") or {} # Normalize header key lookup to be case-insensitive per W3C spec - traceparent = next( - (v for k, v in headers.items() if k.lower() == "traceparent"), None - ) + traceparent = next((v for k, v in headers.items() if k.lower() == "traceparent"), None) if traceparent: # Extract trace_id from traceparent header if available @@ -309,9 +294,7 @@ def _get_trace_context( trace_id = slo_trace_id except Exception as e: - verbose_logger.warning( - f"Unable to parse New Relic trace context from upstream sources: {e}" - ) + verbose_logger.warning(f"Unable to parse New Relic trace context from upstream sources: {e}") if not trace_id: trace_id = uuid.uuid4().hex @@ -439,9 +422,7 @@ def _get_duration( if standard_logging_object: response_time = standard_logging_object.get("response_time") if response_time is not None: - return ( - float(response_time) * 1000.0 - ) # SLO stores seconds; convert to ms + return float(response_time) * 1000.0 # SLO stores seconds; convert to ms duration_ms = kwargs.get("llm_api_duration_ms") if duration_ms is not None: @@ -552,15 +533,11 @@ def _extract_all_messages( # callback an unredacted async_complete_streaming_response, so without # this gate generated content would still reach NR even when the user # has globally disabled message logging. - record_content = self.record_content and not should_redact_message_logging( - kwargs - ) + record_content = self.record_content and not should_redact_message_logging(kwargs) # Extract request messages, preferring StandardLoggingPayload. # SLO messages can be a string (serialized/redacted), so only use it when it's a list. - slo_messages = ( - standard_logging_object.get("messages") if standard_logging_object else None - ) + slo_messages = standard_logging_object.get("messages") if standard_logging_object else None if isinstance(slo_messages, list): request_messages = slo_messages else: @@ -658,9 +635,7 @@ def _record_summary_event( if app and app.enabled: app.record_custom_event("LlmChatCompletionSummary", event_data) else: - verbose_logger.warning( - "New Relic application is not enabled; skipping summary event recording." - ) + verbose_logger.warning("New Relic application is not enabled; skipping summary event recording.") except Exception as e: verbose_logger.warning(f"Failed to record New Relic summary event: {e}") @@ -685,9 +660,7 @@ def _record_message_events( app = _newrelic_agent.application() if not (app and app.enabled): - verbose_logger.warning( - "New Relic application is not enabled; skipping message event recording." - ) + verbose_logger.warning("New Relic application is not enabled; skipping message event recording.") return for message in messages: @@ -763,9 +736,7 @@ def _process_success( self._check_and_emit_periodic_metric() # Use StandardLoggingPayload where available for normalized, pre-computed values - standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") # Get trace context trace_id = self._get_trace_context(kwargs, standard_logging_object) @@ -776,22 +747,16 @@ def _process_success( # Extract data from response llm_response_id = self._extract_completion_id(kwargs, response_obj) vendor = self._get_vendor(kwargs, standard_logging_object) - request_model, response_model = self._get_model_names( - kwargs, response_obj, standard_logging_object - ) + request_model, response_model = self._get_model_names(kwargs, response_obj, standard_logging_object) usage = self._extract_usage(response_obj, standard_logging_object) finish_reason = self._get_finish_reason(response_obj) # Extract additional summary event fields - duration = self._get_duration( - kwargs, start_time, end_time, standard_logging_object - ) + duration = self._get_duration(kwargs, start_time, end_time, standard_logging_object) request_params = self._get_request_params(kwargs, standard_logging_object) # Extract all messages - messages = self._extract_all_messages( - kwargs, response_obj, response_model, vendor, standard_logging_object - ) + messages = self._extract_all_messages(kwargs, response_obj, response_model, vendor, standard_logging_object) # Record summary event self._record_summary_event( diff --git a/litellm/integrations/openmeter.py b/litellm/integrations/openmeter.py index b234ab11ddbd..e9cc68a78416 100644 --- a/litellm/integrations/openmeter.py +++ b/litellm/integrations/openmeter.py @@ -29,9 +29,7 @@ class OpenMeterLogger(CustomLogger): def __init__(self) -> None: super().__init__() self.validate_environment() - self.async_http_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.sync_http_handler = HTTPHandler() def validate_environment(self): @@ -56,8 +54,7 @@ def _common_logic(self, kwargs: dict, response_obj): model = kwargs.get("model") usage = {} if ( - isinstance(response_obj, litellm.ModelResponse) - or isinstance(response_obj, litellm.EmbeddingResponse) + isinstance(response_obj, litellm.ModelResponse) or isinstance(response_obj, litellm.EmbeddingResponse) ) and hasattr(response_obj, "usage"): usage = { "prompt_tokens": response_obj["usage"].get("prompt_tokens", 0), @@ -70,9 +67,7 @@ def _common_logic(self, kwargs: dict, response_obj): # resolved solely from the key-bound user_api_key_user_id. Proxies # serving multi-tenant traffic enable this to prevent clients from # forging attribution by setting `user` in the request body. - trust_request_user = ( - os.getenv("OPENMETER_TRUST_REQUEST_USER", "true").lower() != "false" - ) + trust_request_user = os.getenv("OPENMETER_TRUST_REQUEST_USER", "true").lower() != "false" user_param = kwargs.get("user", None) if trust_request_user else None # If no user provided directly, try to get it from token user_id diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py index c652141a2b62..de543fa042b0 100644 --- a/litellm/integrations/opentelemetry.py +++ b/litellm/integrations/opentelemetry.py @@ -153,22 +153,16 @@ def _resolve_metric_attribute_filter( include = attributes.include_list or None exclude = attributes.exclude_list or None if include and exclude: - raise ValueError( - "otel.attributes: include_list and exclude_list are mutually exclusive" - ) + raise ValueError("otel.attributes: include_list and exclude_list are mutually exclusive") requested = include or exclude or [] if TOKEN_TYPE_ATTRIBUTE in requested: raise ValueError( - f"otel.attributes: {TOKEN_TYPE_ATTRIBUTE} is a structural token-usage " - "discriminator and cannot be filtered" + f"otel.attributes: {TOKEN_TYPE_ATTRIBUTE} is a structural token-usage discriminator and cannot be filtered" ) - unknown = sorted( - name for name in requested if name not in VALID_METRIC_ATTRIBUTE_NAMES - ) + unknown = sorted(name for name in requested if name not in VALID_METRIC_ATTRIBUTE_NAMES) if unknown: raise ValueError( - f"otel.attributes: unknown attribute name(s) {unknown}. " - f"Valid names: {sorted(VALID_METRIC_ATTRIBUTE_NAMES)}" + f"otel.attributes: unknown attribute name(s) {unknown}. Valid names: {sorted(VALID_METRIC_ATTRIBUTE_NAMES)}" ) return ( frozenset(include) if include else None, @@ -212,8 +206,7 @@ def _freeze_for_dedupe(value: object, _depth: int = 0) -> HashableScope: return frozenset(_freeze_for_dedupe(item, _depth + 1) for item in value) if isinstance(value, dict): return frozenset( - (_freeze_for_dedupe(key, _depth + 1), _freeze_for_dedupe(item, _depth + 1)) - for key, item in value.items() + (_freeze_for_dedupe(key, _depth + 1), _freeze_for_dedupe(item, _depth + 1)) for key, item in value.items() ) if isinstance(value, (str, int, float, bytes)) or value is None: return value @@ -250,35 +243,23 @@ def __post_init__(self) -> None: # automatically infer "otlp_http" to send traces to the endpoint. # This fixes an issue where UI-configured OTEL settings would default # to console output instead of sending traces to the configured endpoint. - if ( - self.endpoint - and isinstance(self.exporter, str) - and self.exporter == "console" - ): + if self.endpoint and isinstance(self.exporter, str) and self.exporter == "console": self.exporter = "otlp_http" if not self.service_name: self.service_name = os.getenv("OTEL_SERVICE_NAME", "litellm") if not self.deployment_environment: - self.deployment_environment = os.getenv( - "OTEL_ENVIRONMENT_NAME", "production" - ) + self.deployment_environment = os.getenv("OTEL_ENVIRONMENT_NAME", "production") if not self.model_id: self.model_id = os.getenv("OTEL_MODEL_ID", self.service_name) if self.ignore_context_propagation is None: - self.ignore_context_propagation = str_to_bool( - os.getenv("OTEL_IGNORE_CONTEXT_PROPAGATION") - ) + self.ignore_context_propagation = str_to_bool(os.getenv("OTEL_IGNORE_CONTEXT_PROPAGATION")) # Resolve the env opt-in once here so self.semconv_stability_opt_in is the # single source of truth: the union of programmatic and env categories. - self.semconv_stability_opt_in |= parse_semconv_opt_in( - os.getenv(OTEL_SEMCONV_STABILITY_OPT_IN_ENV) - ) + self.semconv_stability_opt_in |= parse_semconv_opt_in(os.getenv(OTEL_SEMCONV_STABILITY_OPT_IN_ENV)) self.baggage_team_metadata_keys = _normalize_team_metadata_keys( self.baggage_team_metadata_keys - ) or _normalize_team_metadata_keys( - os.getenv("LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS") - ) + ) or _normalize_team_metadata_keys(os.getenv("LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS")) @classmethod def from_env(cls): @@ -293,21 +274,13 @@ def from_env(cls): InMemorySpanExporter, ) - exporter = os.getenv( - "OTEL_EXPORTER_OTLP_PROTOCOL", os.getenv("OTEL_EXPORTER", "console") - ) + exporter = os.getenv("OTEL_EXPORTER_OTLP_PROTOCOL", os.getenv("OTEL_EXPORTER", "console")) endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", os.getenv("OTEL_ENDPOINT")) headers = os.getenv( "OTEL_EXPORTER_OTLP_HEADERS", os.getenv("OTEL_HEADERS") ) # example: OTEL_HEADERS=x-honeycomb-team=B85YgLm96***" - enable_metrics: bool = ( - os.getenv("LITELLM_OTEL_INTEGRATION_ENABLE_METRICS", "false").lower() - == "true" - ) - enable_events: bool = ( - os.getenv("LITELLM_OTEL_INTEGRATION_ENABLE_EVENTS", "false").lower() - == "true" - ) + enable_metrics: bool = os.getenv("LITELLM_OTEL_INTEGRATION_ENABLE_METRICS", "false").lower() == "true" + enable_events: bool = os.getenv("LITELLM_OTEL_INTEGRATION_ENABLE_EVENTS", "false").lower() == "true" service_name = os.getenv("OTEL_SERVICE_NAME", "litellm") deployment_environment = os.getenv("OTEL_ENVIRONMENT_NAME", "production") model_id = os.getenv("OTEL_MODEL_ID", service_name) @@ -342,13 +315,9 @@ def __init__( if config is None: config = OpenTelemetryConfig.from_env() if team_metadata_keys_override is not None: - config.baggage_team_metadata_keys = _normalize_team_metadata_keys( - team_metadata_keys_override - ) + config.baggage_team_metadata_keys = _normalize_team_metadata_keys(team_metadata_keys_override) if metric_attributes_override is not None: - config.attributes = _build_metric_attribute_filter( - metric_attributes_override - ) + config.attributes = _build_metric_attribute_filter(metric_attributes_override) self.config = config self.callback_name = callback_name @@ -415,9 +384,7 @@ def _init_otel_logger_on_litellm_proxy(self): try: from litellm.proxy import proxy_server except ImportError: - verbose_logger.warning( - "Proxy Server is not installed. Skipping OpenTelemetry initialization." - ) + verbose_logger.warning("Proxy Server is not installed. Skipping OpenTelemetry initialization.") return # Add self as a service callback @@ -514,9 +481,7 @@ def _get_or_create_provider( def _skip_set_global(self) -> bool: # langfuse_otel relies on the Langfuse SDK's providers; don't overwrite them. - return self.config.skip_set_global or ( - hasattr(self, "callback_name") and self.callback_name == "langfuse_otel" - ) + return self.config.skip_set_global or (hasattr(self, "callback_name") and self.callback_name == "langfuse_otel") def _compute_capture_mode_from_init_state(self) -> Optional[str]: """Sample explicit settings at init. Returns the resolved mode or @@ -556,11 +521,7 @@ def _resolve_capture_mode(self) -> str: return CAPTURE_MODE_NO_CONTENT if self._capture_mode_cached is not None: return self._capture_mode_cached - return ( - CAPTURE_MODE_SPAN_AND_EVENT - if self.message_logging - else CAPTURE_MODE_NO_CONTENT - ) + return CAPTURE_MODE_SPAN_AND_EVENT if self.message_logging else CAPTURE_MODE_NO_CONTENT def _capture_in_span(self) -> bool: return self._resolve_capture_mode() in ( @@ -676,9 +637,7 @@ def _init_logs(self, logger_provider): from opentelemetry.sdk._logs.export import BatchLogRecordProcessor def create_logger_provider(): - provider = OTLoggerProvider( - resource=self._get_litellm_resource(self.config) - ) + provider = OTLoggerProvider(resource=self._get_litellm_resource(self.config)) log_exporter = self._get_log_exporter() provider.add_log_record_processor( BatchLogRecordProcessor(log_exporter) # type: ignore[arg-type] @@ -875,9 +834,7 @@ async def async_post_call_failure_hook( # _record_exception_on_span only stamps when error_code is set; # bare TypeError etc. has none, and the span is about to be ended. - error_code = ( - error_information.get("error_code") if error_information else None - ) + error_code = error_information.get("error_code") if error_information else None if not error_code: self.set_response_status_code_attribute(parent_otel_span, 500) @@ -951,9 +908,7 @@ def _emit_guardrail_spans_from_request_data( "metadata": metadata, }, } - context = ( - _trace.set_span_in_context(parent_span) if parent_span is not None else None - ) + context = _trace.set_span_in_context(parent_span) if parent_span is not None else None self._create_guardrail_span(kwargs=kwargs, context=context) async def async_post_call_success_hook( @@ -966,9 +921,7 @@ async def async_post_call_success_hook( litellm_logging_obj = data.get("litellm_logging_obj") - if litellm_logging_obj is not None and isinstance( - litellm_logging_obj, LiteLLMLogging - ): + if litellm_logging_obj is not None and isinstance(litellm_logging_obj, LiteLLMLogging): kwargs = litellm_logging_obj.model_call_details parent_span = user_api_key_dict.parent_otel_span @@ -1000,43 +953,31 @@ def get_tracer_to_use_for_request(self, kwargs: dict) -> Tracer: if dynamic_headers is not None: # Create spans using a temporary tracer with dynamic headers tracer_to_use = self._get_tracer_with_dynamic_headers(dynamic_headers) - verbose_logger.debug( - "[OTEL DEBUG] Using DYNAMIC tracer with headers: %s", dynamic_headers - ) + verbose_logger.debug("[OTEL DEBUG] Using DYNAMIC tracer with headers: %s", dynamic_headers) else: # For langfuse_otel without dynamic headers, create a provider with env var credentials if hasattr(self, "callback_name") and self.callback_name == "langfuse_otel": # Use the headers from config (which were set from env vars during init) - env_var_headers = ( - self._get_headers_dictionary(self.OTEL_HEADERS) - if self.OTEL_HEADERS - else {} - ) + env_var_headers = self._get_headers_dictionary(self.OTEL_HEADERS) if self.OTEL_HEADERS else {} if env_var_headers: - tracer_to_use = self._get_tracer_with_dynamic_headers( - env_var_headers - ) + tracer_to_use = self._get_tracer_with_dynamic_headers(env_var_headers) verbose_logger.debug( "[OTEL DEBUG] Using env var credentials for langfuse_otel (master key request)" ) else: # No env vars set, use global tracer (will be NoOp) tracer_to_use = self.tracer - verbose_logger.debug( - "[OTEL DEBUG] No credentials available for langfuse_otel" - ) + verbose_logger.debug("[OTEL DEBUG] No credentials available for langfuse_otel") else: tracer_to_use = self.tracer - verbose_logger.debug( - "[OTEL DEBUG] Using GLOBAL tracer (no dynamic headers)" - ) + verbose_logger.debug("[OTEL DEBUG] Using GLOBAL tracer (no dynamic headers)") return tracer_to_use def _get_dynamic_otel_headers_from_kwargs(self, kwargs) -> Optional[dict]: """Extract dynamic headers from kwargs if available.""" - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params") + standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = kwargs.get( + "standard_callback_dynamic_params" ) if not standard_callback_dynamic_params: @@ -1055,15 +996,11 @@ def _get_tracer_with_dynamic_headers(self, dynamic_headers: dict): # Prevents thread exhaustion by reusing providers for the same credential sets (e.g. per-team keys) cache_key = str(sorted(dynamic_headers.items())) if cache_key in self._tracer_provider_cache: - return self._tracer_provider_cache[cache_key].get_tracer( - LITELLM_TRACER_NAME - ) + return self._tracer_provider_cache[cache_key].get_tracer(LITELLM_TRACER_NAME) # Create a temporary tracer provider with dynamic headers temp_provider = TracerProvider(resource=self._get_litellm_resource(self.config)) - temp_provider.add_span_processor( - self._get_span_processor(dynamic_headers=dynamic_headers) - ) + temp_provider.add_span_processor(self._get_span_processor(dynamic_headers=dynamic_headers)) # Store in cache for reuse self._tracer_provider_cache[cache_key] = temp_provider @@ -1211,19 +1148,13 @@ def _handle_success(self, kwargs, response_obj, start_time, end_time): # Decide whether to create a primary span # Always create if no parent span exists (backward compatibility) # OR if USE_OTEL_LITELLM_REQUEST_SPAN is explicitly enabled - should_create_primary_span = parent_span is None or get_secret_bool( - "USE_OTEL_LITELLM_REQUEST_SPAN" - ) + should_create_primary_span = parent_span is None or get_secret_bool("USE_OTEL_LITELLM_REQUEST_SPAN") if should_create_primary_span: # Create a new litellm_request span - span = self._start_primary_span( - kwargs, response_obj, start_time, end_time, ctx - ) + span = self._start_primary_span(kwargs, response_obj, start_time, end_time, ctx) # Raw-request sub-span (if enabled) - child of litellm_request span - self._maybe_log_raw_request( - kwargs, response_obj, start_time, end_time, span - ) + self._maybe_log_raw_request(kwargs, response_obj, start_time, end_time, span) # Do NOT duplicate attributes onto the parent proxy-request span. # The child litellm_request span already carries all attributes; # copying them to the parent doubles storage and complicates @@ -1239,15 +1170,11 @@ def _handle_success(self, kwargs, response_obj, start_time, end_time): parent_span.set_status(Status(StatusCode.OK)) self.set_attributes(parent_span, kwargs, response_obj) # Raw-request as direct child of parent_span - self._maybe_log_raw_request( - kwargs, response_obj, start_time, end_time, parent_span - ) + self._maybe_log_raw_request(kwargs, response_obj, start_time, end_time, parent_span) # 3. Guardrail span — ensure guardrails are always parented to an # existing span so they never become orphaned root spans (Issue #5). - guardrail_ctx = self._resolve_guardrail_context( - span=span, parent_span=parent_span, fallback_ctx=ctx - ) + guardrail_ctx = self._resolve_guardrail_context(span=span, parent_span=parent_span, fallback_ctx=ctx) self._create_guardrail_span(kwargs=kwargs, context=guardrail_ctx) # 4. Metrics & cost recording @@ -1306,9 +1233,7 @@ def _start_primary_span( span.end(end_time=self._to_ns(end_time)) return span - def _maybe_log_raw_request( - self, kwargs, response_obj, start_time, end_time, parent_span - ): + def _maybe_log_raw_request(self, kwargs, response_obj, start_time, end_time, parent_span): from opentelemetry import trace from opentelemetry.trace import Status, StatusCode @@ -1412,42 +1337,28 @@ def _set_inference_identity_attributes( http_route = metadata.get("user_api_key_request_route") if http_route: - self.safe_set_attribute( - span=span, key=HTTP_ROUTE_ATTRIBUTE, value=http_route - ) + self.safe_set_attribute(span=span, key=HTTP_ROUTE_ATTRIBUTE, value=http_route) # ``user_api_key_team_metadata`` is dropped from the standard logging # payload metadata, so read it from the raw request metadata in kwargs. # ``metadata`` and ``litellm_metadata`` are alternate names for the same # full metadata dict (the name varies by endpoint), so first-truthy wins. - raw_metadata = ( - litellm_params.get("metadata") - or litellm_params.get("litellm_metadata") - or {} - ) + raw_metadata = litellm_params.get("metadata") or litellm_params.get("litellm_metadata") or {} team_metadata = self._team_metadata_json( raw_metadata.get("user_api_key_team_metadata"), self.config.baggage_team_metadata_keys, ) if team_metadata: - self.safe_set_attribute( - span=span, key=TEAM_METADATA_ATTRIBUTE, value=team_metadata - ) + self.safe_set_attribute(span=span, key=TEAM_METADATA_ATTRIBUTE, value=team_metadata) model_group = standard_logging_payload.get("model_group") if model_group: - self.safe_set_attribute( - span=span, key=MODEL_GROUP_ATTRIBUTE, value=model_group - ) + self.safe_set_attribute(span=span, key=MODEL_GROUP_ATTRIBUTE, value=model_group) hidden_params = standard_logging_payload.get("hidden_params") or {} - provider_model = hidden_params.get( - "litellm_model_name" - ) or standard_logging_payload.get("model") + provider_model = hidden_params.get("litellm_model_name") or standard_logging_payload.get("model") if provider_model: - self.safe_set_attribute( - span=span, key=PROVIDER_MODEL_ATTRIBUTE, value=provider_model - ) + self.safe_set_attribute(span=span, key=PROVIDER_MODEL_ATTRIBUTE, value=provider_model) @staticmethod def _team_metadata_json(value: Any, allowed_keys: List[str]) -> Optional[str]: @@ -1473,11 +1384,7 @@ def _ensure_metric_attribute_filter(self) -> None: attributes = self.config.attributes if attributes is None and self.callback_name in (None, "otel"): otel_settings = (litellm.callback_settings or {}).get("otel") or {} - raw = ( - otel_settings.get("attributes") - if isinstance(otel_settings, dict) - else None - ) + raw = otel_settings.get("attributes") if isinstance(otel_settings, dict) else None if raw is not None: attributes = _build_metric_attribute_filter(raw) ( @@ -1492,9 +1399,7 @@ def _filter_metric_attributes(self, attrs: Dict[str, Any]) -> Dict[str, Any]: if self._metric_attr_include is not None: return {k: v for k, v in attrs.items() if k in self._metric_attr_include} if self._metric_attr_exclude is not None: - return { - k: v for k, v in attrs.items() if k not in self._metric_attr_exclude - } + return {k: v for k, v in attrs.items() if k not in self._metric_attr_exclude} return attrs def _record_metrics(self, kwargs, response_obj, start_time, end_time): @@ -1504,9 +1409,7 @@ def _record_metrics(self, kwargs, response_obj, start_time, end_time): common_attrs = { "gen_ai.operation.name": ( - self._gen_ai_operation_name(kwargs) - if self._gen_ai_semconv_latest_experimental - else "chat" + self._gen_ai_operation_name(kwargs) if self._gen_ai_semconv_latest_experimental else "chat" ), "gen_ai.system": provider, "gen_ai.request.model": kwargs.get("model"), @@ -1525,31 +1428,19 @@ def _record_metrics(self, kwargs, response_obj, start_time, end_time): common_attrs[f"metadata.{key}"] = str(value) # get hidden params - hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get( - "hidden_params", {} - ) + hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get("hidden_params", {}) if hidden_params: common_attrs["hidden_params"] = safe_dumps(hidden_params) common_attrs = self._filter_metric_attributes(common_attrs) if self._operation_duration_histogram: - self._operation_duration_histogram.record( - duration_s, attributes=common_attrs - ) - if ( - response_obj - and (usage := response_obj.get("usage")) - and self._token_usage_histogram - ): + self._operation_duration_histogram.record(duration_s, attributes=common_attrs) + if response_obj and (usage := response_obj.get("usage")) and self._token_usage_histogram: in_attrs = {**common_attrs, TOKEN_TYPE_ATTRIBUTE: "input"} out_attrs = {**common_attrs, TOKEN_TYPE_ATTRIBUTE: "output"} - self._token_usage_histogram.record( - usage.get("prompt_tokens", 0), attributes=in_attrs - ) - self._token_usage_histogram.record( - usage.get("completion_tokens", 0), attributes=out_attrs - ) + self._token_usage_histogram.record(usage.get("prompt_tokens", 0), attributes=in_attrs) + self._token_usage_histogram.record(usage.get("completion_tokens", 0), attributes=out_attrs) cost = kwargs.get("response_cost") if self._cost_histogram and cost: @@ -1557,9 +1448,7 @@ def _record_metrics(self, kwargs, response_obj, start_time, end_time): # Record latency metrics (TTFT, TPOT, and Total Generation Time) self._record_time_to_first_token_metric(kwargs, common_attrs) - self._record_time_per_output_token_metric( - kwargs, response_obj, end_time, duration_s, common_attrs - ) + self._record_time_per_output_token_metric(kwargs, response_obj, end_time, duration_s, common_attrs) self._record_response_duration_metric(kwargs, end_time, common_attrs) @staticmethod @@ -1604,9 +1493,7 @@ def _record_time_to_first_token_metric(self, kwargs: dict, common_attrs: dict): return # Skip recording if conversion failed time_to_first_token_seconds = completion_start_ts - api_call_start_ts - self._time_to_first_token_histogram.record( - time_to_first_token_seconds, attributes=common_attrs - ) + self._time_to_first_token_histogram.record(time_to_first_token_seconds, attributes=common_attrs) def _record_time_per_output_token_metric( self, @@ -1643,12 +1530,8 @@ def _record_time_per_output_token_metric( # Fallback to duration_s if conversion failed generation_time_seconds = duration_s if generation_time_seconds > 0: - time_per_output_token_seconds = ( - generation_time_seconds / completion_tokens - ) - self._time_per_output_token_histogram.record( - time_per_output_token_seconds, attributes=common_attrs - ) + time_per_output_token_seconds = generation_time_seconds / completion_tokens + self._time_per_output_token_histogram.record(time_per_output_token_seconds, attributes=common_attrs) return if completion_start_time is not None: @@ -1674,9 +1557,7 @@ def _record_time_per_output_token_metric( if generation_time_seconds > 0: time_per_output_token_seconds = generation_time_seconds / completion_tokens - self._time_per_output_token_histogram.record( - time_per_output_token_seconds, attributes=common_attrs - ) + self._time_per_output_token_histogram.record(time_per_output_token_seconds, attributes=common_attrs) def _record_response_duration_metric( self, @@ -1717,9 +1598,7 @@ def _record_response_duration_metric( response_duration_seconds = end_time_ts - api_call_start_ts if response_duration_seconds > 0: - self._response_duration_histogram.record( - response_duration_seconds, attributes=common_attrs - ) + self._response_duration_histogram.record(response_duration_seconds, attributes=common_attrs) @staticmethod def _otel_log_types(): @@ -1760,9 +1639,7 @@ def _emit_semantic_logs(self, kwargs, response_obj, span: Span): otel_logger = self._logger_provider.get_logger(LITELLM_LOGGER_NAME) parent_ctx = span.get_span_context() - provider = (kwargs.get("litellm_params") or {}).get( - "custom_llm_provider", "Unknown" - ) + provider = (kwargs.get("litellm_params") or {}).get("custom_llm_provider", "Unknown") if self._gen_ai_semconv_latest_experimental: self._emit_inference_details_event( @@ -1856,31 +1733,23 @@ def _resolve_guardrail_context( return _trace.set_span_in_context(parent_span) return fallback_ctx - def _create_guardrail_span( - self, kwargs: Optional[dict], context: Optional[Context] - ): + def _create_guardrail_span(self, kwargs: Optional[dict], context: Optional[Context]): """ Creates a span for Guardrail, if any guardrail information is present in standard_logging_object """ # Create span for guardrail information kwargs = kwargs or {} - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: return - guardrail_information_data = standard_logging_payload.get( - "guardrail_information" - ) + guardrail_information_data = standard_logging_payload.get("guardrail_information") if not guardrail_information_data: return guardrail_information_list = [ - information - for information in guardrail_information_data - if isinstance(information, dict) + information for information in guardrail_information_data if isinstance(information, dict) ] if not guardrail_information_list: @@ -1938,15 +1807,11 @@ def _create_guardrail_span( masked_entity_count = guardrail_information.get("masked_entity_count") if masked_entity_count is not None: - guardrail_span.set_attribute( - "masked_entity_count", safe_dumps(masked_entity_count) - ) + guardrail_span.set_attribute("masked_entity_count", safe_dumps(masked_entity_count)) guardrail_response = guardrail_information.get("guardrail_response") if guardrail_response is not None: - guardrail_span.set_attribute( - "guardrail_response", safe_dumps(guardrail_response) - ) + guardrail_span.set_attribute("guardrail_response", safe_dumps(guardrail_response)) # Surface guardrail_status (success / guardrail_intervened / # guardrail_failed_to_respond / not_run) as a top-level span @@ -1975,9 +1840,7 @@ def _create_guardrail_span( if violation_categories: # OTel sequence attributes must be homogeneous primitives; # serialise to JSON once so set_attribute never coerces. - guardrail_span.set_attribute( - "guardrail_violation_categories", safe_dumps(violation_categories) - ) + guardrail_span.set_attribute("guardrail_violation_categories", safe_dumps(violation_categories)) self._set_team_attributes_from_kwargs(guardrail_span, kwargs) @@ -2015,9 +1878,7 @@ def _handle_failure(self, kwargs, response_obj, start_time, end_time): # Decide whether to create a primary span # Always create if no parent span exists (backward compatibility) # OR if USE_OTEL_LITELLM_REQUEST_SPAN is explicitly enabled - should_create_primary_span = parent_otel_span is None or get_secret_bool( - "USE_OTEL_LITELLM_REQUEST_SPAN" - ) + should_create_primary_span = parent_otel_span is None or get_secret_bool("USE_OTEL_LITELLM_REQUEST_SPAN") span = None if should_create_primary_span: @@ -2085,9 +1946,7 @@ def _record_exception_on_span(self, span: Span, kwargs: dict): span.record_exception(exception) # Get StandardLoggingPayload for structured error information - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: return @@ -2156,9 +2015,7 @@ def _record_exception_on_span(self, span: Span, kwargs: dict): ) except Exception as e: - verbose_logger.exception( - "OpenTelemetry: Error recording exception on span: %s", str(e) - ) + verbose_logger.exception("OpenTelemetry: Error recording exception on span: %s", str(e)) def set_tools_attributes(self, span: Span, tools): import json @@ -2191,9 +2048,7 @@ def set_tools_attributes(self, span: Span, tools): value=json.dumps(function.get("parameters")), ) except Exception as e: - verbose_logger.error( - "OpenTelemetry: Error setting tools attributes: %s", str(e) - ) + verbose_logger.error("OpenTelemetry: Error setting tools attributes: %s", str(e)) pass def cast_as_primitive_value_type(self, value) -> Union[str, bool, int, float]: @@ -2229,9 +2084,7 @@ def _tool_calls_kv_pair( for key in keys: _value = _function.get(key) if _value: - kv_pairs[ - f"{SpanAttributes.LLM_COMPLETIONS.value}.{idx}.function_call.{key}" - ] = _value + kv_pairs[f"{SpanAttributes.LLM_COMPLETIONS.value}.{idx}.function_call.{key}"] = _value return kv_pairs @@ -2240,18 +2093,14 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): if self.callback_name == "langtrace": from litellm.integrations.langtrace import LangtraceAttributes - LangtraceAttributes().set_langtrace_attributes( - span, kwargs, response_obj - ) + LangtraceAttributes().set_langtrace_attributes(span, kwargs, response_obj) return elif self.callback_name == "langfuse_otel": from litellm.integrations.langfuse.langfuse_otel import ( LangfuseOtelLogger, ) - LangfuseOtelLogger.set_langfuse_otel_attributes( - span, kwargs, response_obj - ) + LangfuseOtelLogger.set_langfuse_otel_attributes(span, kwargs, response_obj) return elif self.callback_name == "weave_otel": from litellm.integrations.weave.weave_otel import ( @@ -2264,9 +2113,7 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): optional_params = kwargs.get("optional_params", {}) litellm_params = kwargs.get("litellm_params", {}) or {} - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") if standard_logging_payload is None: raise ValueError("standard_logging_object not found in kwargs") @@ -2277,14 +2124,12 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): ############################################# metadata = standard_logging_payload["metadata"] for key, value in metadata.items(): - self.safe_set_attribute( - span=span, key="metadata.{}".format(key), value=value - ) + self.safe_set_attribute(span=span, key="metadata.{}".format(key), value=value) # get hidden params - hidden_params = getattr( - standard_logging_payload, "hidden_params", None - ) or (standard_logging_payload or {}).get("hidden_params", {}) + hidden_params = getattr(standard_logging_payload, "hidden_params", None) or ( + standard_logging_payload or {} + ).get("hidden_params", {}) if hidden_params: self.safe_set_attribute( span=span, @@ -2298,9 +2143,7 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): litellm_params=litellm_params, ) # Cost breakdown tracking - cost_breakdown: Optional[CostBreakdown] = standard_logging_payload.get( - "cost_breakdown" - ) + cost_breakdown: Optional[CostBreakdown] = standard_logging_payload.get("cost_breakdown") if cost_breakdown: for key, value in cost_breakdown.items(): if value is not None: @@ -2393,9 +2236,7 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): # but Embeddings and Image-gen responses do not. Fall back to # the litellm call ID so every call type can be correlated # across LiteLLM UI, Phoenix traces, and provider logs (Issue #8). - response_id = ( - response_obj.get("id") if response_obj else None - ) or standard_logging_payload.get("id") + response_id = (response_obj.get("id") if response_obj else None) or standard_logging_payload.get("id") if response_id: self.safe_set_attribute( span=span, @@ -2453,11 +2294,7 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): self.set_tools_attributes(span, tools) if kwargs.get("messages"): - transformed_messages = ( - self._transform_messages_to_otel_semantic_conventions( - kwargs.get("messages") - ) - ) + transformed_messages = self._transform_messages_to_otel_semantic_conventions(kwargs.get("messages")) self.safe_set_attribute( span=span, key=SpanAttributes.GEN_AI_INPUT_MESSAGES.value, @@ -2474,11 +2311,7 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): system_instructions = ( kwargs.get("system_instructions") if kwargs.get("system_instructions") is not None - else ( - kwargs.get("instructions") - if kwargs.get("instructions") is not None - else kwargs.get("system") - ) + else (kwargs.get("instructions") if kwargs.get("instructions") is not None else kwargs.get("system")) ) if system_instructions: if isinstance(system_instructions, str): @@ -2489,10 +2322,8 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): value=system_instructions, ) else: - transformed_system_instructions = ( - self._transform_messages_to_otel_semantic_conventions( - system_instructions - ) + transformed_system_instructions = self._transform_messages_to_otel_semantic_conventions( + system_instructions ) self.safe_set_attribute( span=span, @@ -2525,10 +2356,8 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): ############################################# if response_obj is not None: if response_obj.get("choices"): - transformed_choices = ( - self._transform_choices_to_otel_semantic_conventions( - response_obj.get("choices") - ) + transformed_choices = self._transform_choices_to_otel_semantic_conventions( + response_obj.get("choices") ) self.safe_set_attribute( span=span, @@ -2567,9 +2396,7 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): # type="message" contains a "content" list of # OutputText objects (type="output_text"). output_items = response_obj.get("output") - output_messages = self._transform_responses_api_output_to_otel( - output_items - ) + output_messages = self._transform_responses_api_output_to_otel(output_items) if output_messages: self.safe_set_attribute( span=span, @@ -2613,12 +2440,8 @@ def set_attributes(self, span: Span, kwargs, response_obj: Optional[Any]): ) except Exception as e: - self.handle_callback_failure( - callback_name=self.callback_name or "opentelemetry" - ) - verbose_logger.exception( - "OpenTelemetry logging error in set_attributes %s", str(e) - ) + self.handle_callback_failure(callback_name=self.callback_name or "opentelemetry") + verbose_logger.exception("OpenTelemetry logging error in set_attributes %s", str(e)) def _cast_as_primitive_value_type(self, value) -> Union[str, bool, int, float]: """ @@ -2644,9 +2467,7 @@ def safe_set_attribute(self, span: Span, key: str, value: Any): primitive_value = self._cast_as_primitive_value_type(value) span.set_attribute(key, primitive_value) - def _transform_messages_to_otel_semantic_conventions( - self, messages: Union[List[dict], str] - ) -> List[dict]: + def _transform_messages_to_otel_semantic_conventions(self, messages: Union[List[dict], str]) -> List[dict]: """ Transforms LiteLLM/OpenAI style messages into OTEL GenAI 1.38 compliant format. OTEL expects a 'parts' array instead of a single 'content' string. @@ -2687,9 +2508,7 @@ def _transform_messages_to_otel_semantic_conventions( return transformed - def _transform_choices_to_otel_semantic_conventions( - self, choices: List[dict] - ) -> List[dict]: + def _transform_choices_to_otel_semantic_conventions(self, choices: List[dict]) -> List[dict]: """ Transforms choices into OTEL GenAI 1.38 compliant format for output.messages. """ @@ -2698,9 +2517,7 @@ def _transform_choices_to_otel_semantic_conventions( message = choice.get("message") or {} finish_reason = choice.get("finish_reason") - transformed_msg = self._transform_messages_to_otel_semantic_conventions( - [message] - )[0] + transformed_msg = self._transform_messages_to_otel_semantic_conventions([message])[0] if finish_reason: transformed_msg["finish_reason"] = finish_reason @@ -2897,16 +2714,12 @@ def _get_span_context(self, kwargs, default_span: Optional[Span] = None): # Priority 1: Explicit parent span from metadata if parent_otel_span is not None: - verbose_logger.debug( - "OpenTelemetry: Using explicit parent span from metadata" - ) + verbose_logger.debug("OpenTelemetry: Using explicit parent span from metadata") return trace.set_span_in_context(parent_otel_span), None # Priority 2: HTTP traceparent header if traceparent is not None: - verbose_logger.debug( - "OpenTelemetry: Using traceparent header for context propagation" - ) + verbose_logger.debug("OpenTelemetry: Using traceparent header for context propagation") carrier = {"traceparent": traceparent} return ( TraceContextTextMapPropagator().extract(carrier=carrier), @@ -2928,14 +2741,10 @@ def _get_span_context(self, kwargs, default_span: Optional[Span] = None): ) return context.get_current(), current_span except Exception as e: - verbose_logger.debug( - "OpenTelemetry: Error getting current span: %s", str(e) - ) + verbose_logger.debug("OpenTelemetry: Error getting current span: %s", str(e)) # Priority 4: No parent context - verbose_logger.debug( - "OpenTelemetry: No parent context found, creating root span" - ) + verbose_logger.debug("OpenTelemetry: No parent context found, creating root span") return None, None def _get_span_processor(self, dynamic_headers: Optional[dict] = None): @@ -2952,26 +2761,17 @@ def _get_span_processor(self, dynamic_headers: Optional[dict] = None): self.OTEL_ENDPOINT, self.OTEL_HEADERS, ) - _split_otel_headers = OpenTelemetry._get_headers_dictionary( - headers=dynamic_headers or self.OTEL_HEADERS - ) + _split_otel_headers = OpenTelemetry._get_headers_dictionary(headers=dynamic_headers or self.OTEL_HEADERS) if dynamic_headers: verbose_logger.debug( "[OTEL DEBUG] Creating span processor with DYNAMIC headers: %s", - { - k: v[:20] + "..." if len(str(v)) > 20 else v - for k, v in _split_otel_headers.items() - }, + {k: v[:20] + "..." if len(str(v)) > 20 else v for k, v in _split_otel_headers.items()}, ) else: - verbose_logger.debug( - "[OTEL DEBUG] Creating span processor with GLOBAL headers" - ) + verbose_logger.debug("[OTEL DEBUG] Creating span processor with GLOBAL headers") - if hasattr( - self.OTEL_EXPORTER, "export" - ): # Check if it has the export method that SpanExporter requires + if hasattr(self.OTEL_EXPORTER, "export"): # Check if it has the export method that SpanExporter requires verbose_logger.debug( "OpenTelemetry: intiializing SpanExporter. Value of OTEL_EXPORTER: %s", self.OTEL_EXPORTER, @@ -3003,13 +2803,9 @@ def _get_span_processor(self, dynamic_headers: Optional[dict] = None): "OpenTelemetry: intiializing http exporter. Value of OTEL_EXPORTER: %s", self.OTEL_EXPORTER, ) - normalized_endpoint = self._normalize_otel_endpoint( - self.OTEL_ENDPOINT, "traces" - ) + normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, "traces") return BatchSpanProcessor( - OTLPSpanExporterHTTP( - endpoint=normalized_endpoint, headers=_split_otel_headers - ), + OTLPSpanExporterHTTP(endpoint=normalized_endpoint, headers=_split_otel_headers), ) elif self.OTEL_EXPORTER == "otlp_grpc" or self.OTEL_EXPORTER == "grpc": try: @@ -3026,13 +2822,9 @@ def _get_span_processor(self, dynamic_headers: Optional[dict] = None): "OpenTelemetry: intiializing grpc exporter. Value of OTEL_EXPORTER: %s", self.OTEL_EXPORTER, ) - normalized_endpoint = self._normalize_otel_endpoint( - self.OTEL_ENDPOINT, "traces" - ) + normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, "traces") return BatchSpanProcessor( - OTLPSpanExporterGRPC( - endpoint=normalized_endpoint, headers=_split_otel_headers - ), + OTLPSpanExporterGRPC(endpoint=normalized_endpoint, headers=_split_otel_headers), ) else: verbose_logger.debug( @@ -3094,9 +2886,7 @@ def _get_log_exporter(self): self.OTEL_EXPORTER, normalized_endpoint, ) - return OTLPLogExporter( - endpoint=normalized_endpoint, headers=_split_otel_headers - ) + return OTLPLogExporter(endpoint=normalized_endpoint, headers=_split_otel_headers) elif self.OTEL_EXPORTER == "otlp_grpc" or self.OTEL_EXPORTER == "grpc": try: from opentelemetry.exporter.otlp.proto.grpc._log_exporter import ( @@ -3113,9 +2903,7 @@ def _get_log_exporter(self): self.OTEL_EXPORTER, normalized_endpoint, ) - return OTLPLogExporter( - endpoint=normalized_endpoint, headers=_split_otel_headers - ) + return OTLPLogExporter(endpoint=normalized_endpoint, headers=_split_otel_headers) else: verbose_logger.warning( "OpenTelemetry: Unknown log exporter '%s', defaulting to console. Supported: console, otlp_http, otlp_grpc", @@ -3144,9 +2932,7 @@ def _get_metric_reader(self): ) _split_otel_headers = OpenTelemetry._get_headers_dictionary(self.OTEL_HEADERS) - normalized_endpoint = self._normalize_otel_endpoint( - self.OTEL_ENDPOINT, "metrics" - ) + normalized_endpoint = self._normalize_otel_endpoint(self.OTEL_ENDPOINT, "metrics") if self.OTEL_EXPORTER == "console": exporter = ConsoleMetricExporter() @@ -3194,9 +2980,7 @@ def _get_metric_reader(self): exporter = ConsoleMetricExporter() return PeriodicExportingMetricReader(exporter, export_interval_millis=5000) - def _normalize_otel_endpoint( - self, endpoint: Optional[str], signal_type: str - ) -> Optional[str]: + def _normalize_otel_endpoint(self, endpoint: Optional[str], signal_type: str) -> Optional[str]: """ Normalize the endpoint URL for a specific OpenTelemetry signal type. @@ -3445,13 +3229,9 @@ def set_proxy_request_route_attributes( if url_path: self.safe_set_attribute(span=span, key=URL_PATH_ATTRIBUTE, value=url_path) if http_route: - self.safe_set_attribute( - span=span, key=HTTP_ROUTE_ATTRIBUTE, value=http_route - ) + self.safe_set_attribute(span=span, key=HTTP_ROUTE_ATTRIBUTE, value=http_route) - def set_response_status_code_attribute( - self, span: Optional[Span], status_code: Optional[int] - ) -> None: + def set_response_status_code_attribute(self, span: Optional[Span], status_code: Optional[int]) -> None: """ Set OTel-standard ``http.response.status_code`` (int) on the proxy SERVER span. The failure path sets this from the error code in @@ -3483,20 +3263,14 @@ def record_error_attributes_on_span( StandardLoggingPayloadSetup, ) - error_information = StandardLoggingPayloadSetup.get_error_information( - original_exception=exception - ) + error_information = StandardLoggingPayloadSetup.get_error_information(original_exception=exception) error_information["error_code"] = str(status_code) self._record_exception_on_span( span=span, - kwargs={ - "standard_logging_object": {"error_information": error_information} - }, + kwargs={"standard_logging_object": {"error_information": error_information}}, ) - def set_preprocessing_duration_attribute( - self, span: Optional[Span], container: Any - ) -> None: + def set_preprocessing_duration_attribute(self, span: Optional[Span], container: Any) -> None: """ Set ``litellm.preprocessing.duration_ms`` (proxy-receive -> first provider handoff) on the proxy SERVER span. ``litellm_received_at`` diff --git a/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py b/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py index e45fe149e133..98d24f1f7cc1 100644 --- a/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py +++ b/litellm/integrations/opentelemetry_utils/gen_ai_semconv.py @@ -55,9 +55,7 @@ class OTELSemconvCategory(Enum): # Reverse lookup: opt-in token string -> OTELSemconvCategory. -_SEMCONV_CATEGORY_BY_VALUE = { - category.value: category for category in OTELSemconvCategory -} +_SEMCONV_CATEGORY_BY_VALUE = {category.value: category for category in OTELSemconvCategory} # LiteLLM optional_params key -> OTEL gen_ai semconv span attribute. @@ -123,13 +121,9 @@ def safe_set_attribute(self, span: Span, key: str, value: Any) -> None: ... def _capture_in_event(self) -> bool: ... - def _transform_messages_to_otel_semantic_conventions( - self, messages: Union[List[dict], str] - ) -> List[dict]: ... + def _transform_messages_to_otel_semantic_conventions(self, messages: Union[List[dict], str]) -> List[dict]: ... - def _transform_choices_to_otel_semantic_conventions( - self, choices: List[dict] - ) -> List[dict]: ... + def _transform_choices_to_otel_semantic_conventions(self, choices: List[dict]) -> List[dict]: ... def _to_ns(self, dt: datetime) -> int: ... @@ -141,10 +135,7 @@ def _gen_ai_semconv_latest_experimental(self) -> bool: Every semconv behavior is gated on this; ``False`` => legacy output. """ - return ( - OTELSemconvCategory.GEN_AI_LATEST_EXPERIMENTAL - in self.config.semconv_stability_opt_in - ) + return OTELSemconvCategory.GEN_AI_LATEST_EXPERIMENTAL in self.config.semconv_stability_opt_in @staticmethod def _gen_ai_operation_name(kwargs: dict) -> str: @@ -162,9 +153,7 @@ def _gen_ai_operation_name(kwargs: dict) -> str: case _: return "chat" - def _set_semconv_request_attributes( - self, span: Span, optional_params: dict - ) -> None: + def _set_semconv_request_attributes(self, span: Span, optional_params: dict) -> None: """Add ``gen_ai.request.*`` span attributes from ``optional_params``. Covers the sampling params plus the conditionally-required @@ -180,9 +169,7 @@ def _set_semconv_request_attributes( # Spec types this as string[]. safe_set_attribute coerces to a # primitive, so set the array directly via the span API. stop_list = stop if isinstance(stop, list) else [stop] - span.set_attribute( - "gen_ai.request.stop_sequences", [str(s) for s in stop_list] - ) + span.set_attribute("gen_ai.request.stop_sequences", [str(s) for s in stop_list]) # Conditionally required: set only when the request is streaming. if optional_params.get("stream"): @@ -193,30 +180,22 @@ def _set_semconv_request_attributes( # suppressing nonsensical values (0, negative, non-int). n = optional_params.get("n") if isinstance(n, int) and n > 1: - self.safe_set_attribute( - span=span, key="gen_ai.request.choice.count", value=n - ) + self.safe_set_attribute(span=span, key="gen_ai.request.choice.count", value=n) - def _set_semconv_cache_token_attributes( - self, span: Span, standard_logging_payload - ) -> None: + def _set_semconv_cache_token_attributes(self, span: Span, standard_logging_payload) -> None: """Add ``gen_ai.usage.cache_*.input_tokens`` from the usage object. No-op when the payload or the usage values are missing/zero. """ if not standard_logging_payload: return - usage = (standard_logging_payload.get("metadata") or {}).get( - "usage_object" - ) or {} + usage = (standard_logging_payload.get("metadata") or {}).get("usage_object") or {} for source_key, semconv_key in _SEMCONV_CACHE_TOKEN_ATTRIBUTES.items(): value = usage.get(source_key) if value: self.safe_set_attribute(span=span, key=semconv_key, value=value) - def _build_inference_details_attrs( - self, kwargs: dict, response_obj: dict, provider: str - ) -> Dict[str, Any]: + def _build_inference_details_attrs(self, kwargs: dict, response_obj: dict, provider: str) -> Dict[str, Any]: """Build the attribute payload for the inference-details event. Always includes provider/operation; input/output messages are added @@ -230,12 +209,8 @@ def _build_inference_details_attrs( if not self._capture_in_event(): return attrs - input_messages = self._transform_messages_to_otel_semantic_conventions( - kwargs.get("messages") or [] - ) - output_messages = self._transform_choices_to_otel_semantic_conventions( - response_obj.get("choices", []) - ) + input_messages = self._transform_messages_to_otel_semantic_conventions(kwargs.get("messages") or []) + output_messages = self._transform_choices_to_otel_semantic_conventions(response_obj.get("choices", [])) if input_messages: attrs["gen_ai.input.messages"] = safe_dumps(input_messages) if output_messages: @@ -264,8 +239,6 @@ def _emit_inference_details_event( severity_number=SeverityNumber.INFO, severity_text="INFO", body=None, - attributes=self._build_inference_details_attrs( - kwargs, response_obj, provider - ), + attributes=self._build_inference_details_attrs(kwargs, response_obj, provider), ) otel_logger.emit(log_record) diff --git a/litellm/integrations/opik/opik.py b/litellm/integrations/opik/opik.py index b15b024ff09f..fd84ad56247c 100644 --- a/litellm/integrations/opik/opik.py +++ b/litellm/integrations/opik/opik.py @@ -26,9 +26,7 @@ def _should_skip_event(kwargs: Dict[str, Any]) -> bool: """Check if event should be skipped due to missing standard_logging_object.""" if kwargs.get("standard_logging_object") is None: - verbose_logger.debug( - "OpikLogger skipping event; no standard_logging_object found" - ) + verbose_logger.debug("OpikLogger skipping event; no standard_logging_object found") return True return False @@ -39,9 +37,7 @@ class OpikLogger(CustomBatchLogger): """ def __init__(self, **kwargs: Any) -> None: - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.sync_httpx_client = _get_httpx_client() self.opik_project_name: str = ( @@ -165,13 +161,9 @@ async def async_log_success_event( verbose_logger.debug("OpikLogger - Flushing batch") await self.flush_queue() except Exception as e: - verbose_logger.exception( - f"OpikLogger failed to log success event - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"OpikLogger failed to log success event - {str(e)}\n{traceback.format_exc()}") - def _sync_send( - self, url: str, headers: Dict[str, str], batch: Dict[str, Any] - ) -> None: + def _sync_send(self, url: str, headers: Dict[str, str], batch: Dict[str, Any]) -> None: try: response = self.sync_httpx_client.post( url=url, @@ -180,13 +172,9 @@ def _sync_send( ) response.raise_for_status() if response.status_code != 204: - raise Exception( - f"Response from opik API status_code: {response.status_code}, text: {response.text}" - ) + raise Exception(f"Response from opik API status_code: {response.status_code}, text: {response.text}") except Exception as e: - verbose_logger.exception( - f"OpikLogger failed to send batch - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"OpikLogger failed to send batch - {str(e)}\n{traceback.format_exc()}") def log_success_event( self, @@ -257,13 +245,9 @@ def log_success_event( batch={"spans": [span_payload.__dict__]}, ) except Exception as e: - verbose_logger.exception( - f"OpikLogger failed to log success event - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"OpikLogger failed to log success event - {str(e)}\n{traceback.format_exc()}") - async def _submit_batch( - self, url: str, headers: Dict[str, str], batch: Dict[str, Any] - ) -> None: + async def _submit_batch(self, url: str, headers: Dict[str, str], batch: Dict[str, Any]) -> None: try: response = await self.async_httpx_client.post( url=url, @@ -273,13 +257,9 @@ async def _submit_batch( response.raise_for_status() if response.status_code >= 300: - verbose_logger.error( - f"OpikLogger - Error: {response.status_code} - {response.text}" - ) + verbose_logger.error(f"OpikLogger - Error: {response.status_code} - {response.text}") else: - verbose_logger.info( - f"OpikLogger - {len(self.log_queue)} Opik events submitted" - ) + verbose_logger.info(f"OpikLogger - {len(self.log_queue)} Opik events submitted") except Exception as e: verbose_logger.exception(f"OpikLogger failed to send batch - {str(e)}") @@ -302,12 +282,8 @@ async def async_send_batch(self) -> None: # Send trace batch if len(traces) > 0: - await self._submit_batch( - url=self.trace_url, headers=self.headers, batch={"traces": traces} - ) + await self._submit_batch(url=self.trace_url, headers=self.headers, batch={"traces": traces}) verbose_logger.info(f"Sent {len(traces)} traces") if len(spans) > 0: - await self._submit_batch( - url=self.span_url, headers=self.headers, batch={"spans": spans} - ) + await self._submit_batch(url=self.span_url, headers=self.headers, batch={"spans": spans}) verbose_logger.info(f"Sent {len(spans)} spans") diff --git a/litellm/integrations/opik/opik_payload_builder/api.py b/litellm/integrations/opik/opik_payload_builder/api.py index e3ffab80ae85..6a5f9bfddc50 100644 --- a/litellm/integrations/opik/opik_payload_builder/api.py +++ b/litellm/integrations/opik/opik_payload_builder/api.py @@ -44,9 +44,7 @@ def build_opik_payload( standard_logging_metadata = standard_logging_object.get("metadata", {}) or {} # Extract and merge Opik metadata - opik_metadata = extractors.extract_opik_metadata( - litellm_metadata, standard_logging_metadata - ) + opik_metadata = extractors.extract_opik_metadata(litellm_metadata, standard_logging_metadata) # Extract project name current_project_name = opik_metadata.get("project_name", project_name) diff --git a/litellm/integrations/opik/opik_payload_builder/extractors.py b/litellm/integrations/opik/opik_payload_builder/extractors.py index 1e3a664acc1f..73058b2a5240 100644 --- a/litellm/integrations/opik/opik_payload_builder/extractors.py +++ b/litellm/integrations/opik/opik_payload_builder/extractors.py @@ -66,9 +66,7 @@ def extract_opik_metadata( if requester_opik: opik_meta.update(requester_opik) - _logging.verbose_logger.debug( - f"litellm_opik_metadata - {json.dumps(opik_meta, default=str)}" - ) + _logging.verbose_logger.debug(f"litellm_opik_metadata - {json.dumps(opik_meta, default=str)}") return opik_meta @@ -94,9 +92,7 @@ def extract_span_identifiers( try: return current_span_data.trace_id, current_span_data.id except AttributeError: - _logging.verbose_logger.warning( - f"Unexpected current_span_data format: {type(current_span_data)}" - ) + _logging.verbose_logger.warning(f"Unexpected current_span_data format: {type(current_span_data)}") return None, None @@ -156,9 +152,7 @@ def apply_proxy_header_overrides( if isinstance(parsed_tags, list): tags.extend(parsed_tags) except (json.JSONDecodeError, TypeError): - _logging.verbose_logger.warning( - f"Failed to parse tags from header: {value}" - ) + _logging.verbose_logger.warning(f"Failed to parse tags from header: {value}") return project_name, tags, thread_id @@ -226,8 +220,6 @@ def extract_and_build_metadata( # Add debug info if cost calculation failed if "response_cost_failure_debug_info" in litellm_kwargs: - metadata["response_cost_failure_debug_info"] = litellm_kwargs[ - "response_cost_failure_debug_info" - ] + metadata["response_cost_failure_debug_info"] = litellm_kwargs["response_cost_failure_debug_info"] return metadata diff --git a/litellm/integrations/opik/opik_payload_builder/payload_builders.py b/litellm/integrations/opik/opik_payload_builder/payload_builders.py index 4656924fdb5a..4d92650d2b8d 100644 --- a/litellm/integrations/opik/opik_payload_builder/payload_builders.py +++ b/litellm/integrations/opik/opik_payload_builder/payload_builders.py @@ -28,9 +28,7 @@ def build_trace_payload( project_name=project_name, id=trace_id, name=trace_name, - start_time=( - start_time.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") - ), + start_time=(start_time.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")), end_time=end_time.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"), input=input_data, output=output_data, @@ -63,9 +61,7 @@ def build_span_payload( created = response_obj.get("created", 0) span_name = f"{model}_{obj_type}_{created}" - _logging.verbose_logger.debug( - f"OpikLogger creating span with id {span_id} for trace {trace_id}" - ) + _logging.verbose_logger.debug(f"OpikLogger creating span with id {span_id} for trace {trace_id}") return types.SpanPayload( id=span_id, @@ -75,9 +71,7 @@ def build_span_payload( name=span_name, type="llm", model=model, - start_time=( - start_time.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") - ), + start_time=(start_time.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")), end_time=end_time.astimezone(timezone.utc).isoformat().replace("+00:00", "Z"), input=input_data, output=output_data, diff --git a/litellm/integrations/opik/utils.py b/litellm/integrations/opik/utils.py index 43577505c115..7222c9d05021 100644 --- a/litellm/integrations/opik/utils.py +++ b/litellm/integrations/opik/utils.py @@ -43,9 +43,7 @@ def _read_opik_config_file() -> Dict[str, str]: config = configparser.ConfigParser() config.read(config_path) - config_values = { - section: dict(config.items(section)) for section in config.sections() - } + config_values = {section: dict(config.items(section)) for section in config.sections()} if "opik" in config_values: return config_values["opik"] diff --git a/litellm/integrations/otel/emitter.py b/litellm/integrations/otel/emitter.py index 6feaf2734e99..69fc53c5b9d4 100644 --- a/litellm/integrations/otel/emitter.py +++ b/litellm/integrations/otel/emitter.py @@ -58,9 +58,7 @@ def __init__( # The mapper chain is the sole source of span attributes. When not # passed in, resolve it from the config so there's one source of truth. self._mappers: list[AttributeMapper] = ( - list(mappers) - if mappers is not None - else resolve_mappers(config.mapper_names) + list(mappers) if mappers is not None else resolve_mappers(config.mapper_names) ) # Bounded LRU (ordered by insertion / most-recent touch). Storing keys # only — the value is unused — so it behaves like a capped set. @@ -127,11 +125,7 @@ def emit( # LLM-call and MCP tool-call spans carry a dedup key (their request's # call id), so a sync+async double-firing coalesces. ``isinstance`` narrows # the type for mypy and keeps the engine free of duck-typed attribute reads. - dedup_key = ( - data.identity.call_id - if isinstance(data, (LLMCallSpanData, MCPToolCallSpanData)) - else None - ) + dedup_key = data.identity.call_id if isinstance(data, (LLMCallSpanData, MCPToolCallSpanData)) else None if self._seen(dedup_key, role): return None span = self.start_span( diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.py index 79931c0796ca..444845599480 100644 --- a/litellm/integrations/otel/logger.py +++ b/litellm/integrations/otel/logger.py @@ -109,19 +109,13 @@ def __init__( self.config: OpenTelemetryV2Config = config or OpenTelemetryV2Config(**kwargs) self.callback_name = callback_name self._tracer_provider: TracerProvider = ( - tracer_provider - if tracer_provider is not None - else build_tracer_provider(self.config) + tracer_provider if tracer_provider is not None else build_tracer_provider(self.config) ) self.tracer: Tracer = get_tracer(self._tracer_provider, LITELLM_TRACER_NAME) self._metrics_recorder = self._init_metrics(meter_provider) self._metric_filter_error_logged = False - self._emitter = SpanEmitter( - self.tracer, self.config, mappers=resolve_mappers(self.config.mapper_names) - ) - self._tenant_tracers = TenantTracerCache( - self.config, callback_name, LITELLM_TRACER_NAME - ) + self._emitter = SpanEmitter(self.tracer, self.config, mappers=resolve_mappers(self.config.mapper_names)) + self._tenant_tracers = TenantTracerCache(self.config, callback_name, LITELLM_TRACER_NAME) self._open_llm_calls: "OrderedDict[str, _LLMCallSpan]" = OrderedDict() self._init_otel_logger_on_litellm_proxy() @@ -145,9 +139,7 @@ def _init_metrics(self, meter_provider: Any | None) -> "GenAIMetricRecorder | No def _register_in_callback_list(self, callbacks: list) -> None: already_otel = any( - cb.__class__.__module__.startswith(_OTEL_MODULES) - for cb in callbacks - if hasattr(cb, "__class__") + cb.__class__.__module__.startswith(_OTEL_MODULES) for cb in callbacks if hasattr(cb, "__class__") ) if not already_otel: callbacks.append(self) @@ -214,13 +206,9 @@ def log_pre_api_call(self, model, messages, kwargs): call.provisional_span_name, parent_context=parent_context, start_time_ns=start_time_ns, - tracer=self._tenant_tracers.tracer_for( - self.tracer, call.dynamic_params - ), + tracer=self._tenant_tracers.tracer_for(self.tracer, call.dynamic_params), ) - self._open_llm_calls[call_id] = _LLMCallSpan( - span=span, start_time_ns=start_time_ns - ) + self._open_llm_calls[call_id] = _LLMCallSpan(span=span, start_time_ns=start_time_ns) # Evict the oldest open call if the map is over budget. A call that opens # but never closes (a stream that only fires stream events) would linger # otherwise; the evicted span is simply dropped (never exported). @@ -272,9 +260,7 @@ def _emit_mcp_tool_call( no boundary to open it at), deduped on the call id by the emitter. """ raw_payload = kwargs.get("standard_logging_object") - if not raw_payload or not is_mcp_tool_call( - cast(Mapping[str, object], raw_payload) - ): + if not raw_payload or not is_mcp_tool_call(cast(Mapping[str, object], raw_payload)): return False payload = cast("StandardLoggingPayload", raw_payload) data = MCPToolCallSpanData.from_standard_logging_payload( @@ -320,17 +306,13 @@ def _close_llm_call( # it (named provisionally) so it isn't leaked as an open span. carrier.span.end(end_time=to_ns(end_time)) return None - data = LLMCallSpanData.from_standard_logging_payload( - payload, capture_content=self.config.capture_span_content - ) + data = LLMCallSpanData.from_standard_logging_payload(payload, capture_content=self.config.capture_span_content) end_time_ns = to_ns(end_time) if carrier.span is not None: # Born at the boundary: stamp attributes from the typed payload, set # status, and end it. Its parent (the server span) was captured at # creation from real ambient context. - self._emitter.finish_span( - SpanRole.LLM_CALL, carrier.span, data, end_time_ns=end_time_ns - ) + self._emitter.finish_span(SpanRole.LLM_CALL, carrier.span, data, end_time_ns=end_time_ns) return carrier.span # Deferred: ``pre_call`` saw no recordable parent, so create the span now. # The worker copied the request task's context, which carries the anchored @@ -419,12 +401,7 @@ def _emit_service( # zero-duration root with no context, so skip it. Real background work # (budget/reset jobs, spend flush) passes start/end times and still emits # as a root; anything with a parent emits regardless. - if ( - error_override is None - and start_time is None - and end_time is None - and parent_otel_span is None - ): + if error_override is None and start_time is None and end_time is None and parent_otel_span is None: return None if error_override is not None and data.error is None: data = ServiceSpanData( @@ -570,9 +547,7 @@ def select_global_otel_v2_logger( """ if registered is not None: return registered - existing = next( - (cb for cb in in_memory_loggers if isinstance(cb, OpenTelemetryV2)), None - ) + existing = next((cb for cb in in_memory_loggers if isinstance(cb, OpenTelemetryV2)), None) return existing if existing is not None else OpenTelemetryV2() diff --git a/litellm/integrations/otel/mappers/__init__.py b/litellm/integrations/otel/mappers/__init__.py index 9c728678f47d..b0c1d7019db6 100644 --- a/litellm/integrations/otel/mappers/__init__.py +++ b/litellm/integrations/otel/mappers/__init__.py @@ -37,9 +37,7 @@ def resolve_mappers(names: Iterable[str]) -> list[AttributeMapper]: for name in names: factory = _MAPPER_BY_NAME.get(name) if factory is None: - raise ValueError( - f"unknown mapper name {name!r}; known: {sorted(_MAPPER_BY_NAME)}" - ) + raise ValueError(f"unknown mapper name {name!r}; known: {sorted(_MAPPER_BY_NAME)}") out.append(factory()) return out diff --git a/litellm/integrations/otel/mappers/base.py b/litellm/integrations/otel/mappers/base.py index dfdaf77a83e0..6685e34578b3 100644 --- a/litellm/integrations/otel/mappers/base.py +++ b/litellm/integrations/otel/mappers/base.py @@ -14,9 +14,7 @@ AttrScalar = str | bool | int | float # Mirrors ``opentelemetry.util.types.AttributeValue`` (homogeneous sequences) # without importing the SDK, so mappers stay OTel-free. -AttrValue = ( - AttrScalar | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float] -) +AttrValue = AttrScalar | Sequence[str] | Sequence[bool] | Sequence[int] | Sequence[float] AttributeMap = dict[str, AttrValue] # The closed set of span-data types the engine routes through the mapper chain. diff --git a/litellm/integrations/otel/mappers/genai.py b/litellm/integrations/otel/mappers/genai.py index 75330ebd1bde..ad6d3e7ff219 100644 --- a/litellm/integrations/otel/mappers/genai.py +++ b/litellm/integrations/otel/mappers/genai.py @@ -46,18 +46,14 @@ class GenAIMapper: GenAI.REQUEST_FREQUENCY_PENALTY: lambda d: d.request_params.frequency_penalty, GenAI.REQUEST_PRESENCE_PENALTY: lambda d: d.request_params.presence_penalty, GenAI.REQUEST_STOP_SEQUENCES: lambda d: ( - list(d.request_params.stop_sequences) - if d.request_params.stop_sequences - else None + list(d.request_params.stop_sequences) if d.request_params.stop_sequences else None ), GenAI.REQUEST_SEED: lambda d: d.request_params.seed, GenAI.INPUT_MESSAGES: lambda d: serialize_messages(d.messages_in), GenAI.OUTPUT_MESSAGES: lambda d: serialize_messages(output_messages(d)), GenAI.RESPONSE_MODEL: lambda d: d.response_model, GenAI.RESPONSE_ID: lambda d: d.response_id, - GenAI.RESPONSE_FINISH_REASONS: lambda d: ( - list(d.finish_reasons) if d.finish_reasons else None - ), + GenAI.RESPONSE_FINISH_REASONS: lambda d: list(d.finish_reasons) if d.finish_reasons else None, GenAI.USAGE_INPUT_TOKENS: lambda d: d.usage.input_tokens, GenAI.USAGE_OUTPUT_TOKENS: lambda d: d.usage.output_tokens, Error.TYPE: lambda d: d.error.error_type if d.error else None, @@ -80,13 +76,9 @@ class GenAIMapper: f"{LiteLLM.COST_PREFIX}original": lambda d: d.cost.original, f"{LiteLLM.COST_PREFIX}discount_amount": lambda d: d.cost.discount_amount, f"{LiteLLM.COST_PREFIX}discount_percent": lambda d: d.cost.discount_percent, - f"{LiteLLM.COST_PREFIX}margin_fixed_amount": lambda d: ( - d.cost.margin_fixed_amount - ), + f"{LiteLLM.COST_PREFIX}margin_fixed_amount": lambda d: d.cost.margin_fixed_amount, f"{LiteLLM.COST_PREFIX}margin_percent": lambda d: d.cost.margin_percent, - f"{LiteLLM.COST_PREFIX}margin_total_amount": lambda d: ( - d.cost.margin_total_amount - ), + f"{LiteLLM.COST_PREFIX}margin_total_amount": lambda d: d.cost.margin_total_amount, LiteLLM.REQUEST_STREAMING: lambda d: d.is_streaming, } @@ -174,10 +166,5 @@ def _service(cls, data: ServiceSpanData) -> AttributeMap: attrs[DB.SYSTEM_NAME] = system if data.call_type: attrs[DB.OPERATION_NAME] = data.call_type - attrs.update( - { - f"{LiteLLM.METADATA_PREFIX}{key}": value - for key, value in data.event_metadata.items() - } - ) + attrs.update({f"{LiteLLM.METADATA_PREFIX}{key}": value for key, value in data.event_metadata.items()}) return attrs diff --git a/litellm/integrations/otel/mappers/langfuse.py b/litellm/integrations/otel/mappers/langfuse.py index d0af460f752a..79f8f618eff6 100644 --- a/litellm/integrations/otel/mappers/langfuse.py +++ b/litellm/integrations/otel/mappers/langfuse.py @@ -58,13 +58,9 @@ class LangfuseMapper: ), "langfuse.observation.input": lambda d: serialize_messages(d.messages_in), "langfuse.observation.output": lambda d: serialize_messages(output_messages(d)), - "langfuse.observation.usage_details": lambda d: json_if( - collect(LangfuseMapper._USAGE_FIELDS, d.usage) - ), + "langfuse.observation.usage_details": lambda d: json_if(collect(LangfuseMapper._USAGE_FIELDS, d.usage)), "langfuse.observation.cost_details": lambda d: ( - json.dumps({"total": d.response_cost}) - if d.response_cost is not None - else None + json.dumps({"total": d.response_cost}) if d.response_cost is not None else None ), } diff --git a/litellm/integrations/otel/mappers/langtrace.py b/litellm/integrations/otel/mappers/langtrace.py index ec595439fe53..975864b51b4d 100644 --- a/litellm/integrations/otel/mappers/langtrace.py +++ b/litellm/integrations/otel/mappers/langtrace.py @@ -40,12 +40,8 @@ class LangtraceMapper: } _BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = { - "llm.prompts": lambda d: ( - json_or_none(list(d.messages_in)) if d.messages_in else None - ), - "llm.completions": lambda d: ( - json_or_none(output_messages(d)) if d.choices_out else None - ), + "llm.prompts": lambda d: json_or_none(list(d.messages_in)) if d.messages_in else None, + "llm.completions": lambda d: json_or_none(output_messages(d)) if d.choices_out else None, } def map(self, data: SpanData) -> AttributeMap: diff --git a/litellm/integrations/otel/mappers/legacy.py b/litellm/integrations/otel/mappers/legacy.py index 20ffe8b0dd8f..57dc7ed3632e 100644 --- a/litellm/integrations/otel/mappers/legacy.py +++ b/litellm/integrations/otel/mappers/legacy.py @@ -47,9 +47,7 @@ class LegacyMapper: _LEGACY_FREQUENCY_PENALTY: lambda d: d.request_params.frequency_penalty, _LEGACY_PRESENCE_PENALTY: lambda d: d.request_params.presence_penalty, _LEGACY_STOP_SEQUENCES: lambda d: ( - list(d.request_params.stop_sequences) - if d.request_params.stop_sequences - else None + list(d.request_params.stop_sequences) if d.request_params.stop_sequences else None ), } @@ -62,9 +60,7 @@ class LegacyMapper: _SERVICE_ATTRS: dict[str, Callable[[ServiceSpanData], AttrValue | None]] = { _LEGACY_SERVICE: lambda d: d.service_name, _LEGACY_CALL_TYPE: lambda d: d.call_type, - _LEGACY_ERROR: lambda d: ( - d.error.message if d.error is not None and d.error.message else None - ), + _LEGACY_ERROR: lambda d: d.error.message if d.error is not None and d.error.message else None, } def map(self, data: SpanData) -> AttributeMap: diff --git a/litellm/integrations/otel/mappers/openinference.py b/litellm/integrations/otel/mappers/openinference.py index d8195cbe03df..dab9a6169799 100644 --- a/litellm/integrations/otel/mappers/openinference.py +++ b/litellm/integrations/otel/mappers/openinference.py @@ -83,21 +83,14 @@ def _llm_call(cls, data: LLMCallSpanData) -> AttributeMap: **collect(cls._LLM_CALL_ATTRS, data), **collect(cls._BLOB_ATTRS, data), **cls._messages("llm.input_messages", "input.value", data.messages_in), - **cls._messages( - "llm.output_messages", "output.value", output_messages(data) - ), + **cls._messages("llm.output_messages", "output.value", output_messages(data)), **cls._tools(data), } @staticmethod - def _messages( - prefix: str, value_key: str, messages: Sequence[object] - ) -> AttributeMap: + def _messages(prefix: str, value_key: str, messages: Sequence[object]) -> AttributeMap: """Per-message ``{prefix}.{idx}.message.*`` keys + the ``value_key`` blob.""" - parsed = [ - (m.get("role") if isinstance(m, dict) else None, message_content(m)) - for m in messages - ] + parsed = [(m.get("role") if isinstance(m, dict) else None, message_content(m)) for m in messages] attrs = drop_none( { key: value @@ -112,9 +105,7 @@ def _messages( } ) if parsed: - attrs[value_key] = json.dumps( - [{"role": role, "content": content} for role, content in parsed] - ) + attrs[value_key] = json.dumps([{"role": role, "content": content} for role, content in parsed]) return attrs @classmethod diff --git a/litellm/integrations/otel/mappers/utils.py b/litellm/integrations/otel/mappers/utils.py index 6228fc8bbe7a..a91e59e4ab82 100644 --- a/litellm/integrations/otel/mappers/utils.py +++ b/litellm/integrations/otel/mappers/utils.py @@ -47,9 +47,7 @@ def stringify_message(message: object) -> str | None: def serialize_messages(messages: Sequence[object]) -> str | None: """Round-trip a sequence of message dicts through ``stringify_message``.""" - serialized = [ - json.loads(s) for s in (stringify_message(m) for m in messages) if s is not None - ] + serialized = [json.loads(s) for s in (stringify_message(m) for m in messages) if s is not None] return json.dumps(serialized) if serialized else None @@ -62,11 +60,7 @@ def message_content(message: object) -> str | None: return content if isinstance(content, list): # multimodal: concatenate text parts only - parts = [ - part.get("text", "") - for part in content - if isinstance(part, dict) and part.get("type") == "text" - ] + parts = [part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") == "text"] return "".join(p for p in parts if isinstance(p, str)) or None return None diff --git a/litellm/integrations/otel/mappers/weave.py b/litellm/integrations/otel/mappers/weave.py index 54b07299271b..2eb4ad817c7b 100644 --- a/litellm/integrations/otel/mappers/weave.py +++ b/litellm/integrations/otel/mappers/weave.py @@ -19,18 +19,14 @@ class WeaveMapper: _LLM_CALL_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = { # ``display_name`` has the form ``"{operation} {model}"``. The span # name already covers that, but Weave reads this attribute too. - "weave.display_name": lambda d: ( - f"{d.operation.value} {d.request_model}" if d.request_model else None - ), + "weave.display_name": lambda d: f"{d.operation.value} {d.request_model}" if d.request_model else None, "weave.call_id": lambda d: d.identity.call_id or None, } # JSON-payload attributes: each builder returns the serialized blob or None. _BLOB_ATTRS: dict[str, Callable[[LLMCallSpanData], AttrValue | None]] = { # Weave treats the response choices as the "output" payload. - "weave.output": lambda d: ( - json_or_none(list(d.choices_out)) if d.choices_out else None - ), + "weave.output": lambda d: json_or_none(list(d.choices_out)) if d.choices_out else None, } def map(self, data: SpanData) -> AttributeMap: diff --git a/litellm/integrations/otel/model/baggage.py b/litellm/integrations/otel/model/baggage.py index 77ace736c2f9..0903b5ad34ea 100644 --- a/litellm/integrations/otel/model/baggage.py +++ b/litellm/integrations/otel/model/baggage.py @@ -24,20 +24,16 @@ # team_metadata_keys). The single definition of what may be promoted and under # which key. Only the ``TEAM_METADATA`` extractor consults team_metadata_keys # (to filter the team's metadata to an allowlist); the rest ignore it. -_PROMOTABLE: Final[ - dict[str, Callable[[RequestIdentity, str | None, tuple[str, ...]], str | None]] -] = { +_PROMOTABLE: Final[dict[str, Callable[[RequestIdentity, str | None, tuple[str, ...]], str | None]]] = { LiteLLM.TEAM_ID: lambda identity, model, team_metadata_keys: identity.team_id, LiteLLM.TEAM_ALIAS: lambda identity, model, team_metadata_keys: identity.team_alias, - LiteLLM.TEAM_METADATA: lambda identity, model, team_metadata_keys: ( - _filtered_team_metadata_json(identity.team_metadata, team_metadata_keys) + LiteLLM.TEAM_METADATA: lambda identity, model, team_metadata_keys: _filtered_team_metadata_json( + identity.team_metadata, team_metadata_keys ), LiteLLM.KEY_HASH: lambda identity, model, team_metadata_keys: identity.key_hash, LiteLLM.END_USER: lambda identity, model, team_metadata_keys: identity.end_user, GenAI.REQUEST_MODEL: lambda identity, model, team_metadata_keys: model, - LiteLLM.PROVIDER_MODEL: lambda identity, model, team_metadata_keys: ( - identity.provider_model - ), + LiteLLM.PROVIDER_MODEL: lambda identity, model, team_metadata_keys: identity.provider_model, } # Keys promoted by default (a subset of ``_PROMOTABLE``). ``END_USER`` is diff --git a/litellm/integrations/otel/model/config.py b/litellm/integrations/otel/model/config.py index 991b156ae64a..7f33129c5600 100644 --- a/litellm/integrations/otel/model/config.py +++ b/litellm/integrations/otel/model/config.py @@ -122,12 +122,8 @@ class OpenTelemetryV2Config(BaseSettings): default=None, validation_alias=AliasChoices("OTEL_HEADERS", "OTEL_EXPORTER_OTLP_HEADERS"), ) - service_name: str = Field( - default="litellm", validation_alias=AliasChoices("OTEL_SERVICE_NAME") - ) - deployment_environment: str | None = Field( - default=None, validation_alias=AliasChoices("OTEL_ENVIRONMENT_NAME") - ) + service_name: str = Field(default="litellm", validation_alias=AliasChoices("OTEL_SERVICE_NAME")) + deployment_environment: str | None = Field(default=None, validation_alias=AliasChoices("OTEL_ENVIRONMENT_NAME")) enable_metrics: bool = Field( default=False, @@ -139,13 +135,9 @@ class OpenTelemetryV2Config(BaseSettings): ) capture_message_content: str = Field( default=CaptureMessageContent.NO_CONTENT, - validation_alias=AliasChoices( - "OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT" - ), - ) - legacy_compat: bool = Field( - default=True, validation_alias=AliasChoices("LITELLM_OTEL_LEGACY_COMPAT") + validation_alias=AliasChoices("OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT"), ) + legacy_compat: bool = Field(default=True, validation_alias=AliasChoices("LITELLM_OTEL_LEGACY_COMPAT")) # ----- explicit multi-destination / vocabulary configuration ------------ # @@ -179,9 +171,7 @@ class OpenTelemetryV2Config(BaseSettings): baggage_promoted_keys: Annotated[List[str], NoDecode] = Field( default_factory=lambda: list(BAGGAGE_PROMOTED_KEYS), - validation_alias=AliasChoices( - "baggage_promoted_keys", "LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS" - ), + validation_alias=AliasChoices("baggage_promoted_keys", "LITELLM_OTEL_BAGGAGE_PROMOTED_KEYS"), description=( "Identity attribute keys written into Baggage and stamped on every " "child span (e.g. ``litellm.team.id``). Configure via the " @@ -192,9 +182,7 @@ class OpenTelemetryV2Config(BaseSettings): ) baggage_metadata_keys: Annotated[List[str], NoDecode] = Field( default_factory=lambda: list(DEFAULT_BAGGAGE_METADATA_KEYS), - validation_alias=AliasChoices( - "baggage_metadata_keys", "LITELLM_OTEL_BAGGAGE_METADATA_KEYS" - ), + validation_alias=AliasChoices("baggage_metadata_keys", "LITELLM_OTEL_BAGGAGE_METADATA_KEYS"), description=( "Metadata sub-keys promoted under the ``litellm.metadata.*`` " "namespace. Configure via the ``LITELLM_OTEL_BAGGAGE_METADATA_KEYS`` " @@ -204,9 +192,7 @@ class OpenTelemetryV2Config(BaseSettings): ) baggage_team_metadata_keys: Annotated[List[str], NoDecode] = Field( default_factory=lambda: list(DEFAULT_BAGGAGE_TEAM_METADATA_KEYS), - validation_alias=AliasChoices( - "baggage_team_metadata_keys", "LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS" - ), + validation_alias=AliasChoices("baggage_team_metadata_keys", "LITELLM_OTEL_BAGGAGE_TEAM_METADATA_KEYS"), description=( "Sub-keys of the team's free-form metadata promoted under " "``litellm.team.metadata``. Empty by default so none of a team's " diff --git a/litellm/integrations/otel/model/metadata.py b/litellm/integrations/otel/model/metadata.py index 4c9cecfef57d..37bb54643159 100644 --- a/litellm/integrations/otel/model/metadata.py +++ b/litellm/integrations/otel/model/metadata.py @@ -73,26 +73,17 @@ def from_payload(cls, payload: "StandardLoggingPayload") -> "RequestIdentity": model, not just the user-facing one. """ raw_meta = cast(Mapping[str, object], payload.get("metadata") or {}) - metadata = { - key: str(value) - for key, value in raw_meta.items() - if isinstance(value, (str, bool, int, float)) - } + metadata = {key: str(value) for key, value in raw_meta.items() if isinstance(value, (str, bool, int, float))} return cls( call_id=as_str(payload.get("litellm_call_id")) or as_str(payload.get("id")), # StandardLoggingMetadata's canonical key is ``user_api_key_team_id``; # the bare ``team_id`` is a legacy alias and is often empty, so prefer # the canonical key and fall back to the alias. - team_id=as_str(raw_meta.get("user_api_key_team_id")) - or as_str(raw_meta.get("team_id")), - team_alias=as_str(raw_meta.get("user_api_key_team_alias")) - or as_str(raw_meta.get("team_alias")), - team_metadata=_team_metadata_dict( - raw_meta.get("user_api_key_team_metadata") - ), + team_id=as_str(raw_meta.get("user_api_key_team_id")) or as_str(raw_meta.get("team_id")), + team_alias=as_str(raw_meta.get("user_api_key_team_alias")) or as_str(raw_meta.get("team_alias")), + team_metadata=_team_metadata_dict(raw_meta.get("user_api_key_team_metadata")), key_hash=as_str(raw_meta.get("user_api_key_hash")), - end_user=as_str(payload.get("end_user")) - or as_str(raw_meta.get("user_api_key_end_user_id")), + end_user=as_str(payload.get("end_user")) or as_str(raw_meta.get("user_api_key_end_user_id")), provider_model=resolve_provider_model(payload), metadata=metadata, ) @@ -153,18 +144,12 @@ def provider_model(self) -> str | None: return self.identity.provider_model @classmethod - def from_standard_logging_payload( - cls, payload: "StandardLoggingPayload" - ) -> "RequestContext": + def from_standard_logging_payload(cls, payload: "StandardLoggingPayload") -> "RequestContext": raw_meta = cast(Mapping[str, object], payload.get("metadata") or {}) hidden = cast(Mapping[str, object], payload.get("hidden_params") or {}) raw_response = payload.get("response") - response = cast( - Mapping[str, object], raw_response if isinstance(raw_response, dict) else {} - ) - model_group = as_str(payload.get("model_group")) or as_str( - raw_meta.get("model_group") - ) + response = cast(Mapping[str, object], raw_response if isinstance(raw_response, dict) else {}) + model_group = as_str(payload.get("model_group")) or as_str(raw_meta.get("model_group")) return cls( # The user asked for the group; fall back to the call model on the SDK # path, which has no group. Empty string (never None) so the span name @@ -172,8 +157,7 @@ def from_standard_logging_payload( request_model=model_group or as_str(payload.get("model")) or "", response_model=as_str(response.get("model")), model_group=model_group, - model_id=as_str(payload.get("model_id")) - or _model_info_id(raw_meta.get("model_info")), + model_id=as_str(payload.get("model_id")) or _model_info_id(raw_meta.get("model_info")), api_base=as_str(payload.get("api_base")) or as_str(hidden.get("api_base")), identity=RequestIdentity.from_payload(payload), ) @@ -233,9 +217,7 @@ def from_dict(cls, kwargs: Mapping[str, Any]) -> "LLMCallEvent": ) -def _call_id( - payload: "StandardLoggingPayload | None", kwargs: Mapping[str, Any] -) -> str | None: +def _call_id(payload: "StandardLoggingPayload | None", kwargs: Mapping[str, Any]) -> str | None: """The call id from the payload (when closed) or the bare kwargs (at pre_call).""" if payload is not None: call_id = as_str(payload.get("litellm_call_id")) or as_str(payload.get("id")) @@ -268,9 +250,7 @@ def resolve_provider_model(payload: "StandardLoggingPayload") -> str | None: return ( # ``deployment`` survives only on paths that don't strip it from metadata; # harmless (and most precise) to prefer it when present. - as_str(raw_meta.get("deployment")) - or as_str(hidden.get("litellm_model_name")) - or as_str(payload.get("model")) + as_str(raw_meta.get("deployment")) or as_str(hidden.get("litellm_model_name")) or as_str(payload.get("model")) ) diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.py index 82b7df5922c8..a368a8620249 100644 --- a/litellm/integrations/otel/model/payloads.py +++ b/litellm/integrations/otel/model/payloads.py @@ -187,14 +187,10 @@ class GuardrailSpanData: error: SpanError | None = None # Guardrail statuses that mean the guardrail did not pass the request through. - _ERROR_STATUSES: ClassVar[frozenset[str]] = frozenset( - {"guardrail_intervened", "guardrail_failed_to_respond"} - ) + _ERROR_STATUSES: ClassVar[frozenset[str]] = frozenset({"guardrail_intervened", "guardrail_failed_to_respond"}) @classmethod - def from_logging_entry( - cls, entry: "StandardLoggingGuardrailInformation" - ) -> "GuardrailSpanData": + def from_logging_entry(cls, entry: "StandardLoggingGuardrailInformation") -> "GuardrailSpanData": """Build from one ``standard_logging_guardrail_information`` entry. Reads the canonical, provider-agnostic ``StandardLoggingGuardrailInformation`` @@ -279,9 +275,7 @@ class ToolDefinition: name: str description: str | None = None - parameters_json: str | None = ( - None # JSON-serialized schema (str so it's an AttrValue) - ) + parameters_json: str | None = None # JSON-serialized schema (str so it's an AttrValue) @dataclass(frozen=True) @@ -322,9 +316,7 @@ def from_standard_logging_payload( # Normalize ``response`` to a dict once so the content/id reads below are a # plain ``.get`` — no repeated ``isinstance`` guards. raw_response = payload.get("response") - response = cast( - Mapping[str, object], raw_response if isinstance(raw_response, dict) else {} - ) + response = cast(Mapping[str, object], raw_response if isinstance(raw_response, dict) else {}) choices_out = _dicts(response.get("choices")) # ``finish_reasons`` is metadata, not content, so derive it from # ``choices_out`` before gating. The raw message/choice bodies are only @@ -347,9 +339,7 @@ def from_standard_logging_payload( finish_reasons=finish_reasons, error=_parse_error(payload), response_cost=as_float(payload.get("response_cost")), - cost=LLMCost.from_breakdown( - cast("Mapping[str, object] | None", payload.get("cost_breakdown")) - ), + cost=LLMCost.from_breakdown(cast("Mapping[str, object] | None", payload.get("cost_breakdown"))), server=ServerInfo.from_api_base(context.api_base), identity=context.identity, is_streaming=as_bool(payload.get("stream")), @@ -396,14 +386,10 @@ def from_standard_logging_payload( server_name=as_str(meta.get("mcp_server_name")), session_id=as_str(meta.get("mcp_session_id")), arguments_json=( - _json_or_none(meta.get("arguments")) - if capture_content and meta.get("arguments") is not None - else None + _json_or_none(meta.get("arguments")) if capture_content and meta.get("arguments") is not None else None ), result_json=( - _json_or_none(meta.get("result")) - if capture_content and meta.get("result") is not None - else None + _json_or_none(meta.get("result")) if capture_content and meta.get("result") is not None else None ), error=_parse_error(payload), response_cost=as_float(payload.get("response_cost")), @@ -426,9 +412,7 @@ def is_mcp_tool_call(payload: Mapping[str, object]) -> bool: """Whether a closed request's payload is an MCP tool call rather than an LLM call — true when the MCP gateway stamped its tool-call metadata, or the call type says so on a path that hasn't populated the metadata yet.""" - return bool(_mcp_tool_call_metadata(payload)) or ( - payload.get("call_type") == "call_mcp_tool" - ) + return bool(_mcp_tool_call_metadata(payload)) or (payload.get("call_type") == "call_mcp_tool") # --- service event_metadata sanitization ------------------------------------ # @@ -448,9 +432,7 @@ def is_mcp_tool_call(payload: Mapping[str, object]) -> bool: # Keys that carry raw call-site internals — live objects, full kwargs/args. The # operation name is already the span's ``call_type``, so ``function_name`` is # redundant. -_DROP_METADATA_KEYS: frozenset = frozenset( - {"function_kwargs", "function_args", "function_name"} -) +_DROP_METADATA_KEYS: frozenset = frozenset({"function_kwargs", "function_args", "function_name"}) _MAX_METADATA_VALUE_LEN = 1024 _MAX_METADATA_ITEMS = 32 diff --git a/litellm/integrations/otel/model/spans.py b/litellm/integrations/otel/model/spans.py index 1adc1d68ddeb..bc624cf6a573 100644 --- a/litellm/integrations/otel/model/spans.py +++ b/litellm/integrations/otel/model/spans.py @@ -77,26 +77,14 @@ class SpanSpec: SPAN_REGISTRY: dict[SpanRole, SpanSpec] = { - SpanRole.PROXY_REQUEST: SpanSpec( - SpanRole.PROXY_REQUEST, LiteLLMSpanKind.SERVER, parent=None - ), - SpanRole.LLM_CALL: SpanSpec( - SpanRole.LLM_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST - ), + SpanRole.PROXY_REQUEST: SpanSpec(SpanRole.PROXY_REQUEST, LiteLLMSpanKind.SERVER, parent=None), + SpanRole.LLM_CALL: SpanSpec(SpanRole.LLM_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), # The proxy is an MCP client to the upstream server it dispatches the tool # call to, so this is a CLIENT span, sibling of the LLM call under the request. - SpanRole.MCP_TOOL_CALL: SpanSpec( - SpanRole.MCP_TOOL_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST - ), - SpanRole.GUARDRAIL: SpanSpec( - SpanRole.GUARDRAIL, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST - ), - SpanRole.DB_CALL: SpanSpec( - SpanRole.DB_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST - ), - SpanRole.SERVICE: SpanSpec( - SpanRole.SERVICE, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST - ), + SpanRole.MCP_TOOL_CALL: SpanSpec(SpanRole.MCP_TOOL_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), + SpanRole.GUARDRAIL: SpanSpec(SpanRole.GUARDRAIL, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST), + SpanRole.DB_CALL: SpanSpec(SpanRole.DB_CALL, LiteLLMSpanKind.CLIENT, parent=SpanRole.PROXY_REQUEST), + SpanRole.SERVICE: SpanSpec(SpanRole.SERVICE, LiteLLMSpanKind.INTERNAL, parent=SpanRole.PROXY_REQUEST), } @@ -138,9 +126,7 @@ def db_system(service_name: str) -> str | None: # - ``auth`` — emitted instead as a live phase span (see # ``logger.phase_span``) so its DB lookups nest under it, # not as a flat post-hoc service span. -_METRICS_ONLY_SERVICES: frozenset[str] = frozenset( - {"self", "router", "proxy_pre_call", "auth"} -) +_METRICS_ONLY_SERVICES: frozenset[str] = frozenset({"self", "router", "proxy_pre_call", "auth"}) def span_role_for_service(service_name: str) -> SpanRole | None: diff --git a/litellm/integrations/otel/plumbing/context.py b/litellm/integrations/otel/plumbing/context.py index 64790da814b3..ff513c84d952 100644 --- a/litellm/integrations/otel/plumbing/context.py +++ b/litellm/integrations/otel/plumbing/context.py @@ -27,9 +27,7 @@ # and is inherited by ``asyncio.create_task`` children — i.e. the async logging # callbacks that close the span. It is never reset: the contextvar dies with the # request task, so there is nothing to leak. -_request_root_span: "ContextVar[Span | None]" = ContextVar( - "litellm_otel_request_root_span", default=None -) +_request_root_span: "ContextVar[Span | None]" = ContextVar("litellm_otel_request_root_span", default=None) def set_request_root_span(span: Span) -> None: @@ -49,9 +47,7 @@ def request_root_span() -> "Span | None": return span if is_recordable_span(span) else None -def set_request_baggage( - values: Mapping[str, str], context: Context | None = None -) -> Context: +def set_request_baggage(values: Mapping[str, str], context: Context | None = None) -> Context: """Return a context with ``values`` written into Baggage.""" ctx = context for key, value in values.items(): diff --git a/litellm/integrations/otel/plumbing/metrics.py b/litellm/integrations/otel/plumbing/metrics.py index 95ac939ff7fe..cb1f92148763 100644 --- a/litellm/integrations/otel/plumbing/metrics.py +++ b/litellm/integrations/otel/plumbing/metrics.py @@ -81,9 +81,7 @@ class GenAIMetricRecorder: survives. """ - def __init__( - self, metrics: GenAIMetrics, callback_name: Optional[str] = None - ) -> None: + def __init__(self, metrics: GenAIMetrics, callback_name: Optional[str] = None) -> None: self._metrics = metrics self._callback_name = callback_name self._include: Optional[FrozenSet[str]] = None @@ -108,9 +106,7 @@ def record( self._metrics.token_cost.record(cost, attributes=common_attrs) self._record_time_to_first_token(kwargs, common_attrs) - self._record_time_per_output_token( - kwargs, response_obj, end_time, duration_s, common_attrs - ) + self._record_time_per_output_token(kwargs, response_obj, end_time, duration_s, common_attrs) self._record_response_duration(kwargs, end_time, common_attrs) # ------------------------------------------------------------------ # @@ -138,9 +134,7 @@ def _common_attributes(self, kwargs: Mapping[str, Any]) -> dict: else: common_attrs[f"metadata.{key}"] = str(value) - hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get( - "hidden_params", {} - ) + hidden_params = getattr(std_log, "hidden_params", None) or (std_log or {}).get("hidden_params", {}) if hidden_params: common_attrs["hidden_params"] = safe_dumps(hidden_params) @@ -152,11 +146,7 @@ def _ensure_filter(self) -> None: attributes = None if self._callback_name in (None, "otel"): otel_settings = (litellm.callback_settings or {}).get("otel") or {} - raw = ( - otel_settings.get("attributes") - if isinstance(otel_settings, dict) - else None - ) + raw = otel_settings.get("attributes") if isinstance(otel_settings, dict) else None if raw is not None: attributes = _build_metric_attribute_filter(raw) # A bad filter (include_list + exclude_list both set, an unfilterable name) @@ -187,25 +177,17 @@ def _record_token_usage(self, response_obj: Any, common_attrs: dict) -> None: return in_attrs = {**common_attrs, TOKEN_TYPE_ATTRIBUTE: "input"} out_attrs = {**common_attrs, TOKEN_TYPE_ATTRIBUTE: "output"} - self._metrics.token_usage.record( - usage.get("prompt_tokens", 0), attributes=in_attrs - ) - self._metrics.token_usage.record( - usage.get("completion_tokens", 0), attributes=out_attrs - ) + self._metrics.token_usage.record(usage.get("prompt_tokens", 0), attributes=in_attrs) + self._metrics.token_usage.record(usage.get("completion_tokens", 0), attributes=out_attrs) - def _record_time_to_first_token( - self, kwargs: Mapping[str, Any], common_attrs: dict - ) -> None: + def _record_time_to_first_token(self, kwargs: Mapping[str, Any], common_attrs: dict) -> None: if not kwargs.get("optional_params", {}).get("stream", False): return api_call_start = to_seconds(kwargs.get("api_call_start_time")) completion_start = to_seconds(kwargs.get("completion_start_time")) if api_call_start is None or completion_start is None: return - self._metrics.time_to_first_token.record( - completion_start - api_call_start, attributes=common_attrs - ) + self._metrics.time_to_first_token.record(completion_start - api_call_start, attributes=common_attrs) def _record_time_per_output_token( self, @@ -229,27 +211,17 @@ def _record_time_per_output_token( api_call_start_time = kwargs.get("api_call_start_time") if completion_start_time is not None: completion_start = to_seconds(completion_start_time) - generation_time = ( - duration_s - if completion_start is None - else end_ts - completion_start - ) + generation_time = duration_s if completion_start is None else end_ts - completion_start elif api_call_start_time is not None: api_call_start = to_seconds(api_call_start_time) - generation_time = ( - duration_s if api_call_start is None else end_ts - api_call_start - ) + generation_time = duration_s if api_call_start is None else end_ts - api_call_start else: generation_time = duration_s if generation_time > 0: - self._metrics.time_per_output_token.record( - generation_time / completion_tokens, attributes=common_attrs - ) + self._metrics.time_per_output_token.record(generation_time / completion_tokens, attributes=common_attrs) - def _record_response_duration( - self, kwargs: Mapping[str, Any], end_time: datetime, common_attrs: dict - ) -> None: + def _record_response_duration(self, kwargs: Mapping[str, Any], end_time: datetime, common_attrs: dict) -> None: api_call_start_time = kwargs.get("api_call_start_time") if api_call_start_time is None: return diff --git a/litellm/integrations/otel/plumbing/providers.py b/litellm/integrations/otel/plumbing/providers.py index 6d0710397a3d..ac971c6daa8f 100644 --- a/litellm/integrations/otel/plumbing/providers.py +++ b/litellm/integrations/otel/plumbing/providers.py @@ -53,9 +53,7 @@ def to_otel_span_kind(kind: LiteLLMSpanKind) -> SpanKind: _EXPORTER_FACTORIES: dict[str, Callable[[ExporterSpec], SpanExporter]] = {} -def register_exporter_factory( - kind: str, factory: Callable[[ExporterSpec], SpanExporter] -) -> None: +def register_exporter_factory(kind: str, factory: Callable[[ExporterSpec], SpanExporter]) -> None: """Register a custom exporter ``factory`` for the exporter ``kind``.""" _EXPORTER_FACTORIES[kind.lower()] = factory @@ -72,9 +70,7 @@ def __init__( self._allowed_prefixes = tuple(allowed_prefixes) def _is_allowed(self, key: str) -> bool: - return key in self._allowed_keys or any( - key.startswith(prefix) for prefix in self._allowed_prefixes - ) + return key in self._allowed_keys or any(key.startswith(prefix) for prefix in self._allowed_prefixes) def on_start(self, span: Span, parent_context: Context | None = None) -> None: for key, value in baggage.get_all(parent_context).items(): @@ -156,11 +152,7 @@ def build_span_exporter(config: OpenTelemetryV2Config) -> SpanExporter: ``exporter`` / ``endpoint`` / ``headers`` fields. To configure multiple exporters, populate ``config.exporters`` directly. """ - return _exporter_from_spec( - ExporterSpec( - kind=config.exporter, endpoint=config.endpoint, headers=config.headers - ) - ) + return _exporter_from_spec(ExporterSpec(kind=config.exporter, endpoint=config.endpoint, headers=config.headers)) def _otlp_metrics_endpoint(endpoint: str | None) -> str | None: @@ -301,9 +293,7 @@ def build_tracer_provider( """ provider = TracerProvider(resource=build_resource(config)) if baggage_processor is None: - baggage_processor = LiteLLMBaggageSpanProcessor( - allowed_keys=config.baggage_promoted_keys - ) + baggage_processor = LiteLLMBaggageSpanProcessor(allowed_keys=config.baggage_promoted_keys) provider.add_span_processor(baggage_processor) if exporter is not None: @@ -317,11 +307,7 @@ def build_tracer_provider( provider.add_span_processor( _processor_for( exp, - ( - spec.use_simple_processor - if spec.use_simple_processor is not None - else use_simple_processor - ), + (spec.use_simple_processor if spec.use_simple_processor is not None else use_simple_processor), ) ) return provider diff --git a/litellm/integrations/otel/plumbing/routing.py b/litellm/integrations/otel/plumbing/routing.py index 1f2f1b202d96..2f8945e903b4 100644 --- a/litellm/integrations/otel/plumbing/routing.py +++ b/litellm/integrations/otel/plumbing/routing.py @@ -60,9 +60,7 @@ def __init__( self._config = config self._callback_name = callback_name self._tracer_name = tracer_name - self._providers: "OrderedDict[tuple[tuple[str, str], ...], TracerProvider]" = ( - OrderedDict() - ) + self._providers: "OrderedDict[tuple[tuple[str, str], ...], TracerProvider]" = OrderedDict() def tracer_for(self, default: Tracer, dynamic_params: Any) -> Tracer: """Return the tracer for this request. @@ -102,8 +100,7 @@ def _config_with_headers(self, headers: Mapping[str, str]) -> OpenTelemetryV2Con exporters = [ ( spec.model_copy(update=header_update) - if spec.owner == self._callback_name - and spec.kind.lower() not in _NON_OTLP_KINDS + if spec.owner == self._callback_name and spec.kind.lower() not in _NON_OTLP_KINDS else spec ) for spec in self._config.exporters diff --git a/litellm/integrations/otel/presets/__init__.py b/litellm/integrations/otel/presets/__init__.py index c69d257ab524..deaf953ede84 100644 --- a/litellm/integrations/otel/presets/__init__.py +++ b/litellm/integrations/otel/presets/__init__.py @@ -39,9 +39,7 @@ #: routing). Only integrations that support dynamic credentials appear here — #: Arize-Phoenix/Langtrace/Levo/AgentOps don't, so they use the logger's #: default tracer. -DYNAMIC_HEADERS_BY_CALLBACK: dict[ - str, Callable[[StandardCallbackDynamicParams], dict[str, str]] -] = { +DYNAMIC_HEADERS_BY_CALLBACK: dict[str, Callable[[StandardCallbackDynamicParams], dict[str, str]]] = { "arize": arize_dynamic_headers, "langfuse_otel": langfuse_dynamic_headers, "weave_otel": weave_dynamic_headers, diff --git a/litellm/integrations/otel/presets/agentops.py b/litellm/integrations/otel/presets/agentops.py index 7b0783935acb..048b63c89fb0 100644 --- a/litellm/integrations/otel/presets/agentops.py +++ b/litellm/integrations/otel/presets/agentops.py @@ -23,7 +23,7 @@ ) from litellm.integrations.otel.plumbing.providers import register_exporter_factory -_AGENTOPS_ENDPOINT = "https://otlp.agentops.cloud/v1/traces" +_AGENTOPS_ENDPOINT = "https://otlp.agentops.ai/v1/traces" _AGENTOPS_AUTH_ENDPOINT = "https://api.agentops.ai/v3/auth/token" _AGENTOPS_EXPORTER_KIND = "agentops" @@ -32,12 +32,8 @@ class _AgentOpsSettings(BaseSettings): model_config = SettingsConfigDict(case_sensitive=False, extra="ignore") api_key: str | None = Field(default=None, validation_alias="AGENTOPS_API_KEY") - service_name: str = Field( - default="agentops", validation_alias="AGENTOPS_SERVICE_NAME" - ) - environment: str | None = Field( - default=None, validation_alias="AGENTOPS_ENVIRONMENT" - ) + service_name: str = Field(default="agentops", validation_alias="AGENTOPS_SERVICE_NAME") + environment: str | None = Field(default=None, validation_alias="AGENTOPS_ENVIRONMENT") def agentops_preset( @@ -60,9 +56,7 @@ def agentops_preset( ExporterSpec( kind=_AGENTOPS_EXPORTER_KIND, endpoint=_AGENTOPS_ENDPOINT, - options=( - {"api_key": settings.api_key} if settings.api_key else None - ), + options=({"api_key": settings.api_key} if settings.api_key else None), owner=ExporterOwner.AGENTOPS, ), ], @@ -70,11 +64,7 @@ def agentops_preset( **base.resource_attributes, "service.name": settings.service_name, "telemetry.sdk.name": "agentops", - **( - {"deployment.environment": settings.environment} - if settings.environment - else {} - ), + **({"deployment.environment": settings.environment} if settings.environment else {}), }, } ) @@ -120,9 +110,7 @@ def export(self, spans: Any) -> Any: return super().export(spans) options = spec.options or {} - return _LazyAuthAgentOpsExporter( - endpoint=spec.endpoint, api_key=options.get("api_key") - ) + return _LazyAuthAgentOpsExporter(endpoint=spec.endpoint, api_key=options.get("api_key")) def _fetch_agentops_jwt(api_key: str) -> dict[str, Any]: diff --git a/litellm/integrations/otel/presets/arize.py b/litellm/integrations/otel/presets/arize.py index b6af88c6b34a..952062056301 100644 --- a/litellm/integrations/otel/presets/arize.py +++ b/litellm/integrations/otel/presets/arize.py @@ -18,9 +18,7 @@ class _ArizeSettings(BaseSettings): # Standard OTLP headers env var, used as the fallback when no Arize # credentials are configured. - otlp_traces_headers: str | None = Field( - default=None, validation_alias="OTEL_EXPORTER_OTLP_TRACES_HEADERS" - ) + otlp_traces_headers: str | None = Field(default=None, validation_alias="OTEL_EXPORTER_OTLP_TRACES_HEADERS") def arize_preset( @@ -44,11 +42,7 @@ def arize_preset( "mapper_names": ensure_mappers(base.mapper_names, "openinference"), "resource_attributes": { **base.resource_attributes, - **( - {"model_id": arize_cfg.project_name} - if arize_cfg.project_name - else {} - ), + **({"model_id": arize_cfg.project_name} if arize_cfg.project_name else {}), }, } ) diff --git a/litellm/integrations/otel/presets/base.py b/litellm/integrations/otel/presets/base.py index b50908e76524..3b9991f86a4c 100644 --- a/litellm/integrations/otel/presets/base.py +++ b/litellm/integrations/otel/presets/base.py @@ -20,6 +20,4 @@ class Preset(Protocol): test-supplied defaults); the factory calls presets with no arguments. """ - def __call__( - self, *, config_overrides: OpenTelemetryV2Config | None = None - ) -> OpenTelemetryV2Config: ... + def __call__(self, *, config_overrides: OpenTelemetryV2Config | None = None) -> OpenTelemetryV2Config: ... diff --git a/litellm/integrations/otel/presets/phoenix.py b/litellm/integrations/otel/presets/phoenix.py index 5485b5993217..4e7be2c0f515 100644 --- a/litellm/integrations/otel/presets/phoenix.py +++ b/litellm/integrations/otel/presets/phoenix.py @@ -19,9 +19,7 @@ class _PhoenixSettings(BaseSettings): project_name: str = Field( default="default", - validation_alias=AliasChoices( - "PHOENIX_PROJECT_NAME", "PHOENIX_COLLECTOR_PROJECT_NAME" - ), + validation_alias=AliasChoices("PHOENIX_PROJECT_NAME", "PHOENIX_COLLECTOR_PROJECT_NAME"), ) diff --git a/litellm/integrations/posthog.py b/litellm/integrations/posthog.py index 072ae4945a0f..e519736e1627 100644 --- a/litellm/integrations/posthog.py +++ b/litellm/integrations/posthog.py @@ -49,16 +49,12 @@ def __init__(self, **kwargs): self.is_mock_mode = should_use_posthog_mock() if self.is_mock_mode: create_mock_posthog_client() - verbose_logger.debug( - "[POSTHOG MOCK] PostHog logger initialized in mock mode" - ) + verbose_logger.debug("[POSTHOG MOCK] PostHog logger initialized in mock mode") if os.getenv("POSTHOG_API_KEY", None) is None: raise Exception("POSTHOG_API_KEY is not set, set 'POSTHOG_API_KEY=<>'") - self.async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.sync_client = _get_httpx_client() self.POSTHOG_API_KEY = os.getenv("POSTHOG_API_KEY") @@ -73,21 +69,15 @@ def __init__(self, **kwargs): # Register cleanup handler to flush internal queue on exit atexit.register(self._flush_on_exit) - super().__init__( - **kwargs, flush_lock=None, batch_size=POSTHOG_MAX_BATCH_SIZE - ) + super().__init__(**kwargs, flush_lock=None, batch_size=POSTHOG_MAX_BATCH_SIZE) except Exception as e: - verbose_logger.exception( - f"PostHog: Got exception on init PostHog client {str(e)}" - ) + verbose_logger.exception(f"PostHog: Got exception on init PostHog client {str(e)}") raise e def log_success_event(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - "PostHog: Sync logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("PostHog: Sync logging - Enters logging function for model %s", kwargs) api_key, api_url = self._get_credentials_for_request(kwargs) if api_key is None or api_url is None: @@ -109,9 +99,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): response.raise_for_status() if response.status_code != 200: - raise Exception( - f"Response from PostHog API status_code: {response.status_code}, text: {response.text}" - ) + raise Exception(f"Response from PostHog API status_code: {response.status_code}, text: {response.text}") if self.is_mock_mode: verbose_logger.debug("[POSTHOG MOCK] Sync event successfully mocked") @@ -123,9 +111,7 @@ def log_success_event(self, kwargs, response_obj, start_time, end_time): async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - "PostHog: Async logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("PostHog: Async logging - Enters logging function for model %s", kwargs) self._ensure_async_setup() # Lazy initialization await self._log_async_event(kwargs, response_obj, start_time, end_time) except Exception as e: @@ -134,36 +120,26 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - "PostHog: Async logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("PostHog: Async logging - Enters logging function for model %s", kwargs) self._ensure_async_setup() # Lazy initialization await self._log_async_event(kwargs, response_obj, start_time, end_time) except Exception as e: verbose_logger.exception(f"PostHog Layer Error - {str(e)}") pass - async def _log_async_event( - self, kwargs, response_obj=None, start_time=0.0, end_time=0.0 - ): + async def _log_async_event(self, kwargs, response_obj=None, start_time=0.0, end_time=0.0): # Note: response_obj, start_time, end_time not used - all data comes from kwargs api_key, api_url = self._get_credentials_for_request(kwargs) event_payload = self.create_posthog_event_payload(kwargs) # Store event with its credentials for batch sending - self.log_queue.append( - {"event": event_payload, "api_key": api_key, "api_url": api_url} - ) - verbose_logger.debug( - f"PostHog, event added to queue. Will flush in {self.flush_interval} seconds..." - ) + self.log_queue.append({"event": event_payload, "api_key": api_key, "api_url": api_url}) + verbose_logger.debug(f"PostHog, event added to queue. Will flush in {self.flush_interval} seconds...") if len(self.log_queue) >= self.batch_size: await self.flush_queue() - def create_posthog_event_payload( - self, kwargs: Dict[str, Any] - ) -> PostHogEventPayload: + def create_posthog_event_payload(self, kwargs: Dict[str, Any]) -> PostHogEventPayload: """ Helper function to create a PostHog event payload for logging @@ -173,9 +149,7 @@ def create_posthog_event_payload( Returns: PostHogEventPayload: defined in types.py """ - standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object", None - ) + standard_logging_object: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object", None) if standard_logging_object is None: raise ValueError("standard_logging_object not found in kwargs") @@ -207,9 +181,7 @@ def _create_posthog_properties( # Core model information properties["$ai_model"] = self._safe_get(standard_logging_object, "model", "") - properties["$ai_provider"] = self._safe_get( - standard_logging_object, "custom_llm_provider", "" - ) + properties["$ai_provider"] = self._safe_get(standard_logging_object, "custom_llm_provider", "") # Input/Output data messages = self._safe_get(standard_logging_object, "messages") @@ -222,22 +194,16 @@ def _create_posthog_properties( properties["$ai_output_choices"] = response # Token information - properties["$ai_input_tokens"] = self._safe_get( - standard_logging_object, "prompt_tokens", 0 - ) + properties["$ai_input_tokens"] = self._safe_get(standard_logging_object, "prompt_tokens", 0) if event_name == "$ai_generation": - properties["$ai_output_tokens"] = self._safe_get( - standard_logging_object, "completion_tokens", 0 - ) + properties["$ai_output_tokens"] = self._safe_get(standard_logging_object, "completion_tokens", 0) # Cost and performance response_cost = self._safe_get(standard_logging_object, "response_cost") if response_cost is not None: properties["$ai_total_cost_usd"] = response_cost - properties["$ai_latency"] = self._safe_get( - standard_logging_object, "response_time", 0.0 - ) + properties["$ai_latency"] = self._safe_get(standard_logging_object, "response_time", 0.0) # Error handling if self._safe_get(standard_logging_object, "status") == "failure": @@ -257,9 +223,7 @@ def _create_posthog_properties( def _add_trace_properties(self, properties: Dict[str, Any], kwargs: Dict[str, Any]): standard_logging_object = self._safe_get(kwargs, "standard_logging_object", {}) - trace_id = self._safe_get( - standard_logging_object, "trace_id", self._safe_uuid() - ) + trace_id = self._safe_get(standard_logging_object, "trace_id", self._safe_uuid()) properties["$ai_trace_id"] = trace_id span_id = self._safe_get(standard_logging_object, "id", self._safe_uuid()) @@ -270,9 +234,7 @@ def _add_trace_properties(self, properties: Dict[str, Any], kwargs: Dict[str, An if parent_id: properties["$ai_parent_id"] = parent_id - def _add_custom_metadata_properties( - self, properties: Dict[str, Any], kwargs: Dict[str, Any] - ): + def _add_custom_metadata_properties(self, properties: Dict[str, Any], kwargs: Dict[str, Any]): """Add custom metadata fields to PostHog properties""" metadata = self._extract_metadata(kwargs) if not isinstance(metadata, dict): @@ -318,9 +280,7 @@ def _add_custom_metadata_properties( if key not in litellm_internal_fields: properties[key] = value - def _get_distinct_id( - self, standard_logging_object: StandardLoggingPayload, kwargs: Dict[str, Any] - ) -> str: + def _get_distinct_id(self, standard_logging_object: StandardLoggingPayload, kwargs: Dict[str, Any]) -> str: metadata = self._extract_metadata(kwargs) user_id = self._safe_get(metadata, "user_id") if user_id: @@ -334,9 +294,7 @@ def _get_distinct_id( return self._safe_uuid() - def _get_credentials_for_request( - self, kwargs: Dict[str, Any] - ) -> Tuple[Optional[str], Optional[str]]: + def _get_credentials_for_request(self, kwargs: Dict[str, Any]) -> Tuple[Optional[str], Optional[str]]: """ Get PostHog credentials for this request. @@ -349,19 +307,13 @@ def _get_credentials_for_request( Returns: tuple[str, str]: (api_key, api_url) """ - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - kwargs.get("standard_callback_dynamic_params", None) + standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = kwargs.get( + "standard_callback_dynamic_params", None ) if standard_callback_dynamic_params is not None: - api_key = ( - standard_callback_dynamic_params.get("posthog_api_key") - or self.POSTHOG_API_KEY - ) - api_url = ( - standard_callback_dynamic_params.get("posthog_api_url") - or self.posthog_host - ) + api_key = standard_callback_dynamic_params.get("posthog_api_key") or self.POSTHOG_API_KEY + api_url = standard_callback_dynamic_params.get("posthog_api_url") or self.posthog_host else: api_key = self.POSTHOG_API_KEY api_url = self.posthog_host @@ -379,14 +331,10 @@ async def async_send_batch(self): if not self.log_queue: return - verbose_logger.debug( - f"PostHog: Sending batch of {len(self.log_queue)} events" - ) + verbose_logger.debug(f"PostHog: Sending batch of {len(self.log_queue)} events") if self.is_mock_mode: - verbose_logger.debug( - "[POSTHOG MOCK] Mock mode enabled - API calls will be intercepted" - ) + verbose_logger.debug("[POSTHOG MOCK] Mock mode enabled - API calls will be intercepted") # Group events by credentials for batch sending batches_by_credentials: Dict[tuple[str, str], list] = {} @@ -418,13 +366,9 @@ async def async_send_batch(self): ) if self.is_mock_mode: - verbose_logger.debug( - f"[POSTHOG MOCK] Batch of {len(self.log_queue)} events successfully mocked" - ) + verbose_logger.debug(f"[POSTHOG MOCK] Batch of {len(self.log_queue)} events successfully mocked") else: - verbose_logger.debug( - f"PostHog: Batch of {len(self.log_queue)} events successfully sent" - ) + verbose_logger.debug(f"PostHog: Batch of {len(self.log_queue)} events successfully sent") except Exception as e: verbose_logger.exception(f"PostHog Error sending batch API - {str(e)}") @@ -436,9 +380,7 @@ def _ensure_async_setup(self): self._async_initialized = True verbose_logger.debug("PostHog: Async components initialized") except Exception as e: - verbose_logger.error( - f"PostHog: Failed to initialize async components: {str(e)}" - ) + verbose_logger.error(f"PostHog: Failed to initialize async components: {str(e)}") raise def _extract_metadata(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: @@ -469,9 +411,7 @@ def _flush_on_exit(self): if not self.log_queue: return - verbose_logger.debug( - f"PostHog: Flushing {len(self.log_queue)} remaining events on exit" - ) + verbose_logger.debug(f"PostHog: Flushing {len(self.log_queue)} remaining events on exit") try: # Group events by credentials (same logic as async_send_batch) @@ -499,18 +439,12 @@ def _flush_on_exit(self): response.raise_for_status() if response.status_code != 200: - verbose_logger.error( - f"PostHog: Failed to flush on exit - status {response.status_code}" - ) + verbose_logger.error(f"PostHog: Failed to flush on exit - status {response.status_code}") if self.is_mock_mode: - verbose_logger.debug( - f"[POSTHOG MOCK] Successfully flushed {len(self.log_queue)} events on exit" - ) + verbose_logger.debug(f"[POSTHOG MOCK] Successfully flushed {len(self.log_queue)} events on exit") else: - verbose_logger.debug( - f"PostHog: Successfully flushed {len(self.log_queue)} events on exit" - ) + verbose_logger.debug(f"PostHog: Successfully flushed {len(self.log_queue)} events on exit") self.log_queue.clear() except Exception as e: diff --git a/litellm/integrations/posthog_mock_client.py b/litellm/integrations/posthog_mock_client.py index de085b855ce8..3efaabb9f483 100644 --- a/litellm/integrations/posthog_mock_client.py +++ b/litellm/integrations/posthog_mock_client.py @@ -30,6 +30,4 @@ patch_sync_client=True, ) -create_mock_posthog_client, should_use_posthog_mock = create_mock_client_factory( - _config -) +create_mock_posthog_client, should_use_posthog_mock = create_mock_client_factory(_config) diff --git a/litellm/integrations/prometheus.py b/litellm/integrations/prometheus.py index 18fb5d9491e1..b517cb0c38d7 100644 --- a/litellm/integrations/prometheus.py +++ b/litellm/integrations/prometheus.py @@ -100,11 +100,7 @@ def __init__( self._cached_metric_labels: Dict[str, List[str]] = {} _custom_buckets = litellm.prometheus_latency_buckets - self.latency_buckets = ( - tuple(_custom_buckets) - if _custom_buckets is not None - else LATENCY_BUCKETS - ) + self.latency_buckets = tuple(_custom_buckets) if _custom_buckets is not None else LATENCY_BUCKETS self._bounded_prometheus_series_tracker = BoundedPrometheusSeriesTracker() # Create metric factory functions @@ -115,26 +111,20 @@ def __init__( self.litellm_proxy_failed_requests_metric = self._counter_factory( name="litellm_proxy_failed_requests_metric", documentation="Total number of failed responses from proxy - the client did not get a success response from litellm proxy", - labelnames=self.get_labels_for_metric( - "litellm_proxy_failed_requests_metric" - ), + labelnames=self.get_labels_for_metric("litellm_proxy_failed_requests_metric"), ) self.litellm_proxy_total_requests_metric = self._counter_factory( name="litellm_proxy_total_requests_metric", documentation="Total number of requests made to the proxy server - track number of client side requests", - labelnames=self.get_labels_for_metric( - "litellm_proxy_total_requests_metric" - ), + labelnames=self.get_labels_for_metric("litellm_proxy_total_requests_metric"), ) # request latency metrics self.litellm_request_total_latency_metric = self._histogram_factory( "litellm_request_total_latency_metric", "Total latency (seconds) for a request to LiteLLM", - labelnames=self.get_labels_for_metric( - "litellm_request_total_latency_metric" - ), + labelnames=self.get_labels_for_metric("litellm_request_total_latency_metric"), buckets=self.latency_buckets, ) @@ -155,9 +145,7 @@ def __init__( # "team", # "team_alias", # ], - labelnames=self.get_labels_for_metric( - "litellm_llm_api_time_to_first_token_metric" - ), + labelnames=self.get_labels_for_metric("litellm_llm_api_time_to_first_token_metric"), buckets=self.latency_buckets, ) @@ -197,50 +185,38 @@ def __init__( self.litellm_input_cached_tokens_metric = self._counter_factory( "litellm_input_cached_tokens_metric", "Provider-side cached input tokens (e.g. OpenAI prompt_tokens_details.cached_tokens, Anthropic cache_read_input_tokens)", - labelnames=self.get_labels_for_metric( - "litellm_input_cached_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_input_cached_tokens_metric"), ) self.litellm_input_cache_creation_tokens_metric = self._counter_factory( "litellm_input_cache_creation_tokens_metric", "Provider-side input tokens written to prompt cache (e.g. Anthropic cache_creation_input_tokens)", - labelnames=self.get_labels_for_metric( - "litellm_input_cache_creation_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_input_cache_creation_tokens_metric"), ) self.litellm_input_audio_tokens_metric = self._counter_factory( "litellm_input_audio_tokens_metric", "Audio input tokens reported in prompt_tokens_details.audio_tokens", - labelnames=self.get_labels_for_metric( - "litellm_input_audio_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_input_audio_tokens_metric"), ) self.litellm_output_reasoning_tokens_metric = self._counter_factory( "litellm_output_reasoning_tokens_metric", "Reasoning tokens reported in completion_tokens_details.reasoning_tokens", - labelnames=self.get_labels_for_metric( - "litellm_output_reasoning_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_output_reasoning_tokens_metric"), ) self.litellm_output_audio_tokens_metric = self._counter_factory( "litellm_output_audio_tokens_metric", "Audio output tokens reported in completion_tokens_details.audio_tokens", - labelnames=self.get_labels_for_metric( - "litellm_output_audio_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_output_audio_tokens_metric"), ) # Remaining Budget for Team self.litellm_remaining_team_budget_metric = self._gauge_factory( "litellm_remaining_team_budget_metric", "Remaining budget for team", - labelnames=self.get_labels_for_metric( - "litellm_remaining_team_budget_metric" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_team_budget_metric"), ) # Max Budget for Team @@ -254,18 +230,21 @@ def __init__( self.litellm_team_budget_remaining_hours_metric = self._gauge_factory( "litellm_team_budget_remaining_hours_metric", "Remaining days for team budget to be reset", - labelnames=self.get_labels_for_metric( - "litellm_team_budget_remaining_hours_metric" - ), + labelnames=self.get_labels_for_metric("litellm_team_budget_remaining_hours_metric"), + ) + + # Number of members in a team + self.litellm_team_members_metric = self._gauge_factory( + "litellm_team_members_metric", + "Number of members in a team", + labelnames=self.get_labels_for_metric("litellm_team_members_metric"), ) # Remaining Budget for Org self.litellm_remaining_org_budget_metric = self._gauge_factory( "litellm_remaining_org_budget_metric", "Remaining budget for org", - labelnames=self.get_labels_for_metric( - "litellm_remaining_org_budget_metric" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_org_budget_metric"), ) # Max Budget for Org @@ -279,44 +258,34 @@ def __init__( self.litellm_org_budget_remaining_hours_metric = self._gauge_factory( "litellm_org_budget_remaining_hours_metric", "Remaining hours for org budget to be reset", - labelnames=self.get_labels_for_metric( - "litellm_org_budget_remaining_hours_metric" - ), + labelnames=self.get_labels_for_metric("litellm_org_budget_remaining_hours_metric"), ) # Remaining Budget for API Key self.litellm_remaining_api_key_budget_metric = self._gauge_factory( "litellm_remaining_api_key_budget_metric", "Remaining budget for api key", - labelnames=self.get_labels_for_metric( - "litellm_remaining_api_key_budget_metric" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_api_key_budget_metric"), ) # Max Budget for API Key self.litellm_api_key_max_budget_metric = self._gauge_factory( "litellm_api_key_max_budget_metric", "Maximum budget set for api key", - labelnames=self.get_labels_for_metric( - "litellm_api_key_max_budget_metric" - ), + labelnames=self.get_labels_for_metric("litellm_api_key_max_budget_metric"), ) self.litellm_api_key_budget_remaining_hours_metric = self._gauge_factory( "litellm_api_key_budget_remaining_hours_metric", "Remaining hours for api key budget to be reset", - labelnames=self.get_labels_for_metric( - "litellm_api_key_budget_remaining_hours_metric" - ), + labelnames=self.get_labels_for_metric("litellm_api_key_budget_remaining_hours_metric"), ) # Remaining Budget for User self.litellm_remaining_user_budget_metric = self._gauge_factory( "litellm_remaining_user_budget_metric", "Remaining budget for user", - labelnames=self.get_labels_for_metric( - "litellm_remaining_user_budget_metric" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_user_budget_metric"), ) # Max Budget for User @@ -329,9 +298,7 @@ def __init__( self.litellm_user_budget_remaining_hours_metric = self._gauge_factory( "litellm_user_budget_remaining_hours_metric", "Remaining hours for user budget to be reset", - labelnames=self.get_labels_for_metric( - "litellm_user_budget_remaining_hours_metric" - ), + labelnames=self.get_labels_for_metric("litellm_user_budget_remaining_hours_metric"), ) ######################################## @@ -342,18 +309,14 @@ def __init__( self.litellm_remaining_api_key_requests_for_model = self._gauge_factory( "litellm_remaining_api_key_requests_for_model", "Remaining Requests API Key can make for model (model based rpm limit on key)", - labelnames=self.get_labels_for_metric( - "litellm_remaining_api_key_requests_for_model" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_api_key_requests_for_model"), ) # Remaining MODEL TPM limit for API Key self.litellm_remaining_api_key_tokens_for_model = self._gauge_factory( "litellm_remaining_api_key_tokens_for_model", "Remaining Tokens API Key can make for model (model based tpm limit on key)", - labelnames=self.get_labels_for_metric( - "litellm_remaining_api_key_tokens_for_model" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_api_key_tokens_for_model"), ) ######################################## @@ -364,25 +327,19 @@ def __init__( self.litellm_remaining_requests_metric = self._gauge_factory( "litellm_remaining_requests_metric", "LLM Deployment Analytics - remaining requests for model, returned from LLM API Provider", - labelnames=self.get_labels_for_metric( - "litellm_remaining_requests_metric" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_requests_metric"), ) self.litellm_remaining_tokens_metric = self._gauge_factory( "litellm_remaining_tokens_metric", "remaining tokens for model, returned from LLM API Provider", - labelnames=self.get_labels_for_metric( - "litellm_remaining_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_remaining_tokens_metric"), ) self.litellm_overhead_latency_metric = self._histogram_factory( "litellm_overhead_latency_metric", "Latency overhead (milliseconds) added by LiteLLM processing", - labelnames=self.get_labels_for_metric( - "litellm_overhead_latency_metric" - ), + labelnames=self.get_labels_for_metric("litellm_overhead_latency_metric"), buckets=self.latency_buckets, ) @@ -390,9 +347,7 @@ def __init__( self.litellm_request_queue_time_metric = self._histogram_factory( "litellm_request_queue_time_seconds", "Time spent in request queue before processing starts (seconds)", - labelnames=self.get_labels_for_metric( - "litellm_request_queue_time_seconds" - ), + labelnames=self.get_labels_for_metric("litellm_request_queue_time_seconds"), buckets=self.latency_buckets, ) @@ -451,33 +406,25 @@ def __init__( self.litellm_deployment_success_responses = self._counter_factory( name="litellm_deployment_success_responses", documentation="LLM Deployment Analytics - Total number of successful LLM API calls via litellm", - labelnames=self.get_labels_for_metric( - "litellm_deployment_success_responses" - ), + labelnames=self.get_labels_for_metric("litellm_deployment_success_responses"), ) self.litellm_deployment_failure_responses = self._counter_factory( name="litellm_deployment_failure_responses", documentation="LLM Deployment Analytics - Total number of failed LLM API calls for a specific LLM deploymeny. exception_status is the status of the exception from the llm api", - labelnames=self.get_labels_for_metric( - "litellm_deployment_failure_responses" - ), + labelnames=self.get_labels_for_metric("litellm_deployment_failure_responses"), ) self.litellm_deployment_total_requests = self._counter_factory( name="litellm_deployment_total_requests", documentation="LLM Deployment Analytics - Total number of LLM API calls via litellm - success + failure", - labelnames=self.get_labels_for_metric( - "litellm_deployment_total_requests" - ), + labelnames=self.get_labels_for_metric("litellm_deployment_total_requests"), ) # Deployment Latency tracking self.litellm_deployment_latency_per_output_token = self._histogram_factory( name="litellm_deployment_latency_per_output_token", documentation="LLM Deployment Analytics - Latency per output token", - labelnames=self.get_labels_for_metric( - "litellm_deployment_latency_per_output_token" - ), + labelnames=self.get_labels_for_metric("litellm_deployment_latency_per_output_token"), ) self.litellm_deployment_successful_fallbacks = self._counter_factory( @@ -502,9 +449,7 @@ def __init__( self.litellm_llm_api_failed_requests_metric = self._counter_factory( name="litellm_llm_api_failed_requests_metric", documentation="deprecated - use litellm_proxy_failed_requests_metric", - labelnames=self.get_labels_for_metric( - "litellm_llm_api_failed_requests_metric" - ), + labelnames=self.get_labels_for_metric("litellm_llm_api_failed_requests_metric"), ) self.litellm_requests_metric = self._counter_factory( @@ -536,17 +481,13 @@ def __init__( self.litellm_provider_cache_read_input_tokens_metric = self._counter_factory( name="litellm_provider_cache_read_input_tokens_metric", documentation="Total prompt/input tokens read from provider prompt cache (e.g. OpenAI/Anthropic/Gemini/Bedrock)", - labelnames=self.get_labels_for_metric( - "litellm_provider_cache_read_input_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_provider_cache_read_input_tokens_metric"), ) self.litellm_provider_cache_creation_input_tokens_metric = self._counter_factory( name="litellm_provider_cache_creation_input_tokens_metric", documentation="Total prompt/input tokens written to provider prompt cache (e.g. Anthropic/Bedrock)", - labelnames=self.get_labels_for_metric( - "litellm_provider_cache_creation_input_tokens_metric" - ), + labelnames=self.get_labels_for_metric("litellm_provider_cache_creation_input_tokens_metric"), ) # User and Team count metrics @@ -667,9 +608,7 @@ def _parse_prometheus_config(self) -> Dict[str, List[str]]: if validation_results.has_errors: self._pretty_print_validation_errors(validation_results) - error_message = "Configuration validation failed:\n" + "\n".join( - validation_results.all_error_messages - ) + error_message = "Configuration validation failed:\n" + "\n".join(validation_results.all_error_messages) raise ValueError(error_message) # Build label filters from valid configurations @@ -694,17 +633,13 @@ def _validate_all_configurations(self, parsed_configs: List) -> ValidationResult # Validate labels if provided if config.include_labels: - label_error = self._validate_single_metric_labels( - metric_name, config.include_labels - ) + label_error = self._validate_single_metric_labels(metric_name, config.include_labels) if label_error: label_errors.append(label_error) return ValidationResults(metric_errors=metric_errors, label_errors=label_errors) - def _validate_single_metric_name( - self, metric_name: str - ) -> Optional[MetricValidationError]: + def _validate_single_metric_name(self, metric_name: str) -> Optional[MetricValidationError]: """Validate a single metric name""" from typing import get_args @@ -715,16 +650,12 @@ def _validate_single_metric_name( ) return None - def _validate_single_metric_labels( - self, metric_name: str, labels: List[str] - ) -> Optional[LabelValidationError]: + def _validate_single_metric_labels(self, metric_name: str, labels: List[str]) -> Optional[LabelValidationError]: """Validate labels for a single metric""" from typing import cast # Get valid labels for this metric from PrometheusMetricLabels - valid_labels = PrometheusMetricLabels.get_labels( - cast(DEFINED_PROMETHEUS_METRICS, metric_name) - ) + valid_labels = PrometheusMetricLabels.get_labels(cast(DEFINED_PROMETHEUS_METRICS, metric_name)) # Find invalid labels invalid_labels = [label for label in labels if label not in valid_labels] @@ -771,9 +702,7 @@ def _validate_configured_metric_labels(self, metric_name: str, labels: List[str] # Pretty print functions ######################################################### - def _pretty_print_validation_errors( - self, validation_results: ValidationResults - ) -> None: + def _pretty_print_validation_errors(self, validation_results: ValidationResults) -> None: """Pretty print all validation errors using rich""" try: from rich.console import Console @@ -792,12 +721,8 @@ def _pretty_print_validation_errors( # Show invalid metric names if any if validation_results.metric_errors: - invalid_metrics = [ - e.metric_name for e in validation_results.metric_errors - ] - valid_metrics = validation_results.metric_errors[ - 0 - ].valid_metrics # All should have same valid metrics + invalid_metrics = [e.metric_name for e in validation_results.metric_errors] + valid_metrics = validation_results.metric_errors[0].valid_metrics # All should have same valid metrics metrics_error_text = Text( f"Invalid Metric Names: {', '.join(invalid_metrics)}", @@ -812,9 +737,7 @@ def _pretty_print_validation_errors( title_justify="left", border_style="green", ) - metrics_table.add_column( - "Available Metrics", style="cyan", no_wrap=True - ) + metrics_table.add_column("Available Metrics", style="cyan", no_wrap=True) for metric in sorted(valid_metrics): metrics_table.add_row(metric) @@ -896,9 +819,7 @@ def _pretty_print_invalid_labels_error( f"Invalid labels for metric '{metric_name}': {invalid_labels}. Valid labels: {sorted(valid_labels)}" ) - def _pretty_print_invalid_metric_error( - self, invalid_metric_name: str, valid_metrics: tuple - ) -> None: + def _pretty_print_invalid_metric_error(self, invalid_metric_name: str, valid_metrics: tuple) -> None: """Pretty print error message for invalid metric name using rich""" try: from rich.console import Console @@ -935,9 +856,7 @@ def _pretty_print_invalid_metric_error( except ImportError: # Fallback to simple logging if rich is not available - verbose_logger.error( - f"Invalid metric name: {invalid_metric_name}. Valid metrics: {sorted(valid_metrics)}" - ) + verbose_logger.error(f"Invalid metric name: {invalid_metric_name}. Valid metrics: {sorted(valid_metrics)}") ######################################################### # End of pretty print functions @@ -954,9 +873,7 @@ def _valid_metric_name(self, metric_name: str): ) raise ValueError(error.message) - def _pretty_print_prometheus_config( - self, label_filters: Dict[str, List[str]] - ) -> None: + def _pretty_print_prometheus_config(self, label_filters: Dict[str, List[str]]) -> None: """Pretty print the processed prometheus configuration using rich""" try: from rich.console import Console @@ -982,9 +899,7 @@ def _pretty_print_prometheus_config( for metric in sorted(self.enabled_metrics): metrics_table.add_row(metric) else: - metrics_table.add_row( - "[yellow]All metrics enabled (no filter applied)[/yellow]" - ) + metrics_table.add_row("[yellow]All metrics enabled (no filter applied)[/yellow]") # Create label filters table labels_table = Table( @@ -998,11 +913,7 @@ def _pretty_print_prometheus_config( if label_filters: for metric_name, labels in sorted(label_filters.items()): - labels_str = ( - ", ".join(labels) - if labels - else "[dim]No labels specified[/dim]" - ) + labels_str = ", ".join(labels) if labels else "[dim]No labels specified[/dim]" labels_table.add_row(metric_name, labels_str) else: labels_table.add_row( @@ -1050,9 +961,7 @@ def factory(*args, **kwargs): return factory - def get_labels_for_metric( - self, metric_name: DEFINED_PROMETHEUS_METRICS - ) -> List[str]: + def get_labels_for_metric(self, metric_name: DEFINED_PROMETHEUS_METRICS) -> List[str]: """ Get the labels for a metric, filtered if configured. @@ -1081,9 +990,7 @@ def get_labels_for_metric( configured_labels = self.label_filters[metric_name] # Return intersection of configured and default labels to ensure we only use valid labels - filtered_labels = [ - label for label in default_labels if label in configured_labels - ] + filtered_labels = [label for label in default_labels if label in configured_labels] self._cached_metric_labels[metric_name] = filtered_labels return filtered_labels @@ -1146,20 +1053,12 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti ) # unpack kwargs - standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( - "standard_logging_object" - ) + standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get("standard_logging_object") - if standard_logging_payload is None or not isinstance( - standard_logging_payload, dict - ): - raise ValueError( - f"standard_logging_object is required, got={standard_logging_payload}" - ) + if standard_logging_payload is None or not isinstance(standard_logging_payload, dict): + raise ValueError(f"standard_logging_object is required, got={standard_logging_payload}") - if self._should_skip_metrics_for_invalid_key( - kwargs=kwargs, standard_logging_payload=standard_logging_payload - ): + if self._should_skip_metrics_for_invalid_key(kwargs=kwargs, standard_logging_payload=standard_logging_payload): return model = kwargs.get("model", "") @@ -1167,31 +1066,21 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti _metadata = litellm_params.get("metadata") or {} get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking() - end_user_id = get_end_user_id_for_cost_tracking( - litellm_params, service_type="prometheus" - ) + end_user_id = get_end_user_id_for_cost_tracking(litellm_params, service_type="prometheus") user_id = standard_logging_payload["metadata"]["user_api_key_user_id"] user_api_key = standard_logging_payload["metadata"]["user_api_key_hash"] user_api_key_alias = standard_logging_payload["metadata"]["user_api_key_alias"] user_api_team = standard_logging_payload["metadata"]["user_api_key_team_id"] - user_api_team_alias = standard_logging_payload["metadata"][ - "user_api_key_team_alias" - ] - user_api_key_org_id = standard_logging_payload["metadata"].get( - "user_api_key_org_id" - ) - user_api_key_org_alias = standard_logging_payload["metadata"].get( - "user_api_key_org_alias" - ) + user_api_team_alias = standard_logging_payload["metadata"]["user_api_key_team_alias"] + user_api_key_org_id = standard_logging_payload["metadata"].get("user_api_key_org_id") + user_api_key_org_alias = standard_logging_payload["metadata"].get("user_api_key_org_alias") output_tokens = standard_logging_payload["completion_tokens"] tokens_used = standard_logging_payload["total_tokens"] response_cost = standard_logging_payload["response_cost"] combined_metadata = _get_combined_custom_metadata_from_standard_logging_payload( standard_logging_payload=standard_logging_payload ) - if standard_logging_payload is not None and isinstance( - standard_logging_payload, dict - ): + if standard_logging_payload is not None and isinstance(standard_logging_payload, dict): _tags = standard_logging_payload["request_tags"] else: _tags = [] @@ -1221,33 +1110,19 @@ async def async_log_success_event(self, kwargs, response_obj, start_time, end_ti api_provider=standard_logging_payload["custom_llm_provider"], exception_status=None, exception_class=None, - custom_metadata_labels=get_custom_labels_from_metadata( - metadata=combined_metadata - ), - route=standard_logging_payload["metadata"].get( - "user_api_key_request_route" - ), + custom_metadata_labels=get_custom_labels_from_metadata(metadata=combined_metadata), + route=standard_logging_payload["metadata"].get("user_api_key_request_route"), client_ip=standard_logging_payload["metadata"].get("requester_ip_address"), user_agent=standard_logging_payload["metadata"].get("user_agent"), - stream=( - str(standard_logging_payload.get("stream")) - if litellm.prometheus_emit_stream_label - else None - ), + stream=(str(standard_logging_payload.get("stream")) if litellm.prometheus_emit_stream_label else None), ) - if ( - user_api_key is not None - and isinstance(user_api_key, str) - and user_api_key.startswith("sk-") - ): + if user_api_key is not None and isinstance(user_api_key, str) and user_api_key.startswith("sk-"): from litellm.proxy.utils import hash_token user_api_key = hash_token(user_api_key) - label_context = PrometheusLabelFactoryContext( - enum_values - ) # amortized per request. + label_context = PrometheusLabelFactoryContext(enum_values) # amortized per request. # increment total LLM requests and spend metric self._increment_top_level_request_and_spend_metrics( @@ -1371,9 +1246,7 @@ def _increment_token_metrics( verbose_logger.debug("prometheus Logging - Enters token metrics function") # token metrics - if standard_logging_payload is not None and isinstance( - standard_logging_payload, dict - ): + if standard_logging_payload is not None and isinstance(standard_logging_payload, dict): _tags = standard_logging_payload["request_tags"] PrometheusLogger._inc_labeled_counter( @@ -1427,9 +1300,7 @@ def _increment_token_detail_metrics( details (most non-OpenAI/Anthropic models). """ metadata = standard_logging_payload.get("metadata") or {} - usage_object = ( - metadata.get("usage_object") if isinstance(metadata, dict) else None - ) + usage_object = metadata.get("usage_object") if isinstance(metadata, dict) else None if not isinstance(usage_object, dict): return @@ -1440,47 +1311,27 @@ def _increment_token_detail_metrics( ( self.litellm_input_cached_tokens_metric, "litellm_input_cached_tokens_metric", - ( - prompt_details.get("cached_tokens") - if isinstance(prompt_details, dict) - else None - ), + (prompt_details.get("cached_tokens") if isinstance(prompt_details, dict) else None), ), ( self.litellm_input_cache_creation_tokens_metric, "litellm_input_cache_creation_tokens_metric", - ( - prompt_details.get("cache_creation_tokens") - if isinstance(prompt_details, dict) - else None - ), + (prompt_details.get("cache_creation_tokens") if isinstance(prompt_details, dict) else None), ), ( self.litellm_input_audio_tokens_metric, "litellm_input_audio_tokens_metric", - ( - prompt_details.get("audio_tokens") - if isinstance(prompt_details, dict) - else None - ), + (prompt_details.get("audio_tokens") if isinstance(prompt_details, dict) else None), ), ( self.litellm_output_reasoning_tokens_metric, "litellm_output_reasoning_tokens_metric", - ( - completion_details.get("reasoning_tokens") - if isinstance(completion_details, dict) - else None - ), + (completion_details.get("reasoning_tokens") if isinstance(completion_details, dict) else None), ), ( self.litellm_output_audio_tokens_metric, "litellm_output_audio_tokens_metric", - ( - completion_details.get("audio_tokens") - if isinstance(completion_details, dict) - else None - ), + (completion_details.get("audio_tokens") if isinstance(completion_details, dict) else None), ), ] @@ -1549,9 +1400,7 @@ def _increment_cache_metrics( # Provider prompt caching metrics are independent of LiteLLM cache_hit. provider_cache_read_tokens = 0 provider_cache_creation_tokens = 0 - usage_obj = (standard_logging_payload.get("metadata", {}) or {}).get( - "usage_object" - ) + usage_obj = (standard_logging_payload.get("metadata", {}) or {}).get("usage_object") if isinstance(usage_obj, dict): # Prefer explicit provider cache fields when available. _read = usage_obj.get("cache_read_input_tokens") @@ -1689,9 +1538,7 @@ def _set_virtual_key_rate_limit_metrics( # Set remaining rpm/tpm for API Key + model # see parallel_request_limiter.py - variables are set there model_group = get_model_group_from_litellm_kwargs(kwargs) - remaining_requests_variable_name = ( - f"litellm-key-remaining-requests-{model_group}" - ) + remaining_requests_variable_name = f"litellm-key-remaining-requests-{model_group}" remaining_tokens_variable_name = f"litellm-key-remaining-tokens-{model_group}" remaining_requests = metadata.get(remaining_requests_variable_name) @@ -1714,26 +1561,18 @@ def _set_virtual_key_rate_limit_metrics( ) label_context = PrometheusLabelFactoryContext(enum_values) requests_labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - "litellm_remaining_api_key_requests_for_model" - ), + supported_enum_labels=self.get_labels_for_metric("litellm_remaining_api_key_requests_for_model"), enum_values=enum_values, label_context=label_context, ) - self.litellm_remaining_api_key_requests_for_model.labels(**requests_labels).set( - remaining_requests - ) + self.litellm_remaining_api_key_requests_for_model.labels(**requests_labels).set(remaining_requests) tokens_labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - "litellm_remaining_api_key_tokens_for_model" - ), + supported_enum_labels=self.get_labels_for_metric("litellm_remaining_api_key_tokens_for_model"), enum_values=enum_values, label_context=label_context, ) - self.litellm_remaining_api_key_tokens_for_model.labels(**tokens_labels).set( - remaining_tokens - ) + self.litellm_remaining_api_key_tokens_for_model.labels(**tokens_labels).set(remaining_tokens) def _set_latency_metrics( self, @@ -1766,9 +1605,7 @@ def _set_latency_metrics( enum_values=enum_values, label_context=label_context, ) - self.litellm_llm_api_time_to_first_token_metric.labels( - **_ttft_labels - ).observe(time_to_first_token_seconds) + self.litellm_llm_api_time_to_first_token_metric.labels(**_ttft_labels).observe(time_to_first_token_seconds) self._track_end_user_metric_series( self.litellm_llm_api_time_to_first_token_metric, "litellm_llm_api_time_to_first_token_metric", @@ -1785,15 +1622,11 @@ def _set_latency_metrics( ) if api_call_total_time_seconds is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_llm_api_latency_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_llm_api_latency_metric"), enum_values=enum_values, label_context=label_context, ) - self.litellm_llm_api_latency_metric.labels(**_labels).observe( - api_call_total_time_seconds - ) + self.litellm_llm_api_latency_metric.labels(**_labels).observe(api_call_total_time_seconds) self._track_end_user_metric_series( self.litellm_llm_api_latency_metric, "litellm_llm_api_latency_metric", @@ -1807,15 +1640,11 @@ def _set_latency_metrics( ) if total_time_seconds is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_request_total_latency_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_request_total_latency_metric"), enum_values=enum_values, label_context=label_context, ) - self.litellm_request_total_latency_metric.labels(**_labels).observe( - total_time_seconds - ) + self.litellm_request_total_latency_metric.labels(**_labels).observe(total_time_seconds) self._track_end_user_metric_series( self.litellm_request_total_latency_metric, "litellm_request_total_latency_metric", @@ -1824,20 +1653,14 @@ def _set_latency_metrics( # request queue time (time from arrival to processing start) _litellm_params = kwargs.get("litellm_params", {}) or {} - queue_time_seconds = (_litellm_params.get("metadata") or {}).get( - "queue_time_seconds" - ) + queue_time_seconds = (_litellm_params.get("metadata") or {}).get("queue_time_seconds") if queue_time_seconds is not None and queue_time_seconds >= 0: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_request_queue_time_seconds" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_request_queue_time_seconds"), enum_values=enum_values, label_context=label_context, ) - self.litellm_request_queue_time_metric.labels(**_labels).observe( - queue_time_seconds - ) + self.litellm_request_queue_time_metric.labels(**_labels).observe(queue_time_seconds) self._track_end_user_metric_series( self.litellm_request_queue_time_metric, "litellm_request_queue_time_seconds", @@ -1850,13 +1673,9 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti list(kwargs.keys()) if isinstance(kwargs, dict) else type(kwargs).__name__, ) - standard_logging_payload: StandardLoggingPayload = kwargs.get( - "standard_logging_object", {} - ) + standard_logging_payload: StandardLoggingPayload = kwargs.get("standard_logging_object", {}) - if self._should_skip_metrics_for_invalid_key( - kwargs=kwargs, standard_logging_payload=standard_logging_payload - ): + if self._should_skip_metrics_for_invalid_key(kwargs=kwargs, standard_logging_payload=standard_logging_payload): return model = kwargs.get("model", "") @@ -1864,19 +1683,13 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti litellm_params = kwargs.get("litellm_params", {}) or {} get_end_user_id_for_cost_tracking = _get_cached_end_user_id_for_cost_tracking() - end_user_id = get_end_user_id_for_cost_tracking( - litellm_params, service_type="prometheus" - ) + end_user_id = get_end_user_id_for_cost_tracking(litellm_params, service_type="prometheus") user_id = standard_logging_payload["metadata"]["user_api_key_user_id"] user_api_key = standard_logging_payload["metadata"]["user_api_key_hash"] user_api_key_alias = standard_logging_payload["metadata"]["user_api_key_alias"] user_api_team = standard_logging_payload["metadata"]["user_api_key_team_id"] - user_api_team_alias = standard_logging_payload["metadata"][ - "user_api_key_team_alias" - ] - user_api_key_org_id = standard_logging_payload["metadata"].get( - "user_api_key_org_id" - ) + user_api_team_alias = standard_logging_payload["metadata"]["user_api_key_team_alias"] + user_api_key_org_id = standard_logging_payload["metadata"].get("user_api_key_org_id") try: enum_values = UserAPIKeyLabelValues( @@ -1906,9 +1719,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti response_cost=0, ) except Exception as e: - verbose_logger.exception( - "prometheus Layer Error(): Exception occured - {}".format(str(e)) - ) + verbose_logger.exception("prometheus Layer Error(): Exception occured - {}".format(str(e))) pass pass @@ -1936,11 +1747,7 @@ def _extract_status_code( status_code = None # Try from enum_values first (most common in our callbacks) - if ( - enum_values - and hasattr(enum_values, "status_code") - and enum_values.status_code - ): + if enum_values and hasattr(enum_values, "status_code") and enum_values.status_code: try: status_code = int(enum_values.status_code) except (ValueError, TypeError): @@ -1948,9 +1755,7 @@ def _extract_status_code( if not status_code and exception: # ProxyException uses 'code' attribute, other exceptions may use 'status_code' - status_code = getattr(exception, "status_code", None) or getattr( - exception, "code", None - ) + status_code = getattr(exception, "status_code", None) or getattr(exception, "code", None) if status_code is not None: try: status_code = int(status_code) @@ -1960,9 +1765,9 @@ def _extract_status_code( if not status_code and kwargs: exception_in_kwargs = kwargs.get("exception") if exception_in_kwargs: - status_code = getattr( - exception_in_kwargs, "status_code", None - ) or getattr(exception_in_kwargs, "code", None) + status_code = getattr(exception_in_kwargs, "status_code", None) or getattr( + exception_in_kwargs, "code", None + ) if status_code is not None: try: status_code = int(status_code) @@ -2086,12 +1891,8 @@ async def async_post_call_failure_hook( proxy_server_request=request_data.get("proxy_server_request", {}), ) _metadata = request_data.get("metadata", {}) or {} - model_id = _metadata.get("model_info", {}).get("id") or request_data.get( - "model_info", {} - ).get("id") - rate_limit_category, rate_limit_type = self._extract_rate_limit_labels( - original_exception - ) + model_id = _metadata.get("model_info", {}).get("id") or request_data.get("model_info", {}).get("id") + rate_limit_category, rate_limit_type = self._extract_rate_limit_labels(original_exception) enum_values = UserAPIKeyLabelValues( end_user=user_api_key_dict.end_user_id, user=user_api_key_dict.user_id, @@ -2113,11 +1914,7 @@ async def async_post_call_failure_hook( client_ip=_metadata.get("requester_ip_address"), user_agent=_metadata.get("user_agent"), model_id=model_id, - stream=( - str(request_data.get("stream")) - if litellm.prometheus_emit_stream_label - else None - ), + stream=(str(request_data.get("stream")) if litellm.prometheus_emit_stream_label else None), ) _label_ctx = PrometheusLabelFactoryContext(enum_values) PrometheusLogger._inc_labeled_counter( @@ -2136,14 +1933,10 @@ async def async_post_call_failure_hook( ) except Exception as e: - verbose_logger.exception( - "prometheus Layer Error(): Exception occured - {}".format(str(e)) - ) + verbose_logger.exception("prometheus Layer Error(): Exception occured - {}".format(str(e))) pass - async def async_post_call_success_hook( - self, data: dict, user_api_key_dict: UserAPIKeyAuth, response - ): + async def async_post_call_success_hook(self, data: dict, user_api_key_dict: UserAPIKeyAuth, response): """ Proxy level tracking - triggered when the proxy responds with a success response to the client @@ -2161,36 +1954,24 @@ def _safe_get(self, obj: Any, key: str, default: Any = None) -> Any: return obj.get(key, default) return getattr(obj, key, default) - def _extract_deployment_failure_label_values( - self, request_kwargs: dict - ) -> Dict[str, Optional[str]]: + def _extract_deployment_failure_label_values(self, request_kwargs: dict) -> Dict[str, Optional[str]]: """ Extract label values for deployment failure metrics from all available sources in request_kwargs. Falls back to litellm_params metadata and user_api_key_auth when standard_logging_payload has None values. """ - standard_logging_payload = ( - request_kwargs.get("standard_logging_object", {}) or {} - ) + standard_logging_payload = request_kwargs.get("standard_logging_object", {}) or {} _litellm_params = request_kwargs.get("litellm_params", {}) or {} _metadata_raw = self._safe_get(standard_logging_payload, "metadata") or {} if isinstance(_metadata_raw, dict): _metadata = _metadata_raw else: _metadata = { - "user_api_key_alias": getattr( - _metadata_raw, "user_api_key_alias", None - ), - "user_api_key_team_id": getattr( - _metadata_raw, "user_api_key_team_id", None - ), - "user_api_key_team_alias": getattr( - _metadata_raw, "user_api_key_team_alias", None - ), + "user_api_key_alias": getattr(_metadata_raw, "user_api_key_alias", None), + "user_api_key_team_id": getattr(_metadata_raw, "user_api_key_team_id", None), + "user_api_key_team_alias": getattr(_metadata_raw, "user_api_key_team_alias", None), "user_api_key_hash": getattr(_metadata_raw, "user_api_key_hash", None), - "requester_ip_address": getattr( - _metadata_raw, "requester_ip_address", None - ), + "requester_ip_address": getattr(_metadata_raw, "requester_ip_address", None), "user_agent": getattr(_metadata_raw, "user_agent", None), } _litellm_params_metadata = _litellm_params.get("metadata", {}) or {} @@ -2239,9 +2020,7 @@ def _get_hashed_api_key() -> Optional[str]: if val is not None: return val if user_api_key_auth is not None: - return getattr(user_api_key_auth, "api_key", None) or getattr( - user_api_key_auth, "api_key_hash", None - ) + return getattr(user_api_key_auth, "api_key", None) or getattr(user_api_key_auth, "api_key_hash", None) return None return { @@ -2249,10 +2028,8 @@ def _get_hashed_api_key() -> Optional[str]: "team": _get_team_id(), "team_alias": _get_team_alias(), "hashed_api_key": _get_hashed_api_key(), - "client_ip": _metadata.get("requester_ip_address") - or _litellm_params_metadata.get("requester_ip_address"), - "user_agent": _metadata.get("user_agent") - or _litellm_params_metadata.get("user_agent"), + "client_ip": _metadata.get("requester_ip_address") or _litellm_params_metadata.get("requester_ip_address"), + "user_agent": _metadata.get("user_agent") or _litellm_params_metadata.get("user_agent"), } def set_llm_deployment_failure_metrics(self, request_kwargs: dict): @@ -2269,9 +2046,7 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): """ try: verbose_logger.debug("setting remaining tokens requests metric") - standard_logging_payload: StandardLoggingPayload = request_kwargs.get( - "standard_logging_object", {} - ) + standard_logging_payload: StandardLoggingPayload = request_kwargs.get("standard_logging_object", {}) _litellm_params = request_kwargs.get("litellm_params", {}) or {} litellm_model_name = request_kwargs.get("model", None) model_group = standard_logging_payload.get("model_group", None) @@ -2290,9 +2065,9 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): # Fallback: model_group from litellm_metadata if model_group is None: - model_group = (_litellm_params.get("litellm_metadata") or {}).get( - "model_group" - ) or (_litellm_params.get("metadata") or {}).get("model_group") + model_group = (_litellm_params.get("litellm_metadata") or {}).get("model_group") or ( + _litellm_params.get("metadata") or {} + ).get("model_group") llm_provider = _litellm_params.get("custom_llm_provider", None) @@ -2303,26 +2078,14 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): return # Extract context labels from all available sources (fix for None labels) - fallback_values = self._extract_deployment_failure_label_values( - request_kwargs - ) + fallback_values = self._extract_deployment_failure_label_values(request_kwargs) _metadata = standard_logging_payload.get("metadata", {}) or {} - hashed_api_key = fallback_values.get("hashed_api_key") or _metadata.get( - "user_api_key_hash" - ) - api_key_alias = fallback_values.get("api_key_alias") or _metadata.get( - "user_api_key_alias" - ) + hashed_api_key = fallback_values.get("hashed_api_key") or _metadata.get("user_api_key_hash") + api_key_alias = fallback_values.get("api_key_alias") or _metadata.get("user_api_key_alias") team = fallback_values.get("team") or _metadata.get("user_api_key_team_id") - team_alias = fallback_values.get("team_alias") or _metadata.get( - "user_api_key_team_alias" - ) - client_ip = fallback_values.get("client_ip") or _metadata.get( - "requester_ip_address" - ) - user_agent = fallback_values.get("user_agent") or _metadata.get( - "user_agent" - ) + team_alias = fallback_values.get("team_alias") or _metadata.get("user_api_key_team_alias") + client_ip = fallback_values.get("client_ip") or _metadata.get("requester_ip_address") + user_agent = fallback_values.get("user_agent") or _metadata.get("user_agent") # exception_status: prefer status_code, fallback to exception class for known types exception_status = None @@ -2355,9 +2118,7 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): api_base=label_api_base, api_provider=label_api_provider, exception_status=exception_status, - exception_class=( - self._get_exception_class_name(exception) if exception else None - ), + exception_class=(self._get_exception_class_name(exception) if exception else None), requested_model=label_requested_model, hashed_api_key=hashed_api_key, api_key_alias=api_key_alias, @@ -2401,9 +2162,7 @@ def set_llm_deployment_failure_metrics(self, request_kwargs: dict): pass except Exception as e: verbose_logger.debug( - "Prometheus Error: set_llm_deployment_failure_metrics. Exception occured - {}".format( - str(e) - ) + "Prometheus Error: set_llm_deployment_failure_metrics. Exception occured - {}".format(str(e)) ) def _set_deployment_tpm_rpm_limit_metrics( @@ -2423,9 +2182,7 @@ def _set_deployment_tpm_rpm_limit_metrics( if tpm is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_deployment_tpm_limit" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_deployment_tpm_limit"), enum_values=UserAPIKeyLabelValues( litellm_model_name=litellm_model_name, model_id=model_id, @@ -2437,9 +2194,7 @@ def _set_deployment_tpm_rpm_limit_metrics( if rpm is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_deployment_rpm_limit" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_deployment_rpm_limit"), enum_values=UserAPIKeyLabelValues( litellm_model_name=litellm_model_name, model_id=model_id, @@ -2469,16 +2224,12 @@ async def _async_set_router_remaining_metrics( deployment. """ try: - additional_headers = ( - standard_logging_payload.get("hidden_params", {}) or {} - ).get("additional_headers") or {} + additional_headers = (standard_logging_payload.get("hidden_params", {}) or {}).get( + "additional_headers" + ) or {} - already_have_tokens = ( - additional_headers.get("x_ratelimit_remaining_tokens") is not None - ) - already_have_requests = ( - additional_headers.get("x_ratelimit_remaining_requests") is not None - ) + already_have_tokens = additional_headers.get("x_ratelimit_remaining_tokens") is not None + already_have_requests = additional_headers.get("x_ratelimit_remaining_requests") is not None if already_have_tokens and already_have_requests: return @@ -2495,13 +2246,10 @@ async def _async_set_router_remaining_metrics( return try: - remaining_usage = await llm_router.get_remaining_model_group_usage( - model_group - ) + remaining_usage = await llm_router.get_remaining_model_group_usage(model_group) except Exception as e: verbose_logger.exception( - "Prometheus: get_remaining_model_group_usage failed for " - "model_group=%s: %s", + "Prometheus: get_remaining_model_group_usage failed for model_group=%s: %s", model_group, e, ) @@ -2515,31 +2263,22 @@ async def _async_set_router_remaining_metrics( if not already_have_tokens and remaining_tokens is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_tokens_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_tokens_metric"), enum_values=enum_values, label_context=label_context, ) - self.litellm_remaining_tokens_metric.labels(**_labels).set( - remaining_tokens - ) + self.litellm_remaining_tokens_metric.labels(**_labels).set(remaining_tokens) if not already_have_requests and remaining_requests is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_requests_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_requests_metric"), enum_values=enum_values, label_context=label_context, ) - self.litellm_remaining_requests_metric.labels(**_labels).set( - remaining_requests - ) + self.litellm_remaining_requests_metric.labels(**_labels).set(remaining_requests) except Exception as e: verbose_logger.exception( - "Prometheus Error: _async_set_router_remaining_metrics. " - "Exception occured - {}".format(str(e)) + "Prometheus Error: _async_set_router_remaining_metrics. Exception occured - {}".format(str(e)) ) def set_llm_deployment_success_metrics( @@ -2553,9 +2292,7 @@ def set_llm_deployment_success_metrics( ): try: verbose_logger.debug("setting remaining tokens requests metric") - standard_logging_payload: Optional[StandardLoggingPayload] = ( - request_kwargs.get("standard_logging_object") - ) + standard_logging_payload: Optional[StandardLoggingPayload] = request_kwargs.get("standard_logging_object") if standard_logging_payload is None: return @@ -2588,24 +2325,14 @@ def set_llm_deployment_success_metrics( remaining_requests: Optional[int] = None remaining_tokens: Optional[int] = None - if additional_headers := standard_logging_payload["hidden_params"][ - "additional_headers" - ]: + if additional_headers := standard_logging_payload["hidden_params"]["additional_headers"]: # OpenAI / OpenAI Compatible headers - remaining_requests = additional_headers.get( - "x_ratelimit_remaining_requests", None - ) - remaining_tokens = additional_headers.get( - "x_ratelimit_remaining_tokens", None - ) + remaining_requests = additional_headers.get("x_ratelimit_remaining_requests", None) + remaining_tokens = additional_headers.get("x_ratelimit_remaining_tokens", None) - if litellm_overhead_time_ms := standard_logging_payload[ - "hidden_params" - ].get("litellm_overhead_time_ms"): + if litellm_overhead_time_ms := standard_logging_payload["hidden_params"].get("litellm_overhead_time_ms"): _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_overhead_latency_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_overhead_latency_metric"), enum_values=enum_values, label_context=label_context, ) @@ -2621,27 +2348,19 @@ def set_llm_deployment_success_metrics( "litellm_model_name" """ _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_requests_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_requests_metric"), enum_values=enum_values, label_context=label_context, ) - self.litellm_remaining_requests_metric.labels(**_labels).set( - remaining_requests - ) + self.litellm_remaining_requests_metric.labels(**_labels).set(remaining_requests) if remaining_tokens: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_tokens_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_tokens_metric"), enum_values=enum_values, label_context=label_context, ) - self.litellm_remaining_tokens_metric.labels(**_labels).set( - remaining_tokens - ) + self.litellm_remaining_tokens_metric.labels(**_labels).set(remaining_tokens) """ log these labels @@ -2673,14 +2392,9 @@ def set_llm_deployment_success_metrics( response_ms: timedelta = end_time - start_time time_to_first_token_response_time: Optional[timedelta] = None - if ( - request_kwargs.get("stream", None) is not None - and request_kwargs["stream"] is True - ): + if request_kwargs.get("stream", None) is not None and request_kwargs["stream"] is True: # only log ttft for streaming request - time_to_first_token_response_time = ( - request_kwargs.get("completion_start_time", end_time) - start_time - ) + time_to_first_token_response_time = request_kwargs.get("completion_start_time", end_time) - start_time # use the metric that is not None # if streaming - use time_to_first_token_response @@ -2699,15 +2413,11 @@ def set_llm_deployment_success_metrics( enum_values=enum_values, label_context=label_context, ) - self.litellm_deployment_latency_per_output_token.labels( - **_labels - ).observe(latency_per_token) + self.litellm_deployment_latency_per_output_token.labels(**_labels).observe(latency_per_token) except Exception as e: verbose_logger.exception( - "Prometheus Error: set_llm_deployment_success_metrics. Exception occured - {}".format( - str(e) - ) + "Prometheus Error: set_llm_deployment_success_metrics. Exception occured - {}".format(str(e)) ) return @@ -2872,9 +2582,7 @@ def record_check_batch_cost_error(self, error_type: str): error_type=error_type, ).inc() except Exception as e: - verbose_logger.warning( - f"Error recording check batch cost error metric: {e}" - ) + verbose_logger.warning(f"Error recording check batch cost error metric: {e}") @staticmethod def _get_exception_class_name(exception: Exception) -> str: @@ -2900,9 +2608,7 @@ def _get_exception_class_name(exception: Exception) -> str: except ImportError: BudgetExceededError = None # type: ignore[assignment,misc] - if BudgetExceededError is not None and isinstance( - exception, BudgetExceededError - ): + if BudgetExceededError is not None and isinstance(exception, BudgetExceededError): return "BudgetExceededError" exception_class_name = "" @@ -2912,9 +2618,7 @@ def _get_exception_class_name(exception: Exception) -> str: # pretty print the provider name on prometheus # eg. `openai` -> `Openai.` if len(exception_class_name) >= 1: - exception_class_name = ( - exception_class_name[0].upper() + exception_class_name[1:] + "." - ) + exception_class_name = exception_class_name[0].upper() + exception_class_name[1:] + "." exception_class_name += exception.__class__.__name__ return exception_class_name @@ -2940,9 +2644,7 @@ def _extract_rate_limit_labels( validate_rate_limit_type(getattr(exception, "rate_limit_type", None)), ) - async def log_success_fallback_event( - self, original_model_group: str, kwargs: dict, original_exception: Exception - ): + async def log_success_fallback_event(self, original_model_group: str, kwargs: dict, original_exception: Exception): """ Logs a successful LLM fallback event on prometheus @@ -2960,10 +2662,8 @@ async def log_success_fallback_event( ) _metadata_key = get_metadata_variable_name_from_kwargs(kwargs) _metadata = kwargs.get(_metadata_key) or {} - standard_metadata: StandardLoggingMetadata = ( - StandardLoggingPayloadSetup.get_standard_logging_metadata( - metadata=_metadata - ) + standard_metadata: StandardLoggingMetadata = StandardLoggingPayloadSetup.get_standard_logging_metadata( + metadata=_metadata ) _new_model = kwargs.get("model") _tags = cast(List[str], kwargs.get("tags") or []) @@ -2987,9 +2687,7 @@ async def log_success_fallback_event( label_context=PrometheusLabelFactoryContext(enum_values), ) - async def log_failure_fallback_event( - self, original_model_group: str, kwargs: dict, original_exception: Exception - ): + async def log_failure_fallback_event(self, original_model_group: str, kwargs: dict, original_exception: Exception): """ Logs a failed LLM fallback event on prometheus """ @@ -3007,10 +2705,8 @@ async def log_failure_fallback_event( _metadata_key = get_metadata_variable_name_from_kwargs(kwargs) _metadata = kwargs.get(_metadata_key) or {} _tags = cast(List[str], kwargs.get("tags") or []) - standard_metadata: StandardLoggingMetadata = ( - StandardLoggingPayloadSetup.get_standard_logging_metadata( - metadata=_metadata - ) + standard_metadata: StandardLoggingMetadata = StandardLoggingPayloadSetup.get_standard_logging_metadata( + metadata=_metadata ) enum_values = UserAPIKeyLabelValues( @@ -3046,9 +2742,7 @@ def set_litellm_deployment_state( """ ### get labels _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_deployment_state" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_deployment_state"), enum_values=UserAPIKeyLabelValues( litellm_model_name=litellm_model_name, model_id=model_id, @@ -3065,9 +2759,7 @@ def set_deployment_healthy( api_base: str, api_provider: str, ): - self.set_litellm_deployment_state( - 0, litellm_model_name, model_id, api_base, api_provider - ) + self.set_litellm_deployment_state(0, litellm_model_name, model_id, api_base, api_provider) def set_deployment_partial_outage( self, @@ -3076,9 +2768,7 @@ def set_deployment_partial_outage( api_base: Optional[str], api_provider: str, ): - self.set_litellm_deployment_state( - 1, litellm_model_name, model_id, api_base, api_provider - ) + self.set_litellm_deployment_state(1, litellm_model_name, model_id, api_base, api_provider) def set_deployment_complete_outage( self, @@ -3087,9 +2777,7 @@ def set_deployment_complete_outage( api_base: Optional[str], api_provider: str, ): - self.set_litellm_deployment_state( - 2, litellm_model_name, model_id, api_base, api_provider - ) + self.set_litellm_deployment_state(2, litellm_model_name, model_id, api_base, api_provider) def increment_deployment_cooled_down( self, @@ -3117,13 +2805,9 @@ def increment_callback_logging_failure( """ Increment metric when logging to a callback fails (e.g., s3_v2, langfuse, etc.) """ - self.litellm_callback_logging_failures_metric.labels( - callback_name=callback_name - ).inc() + self.litellm_callback_logging_failures_metric.labels(callback_name=callback_name).inc() - def track_provider_remaining_budget( - self, provider: str, spend: float, budget_limit: float - ): + def track_provider_remaining_budget(self, provider: str, spend: float, budget_limit: float): """ Track provider remaining budget in Prometheus """ @@ -3134,9 +2818,7 @@ def track_provider_remaining_budget( ) ) - def _safe_get_remaining_budget( - self, max_budget: Optional[float], spend: Optional[float] - ) -> float: + def _safe_get_remaining_budget(self, max_budget: Optional[float], spend: Optional[float]) -> float: if max_budget is None: return float("inf") @@ -3167,9 +2849,7 @@ async def _initialize_budget_metrics( try: page = 1 page_size = 50 - data, total_count = await data_fetch_function( - page_size=page_size, page=page - ) + data, total_count = await data_fetch_function(page_size=page_size, page=page) if total_count is None: total_count = len(data) @@ -3186,9 +2866,7 @@ async def _initialize_budget_metrics( await set_metrics_function(data) except Exception as e: - verbose_logger.exception( - f"Error initializing {data_type} budget metrics: {str(e)}" - ) + verbose_logger.exception(f"Error initializing {data_type} budget metrics: {str(e)}") async def _initialize_team_budget_metrics(self): """ @@ -3200,17 +2878,11 @@ async def _initialize_team_budget_metrics(self): from litellm.proxy.proxy_server import prisma_client if prisma_client is None: - verbose_logger.debug( - "Prometheus: skipping team metrics initialization, DB not initialized" - ) + verbose_logger.debug("Prometheus: skipping team metrics initialization, DB not initialized") return - async def fetch_teams( - page_size: int, page: int - ) -> Tuple[List[LiteLLM_TeamTable], Optional[int]]: - teams, total_count = await get_paginated_teams( - prisma_client=prisma_client, page_size=page_size, page=page - ) + async def fetch_teams(page_size: int, page: int) -> Tuple[List[LiteLLM_TeamTable], Optional[int]]: + teams, total_count = await get_paginated_teams(prisma_client=prisma_client, page_size=page_size, page=page) if total_count is None: total_count = len(teams) return teams, total_count @@ -3232,9 +2904,7 @@ async def _initialize_api_key_budget_metrics(self): from litellm.proxy.proxy_server import prisma_client if prisma_client is None: - verbose_logger.debug( - "Prometheus: skipping key metrics initialization, DB not initialized" - ) + verbose_logger.debug("Prometheus: skipping key metrics initialization, DB not initialized") return async def fetch_keys( @@ -3274,14 +2944,10 @@ async def _initialize_user_budget_metrics(self): from litellm.proxy.proxy_server import prisma_client if prisma_client is None: - verbose_logger.debug( - "Prometheus: skipping user metrics initialization, DB not initialized" - ) + verbose_logger.debug("Prometheus: skipping user metrics initialization, DB not initialized") return - async def fetch_users( - page_size: int, page: int - ) -> Tuple[List[LiteLLM_UserTable], Optional[int]]: + async def fetch_users(page_size: int, page: int) -> Tuple[List[LiteLLM_UserTable], Optional[int]]: skip = (page - 1) * page_size users = await UserRepository(prisma_client).table.find_many( skip=skip, @@ -3304,9 +2970,7 @@ async def _initialize_org_budget_metrics(self): from litellm.proxy.proxy_server import prisma_client if prisma_client is None: - verbose_logger.debug( - "Prometheus: skipping org metrics initialization, DB not initialized" - ) + verbose_logger.debug("Prometheus: skipping org metrics initialization, DB not initialized") return async def fetch_orgs(page_size: int, page: int) -> Tuple[list, Optional[int]]: @@ -3343,15 +3007,11 @@ async def initialize_remaining_budget_metrics(self): # if using redis, ensure only one pod emits the metrics at a time if pod_lock_manager and pod_lock_manager.redis_cache: - if await pod_lock_manager.acquire_lock( - cronjob_id=PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME - ): + if await pod_lock_manager.acquire_lock(cronjob_id=PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME): try: await self._initialize_remaining_budget_metrics() finally: - await pod_lock_manager.release_lock( - cronjob_id=PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME - ) + await pod_lock_manager.release_lock(cronjob_id=PROMETHEUS_EMIT_BUDGET_METRICS_JOB_NAME) else: # if not using redis, initialize the metrics directly await self._initialize_remaining_budget_metrics() @@ -3378,33 +3038,23 @@ async def _initialize_user_and_team_count_metrics(self): from litellm.proxy.proxy_server import prisma_client if prisma_client is None: - verbose_logger.debug( - "Prometheus: skipping user/team count metrics initialization, DB not initialized" - ) + verbose_logger.debug("Prometheus: skipping user/team count metrics initialization, DB not initialized") return try: # Get total user count total_users = await UserRepository(prisma_client).table.count() self.litellm_total_users_metric.set(total_users) - verbose_logger.debug( - f"Prometheus: set litellm_total_users to {total_users}" - ) + verbose_logger.debug(f"Prometheus: set litellm_total_users to {total_users}") # Get total team count total_teams = await TeamRepository(prisma_client).table.count() self.litellm_teams_count_metric.set(total_teams) - verbose_logger.debug( - f"Prometheus: set litellm_teams_count to {total_teams}" - ) + verbose_logger.debug(f"Prometheus: set litellm_teams_count to {total_teams}") except Exception as e: - verbose_logger.exception( - f"Error initializing user/team count metrics: {str(e)}" - ) + verbose_logger.exception(f"Error initializing user/team count metrics: {str(e)}") - async def _set_key_list_budget_metrics( - self, keys: List[Union[str, UserAPIKeyAuth]] - ): + async def _set_key_list_budget_metrics(self, keys: List[Union[str, UserAPIKeyAuth]]): """Helper function to set budget metrics for a list of keys""" for key in keys: if isinstance(key, UserAPIKeyAuth): @@ -3429,11 +3079,7 @@ async def _set_org_list_budget_metrics(self, orgs: list): org_alias=org.organization_alias or "", spend=org.spend or 0.0, max_budget=budget_table.max_budget if budget_table else None, - budget_reset_at=( - getattr(budget_table, "budget_reset_at", None) - if budget_table - else None - ), + budget_reset_at=(getattr(budget_table, "budget_reset_at", None) if budget_table else None), ) async def _set_team_budget_metrics_after_api_request( @@ -3494,9 +3140,7 @@ async def _assemble_team_object( user_api_key_cache=user_api_key_cache, ) except Exception as e: - verbose_logger.debug( - f"[Non-Blocking] Prometheus: Error getting team info: {str(e)}" - ) + verbose_logger.debug(f"[Non-Blocking] Prometheus: Error getting team info: {str(e)}") return team_object if team_info: @@ -3523,9 +3167,7 @@ def _set_team_budget_metrics( ) _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_team_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_team_budget_metric"), enum_values=enum_values, ) self.litellm_remaining_team_budget_metric.labels(**_labels).set( @@ -3537,9 +3179,7 @@ def _set_team_budget_metrics( if team.max_budget is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_team_max_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_team_max_budget_metric"), enum_values=enum_values, ) self.litellm_team_max_budget_metric.labels(**_labels).set(team.max_budget) @@ -3552,11 +3192,21 @@ def _set_team_budget_metrics( enum_values=enum_values, ) self.litellm_team_budget_remaining_hours_metric.labels(**_labels).set( - self._get_remaining_hours_for_budget_reset( - budget_reset_at=team.budget_reset_at - ) + self._get_remaining_hours_for_budget_reset(budget_reset_at=team.budget_reset_at) ) + def set_team_members_metric(self, team: LiteLLM_TeamTable) -> None: + """Set the team members gauge to the team's current member count.""" + enum_values = UserAPIKeyLabelValues( + team=team.team_id, + team_alias=team.team_alias or "", + ) + _labels = prometheus_label_factory( + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_team_members_metric"), + enum_values=enum_values, + ) + self.litellm_team_members_metric.labels(**_labels).set(len(team.members_with_roles)) + async def _set_org_budget_metrics_after_api_request( self, org_id: Optional[str], @@ -3585,9 +3235,7 @@ async def _set_org_budget_metrics_after_api_request( include_budget_table=True, ) except Exception as e: - verbose_logger.debug( - f"[Non-Blocking] Prometheus: Error getting org info: {str(e)}" - ) + verbose_logger.debug(f"[Non-Blocking] Prometheus: Error getting org info: {str(e)}") return if org_info is None: @@ -3597,9 +3245,7 @@ async def _set_org_budget_metrics_after_api_request( _total_org_spend = (org_info.spend or 0.0) + response_cost budget_table = org_info.litellm_budget_table max_budget = budget_table.max_budget if budget_table else None - budget_reset_at = ( - getattr(budget_table, "budget_reset_at", None) if budget_table else None - ) + budget_reset_at = getattr(budget_table, "budget_reset_at", None) if budget_table else None self._set_org_budget_metrics( org_id=org_id, @@ -3630,9 +3276,7 @@ def _set_org_budget_metrics( ) _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_org_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_org_budget_metric"), enum_values=enum_values, ) self.litellm_remaining_org_budget_metric.labels(**_labels).set( @@ -3644,9 +3288,7 @@ def _set_org_budget_metrics( if max_budget is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_org_max_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_org_max_budget_metric"), enum_values=enum_values, ) self.litellm_org_max_budget_metric.labels(**_labels).set(max_budget) @@ -3659,9 +3301,7 @@ def _set_org_budget_metrics( enum_values=enum_values, ) self.litellm_org_budget_remaining_hours_metric.labels(**_labels).set( - self._get_remaining_hours_for_budget_reset( - budget_reset_at=budget_reset_at - ) + self._get_remaining_hours_for_budget_reset(budget_reset_at=budget_reset_at) ) def _set_key_budget_metrics(self, user_api_key_dict: UserAPIKeyAuth): @@ -3677,9 +3317,7 @@ def _set_key_budget_metrics(self, user_api_key_dict: UserAPIKeyAuth): api_key_alias=user_api_key_dict.key_alias or "", ) _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_api_key_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_api_key_budget_metric"), enum_values=enum_values, ) self.litellm_remaining_api_key_budget_metric.labels(**_labels).set( @@ -3691,20 +3329,14 @@ def _set_key_budget_metrics(self, user_api_key_dict: UserAPIKeyAuth): if user_api_key_dict.max_budget is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_api_key_max_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_api_key_max_budget_metric"), enum_values=enum_values, ) - self.litellm_api_key_max_budget_metric.labels(**_labels).set( - user_api_key_dict.max_budget - ) + self.litellm_api_key_max_budget_metric.labels(**_labels).set(user_api_key_dict.max_budget) if user_api_key_dict.budget_reset_at is not None: self.litellm_api_key_budget_remaining_hours_metric.labels(**_labels).set( - self._get_remaining_hours_for_budget_reset( - budget_reset_at=user_api_key_dict.budget_reset_at - ) + self._get_remaining_hours_for_budget_reset(budget_reset_at=user_api_key_dict.budget_reset_at) ) async def _set_api_key_budget_metrics_after_api_request( @@ -3756,9 +3388,7 @@ async def _assemble_key_object( if key_object: user_api_key_dict.budget_reset_at = key_object.budget_reset_at except Exception as e: - verbose_logger.debug( - f"[Non-Blocking] Prometheus: Error getting key info: {str(e)}" - ) + verbose_logger.debug(f"[Non-Blocking] Prometheus: Error getting key info: {str(e)}") return user_api_key_dict @@ -3820,9 +3450,7 @@ async def _assemble_user_object( check_db_only=False, ) except Exception as e: - verbose_logger.debug( - f"[Non-Blocking] Prometheus: Error getting user info: {str(e)}" - ) + verbose_logger.debug(f"[Non-Blocking] Prometheus: Error getting user info: {str(e)}") return user_object if user_info: @@ -3854,9 +3482,7 @@ def _set_user_budget_metrics( ) _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_remaining_user_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_remaining_user_budget_metric"), enum_values=enum_values, ) self.litellm_remaining_user_budget_metric.labels(**_labels).set( @@ -3868,9 +3494,7 @@ def _set_user_budget_metrics( if user.max_budget is not None: _labels = prometheus_label_factory( - supported_enum_labels=self.get_labels_for_metric( - metric_name="litellm_user_max_budget_metric" - ), + supported_enum_labels=self.get_labels_for_metric(metric_name="litellm_user_max_budget_metric"), enum_values=enum_values, ) self.litellm_user_max_budget_metric.labels(**_labels).set(user.max_budget) @@ -3883,18 +3507,14 @@ def _set_user_budget_metrics( enum_values=enum_values, ) self.litellm_user_budget_remaining_hours_metric.labels(**_labels).set( - self._get_remaining_hours_for_budget_reset( - budget_reset_at=user.budget_reset_at - ) + self._get_remaining_hours_for_budget_reset(budget_reset_at=user.budget_reset_at) ) def _get_remaining_hours_for_budget_reset(self, budget_reset_at: datetime) -> float: """ Get remaining hours for budget reset """ - return ( - budget_reset_at - datetime.now(budget_reset_at.tzinfo) - ).total_seconds() / 3600 + return (budget_reset_at - datetime.now(budget_reset_at.tzinfo)).total_seconds() / 3600 def _safe_duration_seconds( self, @@ -3920,10 +3540,8 @@ def initialize_budget_metrics_cron_job(scheduler: AsyncIOScheduler): """ from litellm.constants import PROMETHEUS_BUDGET_METRICS_REFRESH_INTERVAL_MINUTES - prometheus_loggers: List[CustomLogger] = ( - litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=PrometheusLogger - ) + prometheus_loggers: List[CustomLogger] = litellm.logging_callback_manager.get_custom_loggers_for_type( + callback_type=PrometheusLogger ) # we need to get the initialized prometheus logger instance(s) and call logger.initialize_remaining_budget_metrics() on them verbose_logger.debug("found %s prometheus loggers", len(prometheus_loggers)) @@ -3968,9 +3586,7 @@ def _mount_metrics_endpoint(): # Mount the metrics app to the app app.mount("/metrics", metrics_app) - verbose_proxy_logger.debug( - "Starting Prometheus Metrics on /metrics (no authentication)" - ) + verbose_proxy_logger.debug("Starting Prometheus Metrics on /metrics (no authentication)") def _prometheus_labels_from_context( @@ -3978,15 +3594,11 @@ def _prometheus_labels_from_context( ctx: PrometheusLabelFactoryContext, ) -> Dict[str, Optional[str]]: filtered_labels: Dict[str, Optional[str]] = { - label: ctx._sanitized_enum[label] - for label in supported_enum_labels - if label in ctx._sanitized_enum + label: ctx._sanitized_enum[label] for label in supported_enum_labels if label in ctx._sanitized_enum } if UserAPIKeyLabelNames.END_USER.value in filtered_labels: - filtered_labels[UserAPIKeyLabelNames.END_USER.value] = ( - ctx.get_resolved_end_user() - ) + filtered_labels[UserAPIKeyLabelNames.END_USER.value] = ctx.get_resolved_end_user() for sk, val in ctx._custom_by_sanitized_key.items(): if sk in supported_enum_labels: @@ -4020,9 +3632,7 @@ def prometheus_label_factory( """ if label_context is not None: if label_context.enum_values is not enum_values: - raise ValueError( - "label_context.enum_values must be the same object as enum_values" - ) + raise ValueError("label_context.enum_values must be the same object as enum_values") return _prometheus_labels_from_context(supported_enum_labels, label_context) # Extract dictionary from Pydantic object @@ -4111,25 +3721,17 @@ def _get_combined_custom_metadata_from_standard_logging_payload( return {} requester_metadata = standard_logging_metadata.get("requester_metadata") - user_api_key_auth_metadata = standard_logging_metadata.get( - "user_api_key_auth_metadata" - ) + user_api_key_auth_metadata = standard_logging_metadata.get("user_api_key_auth_metadata") spend_logs_metadata = standard_logging_metadata.get("spend_logs_metadata") return { **(requester_metadata if isinstance(requester_metadata, dict) else {}), - **( - user_api_key_auth_metadata - if isinstance(user_api_key_auth_metadata, dict) - else {} - ), + **(user_api_key_auth_metadata if isinstance(user_api_key_auth_metadata, dict) else {}), **(spend_logs_metadata if isinstance(spend_logs_metadata, dict) else {}), } -def _tag_matches_wildcard_configured_pattern( - tags: Sequence[str], configured_tag: str -) -> bool: +def _tag_matches_wildcard_configured_pattern(tags: Sequence[str], configured_tag: str) -> bool: """ Check if any of the request tags matches a wildcard configured pattern @@ -4199,9 +3801,7 @@ def get_custom_labels_from_tags(tags: Sequence[str]) -> Dict[str, str]: continue # Use PatternMatchRouter for wildcard pattern matching - if "*" in configured_tag and _tag_matches_wildcard_configured_pattern( - tags=tags, configured_tag=configured_tag - ): + if "*" in configured_tag and _tag_matches_wildcard_configured_pattern(tags=tags, configured_tag=configured_tag): result[label_name] = "true" continue diff --git a/litellm/integrations/prometheus_helpers/__init__.py b/litellm/integrations/prometheus_helpers/__init__.py index 784ab524dd52..7de072ecd033 100644 --- a/litellm/integrations/prometheus_helpers/__init__.py +++ b/litellm/integrations/prometheus_helpers/__init__.py @@ -57,9 +57,7 @@ def __init__(self, enum_values: UserAPIKeyLabelValues) -> None: if enum_values.custom_metadata_labels is not None: for key, value in enum_values.custom_metadata_labels.items(): sk = _sanitize_prometheus_label_name(key) - self._custom_by_sanitized_key[sk] = _sanitize_prometheus_label_value( - value - ) + self._custom_by_sanitized_key[sk] = _sanitize_prometheus_label_value(value) self._tag_labels: Dict[str, Optional[str]] = {} if enum_values.tags is not None: # Late import avoids circular import: ``prometheus`` imports this module. diff --git a/litellm/integrations/prometheus_helpers/bounded_prometheus_series_tracker.py b/litellm/integrations/prometheus_helpers/bounded_prometheus_series_tracker.py index d834ae201420..61b4d5ab96e4 100644 --- a/litellm/integrations/prometheus_helpers/bounded_prometheus_series_tracker.py +++ b/litellm/integrations/prometheus_helpers/bounded_prometheus_series_tracker.py @@ -86,9 +86,7 @@ def _remove_metric_series( series.pop(label_values, None) @staticmethod - def _remove_metric_child( - metric: Any, label_values: tuple[Optional[str], ...] - ) -> bool: + def _remove_metric_child(metric: Any, label_values: tuple[Optional[str], ...]) -> bool: """ Remove the Prometheus child for ``label_values`` and report whether the tracker should commit the matching state change. diff --git a/litellm/integrations/prometheus_helpers/prometheus_api.py b/litellm/integrations/prometheus_helpers/prometheus_api.py index 0901d7b6801a..038788f0522c 100644 --- a/litellm/integrations/prometheus_helpers/prometheus_api.py +++ b/litellm/integrations/prometheus_helpers/prometheus_api.py @@ -16,9 +16,7 @@ PROMETHEUS_URL: Optional[str] = get_secret("PROMETHEUS_URL") # type: ignore PROMETHEUS_SELECTED_INSTANCE: Optional[str] = get_secret("PROMETHEUS_SELECTED_INSTANCE") # type: ignore -async_http_handler = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback -) +async_http_handler = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) async def get_metric_from_prometheus( @@ -26,9 +24,7 @@ async def get_metric_from_prometheus( ): # Get the start of the current day in Unix timestamp if PROMETHEUS_URL is None: - raise ValueError( - "PROMETHEUS_URL not set please set 'PROMETHEUS_URL=<>' in .env" - ) + raise ValueError("PROMETHEUS_URL not set please set 'PROMETHEUS_URL=<>' in .env") query = f"{metric_name}[24h]" now = int(time.time()) @@ -111,9 +107,7 @@ async def get_daily_spend_from_prometheus(api_key: Optional[str]): ...] """ if PROMETHEUS_URL is None: - raise ValueError( - "PROMETHEUS_URL not set please set 'PROMETHEUS_URL=<>' in .env" - ) + raise ValueError("PROMETHEUS_URL not set please set 'PROMETHEUS_URL=<>' in .env") # Calculate the start and end dates for the last 30 days end_date = datetime.utcnow() @@ -129,11 +123,7 @@ async def get_daily_spend_from_prometheus(api_key: Optional[str]): query = "sum(delta(litellm_spend_metric_total[1d]))" else: quoted_api_key = _quote_promql_string_literal(api_key) - query = ( - "sum(delta(litellm_spend_metric_total{" - f"hashed_api_key={quoted_api_key}" - "}[1d]))" - ) + query = f"sum(delta(litellm_spend_metric_total{{hashed_api_key={quoted_api_key}}}[1d]))" params = { "query": query, diff --git a/litellm/integrations/prometheus_services.py b/litellm/integrations/prometheus_services.py index af8b1d0866ea..db005aaffc5e 100644 --- a/litellm/integrations/prometheus_services.py +++ b/litellm/integrations/prometheus_services.py @@ -32,16 +32,10 @@ def __init__( from prometheus_client import REGISTRY, Counter, Gauge, Histogram from prometheus_client.gc_collector import Collector except ImportError: - raise Exception( - "Missing prometheus_client. Run `pip install prometheus-client`" - ) + raise Exception("Missing prometheus_client. Run `pip install prometheus-client`") _custom_buckets = litellm.prometheus_latency_buckets - self.latency_buckets = ( - tuple(_custom_buckets) - if _custom_buckets is not None - else LATENCY_BUCKETS - ) + self.latency_buckets = tuple(_custom_buckets) if _custom_buckets is not None else LATENCY_BUCKETS self.Histogram = Histogram self.Counter = Counter @@ -50,9 +44,7 @@ def __init__( verbose_logger.debug("in init prometheus services metrics") - self.payload_to_prometheus_map: Dict[ - str, List[Union[Histogram, Counter, Gauge, Collector]] - ] = {} + self.payload_to_prometheus_map: Dict[str, List[Union[Histogram, Counter, Gauge, Collector]]] = {} for service in ServiceTypes: service_metrics: List[Union[Histogram, Counter, Gauge, Collector]] = [] @@ -61,9 +53,7 @@ def __init__( # Initialize only the configured metrics for each service if ServiceMetrics.HISTOGRAM in metrics_to_initialize: - histogram = self.create_histogram( - service.value, type_of_request="latency" - ) + histogram = self.create_histogram(service.value, type_of_request="latency") if histogram: service_metrics.append(histogram) @@ -75,9 +65,7 @@ def __init__( ) if counter_failed_request: service_metrics.append(counter_failed_request) - counter_total_requests = self.create_counter( - service.value, type_of_request="total_requests" - ) + counter_total_requests = self.create_counter(service.value, type_of_request="total_requests") if counter_total_requests: service_metrics.append(counter_total_requests) @@ -99,9 +87,7 @@ def __init__( print_verbose(f"Got exception on init prometheus client {str(e)}") raise e - def _get_service_metrics_initialize( - self, service: ServiceTypes - ) -> List[ServiceMetrics]: + def _get_service_metrics_initialize(self, service: ServiceTypes) -> List[ServiceMetrics]: DEFAULT_METRICS = [ServiceMetrics.COUNTER, ServiceMetrics.HISTOGRAM] if service not in DEFAULT_SERVICE_CONFIGS: return DEFAULT_METRICS @@ -146,9 +132,7 @@ def create_gauge(self, service: str, type_of_request: str): is_registered = self.is_metric_registered(metric_name) if is_registered: return self._get_metric(metric_name) - return self.Gauge( - metric_name, "Gauge for {} service".format(service), labelnames=[service] - ) + return self.Gauge(metric_name, "Gauge for {} service".format(service), labelnames=[service]) def create_counter( self, diff --git a/litellm/integrations/prompt_layer.py b/litellm/integrations/prompt_layer.py index 190b995fa4ec..52209b2953fe 100644 --- a/litellm/integrations/prompt_layer.py +++ b/litellm/integrations/prompt_layer.py @@ -33,11 +33,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): tags = kwargs["litellm_params"]["metadata"]["pl_tags"] # Remove "pl_tags" from metadata - metadata = { - k: v - for k, v in kwargs["litellm_params"]["metadata"].items() - if k != "pl_tags" - } + metadata = {k: v for k, v in kwargs["litellm_params"]["metadata"].items() if k != "pl_tags"} print_verbose( f"Prompt Layer Logging - Enters logging function for model kwargs: {new_kwargs}\n, response: {response_obj}" @@ -68,9 +64,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): if not request_response.json().get("success", False): raise Exception("Promptlayer did not successfully log the response!") - print_verbose( - f"Prompt Layer Logging: success - final response object: {request_response.text}" - ) + print_verbose(f"Prompt Layer Logging: success - final response object: {request_response.text}") if "request_id" in response_json: if metadata: @@ -82,9 +76,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): "metadata": metadata, }, ) - print_verbose( - f"Prompt Layer Logging: success - metadata post response object: {response.text}" - ) + print_verbose(f"Prompt Layer Logging: success - metadata post response object: {response.text}") except Exception: print_verbose(f"error: Prompt Layer Error - {traceback.format_exc()}") diff --git a/litellm/integrations/prompt_management_base.py b/litellm/integrations/prompt_management_base.py index 9c626aea8499..6d77e959e2df 100644 --- a/litellm/integrations/prompt_management_base.py +++ b/litellm/integrations/prompt_management_base.py @@ -119,9 +119,7 @@ async def async_compile_prompt( compiled_prompt_client["completed_messages"] = messages return compiled_prompt_client - def _get_model_from_prompt( - self, prompt_management_client: PromptManagementClient, model: str - ) -> str: + def _get_model_from_prompt(self, prompt_management_client: PromptManagementClient, model: str) -> str: if prompt_management_client["prompt_template_model"] is not None: return prompt_management_client["prompt_template_model"] else: @@ -138,23 +136,15 @@ def post_compile_prompt_processing( ): completed_messages = prompt_template["completed_messages"] or messages - prompt_template_optional_params = ( - prompt_template["prompt_template_optional_params"] or {} - ) + prompt_template_optional_params = prompt_template["prompt_template_optional_params"] or {} updated_non_default_params = { **non_default_params, - **( - prompt_template_optional_params - if not ignore_prompt_manager_optional_params - else {} - ), + **(prompt_template_optional_params if not ignore_prompt_manager_optional_params else {}), } if not ignore_prompt_manager_model: - model = self._get_model_from_prompt( - prompt_management_client=prompt_template, model=model - ) + model = self._get_model_from_prompt(prompt_management_client=prompt_template, model=model) else: model = model diff --git a/litellm/integrations/rubrik.py b/litellm/integrations/rubrik.py index 922d8f71cf01..2b54a411ec74 100644 --- a/litellm/integrations/rubrik.py +++ b/litellm/integrations/rubrik.py @@ -83,29 +83,20 @@ def __init__( parsed_rate = float(rbrk_sampling_rate.strip()) self.sampling_rate = max(0.0, min(1.0, parsed_rate)) if parsed_rate != self.sampling_rate: - verbose_logger.warning( - f"RUBRIK_SAMPLING_RATE={parsed_rate} clamped to " - f"{self.sampling_rate}" - ) + verbose_logger.warning(f"RUBRIK_SAMPLING_RATE={parsed_rate} clamped to {self.sampling_rate}") except ValueError: - verbose_logger.warning( - f"Invalid RUBRIK_SAMPLING_RATE: {rbrk_sampling_rate!r}, using 1.0" - ) + verbose_logger.warning(f"Invalid RUBRIK_SAMPLING_RATE: {rbrk_sampling_rate!r}, using 1.0") self.key = api_key or os.getenv("RUBRIK_API_KEY") if not self.key: - verbose_logger.warning( - "Rubrik: No API key configured. Requests will be unauthenticated." - ) + verbose_logger.warning("Rubrik: No API key configured. Requests will be unauthenticated.") _batch_size = os.getenv("RUBRIK_BATCH_SIZE") if _batch_size: try: self.batch_size = int(_batch_size) except ValueError: - verbose_logger.warning( - f"Invalid RUBRIK_BATCH_SIZE: {_batch_size!r}, using default" - ) + verbose_logger.warning(f"Invalid RUBRIK_BATCH_SIZE: {_batch_size!r}, using default") # Cap the in-memory retry queue so a Rubrik webhook outage cannot let # authenticated traffic accumulate prompt/response payloads until the @@ -118,18 +109,13 @@ def __init__( _webhook_url = api_base or os.getenv("RUBRIK_WEBHOOK_URL") if _webhook_url is None: - raise ValueError( - "Rubrik webhook URL not configured. " - "Set RUBRIK_WEBHOOK_URL or pass api_base." - ) + raise ValueError("Rubrik webhook URL not configured. Set RUBRIK_WEBHOOK_URL or pass api_base.") _webhook_url = _webhook_url.rstrip("/").removesuffix("/v1") self.tool_blocking_endpoint = f"{_webhook_url}{_WEBHOOK_PATH_TOOL_BLOCKING}" self.logging_endpoint = f"{_webhook_url}{_WEBHOOK_PATH_LOGGING_BATCH}" - self.async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + self.async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) self.tool_blocking_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback, @@ -143,9 +129,7 @@ def __init__( # Periodic flush is started lazily on the first log event so that # low-traffic deployments still get their batches drained even when the # logger is instantiated outside a running event loop (sync init). - self._flush_task: Optional[asyncio.Task[Any]] = ( - self._start_periodic_flush_task() - ) + self._flush_task: Optional[asyncio.Task[Any]] = self._start_periodic_flush_task() def _start_periodic_flush_task(self) -> Optional[asyncio.Task[Any]]: """Start the periodic flush task only when an event loop is already running.""" @@ -153,8 +137,7 @@ def _start_periodic_flush_task(self) -> Optional[asyncio.Task[Any]]: loop = asyncio.get_running_loop() except RuntimeError: verbose_logger.debug( - "Rubrik logger init: no running event loop, " - "periodic flush will start on first log event." + "Rubrik logger init: no running event loop, periodic flush will start on first log event." ) return None return loop.create_task(self.periodic_flush()) @@ -197,9 +180,7 @@ async def apply_guardrail( return inputs try: - return await self._check_tool_calls( - inputs, tool_calls, request_data, logging_obj - ) + return await self._check_tool_calls(inputs, tool_calls, request_data, logging_obj) except ModifyResponseException: raise except _MalformedToolBlockingResponseError as e: @@ -218,8 +199,7 @@ async def apply_guardrail( return inputs except Exception as e: verbose_logger.error( - f"Tool blocking hook failed: {e}. " - "Returning original response unchanged.", + f"Tool blocking hook failed: {e}. Returning original response unchanged.", exc_info=True, ) return inputs @@ -234,26 +214,19 @@ async def _check_tool_calls( """Send tool calls to blocking service, raise if any are blocked.""" message_tool_calls = self._normalize_tool_calls(tool_calls) - call_details = ( - getattr(logging_obj, "model_call_details", {}) if logging_obj else {} - ) + call_details = getattr(logging_obj, "model_call_details", {}) if logging_obj else {} response = request_data.get("response") request_id = getattr(response, "id", None) if response else None if logging_obj and not call_details: verbose_logger.warning( - "Rubrik: logging_obj present but model_call_details is empty " - "-- request context will be missing" + "Rubrik: logging_obj present but model_call_details is empty -- request context will be missing" ) response_data = self._build_tool_call_payload(message_tool_calls, request_id) req_data = self._extract_request_data(call_details) - service_response = await self._post_to_tool_blocking_service( - response_data, req_data - ) - blocked_explanation = self._extract_blocked_tools( - service_response, message_tool_calls - ) + service_response = await self._post_to_tool_blocking_service(response_data, req_data) + blocked_explanation = self._extract_blocked_tools(service_response, message_tool_calls) if blocked_explanation is not None: model = self._resolve_model(request_data, call_details) @@ -294,9 +267,7 @@ def _normalize_tool_calls(tool_calls: Any) -> list[ChatCompletionMessageToolCall ) ) else: - raise TypeError( - f"Cannot normalize tool_call of type {type(tc).__name__}" - ) + raise TypeError(f"Cannot normalize tool_call of type {type(tc).__name__}") return result @staticmethod @@ -316,9 +287,7 @@ def _build_tool_call_payload( "message": { "role": "assistant", "content": None, - "tool_calls": [ - tc.model_dump(exclude_none=True) for tc in tool_calls - ], + "tool_calls": [tc.model_dump(exclude_none=True) for tc in tool_calls], }, "finish_reason": "tool_calls", } @@ -347,16 +316,10 @@ def _sanitize_proxy_server_request(proxy_server_request: Any) -> Any: request ``body`` so proxy credentials are not exfiltrated.""" if not isinstance(proxy_server_request, dict): return proxy_server_request - return { - key: proxy_server_request[key] - for key in ("url", "method") - if key in proxy_server_request - } + return {key: proxy_server_request[key] for key in ("url", "method") if key in proxy_server_request} @staticmethod - def _resolve_model( - request_data: dict[str, Any], call_details: dict[str, Any] - ) -> str: + def _resolve_model(request_data: dict[str, Any], call_details: dict[str, Any]) -> str: """Get the model name for the ModifyResponseException.""" response = request_data.get("response") if response and hasattr(response, "model"): @@ -365,21 +328,14 @@ def _resolve_model( # -- Logging hooks --------------------------------------------------------- - async def _prepare_log_payload( - self, kwargs: dict, event_type: str - ) -> StandardLoggingPayload | None: + async def _prepare_log_payload(self, kwargs: dict, event_type: str) -> StandardLoggingPayload | None: """Shared logic for success and failure logging.""" if random.random() > self.sampling_rate: - verbose_logger.debug( - f"Skipping Rubrik {event_type} logging " - f"(sampling_rate={self.sampling_rate})" - ) + verbose_logger.debug(f"Skipping Rubrik {event_type} logging (sampling_rate={self.sampling_rate})") return None # Deep-copy so mutations don't affect other callbacks sharing this object - standard_logging_payload: StandardLoggingPayload = safe_deep_copy( - kwargs["standard_logging_object"] - ) + standard_logging_payload: StandardLoggingPayload = safe_deep_copy(kwargs["standard_logging_object"]) # For Anthropic /v1/messages requests, LiteLLM creates a separate # ModelResponse (with a generated chatcmpl-* id) for logging, which @@ -431,8 +387,7 @@ async def _enqueue_log_event(self, kwargs: dict, event_type: str): await self.flush_queue() except Exception as e: verbose_logger.error( - f"Rubrik {event_type} logging hook failed: {e}. " - "Skipping logging for this event.", + f"Rubrik {event_type} logging hook failed: {e}. Skipping logging for this event.", exc_info=True, ) @@ -474,9 +429,7 @@ async def _log_batch_to_rubrik(self, data): ) response.raise_for_status() except httpx.HTTPStatusError as e: - verbose_logger.exception( - f"Rubrik HTTP Error: {e.response.status_code} - {e.response.text}" - ) + verbose_logger.exception(f"Rubrik HTTP Error: {e.response.status_code} - {e.response.text}") raise except Exception: verbose_logger.exception("Rubrik Layer Error") @@ -494,9 +447,7 @@ async def async_send_batch(self): return log_queue_snapshot = list(self.log_queue) - verbose_logger.debug( - "Rubrik: Flushing batch of %s events", len(log_queue_snapshot) - ) + verbose_logger.debug("Rubrik: Flushing batch of %s events", len(log_queue_snapshot)) await self._log_batch_to_rubrik( data=log_queue_snapshot, ) @@ -549,9 +500,7 @@ async def _post_to_tool_blocking_service( "request": request_data, "response": response_data, } - verbose_logger.debug( - f"Sending request to tool blocking service: {self.tool_blocking_endpoint}" - ) + verbose_logger.debug(f"Sending request to tool blocking service: {self.tool_blocking_endpoint}") http_response = await self.tool_blocking_client.post( self.tool_blocking_endpoint, json=envelope, @@ -577,24 +526,19 @@ def _extract_blocked_tools( """ choices = service_response.get("choices", []) if not choices: - raise _MalformedToolBlockingResponseError( - "Tool blocking service returned empty response" - ) + raise _MalformedToolBlockingResponseError("Tool blocking service returned empty response") message = choices[0].get("message", {}) returned_tool_calls = message.get("tool_calls") or [] blocking_explanation = message.get("content", "") allowed_id_counts: Counter = Counter( - tc["id"] - for tc in returned_tool_calls - if isinstance(tc, dict) and tc.get("id") + tc["id"] for tc in returned_tool_calls if isinstance(tc, dict) and tc.get("id") ) required_id_counts: Counter = Counter(tc.id for tc in all_tool_calls if tc.id) all_allowed = len(returned_tool_calls) >= len(all_tool_calls) and all( - allowed_id_counts.get(tc_id, 0) >= count - for tc_id, count in required_id_counts.items() + allowed_id_counts.get(tc_id, 0) >= count for tc_id, count in required_id_counts.items() ) if all_allowed: diff --git a/litellm/integrations/s3.py b/litellm/integrations/s3.py index 2e70b1d65197..53a982cd2c48 100644 --- a/litellm/integrations/s3.py +++ b/litellm/integrations/s3.py @@ -29,9 +29,7 @@ def __init__( import boto3 try: - verbose_logger.debug( - f"in init s3 logger - s3_callback_params {litellm.s3_callback_params}" - ) + verbose_logger.debug(f"in init s3 logger - s3_callback_params {litellm.s3_callback_params}") s3_use_team_prefix = False @@ -47,21 +45,13 @@ def __init__( s3_use_ssl = litellm.s3_callback_params.get("s3_use_ssl", True) s3_verify = litellm.s3_callback_params.get("s3_verify") s3_endpoint_url = litellm.s3_callback_params.get("s3_endpoint_url") - s3_aws_access_key_id = litellm.s3_callback_params.get( - "s3_aws_access_key_id" - ) - s3_aws_secret_access_key = litellm.s3_callback_params.get( - "s3_aws_secret_access_key" - ) - s3_aws_session_token = litellm.s3_callback_params.get( - "s3_aws_session_token" - ) + s3_aws_access_key_id = litellm.s3_callback_params.get("s3_aws_access_key_id") + s3_aws_secret_access_key = litellm.s3_callback_params.get("s3_aws_secret_access_key") + s3_aws_session_token = litellm.s3_callback_params.get("s3_aws_session_token") s3_config = litellm.s3_callback_params.get("s3_config") s3_path = litellm.s3_callback_params.get("s3_path") # done reading litellm.s3_callback_params - s3_use_team_prefix = bool( - litellm.s3_callback_params.get("s3_use_team_prefix", False) - ) + s3_use_team_prefix = bool(litellm.s3_callback_params.get("s3_use_team_prefix", False)) self.s3_use_team_prefix = s3_use_team_prefix self.bucket_name = s3_bucket_name self.s3_path = s3_path @@ -84,23 +74,17 @@ def __init__( print_verbose(f"Got exception on init s3 client {str(e)}") raise e - async def _async_log_event( - self, kwargs, response_obj, start_time, end_time, print_verbose - ): + async def _async_log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): self.log_event(kwargs, response_obj, start_time, end_time, print_verbose) def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): try: - verbose_logger.debug( - f"s3 Logging - Enters logging function for model {kwargs}" - ) + verbose_logger.debug(f"s3 Logging - Enters logging function for model {kwargs}") # construct payload to send to s3 # follows the same params as langfuse.py litellm_params = kwargs.get("litellm_params", {}) - metadata = ( - litellm_params.get("metadata", {}) or {} - ) # if litellm_params['metadata'] == None + metadata = litellm_params.get("metadata", {}) or {} # if litellm_params['metadata'] == None # Clean Metadata before logging - never log raw metadata # the raw metadata can contain circular references which leads to infinite recursion @@ -131,11 +115,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): team_alias = payload["metadata"].get("user_api_key_team_alias") team_alias_prefix = "" - if ( - litellm.enable_preview_features - and self.s3_use_team_prefix - and team_alias is not None - ): + if litellm.enable_preview_features and self.s3_use_team_prefix and team_alias is not None: team_alias_prefix = f"{team_alias}/" s3_file_name = litellm.utils.get_logging_id(start_time, payload) or "" @@ -147,11 +127,7 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): ) s3_object_download_filename = ( - "time-" - + start_time.strftime("%Y-%m-%dT%H-%M-%S-%f") - + "_" - + payload["id"] - + ".json" + "time-" + start_time.strftime("%Y-%m-%dT%H-%M-%S-%f") + "_" + payload["id"] + ".json" ) from litellm.litellm_core_utils.safe_json_dumps import safe_dumps @@ -186,11 +162,7 @@ def get_s3_object_key( s3_file_name: str, ) -> str: s3_object_key = ( - (s3_path.rstrip("/") + "/" if s3_path else "") - + prefix - + start_time.strftime("%Y-%m-%d") - + "/" - + s3_file_name + (s3_path.rstrip("/") + "/" if s3_path else "") + prefix + start_time.strftime("%Y-%m-%d") + "/" + s3_file_name ) # we need the s3 key to include the time, so we log cache hits too s3_object_key += ".json" return s3_object_key diff --git a/litellm/integrations/s3_v2.py b/litellm/integrations/s3_v2.py index 4ed8a809a130..939289f96ea2 100644 --- a/litellm/integrations/s3_v2.py +++ b/litellm/integrations/s3_v2.py @@ -61,8 +61,7 @@ def __init__( _masker = SensitiveDataMasker() if s3_callback_params_override is not None: verbose_logger.debug( - f"in init s3 logger (audit override) - " - f"{_masker.mask_dict(dict(s3_callback_params_override))}" + f"in init s3 logger (audit override) - {_masker.mask_dict(dict(s3_callback_params_override))}" ) else: verbose_logger.debug( @@ -98,9 +97,7 @@ def __init__( # IMPORTANT # Create httpx client AFTER _init_s3_params so we have the correct s3_verify value - verbose_logger.debug( - f"s3_v2 logger creating async httpx client with s3_verify={self.s3_verify}" - ) + verbose_logger.debug(f"s3_v2 logger creating async httpx client with s3_verify={self.s3_verify}") self.async_httpx_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback, params={"ssl_verify": self.s3_verify}, @@ -109,9 +106,7 @@ def __init__( asyncio.create_task(self.periodic_flush()) self.flush_lock = asyncio.Lock() - verbose_logger.debug( - f"s3 flush interval: {s3_flush_interval}, s3 batch size: {s3_batch_size}" - ) + verbose_logger.debug(f"s3 flush interval: {s3_flush_interval}, s3 batch size: {s3_batch_size}") # Call CustomLogger's __init__ CustomBatchLogger.__init__( self, @@ -161,75 +156,42 @@ def _init_s3_params( if params_source is None: params_source = litellm.s3_callback_params or {} params: dict = { - key: ( - litellm.get_secret(value) - if isinstance(value, str) and value.startswith("os.environ/") - else value - ) + key: (litellm.get_secret(value) if isinstance(value, str) and value.startswith("os.environ/") else value) for key, value in params_source.items() } self.s3_bucket_name = params.get("s3_bucket_name") or s3_bucket_name self.s3_region_name = params.get("s3_region_name") or s3_region_name self.s3_api_version = params.get("s3_api_version") or s3_api_version - self.s3_use_ssl = ( - params.get("s3_use_ssl", True) - if params.get("s3_use_ssl") is not None - else s3_use_ssl - ) - self.s3_verify = ( - params.get("s3_verify") - if params.get("s3_verify") is not None - else s3_verify - ) + self.s3_use_ssl = params.get("s3_use_ssl", True) if params.get("s3_use_ssl") is not None else s3_use_ssl + self.s3_verify = params.get("s3_verify") if params.get("s3_verify") is not None else s3_verify self.s3_endpoint_url = params.get("s3_endpoint_url") or s3_endpoint_url - self.s3_aws_access_key_id = ( - params.get("s3_aws_access_key_id") or s3_aws_access_key_id - ) + self.s3_aws_access_key_id = params.get("s3_aws_access_key_id") or s3_aws_access_key_id - self.s3_aws_secret_access_key = ( - params.get("s3_aws_secret_access_key") or s3_aws_secret_access_key - ) + self.s3_aws_secret_access_key = params.get("s3_aws_secret_access_key") or s3_aws_secret_access_key - self.s3_aws_session_token = ( - params.get("s3_aws_session_token") or s3_aws_session_token - ) + self.s3_aws_session_token = params.get("s3_aws_session_token") or s3_aws_session_token - self.s3_aws_session_name = ( - params.get("s3_aws_session_name") or s3_aws_session_name - ) + self.s3_aws_session_name = params.get("s3_aws_session_name") or s3_aws_session_name - self.s3_aws_profile_name = ( - params.get("s3_aws_profile_name") or s3_aws_profile_name - ) + self.s3_aws_profile_name = params.get("s3_aws_profile_name") or s3_aws_profile_name self.s3_aws_role_name = params.get("s3_aws_role_name") or s3_aws_role_name - self.s3_aws_web_identity_token = ( - params.get("s3_aws_web_identity_token") or s3_aws_web_identity_token - ) + self.s3_aws_web_identity_token = params.get("s3_aws_web_identity_token") or s3_aws_web_identity_token - self.s3_aws_sts_endpoint = ( - params.get("s3_aws_sts_endpoint") or s3_aws_sts_endpoint - ) + self.s3_aws_sts_endpoint = params.get("s3_aws_sts_endpoint") or s3_aws_sts_endpoint self.s3_config = params.get("s3_config") or s3_config self.s3_path = params.get("s3_path") or s3_path - self.s3_use_team_prefix = ( - bool(params.get("s3_use_team_prefix", False)) or s3_use_team_prefix - ) + self.s3_use_team_prefix = bool(params.get("s3_use_team_prefix", False)) or s3_use_team_prefix - self.s3_use_key_prefix = ( - bool(params.get("s3_use_key_prefix", False)) or s3_use_key_prefix - ) + self.s3_use_key_prefix = bool(params.get("s3_use_key_prefix", False)) or s3_use_key_prefix - self.s3_strip_base64_files = ( - bool(params.get("s3_strip_base64_files", False)) or s3_strip_base64_files - ) + self.s3_strip_base64_files = bool(params.get("s3_strip_base64_files", False)) or s3_strip_base64_files self.s3_use_virtual_hosted_style = ( - bool(params.get("s3_use_virtual_hosted_style", False)) - or s3_use_virtual_hosted_style + bool(params.get("s3_use_virtual_hosted_style", False)) or s3_use_virtual_hosted_style ) return @@ -251,9 +213,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti ) pass - async def async_log_audit_log_event( - self, audit_log: StandardAuditLogPayload - ) -> None: + async def async_log_audit_log_event(self, audit_log: StandardAuditLogPayload) -> None: """Batch audit logs and upload to S3 under audit_logs/ prefix.""" try: from datetime import timezone @@ -265,9 +225,7 @@ async def async_log_audit_log_event( s3_path = s3_path.rstrip("/") + "/" if s3_path else "" s3_object_key = ( - f"{s3_path}audit_logs/" - f"{now.strftime('%Y-%m-%d')}/" - f"{now.strftime('%H-%M-%S')}_{audit_log_id}.json" + f"{s3_path}audit_logs/{now.strftime('%Y-%m-%d')}/{now.strftime('%H-%M-%S')}_{audit_log_id}.json" ) element = s3BatchLoggingElement( @@ -285,9 +243,7 @@ async def async_log_audit_log_event( async def _async_log_event_base(self, kwargs, response_obj, start_time, end_time): try: - verbose_logger.debug( - f"s3 Logging - Enters logging function for model {kwargs}" - ) + verbose_logger.debug(f"s3 Logging - Enters logging function for model {kwargs}") s3_batch_logging_element = self.create_s3_batch_logging_element( start_time=start_time, @@ -303,9 +259,7 @@ async def _async_log_event_base(self, kwargs, response_obj, start_time, end_time ) return - verbose_logger.debug( - "\ns3 Logger - Logging payload = %s", s3_batch_logging_element - ) + verbose_logger.debug("\ns3 Logger - Logging payload = %s", s3_batch_logging_element) self.log_queue.append(s3_batch_logging_element) verbose_logger.debug( @@ -317,9 +271,7 @@ async def _async_log_event_base(self, kwargs, response_obj, start_time, end_time verbose_logger.exception(f"s3 Layer Error - {str(e)}") self.handle_callback_failure(callback_name="S3Logger") - async def async_upload_data_to_s3( - self, batch_logging_element: s3BatchLoggingElement - ): + async def async_upload_data_to_s3(self, batch_logging_element: s3BatchLoggingElement): try: import hashlib @@ -344,9 +296,7 @@ async def async_upload_data_to_s3( aws_sts_endpoint=self.s3_aws_sts_endpoint, ) - verbose_logger.debug( - f"s3_v2 logger - uploading data to s3 - {batch_logging_element.s3_object_key}" - ) + verbose_logger.debug(f"s3_v2 logger - uploading data to s3 - {batch_logging_element.s3_object_key}") verbose_logger.debug(f"s3_v2 logger - s3_verify setting: {self.s3_verify}") # Prepare the URL @@ -355,24 +305,12 @@ async def async_upload_data_to_s3( if self.s3_endpoint_url and self.s3_bucket_name: if self.s3_use_virtual_hosted_style: # Virtual-hosted-style: bucket.endpoint/key - endpoint_host = self.s3_endpoint_url.replace( - "https://", "" - ).replace("http://", "") - protocol = ( - "https://" - if self.s3_endpoint_url.startswith("https://") - else "http://" - ) + endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "") + protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://" url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{batch_logging_element.s3_object_key}" else: # Path-style: endpoint/bucket/key - url = ( - self.s3_endpoint_url - + "/" - + self.s3_bucket_name - + "/" - + batch_logging_element.s3_object_key - ) + url = self.s3_endpoint_url + "/" + self.s3_bucket_name + "/" + batch_logging_element.s3_object_key # Convert JSON to string json_string = safe_dumps(batch_logging_element.payload) @@ -398,9 +336,7 @@ async def async_upload_data_to_s3( data=prepped.body, headers=prepped.headers, ) - aws_region_name = self.get_aws_region_name_for_non_llm_api_calls( - aws_region_name=self.s3_region_name - ) + aws_region_name = self.get_aws_region_name_for_non_llm_api_calls(aws_region_name=self.s3_region_name) SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request) # Prepare the signed headers @@ -412,9 +348,7 @@ async def async_upload_data_to_s3( # Make the request with retry for transient S3 errors (500/503) max_retries = 3 for attempt in range(max_retries): - response = await self.async_httpx_client.put( - request_url, data=json_string, headers=signed_headers - ) + response = await self.async_httpx_client.put(request_url, data=json_string, headers=signed_headers) if response.status_code in (500, 503) and attempt < max_retries - 1: wait_time = 2**attempt # 1s, 2s verbose_logger.warning( @@ -471,22 +405,16 @@ def create_s3_batch_logging_element( return None if self.s3_strip_base64_files: - standard_logging_payload = self._strip_base64_from_messages_sync( - standard_logging_payload - ) + standard_logging_payload = self._strip_base64_from_messages_sync(standard_logging_payload) # Base prefix (default empty) prefix_components = [] if self.s3_use_team_prefix: - team_alias = standard_logging_payload.get("metadata", {}).get( - "user_api_key_team_alias", None - ) + team_alias = standard_logging_payload.get("metadata", {}).get("user_api_key_team_alias", None) if team_alias: prefix_components.append(team_alias) if self.s3_use_key_prefix: - user_api_key_alias = standard_logging_payload.get("metadata", {}).get( - "user_api_key_alias", None - ) + user_api_key_alias = standard_logging_payload.get("metadata", {}).get("user_api_key_alias", None) if user_api_key_alias: prefix_components.append(user_api_key_alias) @@ -495,9 +423,7 @@ def create_s3_batch_logging_element( if prefix_path: prefix_path += "/" - s3_file_name = ( - litellm.utils.get_logging_id(start_time, standard_logging_payload) or "" - ) + s3_file_name = litellm.utils.get_logging_id(start_time, standard_logging_payload) or "" verbose_logger.debug( f"Creating s3 file with prefix_components={prefix_components},prefix_path={prefix_path} and {s3_file_name}" ) @@ -509,7 +435,9 @@ def create_s3_batch_logging_element( ) verbose_logger.debug(f"s3_object_key={s3_object_key}") - s3_object_download_filename = f"time-{start_time.strftime('%Y-%m-%dT%H-%M-%S-%f')}_{standard_logging_payload['id']}.json" + s3_object_download_filename = ( + f"time-{start_time.strftime('%Y-%m-%dT%H-%M-%S-%f')}_{standard_logging_payload['id']}.json" + ) return s3BatchLoggingElement( payload=dict(standard_logging_payload), @@ -528,9 +456,7 @@ def upload_data_to_s3(self, batch_logging_element: s3BatchLoggingElement): except ImportError: raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") try: - verbose_logger.debug( - f"s3_v2 logger - uploading data to s3 - {batch_logging_element.s3_object_key}" - ) + verbose_logger.debug(f"s3_v2 logger - uploading data to s3 - {batch_logging_element.s3_object_key}") credentials: Credentials = self.get_credentials( aws_access_key_id=self.s3_aws_access_key_id, aws_secret_access_key=self.s3_aws_secret_access_key, @@ -544,24 +470,12 @@ def upload_data_to_s3(self, batch_logging_element: s3BatchLoggingElement): if self.s3_endpoint_url and self.s3_bucket_name: if self.s3_use_virtual_hosted_style: # Virtual-hosted-style: bucket.endpoint/key - endpoint_host = self.s3_endpoint_url.replace( - "https://", "" - ).replace("http://", "") - protocol = ( - "https://" - if self.s3_endpoint_url.startswith("https://") - else "http://" - ) + endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "") + protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://" url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{batch_logging_element.s3_object_key}" else: # Path-style: endpoint/bucket/key - url = ( - self.s3_endpoint_url - + "/" - + self.s3_bucket_name - + "/" - + batch_logging_element.s3_object_key - ) + url = self.s3_endpoint_url + "/" + self.s3_bucket_name + "/" + batch_logging_element.s3_object_key # Convert JSON to string json_string = safe_dumps(batch_logging_element.payload) @@ -587,9 +501,7 @@ def upload_data_to_s3(self, batch_logging_element: s3BatchLoggingElement): data=prepped.body, headers=prepped.headers, ) - aws_region_name = self.get_aws_region_name_for_non_llm_api_calls( - aws_region_name=self.s3_region_name - ) + aws_region_name = self.get_aws_region_name_for_non_llm_api_calls(aws_region_name=self.s3_region_name) SigV4Auth(credentials, "s3", aws_region_name).add_auth(aws_request) # Prepare the signed headers @@ -599,18 +511,12 @@ def upload_data_to_s3(self, batch_logging_element: s3BatchLoggingElement): request_url = prepped.url or url httpx_client = _get_httpx_client( - params=( - {"ssl_verify": self.s3_verify} - if self.s3_verify is not None - else None - ) + params=({"ssl_verify": self.s3_verify} if self.s3_verify is not None else None) ) # Make the request with retry for transient S3 errors (500/503) max_retries = 3 for attempt in range(max_retries): - response = httpx_client.put( - request_url, data=json_string, headers=signed_headers - ) + response = httpx_client.put(request_url, data=json_string, headers=signed_headers) if response.status_code in (500, 503) and attempt < max_retries - 1: wait_time = 2**attempt # 1s, 2s verbose_logger.warning( @@ -662,9 +568,7 @@ async def _download_object_from_s3(self, s3_object_key: str) -> Optional[dict]: aws_sts_endpoint=self.s3_aws_sts_endpoint, ) - verbose_logger.debug( - f"s3_v2 logger - downloading data from s3 - {s3_object_key}" - ) + verbose_logger.debug(f"s3_v2 logger - downloading data from s3 - {s3_object_key}") # Prepare the URL url = f"https://{self.s3_bucket_name}.s3.{self.s3_region_name}.amazonaws.com/{s3_object_key}" @@ -672,24 +576,12 @@ async def _download_object_from_s3(self, s3_object_key: str) -> Optional[dict]: if self.s3_endpoint_url and self.s3_bucket_name: if self.s3_use_virtual_hosted_style: # Virtual-hosted-style: bucket.endpoint/key - endpoint_host = self.s3_endpoint_url.replace( - "https://", "" - ).replace("http://", "") - protocol = ( - "https://" - if self.s3_endpoint_url.startswith("https://") - else "http://" - ) + endpoint_host = self.s3_endpoint_url.replace("https://", "").replace("http://", "") + protocol = "https://" if self.s3_endpoint_url.startswith("https://") else "http://" url = f"{protocol}{self.s3_bucket_name}.{endpoint_host}/{s3_object_key}" else: # Path-style: endpoint/bucket/key - url = ( - self.s3_endpoint_url - + "/" - + self.s3_bucket_name - + "/" - + s3_object_key - ) + url = self.s3_endpoint_url + "/" + self.s3_bucket_name + "/" + s3_object_key # Prepare the request for GET operation # For GET requests, we need x-amz-content-sha256 with hash of empty string @@ -712,14 +604,10 @@ async def _download_object_from_s3(self, s3_object_key: str) -> Optional[dict]: signed_headers = dict(aws_request.headers.items()) request_url = prepped.url or url - response = await self.async_httpx_client.get( - request_url, headers=signed_headers - ) + response = await self.async_httpx_client.get(request_url, headers=signed_headers) if response.status_code != 200: - verbose_logger.exception( - "S3 object not found, saw response=", response.text - ) + verbose_logger.exception("S3 object not found, saw response=", response.text) return None # Parse JSON response @@ -750,7 +638,5 @@ async def get_proxy_server_request_from_cold_storage_with_object_key( downloaded_object = await self._download_object_from_s3(object_key) return downloaded_object except Exception as e: - verbose_logger.exception( - f"Error retrieving object {object_key} from cold storage: {str(e)}" - ) + verbose_logger.exception(f"Error retrieving object {object_key} from cold storage: {str(e)}") return None diff --git a/litellm/integrations/sqs.py b/litellm/integrations/sqs.py index 6cbd2c7974f0..8c0b06df8883 100644 --- a/litellm/integrations/sqs.py +++ b/litellm/integrations/sqs.py @@ -69,9 +69,7 @@ def __init__( **kwargs, ) -> None: try: - verbose_logger.debug( - f"in init sqs logger - sqs_callback_params {litellm.aws_sqs_callback_params}" - ) + verbose_logger.debug(f"in init sqs logger - sqs_callback_params {litellm.aws_sqs_callback_params}") self.async_httpx_client = get_async_httpx_client( llm_provider=httpxSpecialProvider.LoggingCallback, @@ -103,9 +101,7 @@ def __init__( asyncio.create_task(self.periodic_flush()) self.flush_lock = asyncio.Lock() - verbose_logger.debug( - f"sqs flush interval: {sqs_flush_interval}, sqs batch size: {sqs_batch_size}" - ) + verbose_logger.debug(f"sqs flush interval: {sqs_flush_interval}, sqs batch size: {sqs_batch_size}") CustomBatchLogger.__init__( self, @@ -150,109 +146,66 @@ def _init_sqs_params( if isinstance(value, str) and value.startswith("os.environ/"): litellm.aws_sqs_callback_params[key] = litellm.get_secret(value) - self.sqs_queue_url = ( - litellm.aws_sqs_callback_params.get("sqs_queue_url") or sqs_queue_url - ) - self.sqs_region_name = ( - litellm.aws_sqs_callback_params.get("sqs_region_name") or sqs_region_name - ) - self.sqs_api_version = ( - litellm.aws_sqs_callback_params.get("sqs_api_version") or sqs_api_version - ) - self.sqs_use_ssl = ( - litellm.aws_sqs_callback_params.get("sqs_use_ssl", True) or sqs_use_ssl - ) - self.sqs_verify = ( - litellm.aws_sqs_callback_params.get("sqs_verify") or sqs_verify - ) - self.sqs_endpoint_url = ( - litellm.aws_sqs_callback_params.get("sqs_endpoint_url") or sqs_endpoint_url - ) + self.sqs_queue_url = litellm.aws_sqs_callback_params.get("sqs_queue_url") or sqs_queue_url + self.sqs_region_name = litellm.aws_sqs_callback_params.get("sqs_region_name") or sqs_region_name + self.sqs_api_version = litellm.aws_sqs_callback_params.get("sqs_api_version") or sqs_api_version + self.sqs_use_ssl = litellm.aws_sqs_callback_params.get("sqs_use_ssl", True) or sqs_use_ssl + self.sqs_verify = litellm.aws_sqs_callback_params.get("sqs_verify") or sqs_verify + self.sqs_endpoint_url = litellm.aws_sqs_callback_params.get("sqs_endpoint_url") or sqs_endpoint_url self.sqs_aws_access_key_id = ( - litellm.aws_sqs_callback_params.get("sqs_aws_access_key_id") - or sqs_aws_access_key_id + litellm.aws_sqs_callback_params.get("sqs_aws_access_key_id") or sqs_aws_access_key_id ) self.sqs_aws_secret_access_key = ( - litellm.aws_sqs_callback_params.get("sqs_aws_secret_access_key") - or sqs_aws_secret_access_key + litellm.aws_sqs_callback_params.get("sqs_aws_secret_access_key") or sqs_aws_secret_access_key ) self.sqs_aws_session_token = ( - litellm.aws_sqs_callback_params.get("sqs_aws_session_token") - or sqs_aws_session_token + litellm.aws_sqs_callback_params.get("sqs_aws_session_token") or sqs_aws_session_token ) - self.sqs_aws_session_name = ( - litellm.aws_sqs_callback_params.get("sqs_aws_session_name") - or sqs_aws_session_name - ) + self.sqs_aws_session_name = litellm.aws_sqs_callback_params.get("sqs_aws_session_name") or sqs_aws_session_name - self.sqs_aws_profile_name = ( - litellm.aws_sqs_callback_params.get("sqs_aws_profile_name") - or sqs_aws_profile_name - ) + self.sqs_aws_profile_name = litellm.aws_sqs_callback_params.get("sqs_aws_profile_name") or sqs_aws_profile_name - self.sqs_aws_role_name = ( - litellm.aws_sqs_callback_params.get("sqs_aws_role_name") - or sqs_aws_role_name - ) + self.sqs_aws_role_name = litellm.aws_sqs_callback_params.get("sqs_aws_role_name") or sqs_aws_role_name self.sqs_aws_web_identity_token = ( - litellm.aws_sqs_callback_params.get("sqs_aws_web_identity_token") - or sqs_aws_web_identity_token + litellm.aws_sqs_callback_params.get("sqs_aws_web_identity_token") or sqs_aws_web_identity_token ) - self.sqs_aws_sts_endpoint = ( - litellm.aws_sqs_callback_params.get("sqs_aws_sts_endpoint") - or sqs_aws_sts_endpoint - ) + self.sqs_aws_sts_endpoint = litellm.aws_sqs_callback_params.get("sqs_aws_sts_endpoint") or sqs_aws_sts_endpoint self.sqs_strip_base64_files = ( - litellm.aws_sqs_callback_params.get("sqs_strip_base64_files", False) - or sqs_strip_base64_files + litellm.aws_sqs_callback_params.get("sqs_strip_base64_files", False) or sqs_strip_base64_files ) self.sqs_aws_use_application_level_encryption = ( - litellm.aws_sqs_callback_params.get( - "sqs_aws_use_application_level_encryption", False - ) + litellm.aws_sqs_callback_params.get("sqs_aws_use_application_level_encryption", False) or sqs_aws_use_application_level_encryption ) self.sqs_app_encryption_key_b64 = ( - litellm.aws_sqs_callback_params.get("sqs_app_encryption_key_b64") - or sqs_app_encryption_key_b64 + litellm.aws_sqs_callback_params.get("sqs_app_encryption_key_b64") or sqs_app_encryption_key_b64 ) self.sqs_app_encryption_aad = ( - litellm.aws_sqs_callback_params.get("sqs_app_encryption_aad") - or sqs_app_encryption_aad + litellm.aws_sqs_callback_params.get("sqs_app_encryption_aad") or sqs_app_encryption_aad ) self.app_crypto: Optional["AppCrypto"] = None if self.sqs_aws_use_application_level_encryption: from litellm.litellm_core_utils.app_crypto import AppCrypto if not self.sqs_app_encryption_key_b64: - raise ValueError( - "sqs_app_encryption_key_b64 is required when encryption is enabled." - ) + raise ValueError("sqs_app_encryption_key_b64 is required when encryption is enabled.") key = base64.b64decode(self.sqs_app_encryption_key_b64) self.app_crypto = AppCrypto(key) verbose_logger.debug("SQSLogger: Application-level encryption enabled.") - self.sqs_config = ( - litellm.aws_sqs_callback_params.get("sqs_config") or sqs_config - ) + self.sqs_config = litellm.aws_sqs_callback_params.get("sqs_config") or sqs_config - async def async_log_success_event( - self, kwargs, response_obj, start_time, end_time - ) -> None: + async def async_log_success_event(self, kwargs, response_obj, start_time, end_time) -> None: try: - verbose_logger.debug( - "SQS Logging - Enters logging function for model %s", kwargs - ) + verbose_logger.debug("SQS Logging - Enters logging function for model %s", kwargs) standard_logging_payload = kwargs.get("standard_logging_object") if self.sqs_strip_base64_files: - standard_logging_payload = await self._strip_base64_from_messages( - standard_logging_payload - ) + standard_logging_payload = await self._strip_base64_from_messages(standard_logging_payload) if standard_logging_payload is None: raise ValueError("standard_logging_payload is None") @@ -271,9 +224,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti if standard_logging_payload is None: raise ValueError("standard_logging_payload is None") if self.sqs_strip_base64_files: - standard_logging_payload = await self._strip_base64_from_messages( - standard_logging_payload - ) + standard_logging_payload = await self._strip_base64_from_messages(standard_logging_payload) self.log_queue.append(standard_logging_payload) verbose_logger.debug( @@ -283,9 +234,7 @@ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_ti ) except Exception as e: - verbose_logger.exception( - f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}" - ) + verbose_logger.exception(f"Datadog Layer Error - {str(e)}\n{traceback.format_exc()}") pass async def async_send_batch(self) -> None: @@ -324,28 +273,21 @@ async def async_send_message(self, payload: StandardLoggingPayload) -> None: json_data = json.loads(safe_dumps(payload)) if self.app_crypto: - aad_bytes = ( - self.sqs_app_encryption_aad.encode("utf-8") - if self.sqs_app_encryption_aad - else None - ) + aad_bytes = self.sqs_app_encryption_aad.encode("utf-8") if self.sqs_app_encryption_aad else None encrypted = self.app_crypto.encrypt_json(json_data, aad=aad_bytes) json_string = json.dumps({"__encrypted__": True, "payload": encrypted}) else: json_string = safe_dumps(payload) - body = ( - f"Action={SQS_SEND_MESSAGE_ACTION}&Version={SQS_API_VERSION}&MessageBody=" - + quote(json_string, safe="") + body = f"Action={SQS_SEND_MESSAGE_ACTION}&Version={SQS_API_VERSION}&MessageBody=" + quote( + json_string, safe="" ) headers = { "Content-Type": "application/x-www-form-urlencoded", } - req = requests.Request( - "POST", self.sqs_queue_url, data=body, headers=headers - ) + req = requests.Request("POST", self.sqs_queue_url, data=body, headers=headers) prepped = req.prepare() aws_request = AWSRequest( @@ -377,13 +319,9 @@ async def async_health_check(self) -> IntegrationHealthCheckStatus: ) # Create a minimal standard logging payload - standard_logging_object: StandardLoggingPayload = ( - create_dummy_standard_logging_payload() - ) + standard_logging_object: StandardLoggingPayload = create_dummy_standard_logging_payload() # Attempt to send a single message await self.async_send_message(standard_logging_object) return IntegrationHealthCheckStatus(status="healthy", error_message=None) except Exception as e: - return IntegrationHealthCheckStatus( - status="unhealthy", error_message=str(e) - ) + return IntegrationHealthCheckStatus(status="unhealthy", error_message=str(e)) diff --git a/litellm/integrations/supabase.py b/litellm/integrations/supabase.py index 7eb007f813d4..18cf4f9549c3 100644 --- a/litellm/integrations/supabase.py +++ b/litellm/integrations/supabase.py @@ -31,13 +31,9 @@ def __init__(self): self.supabase_url, self.supabase_key ) - def input_log_event( - self, model, messages, end_user, litellm_call_id, print_verbose - ): + def input_log_event(self, model, messages, end_user, litellm_call_id, print_verbose): try: - print_verbose( - f"Supabase Logging - Enters input logging function for model {model}" - ) + print_verbose(f"Supabase Logging - Enters input logging function for model {model}") supabase_data_obj = { "model": model, "messages": messages, @@ -45,11 +41,7 @@ def input_log_event( "status": "initiated", "litellm_call_id": litellm_call_id, } - data, count = ( - self.supabase_client.table(self.supabase_table_name) - .insert(supabase_data_obj) - .execute() - ) + data, count = self.supabase_client.table(self.supabase_table_name).insert(supabase_data_obj).execute() print_verbose(f"data: {data}") except Exception: print_verbose(f"Supabase Logging Error - {traceback.format_exc()}") @@ -67,9 +59,7 @@ def log_event( print_verbose, ): try: - print_verbose( - f"Supabase Logging - Enters logging function for model {model}, response_obj: {response_obj}" - ) + print_verbose(f"Supabase Logging - Enters logging function for model {model}, response_obj: {response_obj}") total_cost = litellm.completion_cost(completion_response=response_obj) @@ -85,9 +75,7 @@ def log_event( "litellm_call_id": litellm_call_id, "status": "success", } - print_verbose( - f"Supabase Logging - final data object: {supabase_data_obj}" - ) + print_verbose(f"Supabase Logging - final data object: {supabase_data_obj}") data, count = ( self.supabase_client.table(self.supabase_table_name) .upsert(supabase_data_obj, on_conflict="litellm_call_id") @@ -106,9 +94,7 @@ def log_event( "litellm_call_id": litellm_call_id, "status": "failure", } - print_verbose( - f"Supabase Logging - final data object: {supabase_data_obj}" - ) + print_verbose(f"Supabase Logging - final data object: {supabase_data_obj}") data, count = ( self.supabase_client.table(self.supabase_table_name) .upsert(supabase_data_obj, on_conflict="litellm_call_id") diff --git a/litellm/integrations/traceloop.py b/litellm/integrations/traceloop.py index b4f3905c8e8f..77f20972f7ae 100644 --- a/litellm/integrations/traceloop.py +++ b/litellm/integrations/traceloop.py @@ -40,23 +40,17 @@ def log_event( from opentelemetry.trace import SpanKind, Status, StatusCode try: - print_verbose( - f"Traceloop Logging - Enters logging function for model {kwargs}" - ) + print_verbose(f"Traceloop Logging - Enters logging function for model {kwargs}") tracer = self.tracer_wrapper.get_tracer() optional_params = kwargs.get("optional_params", {}) start_time = int(start_time.timestamp()) end_time = int(end_time.timestamp()) - span = tracer.start_span( - "litellm.completion", kind=SpanKind.CLIENT, start_time=start_time - ) + span = tracer.start_span("litellm.completion", kind=SpanKind.CLIENT, start_time=start_time) if span.is_recording(): - span.set_attribute( - SpanAttributes.LLM_REQUEST_MODEL, kwargs.get("model") - ) + span.set_attribute(SpanAttributes.LLM_REQUEST_MODEL, kwargs.get("model")) if "stop" in optional_params: span.set_attribute( SpanAttributes.LLM_CHAT_STOP_SEQUENCES, @@ -73,18 +67,14 @@ def log_event( optional_params.get("presence_penalty"), ) if "top_p" in optional_params: - span.set_attribute( - SpanAttributes.LLM_REQUEST_TOP_P, optional_params.get("top_p") - ) + span.set_attribute(SpanAttributes.LLM_REQUEST_TOP_P, optional_params.get("top_p")) if "tools" in optional_params or "functions" in optional_params: span.set_attribute( SpanAttributes.LLM_REQUEST_FUNCTIONS, optional_params.get("tools", optional_params.get("functions")), ) if "user" in optional_params: - span.set_attribute( - SpanAttributes.LLM_USER, optional_params.get("user") - ) + span.set_attribute(SpanAttributes.LLM_USER, optional_params.get("user")) if "max_tokens" in optional_params: span.set_attribute( SpanAttributes.LLM_REQUEST_MAX_TOKENS, @@ -106,9 +96,7 @@ def log_event( prompt.get("content"), ) - span.set_attribute( - SpanAttributes.LLM_RESPONSE_MODEL, response_obj.get("model") - ) + span.set_attribute(SpanAttributes.LLM_RESPONSE_MODEL, response_obj.get("model")) usage = response_obj.get("usage") if usage: span.set_attribute( @@ -138,11 +126,7 @@ def log_event( choice.get("message").get("content"), ) - if ( - level == "ERROR" - and status_message is not None - and isinstance(status_message, str) - ): + if level == "ERROR" and status_message is not None and isinstance(status_message, str): span.record_exception(Exception(status_message)) span.set_status(Status(StatusCode.ERROR, status_message)) diff --git a/litellm/integrations/vantage/vantage_logger.py b/litellm/integrations/vantage/vantage_logger.py index 1e6e46b36aed..be8907f07ffa 100644 --- a/litellm/integrations/vantage/vantage_logger.py +++ b/litellm/integrations/vantage/vantage_logger.py @@ -45,12 +45,8 @@ def __init__( ) -> None: resolved_api_key = api_key or os.getenv("VANTAGE_API_KEY") resolved_token = integration_token or os.getenv("VANTAGE_INTEGRATION_TOKEN") - resolved_base_url = base_url or os.getenv( - "VANTAGE_BASE_URL", "https://api.vantage.sh" - ) - resolved_frequency = ( - frequency or os.getenv("VANTAGE_EXPORT_FREQUENCY") or "hourly" - ).lower() + resolved_base_url = base_url or os.getenv("VANTAGE_BASE_URL", "https://api.vantage.sh") + resolved_frequency = (frequency or os.getenv("VANTAGE_EXPORT_FREQUENCY") or "hourly").lower() raw_interval = interval_seconds or os.getenv("VANTAGE_EXPORT_INTERVAL_SECONDS") resolved_interval: Optional[int] = None @@ -83,11 +79,7 @@ def __init__( verbose_logger.debug( "VantageLogger initialized (integration_token=%s)", - ( - resolved_token[:4] + "***" - if resolved_token and len(resolved_token) > 4 - else "***" - ), + (resolved_token[:4] + "***" if resolved_token and len(resolved_token) > 4 else "***"), ) async def initialize_focus_export_job(self) -> None: @@ -106,18 +98,14 @@ async def initialize_focus_export_job(self) -> None: pod_lock_manager = getattr(writer, "pod_lock_manager", None) if pod_lock_manager and pod_lock_manager.redis_cache: - acquired = await pod_lock_manager.acquire_lock( - cronjob_id=VANTAGE_USAGE_DATA_JOB_NAME - ) + acquired = await pod_lock_manager.acquire_lock(cronjob_id=VANTAGE_USAGE_DATA_JOB_NAME) if not acquired: verbose_logger.debug("Vantage export: unable to acquire pod lock") return try: await self._run_scheduled_export() finally: - await pod_lock_manager.release_lock( - cronjob_id=VANTAGE_USAGE_DATA_JOB_NAME - ) + await pod_lock_manager.release_lock(cronjob_id=VANTAGE_USAGE_DATA_JOB_NAME) else: await self._run_scheduled_export() @@ -126,10 +114,8 @@ async def init_vantage_background_job( scheduler: AsyncIOScheduler, ) -> None: """Register the Vantage export job with the provided scheduler.""" - vantage_loggers: List[CustomLogger] = ( - litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=VantageLogger - ) + vantage_loggers: List[CustomLogger] = litellm.logging_callback_manager.get_custom_loggers_for_type( + callback_type=VantageLogger ) if not vantage_loggers: verbose_logger.debug("No Vantage logger registered; skipping scheduler") diff --git a/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py b/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py index c54b6e4cced4..0ba6da78b27e 100644 --- a/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py +++ b/litellm/integrations/vector_store_integrations/vector_store_pre_call_hook.py @@ -103,9 +103,7 @@ async def async_get_chat_completion_prompt( query = self._extract_query_from_messages(messages) if not query: - verbose_logger.debug( - "No query found in messages for vector store search" - ) + verbose_logger.debug("No query found in messages for vector store search") return model, messages, non_default_params modified_messages: List[AllMessageValues] = messages.copy() @@ -115,9 +113,7 @@ async def async_get_chat_completion_prompt( # Get vector store id from the vector store config vector_store_id = vector_store_to_run.get("vector_store_id", "") custom_llm_provider = vector_store_to_run.get("custom_llm_provider") - litellm_params_for_vector_store = ( - vector_store_to_run.get("litellm_params", {}) or {} - ) + litellm_params_for_vector_store = vector_store_to_run.get("litellm_params", {}) or {} # Call litellm.vector_stores.search() with the required parameters search_response = await litellm.vector_stores.asearch( **{ @@ -141,15 +137,11 @@ async def async_get_chat_completion_prompt( # Get the number of results for logging num_results = 0 num_results = len(search_response.get("data", []) or []) - verbose_logger.debug( - f"Vector store search completed. Added context from {num_results} results" - ) + verbose_logger.debug(f"Vector store search completed. Added context from {num_results} results") # Store search results as-is (already in OpenAI-compatible format) if litellm_logging_obj and all_search_results: - litellm_logging_obj.model_call_details["search_results"] = ( - all_search_results - ) + litellm_logging_obj.model_call_details["search_results"] = all_search_results return model, modified_messages, non_default_params @@ -158,9 +150,7 @@ async def async_get_chat_completion_prompt( # Return original parameters on error return model, messages, non_default_params - def _extract_query_from_messages( - self, messages: List[AllMessageValues] - ) -> Optional[str]: + def _extract_query_from_messages(self, messages: List[AllMessageValues]) -> Optional[str]: """ Extract the query from the last user message. @@ -184,11 +174,7 @@ def _extract_query_from_messages( elif isinstance(content, list) and len(content) > 0: # Handle list of content items, extract text from first text item for item in content: - if ( - isinstance(item, dict) - and item.get("type") == "text" - and "text" in item - ): + if isinstance(item, dict) and item.get("type") == "text" and "text" in item: return item["text"] return None @@ -208,18 +194,14 @@ def _append_search_results_to_messages( Returns: Modified list of messages with context appended """ - search_response_data: Optional[List[VectorStoreSearchResult]] = ( - search_response.get("data") - ) + search_response_data: Optional[List[VectorStoreSearchResult]] = search_response.get("data") if not search_response_data: return messages context_content = self.CONTENT_PREFIX_STRING for result in search_response_data: - result_content: Optional[List[VectorStoreResultContent]] = result.get( - "content" - ) + result_content: Optional[List[VectorStoreResultContent]] = result.get("content") if result_content: for content_item in result_content: content_text: Optional[str] = content_item.get("text") @@ -253,9 +235,7 @@ async def async_post_call_success_deployment_hook( to the response's provider_specific_fields. """ try: - verbose_logger.debug( - "VectorStorePreCallHook.async_post_call_success_deployment_hook called" - ) + verbose_logger.debug("VectorStorePreCallHook.async_post_call_success_deployment_hook called") # Get logging object from request_data litellm_logging_obj = request_data.get("litellm_logging_obj") @@ -263,13 +243,11 @@ async def async_post_call_success_deployment_hook( verbose_logger.debug("No litellm_logging_obj in request_data") return None - verbose_logger.debug( - f"model_call_details keys: {list(litellm_logging_obj.model_call_details.keys())}" - ) + verbose_logger.debug(f"model_call_details keys: {list(litellm_logging_obj.model_call_details.keys())}") # Get search results from model_call_details (already in OpenAI format) - search_results: Optional[List[VectorStoreSearchResponse]] = ( - litellm_logging_obj.model_call_details.get("search_results") + search_results: Optional[List[VectorStoreSearchResponse]] = litellm_logging_obj.model_call_details.get( + "search_results" ) verbose_logger.debug(f"Search results found: {search_results is not None}") @@ -283,30 +261,21 @@ async def async_post_call_success_deployment_hook( for choice in response.choices: if hasattr(choice, "message") and choice.message: # Get existing provider_specific_fields or create new dict - provider_fields = ( - getattr(choice.message, "provider_specific_fields", None) - or {} - ) + provider_fields = getattr(choice.message, "provider_specific_fields", None) or {} # Add search results (already in OpenAI-compatible format) provider_fields["search_results"] = search_results # Set the provider_specific_fields - setattr( - choice.message, "provider_specific_fields", provider_fields - ) + setattr(choice.message, "provider_specific_fields", provider_fields) - verbose_logger.debug( - f"Added {len(search_results)} search results to response" - ) + verbose_logger.debug(f"Added {len(search_results)} search results to response") # Return modified response return response except Exception as e: - verbose_logger.exception( - f"Error adding search results to response: {str(e)}" - ) + verbose_logger.exception(f"Error adding search results to response: {str(e)}") # Don't fail the request if search results fail to be added return None @@ -323,18 +292,12 @@ async def async_post_call_streaming_deployment_hook( search results to the stream before it's returned to the user. """ try: - verbose_logger.debug( - "VectorStorePreCallHook.async_post_call_streaming_deployment_hook called" - ) + verbose_logger.debug("VectorStorePreCallHook.async_post_call_streaming_deployment_hook called") # Get search results from model_call_details (already in OpenAI format) - search_results: Optional[List[VectorStoreSearchResponse]] = ( - request_data.get("search_results") - ) + search_results: Optional[List[VectorStoreSearchResponse]] = request_data.get("search_results") - verbose_logger.debug( - f"Search results found for streaming chunk: {search_results is not None}" - ) + verbose_logger.debug(f"Search results found for streaming chunk: {search_results is not None}") if not search_results: verbose_logger.debug("No search results found for streaming chunk") @@ -345,10 +308,7 @@ async def async_post_call_streaming_deployment_hook( for choice in response_chunk.choices: if hasattr(choice, "delta") and choice.delta: # Get existing provider_specific_fields or create new dict - provider_fields = ( - getattr(choice.delta, "provider_specific_fields", None) - or {} - ) + provider_fields = getattr(choice.delta, "provider_specific_fields", None) or {} # Add search results (already in OpenAI-compatible format) provider_fields["search_results"] = search_results @@ -356,16 +316,12 @@ async def async_post_call_streaming_deployment_hook( # Set the provider_specific_fields choice.delta.provider_specific_fields = provider_fields - verbose_logger.debug( - f"Added {len(search_results)} search results to streaming chunk" - ) + verbose_logger.debug(f"Added {len(search_results)} search results to streaming chunk") # Return modified chunk return response_chunk except Exception as e: - verbose_logger.exception( - f"Error adding search results to streaming chunk: {str(e)}" - ) + verbose_logger.exception(f"Error adding search results to streaming chunk: {str(e)}") # Don't fail the request if search results fail to be added return response_chunk diff --git a/litellm/integrations/weave/weave_otel.py b/litellm/integrations/weave/weave_otel.py index 796a33a34d5f..c43afe7b6ca4 100644 --- a/litellm/integrations/weave/weave_otel.py +++ b/litellm/integrations/weave/weave_otel.py @@ -56,14 +56,10 @@ def set_messages(span: "Span", kwargs: dict[str, Any]): prompt["functions"] = functions if tools is not None: prompt["tools"] = tools - safe_set_attribute( - span, OpenInferenceSpanAttributes.INPUT_VALUE, json.dumps(prompt) - ) + safe_set_attribute(span, OpenInferenceSpanAttributes.INPUT_VALUE, json.dumps(prompt)) -def _set_weave_specific_attributes( - span: Span, kwargs: dict[str, Any], response_obj: Any -): +def _set_weave_specific_attributes(span: Span, kwargs: dict[str, Any], response_obj: Any): """ Sets Weave-specific metadata attributes onto the OTEL span. @@ -106,9 +102,7 @@ def _set_weave_specific_attributes( output_dict = response_obj if output_dict: - safe_set_attribute( - span, OpenInferenceSpanAttributes.OUTPUT_VALUE, safe_dumps(output_dict) - ) + safe_set_attribute(span, OpenInferenceSpanAttributes.OUTPUT_VALUE, safe_dumps(output_dict)) def _get_weave_authorization_header(api_key: str) -> str: @@ -142,9 +136,7 @@ def get_weave_otel_config() -> WeaveOtelConfig: host = os.getenv("WANDB_HOST") if not api_key: - raise ValueError( - "WANDB_API_KEY must be set for Weave OpenTelemetry integration." - ) + raise ValueError("WANDB_API_KEY must be set for Weave OpenTelemetry integration.") if not project_id: raise ValueError( @@ -233,9 +225,7 @@ def __init__( super().__init__(config=config, callback_name=callback_name, **kwargs) - def _maybe_log_raw_request( - self, kwargs, response_obj, start_time, end_time, parent_span - ): + def _maybe_log_raw_request(self, kwargs, response_obj, start_time, end_time, parent_span): """ Override to skip creating the raw_gen_ai_request child span. @@ -293,9 +283,7 @@ def _handle_success(self, kwargs, response_obj, start_time, end_time): primary_span_parent = None # 1. Primary span - span = self._start_primary_span( - kwargs, response_obj, start_time, end_time, ctx, primary_span_parent - ) + span = self._start_primary_span(kwargs, response_obj, start_time, end_time, ctx, primary_span_parent) # 2. Raw-request sub-span (skipped for Weave via _maybe_log_raw_request override) self._maybe_log_raw_request(kwargs, response_obj, start_time, end_time, span) @@ -329,9 +317,7 @@ def construct_dynamic_otel_headers( dynamic_headers = {} dynamic_wandb_api_key = standard_callback_dynamic_params.get("wandb_api_key") - dynamic_weave_project_id = standard_callback_dynamic_params.get( - "weave_project_id" - ) + dynamic_weave_project_id = standard_callback_dynamic_params.get("weave_project_id") if dynamic_wandb_api_key: auth_header = _get_weave_authorization_header( diff --git a/litellm/integrations/websearch_interception/handler.py b/litellm/integrations/websearch_interception/handler.py index f29b378fcdec..2e11405af3f5 100644 --- a/litellm/integrations/websearch_interception/handler.py +++ b/litellm/integrations/websearch_interception/handler.py @@ -80,9 +80,7 @@ def __init__( if enabled_providers is None: self.enabled_providers = [LlmProviders.BEDROCK.value] else: - self.enabled_providers = [ - p.value if isinstance(p, LlmProviders) else p for p in enabled_providers - ] + self.enabled_providers = [p.value if isinstance(p, LlmProviders) else p for p in enabled_providers] self.search_tool_name = search_tool_name self._request_has_websearch = False # Track if current request has web search @@ -118,10 +116,7 @@ async def try_short_circuit_search( # Check if provider is in enabled list provider_str = custom_llm_provider or "" - if ( - self.enabled_providers is not None - and provider_str not in self.enabled_providers - ): + if self.enabled_providers is not None and provider_str not in self.enabled_providers: return None # Only short-circuit for providers without native Anthropic Messages @@ -132,10 +127,8 @@ async def try_short_circuit_search( # return raw search text — a regression for existing users. try: provider_enum = LlmProviders(provider_str) - anthropic_config = ( - ProviderConfigManager.get_provider_anthropic_messages_config( - model=model, provider=provider_enum - ) + anthropic_config = ProviderConfigManager.get_provider_anthropic_messages_config( + model=model, provider=provider_enum ) if anthropic_config is not None: verbose_logger.debug( @@ -160,8 +153,7 @@ async def try_short_circuit_search( return None verbose_logger.debug( - "WebSearchInterception: Short-circuit search detected " - f"(provider={provider_str}, query='{query}')" + f"WebSearchInterception: Short-circuit search detected (provider={provider_str}, query='{query}')" ) # Native clients (Claude Desktop / Cowork / Anthropic SDK) make a @@ -180,9 +172,7 @@ async def try_short_circuit_search( try: search_result_text, structured = await self._execute_search(query) except Exception as e: - verbose_logger.error( - f"WebSearchInterception: Short-circuit search failed: {e}" - ) + verbose_logger.error(f"WebSearchInterception: Short-circuit search failed: {e}") search_result_text, structured = f"Search failed: {e}", None content: List[Dict[str, Any]] = [] @@ -225,9 +215,7 @@ async def try_short_circuit_search( ) return response - async def async_pre_call_deployment_hook( - self, kwargs: Dict[str, Any], call_type: Optional[Any] - ) -> Optional[dict]: + async def async_pre_call_deployment_hook(self, kwargs: Dict[str, Any], call_type: Optional[Any]) -> Optional[dict]: """ Pre-call hook to convert native Anthropic web_search tools to regular tools. @@ -237,14 +225,12 @@ async def async_pre_call_deployment_hook( """ # Check if this is for an enabled provider # Try top-level kwargs first, then nested litellm_params, then derive from model name - custom_llm_provider = kwargs.get("custom_llm_provider", "") or kwargs.get( - "litellm_params", {} - ).get("custom_llm_provider", "") + custom_llm_provider = kwargs.get("custom_llm_provider", "") or kwargs.get("litellm_params", {}).get( + "custom_llm_provider", "" + ) if not custom_llm_provider: try: - _, custom_llm_provider, _, _ = litellm.get_llm_provider( - model=kwargs.get("model", "") - ) + _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=kwargs.get("model", "")) except Exception: custom_llm_provider = "" if custom_llm_provider not in self.enabled_providers: @@ -261,9 +247,7 @@ async def async_pre_call_deployment_hook( if not has_websearch: return None - verbose_logger.debug( - "WebSearchInterception: Converting native web_search tools to LiteLLM standard" - ) + verbose_logger.debug("WebSearchInterception: Converting native web_search tools to LiteLLM standard") # If the client sent an Anthropic-native web_search_* tool, mark the # request so the agentic loop emits native web_search_tool_result @@ -291,18 +275,14 @@ async def async_pre_call_deployment_hook( kwargs["tools"] = converted_tools if kwargs.get("stream"): - verbose_logger.debug( - "WebSearchInterception: deployment hook converting stream=True to stream=False" - ) + verbose_logger.debug("WebSearchInterception: deployment hook converting stream=True to stream=False") kwargs["stream"] = False kwargs["_websearch_interception_converted_stream"] = True return kwargs @classmethod - def from_config_yaml( - cls, config: WebSearchInterceptionConfig - ) -> "WebSearchInterceptionLogger": + def from_config_yaml(cls, config: WebSearchInterceptionConfig) -> "WebSearchInterceptionLogger": """ Initialize WebSearchInterceptionLogger from proxy config.yaml parameters. @@ -345,9 +325,33 @@ def from_config_yaml( search_tool_name=search_tool_name, ) - async def async_pre_request_hook( - self, model: str, messages: List[Dict], kwargs: Dict - ) -> Optional[Dict]: + @staticmethod + def _tool_name(tool: dict[str, Any]) -> Optional[str]: + """Effective tool name, handling OpenAI ``function`` wrapper shape.""" + fn = tool.get("function") + if tool.get("type") == "function" and isinstance(fn, dict): + return fn.get("name") + return tool.get("name") + + @classmethod + def _sync_forced_tool_choice(cls, tool_choice: Any, converted_tools: list[dict[str, Any]]) -> Any: + """Repoint a forced ``tool_choice`` at ``litellm_web_search`` when it + names a web-search tool that was just converted away. + + Native clients (e.g. Claude Code) force the search tool via + ``tool_choice={"type": "tool", "name": "web_search"}``. Since the tool + definition gets renamed to ``litellm_web_search``, an unrewritten + ``tool_choice`` points at a tool that no longer exists, which Anthropic + rejects with "Tool 'web_search' not found in provided tools". + """ + if not isinstance(tool_choice, dict) or tool_choice.get("type") != "tool": + return tool_choice + converted_names = {cls._tool_name(t) for t in converted_tools} + if tool_choice.get("name") in converted_names: + return tool_choice + return {**tool_choice, "name": LITELLM_WEB_SEARCH_TOOL_NAME} + + async def async_pre_request_hook(self, model: str, messages: List[Dict], kwargs: Dict) -> Optional[Dict]: """ Pre-request hook to convert native web search tools to LiteLLM standard. @@ -363,9 +367,7 @@ async def async_pre_request_hook( Modified kwargs dict with converted tools, or None if no modifications needed """ # Check if this request is for an enabled provider - custom_llm_provider = kwargs.get("litellm_params", {}).get( - "custom_llm_provider", "" - ) + custom_llm_provider = kwargs.get("litellm_params", {}).get("custom_llm_provider", "") verbose_logger.debug( f"WebSearchInterception: Pre-request hook called" @@ -373,10 +375,7 @@ async def async_pre_request_hook( f" - enabled_providers={self.enabled_providers or 'ALL'}" ) - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: verbose_logger.debug( f"WebSearchInterception: Skipping - provider {custom_llm_provider} not in {self.enabled_providers}" ) @@ -392,9 +391,7 @@ async def async_pre_request_hook( if not has_websearch: return None - verbose_logger.debug( - f"WebSearchInterception: Pre-request hook triggered for provider={custom_llm_provider}" - ) + verbose_logger.debug(f"WebSearchInterception: Pre-request hook triggered for provider={custom_llm_provider}") # If the client sent an Anthropic-native web_search_* tool, mark the # request so the agentic loop emits native web_search_tool_result @@ -422,11 +419,12 @@ async def async_pre_request_hook( f"WebSearchInterception: Tools after conversion: {[t.get('name') for t in converted_tools]}" ) + if "tool_choice" in kwargs: + kwargs["tool_choice"] = self._sync_forced_tool_choice(kwargs.get("tool_choice"), converted_tools) + # Also convert here for direct callers that bypass the deployment hook. if kwargs.get("stream"): - verbose_logger.debug( - "WebSearchInterception: Converting stream=True to stream=False" - ) + verbose_logger.debug("WebSearchInterception: Converting stream=True to stream=False") kwargs["stream"] = False kwargs["_websearch_interception_converted_stream"] = True @@ -449,18 +447,13 @@ async def async_should_run_agentic_loop( For chat completions, use async_should_run_chat_completion_agentic_loop instead. """ - verbose_logger.debug( - f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}" - ) + verbose_logger.debug(f"WebSearchInterception: Hook called! provider={custom_llm_provider}, stream={stream}") verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") # Check if provider should be intercepted # Note: custom_llm_provider is already normalized by get_llm_provider() # (e.g., "bedrock/invoke/..." -> "bedrock") - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: verbose_logger.debug( f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})" ) @@ -480,9 +473,7 @@ async def async_should_run_agentic_loop( ) if not should_intercept: - verbose_logger.debug( - "WebSearchInterception: No WebSearch tool_use detected in response" - ) + verbose_logger.debug("WebSearchInterception: No WebSearch tool_use detected in response") return False, {} verbose_logger.debug( @@ -514,9 +505,7 @@ async def async_should_run_agentic_loop( thinking_block_dict: Dict = {"type": block_type} if block_type == "thinking": thinking_block_dict["thinking"] = getattr(block, "thinking", "") - thinking_block_dict["signature"] = getattr( - block, "signature", "" - ) + thinking_block_dict["signature"] = getattr(block, "signature", "") else: # redacted_thinking thinking_block_dict["data"] = getattr(block, "data", "") thinking_blocks.append(thinking_block_dict) @@ -558,23 +547,16 @@ async def async_should_run_chat_completion_agentic_loop( verbose_logger.debug(f"WebSearchInterception: Response type: {type(response)}") # Check if provider should be intercepted - if ( - self.enabled_providers is not None - and custom_llm_provider not in self.enabled_providers - ): + if self.enabled_providers is not None and custom_llm_provider not in self.enabled_providers: verbose_logger.debug( f"WebSearchInterception: Skipping provider {custom_llm_provider} (not in enabled list: {self.enabled_providers})" ) return False, {} # Check if tools include any web search tool (strict check for chat completions) - has_websearch_tool = any( - is_web_search_tool_chat_completion(t) for t in (tools or []) - ) + has_websearch_tool = any(is_web_search_tool_chat_completion(t) for t in (tools or [])) if not has_websearch_tool: - verbose_logger.debug( - "WebSearchInterception: No litellm_web_search tool in request" - ) + verbose_logger.debug("WebSearchInterception: No litellm_web_search tool in request") return False, {} # Detect WebSearch tool_calls in response (OpenAI format) @@ -585,9 +567,7 @@ async def async_should_run_chat_completion_agentic_loop( ) if not should_intercept: - verbose_logger.debug( - "WebSearchInterception: No WebSearch tool_calls detected in response" - ) + verbose_logger.debug("WebSearchInterception: No WebSearch tool_calls detected in response") return False, {} verbose_logger.debug( @@ -624,9 +604,7 @@ async def async_run_agentic_loop( tool_calls = tools["tool_calls"] thinking_blocks = tools.get("thinking_blocks", []) - verbose_logger.debug( - f"WebSearchInterception: Executing agentic loop for {len(tool_calls)} search(es)" - ) + verbose_logger.debug(f"WebSearchInterception: Executing agentic loop for {len(tool_calls)} search(es)") return await self._execute_agentic_loop( model=model, @@ -673,11 +651,9 @@ async def async_build_agentic_loop_plan( # (while we still have the structured SearchResponse list) and stash # them on plan metadata for the post-hook to inject. if kwargs.get(WEBSEARCH_EMIT_NATIVE_BLOCKS_KEY): - metadata[WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY] = ( - self._build_native_result_blocks( - tool_calls=tool_calls, - structured_results=structured_results, - ) + metadata[WEBSEARCH_NATIVE_BLOCKS_METADATA_KEY] = self._build_native_result_blocks( + tool_calls=tool_calls, + structured_results=structured_results, ) return AgenticLoopPlan( @@ -726,9 +702,7 @@ def _build_native_result_blocks( return blocks @staticmethod - def _inject_native_blocks( - response: Any, native_blocks: List[Dict[str, Any]] - ) -> Any: + def _inject_native_blocks(response: Any, native_blocks: List[Dict[str, Any]]) -> Any: """Prepend native blocks to response content, dict or object form.""" if not native_blocks: return response @@ -743,8 +717,7 @@ def _inject_native_blocks( # Object refused write — fall through and leave the response # untouched rather than crash the request. verbose_logger.debug( - "WebSearchInterception: could not inject native blocks into " - f"response of type {type(response).__name__}" + f"WebSearchInterception: could not inject native blocks into response of type {type(response).__name__}" ) return response @@ -858,9 +831,7 @@ def _prepare_followup_kwargs(kwargs: Dict) -> Dict: """ _internal_keys = {"litellm_logging_obj"} return { - k: v - for k, v in kwargs.items() - if not k.startswith("_websearch_interception") and k not in _internal_keys + k: v for k, v in kwargs.items() if not k.startswith("_websearch_interception") and k not in _internal_keys } async def _execute_agentic_loop( @@ -942,21 +913,15 @@ async def _build_anthropic_request_patch( for tool_call in tool_calls: query = tool_call["input"].get("query") if query: - verbose_logger.debug( - f"WebSearchInterception: Queuing search for query='{query}'" - ) + verbose_logger.debug(f"WebSearchInterception: Queuing search for query='{query}'") search_tasks.append(self._execute_search(query)) else: - verbose_logger.debug( - f"WebSearchInterception: Tool call {tool_call['id']} has no query" - ) + verbose_logger.debug(f"WebSearchInterception: Tool call {tool_call['id']} has no query") # Add empty result for tools without query search_tasks.append(self._create_empty_search_result()) # Execute searches in parallel - verbose_logger.debug( - f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel" - ) + verbose_logger.debug(f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel") search_results = await asyncio.gather(*search_tasks, return_exceptions=True) # Split the gathered (text, structured) tuples into two parallel lists. @@ -966,29 +931,17 @@ async def _build_anthropic_request_patch( structured_results: List[Optional[SearchResponse]] = [] for i, result in enumerate(search_results): if isinstance(result, Exception): - verbose_logger.error( - f"WebSearchInterception: Search {i} failed with error: {str(result)}" - ) + verbose_logger.error(f"WebSearchInterception: Search {i} failed with error: {str(result)}") final_search_results.append(f"Search failed: {str(result)}") structured_results.append(None) elif isinstance(result, tuple) and len(result) == 2: text_value, structured_value = result - final_search_results.append( - cast(str, text_value) - if isinstance(text_value, str) - else str(text_value) - ) - structured_results.append( - structured_value - if isinstance(structured_value, SearchResponse) - else None - ) + final_search_results.append(cast(str, text_value) if isinstance(text_value, str) else str(text_value)) + structured_results.append(structured_value if isinstance(structured_value, SearchResponse) else None) else: # Defensive: legacy callers / unexpected shape — preserve text, # drop structure. - verbose_logger.debug( - f"WebSearchInterception: Unexpected result type {type(result)} at index {i}" - ) + verbose_logger.debug(f"WebSearchInterception: Unexpected result type {type(result)} at index {i}") final_search_results.append(str(result)) structured_results.append(None) @@ -1002,35 +955,24 @@ async def _build_anthropic_request_patch( follow_up_messages = messages + [assistant_message, cast(Dict, user_message)] # Correlation context for structured logging - _call_id = getattr(logging_obj, "litellm_call_id", None) or kwargs.get( - "litellm_call_id", "unknown" - ) + _call_id = getattr(logging_obj, "litellm_call_id", None) or kwargs.get("litellm_call_id", "unknown") full_model_name = model # safe default before try block - max_tokens = self._resolve_max_tokens( - anthropic_messages_optional_request_params, kwargs - ) + max_tokens = self._resolve_max_tokens(anthropic_messages_optional_request_params, kwargs) - verbose_logger.debug( - f"WebSearchInterception: Using max_tokens={max_tokens} for follow-up request" - ) + verbose_logger.debug(f"WebSearchInterception: Using max_tokens={max_tokens} for follow-up request") optional_params_without_max_tokens = { - k: v - for k, v in anthropic_messages_optional_request_params.items() - if k != "max_tokens" + k: v for k, v in anthropic_messages_optional_request_params.items() if k != "max_tokens" } kwargs_for_followup = self._prepare_followup_kwargs(kwargs) if logging_obj is not None: - agentic_params = logging_obj.model_call_details.get( - "agentic_loop_params", {} - ) + agentic_params = logging_obj.model_call_details.get("agentic_loop_params", {}) full_model_name = agentic_params.get("model", model) verbose_logger.debug( - "WebSearchInterception: Built anthropic request patch " - "[call_id=%s model=%s messages=%d searches=%d]", + "WebSearchInterception: Built anthropic request patch [call_id=%s model=%s messages=%d searches=%d]", _call_id, full_model_name, len(follow_up_messages), @@ -1079,9 +1021,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons ] if matching_tools: search_tool = matching_tools[0] - search_provider = search_tool.get("litellm_params", {}).get( - "search_provider" - ) + search_provider = search_tool.get("litellm_params", {}).get("search_provider") verbose_logger.debug( f"WebSearchInterception: Found search tool '{self.search_tool_name}' " f"with provider '{search_provider}'" @@ -1095,9 +1035,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons # If no specific tool or not found, use first available if not search_provider and llm_router.search_tools: first_tool = llm_router.search_tools[0] - search_provider = first_tool.get("litellm_params", {}).get( - "search_provider" - ) + search_provider = first_tool.get("litellm_params", {}).get("search_provider") verbose_logger.debug( f"WebSearchInterception: Using first available search tool with provider '{search_provider}'" ) @@ -1123,9 +1061,7 @@ async def _execute_search(self, query: str) -> Tuple[str, Optional[SearchRespons ) return search_result_text, result except Exception as e: - verbose_logger.error( - f"WebSearchInterception: Search failed for '{query}': {str(e)}" - ) + verbose_logger.error(f"WebSearchInterception: Search failed for '{query}': {str(e)}") raise async def _execute_chat_completion_agentic_loop( @@ -1185,21 +1121,15 @@ async def _build_chat_completion_request_patch( query = args.get("query") if query: - verbose_logger.debug( - f"WebSearchInterception: Queuing search for query='{query}'" - ) + verbose_logger.debug(f"WebSearchInterception: Queuing search for query='{query}'") search_tasks.append(self._execute_search(query)) else: - verbose_logger.debug( - f"WebSearchInterception: Tool call {tool_call.get('id')} has no query" - ) + verbose_logger.debug(f"WebSearchInterception: Tool call {tool_call.get('id')} has no query") # Add empty result for tools without query search_tasks.append(self._create_empty_search_result()) # Execute searches in parallel - verbose_logger.debug( - f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel" - ) + verbose_logger.debug(f"WebSearchInterception: Executing {len(search_tasks)} search(es) in parallel") search_results = await asyncio.gather(*search_tasks, return_exceptions=True) # Chat-completion path only needs text — OpenAI tool_result format @@ -1207,21 +1137,13 @@ async def _build_chat_completion_request_patch( final_search_results: List[str] = [] for i, result in enumerate(search_results): if isinstance(result, Exception): - verbose_logger.error( - f"WebSearchInterception: Search {i} failed with error: {str(result)}" - ) + verbose_logger.error(f"WebSearchInterception: Search {i} failed with error: {str(result)}") final_search_results.append(f"Search failed: {str(result)}") elif isinstance(result, tuple) and len(result) == 2: text_value, _ = result - final_search_results.append( - cast(str, text_value) - if isinstance(text_value, str) - else str(text_value) - ) + final_search_results.append(cast(str, text_value) if isinstance(text_value, str) else str(text_value)) else: - verbose_logger.debug( - f"WebSearchInterception: Unexpected result type {type(result)} at index {i}" - ) + verbose_logger.debug(f"WebSearchInterception: Unexpected result type {type(result)} at index {i}") final_search_results.append(str(result)) # Build assistant and tool messages using transformation @@ -1237,9 +1159,7 @@ async def _build_chat_completion_request_patch( # Make follow-up request with search results # For OpenAI format, tool_messages_or_user is a list of tool messages if response_format == "openai": - follow_up_messages = ( - messages + [assistant_message] + cast(List[Dict], tool_messages_or_user) - ) + follow_up_messages = messages + [assistant_message] + cast(List[Dict], tool_messages_or_user) else: # For Anthropic format (shouldn't happen in this method, but handle it) follow_up_messages = messages + [ @@ -1247,12 +1167,8 @@ async def _build_chat_completion_request_patch( cast(Dict, tool_messages_or_user), ] - verbose_logger.debug( - "WebSearchInterception: Making follow-up chat completion request with search results" - ) - verbose_logger.debug( - f"WebSearchInterception: Follow-up messages count: {len(follow_up_messages)}" - ) + verbose_logger.debug("WebSearchInterception: Making follow-up chat completion request with search results") + verbose_logger.debug(f"WebSearchInterception: Follow-up messages count: {len(follow_up_messages)}") # Remove internal parameters that shouldn't be passed to follow-up request internal_params = { @@ -1265,9 +1181,7 @@ async def _build_chat_completion_request_patch( "custom_prompt_dict", } kwargs_for_followup = { - k: v - for k, v in kwargs.items() - if not k.startswith("_websearch_interception") and k not in internal_params + k: v for k, v in kwargs.items() if not k.startswith("_websearch_interception") and k not in internal_params } full_model_name = model diff --git a/litellm/integrations/websearch_interception/transformation.py b/litellm/integrations/websearch_interception/transformation.py index 9c20a3f6c775..7bbcd7ebff65 100644 --- a/litellm/integrations/websearch_interception/transformation.py +++ b/litellm/integrations/websearch_interception/transformation.py @@ -53,9 +53,7 @@ def transform_request( if stream: # This should not happen in practice since we convert streaming to non-streaming # in async_log_pre_api_call, but keep this check for safety - verbose_logger.warning( - "WebSearchInterception: Unexpected streaming response, skipping interception" - ) + verbose_logger.warning("WebSearchInterception: Unexpected streaming response, skipping interception") return False, [] # Parse non-streaming response based on format @@ -75,9 +73,7 @@ def _detect_from_non_streaming_response( content = response.get("content", []) else: if not hasattr(response, "content"): - verbose_logger.debug( - "WebSearchInterception: Response has no content attribute" - ) + verbose_logger.debug("WebSearchInterception: Response has no content attribute") return False, [] content = response.content or [] @@ -118,9 +114,7 @@ def _detect_from_non_streaming_response( "input": block_input, } tool_calls.append(tool_call) - verbose_logger.debug( - f"WebSearchInterception: Found {block_name} tool_use with id={tool_call['id']}" - ) + verbose_logger.debug(f"WebSearchInterception: Found {block_name} tool_use with id={tool_call['id']}") return len(tool_calls) > 0, tool_calls @@ -135,9 +129,7 @@ def _detect_from_openai_response( choices = response.get("choices", []) else: if not hasattr(response, "choices"): - verbose_logger.debug( - "WebSearchInterception: Response has no choices attribute" - ) + verbose_logger.debug("WebSearchInterception: Response has no choices attribute") return False, [] choices = response.choices or [] @@ -174,24 +166,16 @@ def _detect_from_openai_response( tool_id = tool_call.get("id") tool_type = tool_call.get("type") function = tool_call.get("function", {}) - function_name = ( - function.get("name") - if isinstance(function, dict) - else getattr(function, "name", None) - ) + function_name = function.get("name") if isinstance(function, dict) else getattr(function, "name", None) function_arguments = ( - function.get("arguments") - if isinstance(function, dict) - else getattr(function, "arguments", None) + function.get("arguments") if isinstance(function, dict) else getattr(function, "arguments", None) ) else: tool_id = getattr(tool_call, "id", None) tool_type = getattr(tool_call, "type", None) function = getattr(tool_call, "function", None) function_name = getattr(function, "name", None) if function else None - function_arguments = ( - getattr(function, "arguments", None) if function else None - ) + function_arguments = getattr(function, "arguments", None) if function else None # Detect function-style web search tool_calls. ``WebSearch`` is # intentionally omitted — see is_web_search_tool for the Cowork @@ -225,9 +209,7 @@ def _detect_from_openai_response( "input": arguments, # For compatibility with Anthropic format } tool_calls.append(tool_call_dict) - verbose_logger.debug( - f"WebSearchInterception: Found {function_name} tool_call with id={tool_id}" - ) + verbose_logger.debug(f"WebSearchInterception: Found {function_name} tool_call with id={tool_id}") return len(tool_calls) > 0, tool_calls @@ -259,9 +241,7 @@ def transform_response( For OpenAI: assistant_message with tool_calls, tool_messages list with tool results """ if response_format == "openai": - return WebSearchTransformation._transform_response_openai( - tool_calls, search_results - ) + return WebSearchTransformation._transform_response_openai(tool_calls, search_results) else: return WebSearchTransformation._transform_response_anthropic( tool_calls, search_results, thinking_blocks=thinking_blocks @@ -332,11 +312,7 @@ def _transform_response_openai( "type": "function", "function": { "name": tc["name"], - "arguments": ( - json.dumps(tc["input"]) - if isinstance(tc["input"], dict) - else str(tc["input"]) - ), + "arguments": (json.dumps(tc["input"]) if isinstance(tc["input"], dict) else str(tc["input"])), }, } for tc in tool_calls @@ -421,10 +397,7 @@ def format_search_response(result: SearchResponse) -> str: if hasattr(result, "results") and result.results: # Format results as text search_result_text = "\n\n".join( - [ - f"Title: {r.title}\nURL: {r.url}\nSnippet: {r.snippet}" - for r in result.results - ] + [f"Title: {r.title}\nURL: {r.url}\nSnippet: {r.snippet}" for r in result.results] ) else: search_result_text = str(result) diff --git a/litellm/integrations/weights_biases.py b/litellm/integrations/weights_biases.py index 5f087fe219a2..6d002ac4a378 100644 --- a/litellm/integrations/weights_biases.py +++ b/litellm/integrations/weights_biases.py @@ -23,9 +23,7 @@ class OpenAIResponse(Protocol[K, V]): # type: ignore def __getitem__(self, key: K) -> V: ... - def get( - self, key: K, default: Optional[V] = None - ) -> Optional[V]: ... # pragma: no cover + def get(self, key: K, default: Optional[V] = None) -> Optional[V]: ... # pragma: no cover class OpenAIRequestResponseResolver: def __call__( @@ -40,13 +38,9 @@ def __call__( elif response["object"] == "text_completion": return self._resolve_completion(request, response, time_elapsed) elif response["object"] == "chat.completion": - return self._resolve_chat_completion( - request, response, time_elapsed - ) + return self._resolve_chat_completion(request, response, time_elapsed) else: - logger.debug( - f"Unknown OpenAI response object: {response['object']}" - ) + logger.debug(f"Unknown OpenAI response object: {response['object']}") except Exception as e: logger.warning(f"Failed to resolve request/response: {e}") return None @@ -88,13 +82,8 @@ def _resolve_edit( time_elapsed: float, ) -> trace_tree.WBTraceTree: """Resolves the request and response objects for `openai.Edit`.""" - request_str = ( - f"\n\n**Instruction**: {request['instruction']}\n\n" - f"**Input**: {request['input']}\n" - ) - choices = [ - f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"] - ] + request_str = f"\n\n**Instruction**: {request['instruction']}\n\n**Input**: {request['input']}\n" + choices = [f"\n\n**Edited**: {choice['text']}\n" for choice in response["choices"]] return self._request_response_result_to_trace( request=request, @@ -112,10 +101,7 @@ def _resolve_completion( ) -> trace_tree.WBTraceTree: """Resolves the request and response objects for `openai.Completion`.""" request_str = f"\n\n**Prompt**: {request['prompt']}\n" - choices = [ - f"\n\n**Completion**: {choice['text']}\n" - for choice in response["choices"] - ] + choices = [f"\n\n**Completion**: {choice['text']}\n" for choice in response["choices"]] return self._request_response_result_to_trace( request=request, @@ -184,13 +170,9 @@ def __init__(self): try: pass except Exception: - raise Exception( - "\033[91m wandb not installed, try running 'pip install wandb' to fix this error\033[0m" - ) + raise Exception("\033[91m wandb not installed, try running 'pip install wandb' to fix this error\033[0m") if imported_openAIResponse is False: - raise Exception( - "\033[91m wandb not installed, try running 'pip install wandb' to fix this error\033[0m" - ) + raise Exception("\033[91m wandb not installed, try running 'pip install wandb' to fix this error\033[0m") self.resolver = OpenAIRequestResponseResolver() def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): @@ -202,18 +184,14 @@ def log_event(self, kwargs, response_obj, start_time, end_time, print_verbose): run = wandb.init() print_verbose(response_obj) - trace = self.resolver( - kwargs, response_obj, (end_time - start_time).total_seconds() - ) + trace = self.resolver(kwargs, response_obj, (end_time - start_time).total_seconds()) if trace is not None and run is not None: run.log({"trace": trace}) if run is not None: run.finish() - print_verbose( - f"W&B Logging Logging - final response object: {response_obj}" - ) + print_verbose(f"W&B Logging Logging - final response object: {response_obj}") except Exception: print_verbose(f"W&B Logging Layer Error - {traceback.format_exc()}") pass diff --git a/litellm/interactions/agents/http_handler.py b/litellm/interactions/agents/http_handler.py index d45ca6f43468..394b0f726346 100644 --- a/litellm/interactions/agents/http_handler.py +++ b/litellm/interactions/agents/http_handler.py @@ -62,9 +62,7 @@ def create_agent( api_base=litellm_params.get("api_base"), litellm_params=dict(litellm_params), ) - data = agents_api_config.transform_create_request( - name=name, litellm_params=dict(litellm_params) - ) + data = agents_api_config.transform_create_request(name=name, litellm_params=dict(litellm_params)) if extra_body: data.update(extra_body) @@ -78,9 +76,7 @@ def create_agent( }, ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=data, timeout=timeout or request_timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=data, timeout=timeout or request_timeout) except Exception as e: raise self._handle_error(e=e, provider_config=agents_api_config) @@ -88,9 +84,7 @@ def create_agent( original_response=response.text, additional_args={"complete_input_dict": data}, ) - return agents_api_config.transform_create_response( - raw_response=response, name=name - ) + return agents_api_config.transform_create_response(raw_response=response, name=name) async def async_create_agent( self, @@ -111,9 +105,7 @@ async def async_create_agent( api_base=litellm_params.get("api_base"), litellm_params=dict(litellm_params), ) - data = agents_api_config.transform_create_request( - name=name, litellm_params=dict(litellm_params) - ) + data = agents_api_config.transform_create_request(name=name, litellm_params=dict(litellm_params)) if extra_body: data.update(extra_body) @@ -137,9 +129,7 @@ async def async_create_agent( original_response=response.text, additional_args={"complete_input_dict": data}, ) - return agents_api_config.transform_create_response( - raw_response=response, name=name - ) + return agents_api_config.transform_create_response(raw_response=response, name=name) # ------------------------------------------------------------------ # # LIST # @@ -208,9 +198,7 @@ async def async_list_agents( additional_args={"api_base": url, "headers": headers}, ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=agents_api_config) @@ -262,9 +250,7 @@ def get_agent( raise self._handle_error(e=e, provider_config=agents_api_config) logging_obj.post_call(original_response=response.text, additional_args={}) - return agents_api_config.transform_get_response( - raw_response=response, name=name - ) + return agents_api_config.transform_get_response(raw_response=response, name=name) async def async_get_agent( self, @@ -291,16 +277,12 @@ async def async_get_agent( additional_args={"api_base": url, "headers": headers}, ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=agents_api_config) logging_obj.post_call(original_response=response.text, additional_args={}) - return agents_api_config.transform_get_response( - raw_response=response, name=name - ) + return agents_api_config.transform_get_response(raw_response=response, name=name) # ------------------------------------------------------------------ # # DELETE # @@ -342,16 +324,12 @@ def delete_agent( additional_args={"api_base": url, "headers": headers}, ) try: - response = sync_httpx_client.delete( - url=url, headers=headers, timeout=timeout or request_timeout - ) + response = sync_httpx_client.delete(url=url, headers=headers, timeout=timeout or request_timeout) except Exception as e: raise self._handle_error(e=e, provider_config=agents_api_config) logging_obj.post_call(original_response=response.text, additional_args={}) - return agents_api_config.transform_delete_response( - raw_response=response, name=name - ) + return agents_api_config.transform_delete_response(raw_response=response, name=name) async def async_delete_agent( self, @@ -378,16 +356,12 @@ async def async_delete_agent( additional_args={"api_base": url, "headers": headers}, ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, timeout=timeout or request_timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, timeout=timeout or request_timeout) except Exception as e: raise self._handle_error(e=e, provider_config=agents_api_config) logging_obj.post_call(original_response=response.text, additional_args={}) - return agents_api_config.transform_delete_response( - raw_response=response, name=name - ) + return agents_api_config.transform_delete_response(raw_response=response, name=name) # ------------------------------------------------------------------ # # LIST VERSIONS # @@ -434,9 +408,7 @@ def list_agent_versions( raise self._handle_error(e=e, provider_config=agents_api_config) logging_obj.post_call(original_response=response.text, additional_args={}) - return agents_api_config.transform_list_versions_response( - raw_response=response, name=name - ) + return agents_api_config.transform_list_versions_response(raw_response=response, name=name) async def async_list_agent_versions( self, @@ -463,16 +435,12 @@ async def async_list_agent_versions( additional_args={"api_base": url, "headers": headers}, ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=agents_api_config) logging_obj.post_call(original_response=response.text, additional_args={}) - return agents_api_config.transform_list_versions_response( - raw_response=response, name=name - ) + return agents_api_config.transform_list_versions_response(raw_response=response, name=name) agents_http_handler = AgentsHTTPHandler() diff --git a/litellm/interactions/agents/main.py b/litellm/interactions/agents/main.py index f56c6f3ed5e7..ce63332c1a62 100644 --- a/litellm/interactions/agents/main.py +++ b/litellm/interactions/agents/main.py @@ -165,9 +165,7 @@ def create( **kwargs: Forwarded to GenericLiteLLMParams (api_key, api_base, etc.). """ local_vars = locals() - custom_llm_provider = ( - custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" - ) + custom_llm_provider = custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" try: _is_async = kwargs.pop("acreate_agent", False) is True if base_agent is not None: @@ -178,9 +176,7 @@ def create( kwargs["base_environment"] = base_environment kwargs.setdefault("custom_llm_provider", custom_llm_provider) litellm_params = GenericLiteLLMParams(**kwargs) - logging_obj = _make_logging_obj( - kwargs, name, custom_llm_provider, "create_agent", {} - ) + logging_obj = _make_logging_obj(kwargs, name, custom_llm_provider, "create_agent", {}) config = _get_agents_api_config(custom_llm_provider) return agents_http_handler.create_agent( agents_api_config=config, @@ -250,16 +246,12 @@ def list( ) -> Union[AgentListResponse, Coroutine[Any, Any, AgentListResponse]]: """Sync: List all agents on the provider side.""" local_vars = locals() - custom_llm_provider = ( - custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" - ) + custom_llm_provider = custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" try: _is_async = kwargs.pop("alist_agents", False) is True kwargs.setdefault("custom_llm_provider", custom_llm_provider) litellm_params = GenericLiteLLMParams(**kwargs) - logging_obj = _make_logging_obj( - kwargs, "", custom_llm_provider, "list_agents", {} - ) + logging_obj = _make_logging_obj(kwargs, "", custom_llm_provider, "list_agents", {}) config = _get_agents_api_config(custom_llm_provider) return agents_http_handler.list_agents( agents_api_config=config, @@ -330,16 +322,12 @@ def get( ) -> Union[AgentCreateResponse, Coroutine[Any, Any, AgentCreateResponse]]: """Sync: Get a specific agent by name.""" local_vars = locals() - custom_llm_provider = ( - custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" - ) + custom_llm_provider = custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" try: _is_async = kwargs.pop("aget_agent", False) is True kwargs.setdefault("custom_llm_provider", custom_llm_provider) litellm_params = GenericLiteLLMParams(**kwargs) - logging_obj = _make_logging_obj( - kwargs, name, custom_llm_provider, "get_agent", {"name": name} - ) + logging_obj = _make_logging_obj(kwargs, name, custom_llm_provider, "get_agent", {"name": name}) config = _get_agents_api_config(custom_llm_provider) return agents_http_handler.get_agent( agents_api_config=config, @@ -411,16 +399,12 @@ def delete( ) -> Union[AgentDeleteResult, Coroutine[Any, Any, AgentDeleteResult]]: """Sync: Delete a specific agent by name.""" local_vars = locals() - custom_llm_provider = ( - custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" - ) + custom_llm_provider = custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" try: _is_async = kwargs.pop("adelete_agent", False) is True kwargs.setdefault("custom_llm_provider", custom_llm_provider) litellm_params = GenericLiteLLMParams(**kwargs) - logging_obj = _make_logging_obj( - kwargs, name, custom_llm_provider, "delete_agent", {"name": name} - ) + logging_obj = _make_logging_obj(kwargs, name, custom_llm_provider, "delete_agent", {"name": name}) config = _get_agents_api_config(custom_llm_provider) return agents_http_handler.delete_agent( agents_api_config=config, @@ -492,16 +476,12 @@ def list_versions( ) -> Union[AgentVersionsResponse, Coroutine[Any, Any, AgentVersionsResponse]]: """Sync: List versions of a specific agent.""" local_vars = locals() - custom_llm_provider = ( - custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" - ) + custom_llm_provider = custom_llm_provider or kwargs.get("custom_llm_provider") or "gemini" try: _is_async = kwargs.pop("alist_agent_versions", False) is True kwargs.setdefault("custom_llm_provider", custom_llm_provider) litellm_params = GenericLiteLLMParams(**kwargs) - logging_obj = _make_logging_obj( - kwargs, name, custom_llm_provider, "list_agent_versions", {"name": name} - ) + logging_obj = _make_logging_obj(kwargs, name, custom_llm_provider, "list_agent_versions", {"name": name}) config = _get_agents_api_config(custom_llm_provider) return agents_http_handler.list_agent_versions( agents_api_config=config, diff --git a/litellm/interactions/http_handler.py b/litellm/interactions/http_handler.py index 695da2be89a1..0e5769933fe2 100644 --- a/litellm/interactions/http_handler.py +++ b/litellm/interactions/http_handler.py @@ -64,9 +64,7 @@ def _sync_client( litellm_params: GenericLiteLLMParams, client: Optional[HTTPHandler], ) -> HTTPHandler: - return client or _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + return client or _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) def _async_client( self, @@ -117,9 +115,7 @@ def create_interaction( Coroutine[ Any, Any, - Union[ - InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse] - ], + Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]], ], ]: """ @@ -144,9 +140,7 @@ def create_interaction( ) if client is None: - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -233,9 +227,7 @@ async def async_create_interaction( timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[AsyncHTTPHandler] = None, stream: Optional[bool] = None, - ) -> Union[ - InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse] - ]: + ) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]: """ Create a new interaction (async version). """ @@ -382,9 +374,7 @@ def get_interaction( ) if client is None: - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -503,9 +493,7 @@ def delete_interaction( ) if client is None: - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -626,9 +614,7 @@ def cancel_interaction( ) if client is None: - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client diff --git a/litellm/interactions/litellm_responses_transformation/handler.py b/litellm/interactions/litellm_responses_transformation/handler.py index b121ee37de6b..4b108ee47d7e 100644 --- a/litellm/interactions/litellm_responses_transformation/handler.py +++ b/litellm/interactions/litellm_responses_transformation/handler.py @@ -123,9 +123,7 @@ async def async_interactions_api_handler( input: Optional[InteractionInput], optional_params: InteractionsAPIOptionalRequestParams, **kwargs, - ) -> Union[ - InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse] - ]: + ) -> Union[InteractionsAPIResponse, AsyncIterator[InteractionsAPIStreamingResponse]]: """Async handler for interactions API requests.""" # Call litellm.aresponses() # Note: litellm.aresponses() returns Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator] diff --git a/litellm/interactions/litellm_responses_transformation/streaming_iterator.py b/litellm/interactions/litellm_responses_transformation/streaming_iterator.py index 4a3eb63084ee..6b10a36c1798 100644 --- a/litellm/interactions/litellm_responses_transformation/streaming_iterator.py +++ b/litellm/interactions/litellm_responses_transformation/streaming_iterator.py @@ -92,9 +92,7 @@ def __init__( # Event builders # ------------------------------------------------------------------ - def _build_interaction_start_event( - self, interaction_id: str - ) -> InteractionsAPIStreamingResponse: + def _build_interaction_start_event(self, interaction_id: str) -> InteractionsAPIStreamingResponse: event_type = "interaction.start" if self._use_legacy else "interaction.created" return InteractionsAPIStreamingResponse( event_type=event_type, @@ -104,9 +102,7 @@ def _build_interaction_start_event( model=self.model, ) - def _build_content_start_event( - self, interaction_id: str - ) -> InteractionsAPIStreamingResponse: + def _build_content_start_event(self, interaction_id: str) -> InteractionsAPIStreamingResponse: if self._use_legacy: return InteractionsAPIStreamingResponse( event_type="content.start", @@ -120,9 +116,7 @@ def _build_content_start_event( step={"type": "model_output", "content": []}, ) - def _build_text_delta_event( - self, interaction_id: str, delta_text: str - ) -> InteractionsAPIStreamingResponse: + def _build_text_delta_event(self, interaction_id: str, delta_text: str) -> InteractionsAPIStreamingResponse: if self._use_legacy: return InteractionsAPIStreamingResponse( event_type="content.delta", @@ -136,9 +130,7 @@ def _build_text_delta_event( delta={"type": "text", "text": delta_text}, ) - def _build_content_stop_event( - self, interaction_id: Optional[str] - ) -> InteractionsAPIStreamingResponse: + def _build_content_stop_event(self, interaction_id: Optional[str]) -> InteractionsAPIStreamingResponse: if self._use_legacy: return InteractionsAPIStreamingResponse( event_type="content.stop", @@ -151,9 +143,7 @@ def _build_content_stop_event( index=0, ) - def _build_completion_event( - self, response_id: str - ) -> InteractionsAPIStreamingResponse: + def _build_completion_event(self, response_id: str) -> InteractionsAPIStreamingResponse: if self._use_legacy: return InteractionsAPIStreamingResponse( event_type="interaction.complete", @@ -197,13 +187,9 @@ def _events_for_chunk( # Text delta: emit any missing start events, then the delta itself. if isinstance(responses_chunk, OutputTextDeltaEvent): - delta_text = ( - responses_chunk.delta if isinstance(responses_chunk.delta, str) else "" - ) + delta_text = responses_chunk.delta if isinstance(responses_chunk.delta, str) else "" self.collected_text += delta_text - interaction_id = ( - getattr(responses_chunk, "item_id", None) or f"interaction_{id(self)}" - ) + interaction_id = getattr(responses_chunk, "item_id", None) or f"interaction_{id(self)}" if self._interaction_id is None: self._interaction_id = interaction_id @@ -223,9 +209,7 @@ def _events_for_chunk( if not self.sent_interaction_start: self.sent_interaction_start = True response_id = ( - getattr(responses_chunk.response, "id", None) - if hasattr(responses_chunk, "response") - else None + getattr(responses_chunk.response, "id", None) if hasattr(responses_chunk, "response") else None ) or f"interaction_{id(self)}" if self._interaction_id is None: self._interaction_id = response_id @@ -241,11 +225,7 @@ def _events_for_chunk( if isinstance(responses_chunk, ResponseCompletedEvent): self.finished = True response = responses_chunk.response - response_id = ( - self._interaction_id - or getattr(response, "id", None) - or f"interaction_{id(self)}" - ) + response_id = self._interaction_id or getattr(response, "id", None) or f"interaction_{id(self)}" terminal: List[InteractionsAPIStreamingResponse] = [] if self.sent_content_start: @@ -290,9 +270,7 @@ def __next__(self) -> InteractionsAPIStreamingResponse: if self.finished: raise StopIteration - sync_iterator = cast( - SyncResponsesAPIStreamingIterator, self.responses_stream_iterator - ) + sync_iterator = cast(SyncResponsesAPIStreamingIterator, self.responses_stream_iterator) while True: try: chunk = next(sync_iterator) @@ -318,9 +296,7 @@ async def __anext__(self) -> InteractionsAPIStreamingResponse: if self.finished: raise StopAsyncIteration - async_iterator = cast( - ResponsesAPIStreamingIterator, self.responses_stream_iterator - ) + async_iterator = cast(ResponsesAPIStreamingIterator, self.responses_stream_iterator) while True: try: chunk = await async_iterator.__anext__() diff --git a/litellm/interactions/litellm_responses_transformation/transformation.py b/litellm/interactions/litellm_responses_transformation/transformation.py index 0ff1a97cd0ba..a2d8ebc5d4c0 100644 --- a/litellm/interactions/litellm_responses_transformation/transformation.py +++ b/litellm/interactions/litellm_responses_transformation/transformation.py @@ -46,9 +46,7 @@ def transform_interactions_request_to_responses_request( # Transform input if input is not None: responses_request["input"] = ( - LiteLLMResponsesInteractionsConfig._transform_interactions_input_to_responses_input( - input - ) + LiteLLMResponsesInteractionsConfig._transform_interactions_input_to_responses_input(input) ) # Transform system_instruction -> instructions @@ -71,9 +69,7 @@ def transform_interactions_request_to_responses_request( # Responses API doesn't have top_k, skip it pass if "max_output_tokens" in generation_config: - responses_request["max_output_tokens"] = generation_config[ - "max_output_tokens" - ] + responses_request["max_output_tokens"] = generation_config["max_output_tokens"] # Pass through other optional params that match passthrough_params = ["stream", "store", "metadata", "user"] @@ -115,11 +111,7 @@ def _transform_interactions_input_to_responses_input( content = turn.get("content", []) # Transform content array - transformed_content = ( - LiteLLMResponsesInteractionsConfig._transform_content_array( - content - ) - ) + transformed_content = LiteLLMResponsesInteractionsConfig._transform_content_array(content) messages.append( { @@ -141,11 +133,7 @@ def _transform_interactions_input_to_responses_input( else: content_list = [] - transformed_content = ( - LiteLLMResponsesInteractionsConfig._transform_content_array( - content_list - ) - ) + transformed_content = LiteLLMResponsesInteractionsConfig._transform_content_array(content_list) messages.append( { @@ -164,9 +152,7 @@ def _transform_interactions_input_to_responses_input( { "role": "user", "content": LiteLLMResponsesInteractionsConfig._transform_content_array( - input.get("content", []) - if isinstance(input.get("content"), list) - else [input] + input.get("content", []) if isinstance(input.get("content"), list) else [input] ), } ], @@ -244,10 +230,7 @@ def transform_responses_response_to_interactions_response( # of `outputs` / `steps` don't leak into the other. outputs.append({"type": "text", "text": text}) model_output_contents.append({"type": "text", "text": text}) - elif ( - isinstance(content_item, dict) - and content_item.get("type") == "text" - ): + elif isinstance(content_item, dict) and content_item.get("type") == "text": outputs.append({**content_item}) model_output_contents.append({**content_item}) if model_output_contents: diff --git a/litellm/interactions/main.py b/litellm/interactions/main.py index d99cc3d11c7a..8634269ee948 100644 --- a/litellm/interactions/main.py +++ b/litellm/interactions/main.py @@ -134,9 +134,7 @@ async def acreate( kwargs["acreate_interaction"] = True if custom_llm_provider is None and model: - _, custom_llm_provider, _, _ = litellm.get_llm_provider( - model=model, api_base=kwargs.get("api_base", None) - ) + _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model, api_base=kwargs.get("api_base", None)) elif custom_llm_provider is None: custom_llm_provider = "gemini" @@ -290,18 +288,11 @@ def create( # Get optional params using utility (similar to responses API pattern) local_vars.update(kwargs) - optional_params = ( - InteractionsAPIRequestUtils.get_requested_interactions_api_optional_params( - local_vars - ) - ) + optional_params = InteractionsAPIRequestUtils.get_requested_interactions_api_optional_params(local_vars) # Check if this is a bridge provider (litellm_responses) - similar to responses API # Either provider is explicitly "litellm_responses" or no config found (bridge to responses) - if ( - custom_llm_provider == "litellm_responses" - or interactions_api_config is None - ): + if custom_llm_provider == "litellm_responses" or interactions_api_config is None: # Bridge to litellm.responses() for non-native providers from litellm.interactions.litellm_responses_transformation.handler import ( LiteLLMResponsesInteractionsHandler, @@ -425,9 +416,7 @@ def get( ) if interactions_api_config is None: - raise ValueError( - f"Interactions API not supported for: {custom_llm_provider}" - ) + raise ValueError(f"Interactions API not supported for: {custom_llm_provider}") litellm_logging_obj.update_from_kwargs( kwargs=kwargs, @@ -529,9 +518,7 @@ def delete( ) if interactions_api_config is None: - raise ValueError( - f"Interactions API not supported for: {custom_llm_provider}" - ) + raise ValueError(f"Interactions API not supported for: {custom_llm_provider}") litellm_logging_obj.update_from_kwargs( kwargs=kwargs, @@ -633,9 +620,7 @@ def cancel( ) if interactions_api_config is None: - raise ValueError( - f"Interactions API not supported for: {custom_llm_provider}" - ) + raise ValueError(f"Interactions API not supported for: {custom_llm_provider}") litellm_logging_obj.update_from_kwargs( kwargs=kwargs, diff --git a/litellm/interactions/streaming_iterator.py b/litellm/interactions/streaming_iterator.py index 561686a3e1b7..45c5443cfd2c 100644 --- a/litellm/interactions/streaming_iterator.py +++ b/litellm/interactions/streaming_iterator.py @@ -57,20 +57,14 @@ def __init__( # set hidden params for response headers _api_base = get_api_base( model=model or "", - optional_params=self.logging_obj.model_call_details.get( - "litellm_params", {} - ), - ) - _model_info: Dict = ( - litellm_metadata.get("model_info", {}) if litellm_metadata else {} + optional_params=self.logging_obj.model_call_details.get("litellm_params", {}), ) + _model_info: Dict = litellm_metadata.get("model_info", {}) if litellm_metadata else {} self._hidden_params = { "model_id": _model_info.get("id", None), "api_base": _api_base, } - self._hidden_params["additional_headers"] = process_response_headers( - self.response.headers or {} - ) + self._hidden_params["additional_headers"] = process_response_headers(self.response.headers or {}) def _process_chunk(self, chunk: str) -> Optional[InteractionsAPIStreamingResponse]: """Process a single chunk of data from the stream.""" @@ -93,12 +87,10 @@ def _process_chunk(self, chunk: str) -> Optional[InteractionsAPIStreamingRespons # Format as InteractionsAPIStreamingResponse if isinstance(parsed_chunk, dict): - streaming_response = ( - self.interactions_api_config.transform_streaming_response( - model=self.model, - parsed_chunk=parsed_chunk, - logging_obj=self.logging_obj, - ) + streaming_response = self.interactions_api_config.transform_streaming_response( + model=self.model, + parsed_chunk=parsed_chunk, + logging_obj=self.logging_obj, ) # Store the completed response. @@ -107,8 +99,7 @@ def _process_chunk(self, chunk: str) -> Optional[InteractionsAPIStreamingRespons # Remove the legacy check after June 8, 2026. if streaming_response and ( getattr(streaming_response, "status", None) == "completed" - or getattr(streaming_response, "event_type", None) - == "interaction.completed" + or getattr(streaming_response, "event_type", None) == "interaction.completed" ): self.completed_response = streaming_response self._handle_logging_completed_response() @@ -118,9 +109,7 @@ def _process_chunk(self, chunk: str) -> Optional[InteractionsAPIStreamingRespons return None except json.JSONDecodeError: # If we can't parse the chunk, continue - verbose_logger.debug( - f"Failed to parse streaming chunk: {stripped_chunk[:200]}..." - ) + verbose_logger.debug(f"Failed to parse streaming chunk: {stripped_chunk[:200]}...") return None def _handle_logging_completed_response(self): diff --git a/litellm/interactions/utils.py b/litellm/interactions/utils.py index 84437f4d3d82..3dffaa538ba6 100644 --- a/litellm/interactions/utils.py +++ b/litellm/interactions/utils.py @@ -72,17 +72,13 @@ def get_requested_interactions_api_optional_params( special_params = params.pop("kwargs", {}) additional_drop_params = params.pop("additional_drop_params", None) - non_default_params = ( - PreProcessNonDefaultParams.base_pre_process_non_default_params( - passed_params=params, - special_params=special_params, - custom_llm_provider=custom_llm_provider, - additional_drop_params=additional_drop_params, - default_param_values={ - k: None for k in INTERACTIONS_API_OPTIONAL_PARAMS - }, - additional_endpoint_specific_params=["input", "model", "agent"], - ) + non_default_params = PreProcessNonDefaultParams.base_pre_process_non_default_params( + passed_params=params, + special_params=special_params, + custom_llm_provider=custom_llm_provider, + additional_drop_params=additional_drop_params, + default_param_values={k: None for k in INTERACTIONS_API_OPTIONAL_PARAMS}, + additional_endpoint_specific_params=["input", "model", "agent"], ) return cast(InteractionsAPIOptionalRequestParams, non_default_params) diff --git a/litellm/litellm_core_utils/asyncify.py b/litellm/litellm_core_utils/asyncify.py index 8d56a1bbe2a9..095851711479 100644 --- a/litellm/litellm_core_utils/asyncify.py +++ b/litellm/litellm_core_utils/asyncify.py @@ -45,9 +45,7 @@ def asyncify( and returns the result. """ - async def wrapper( - *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs - ) -> T_Retval: + async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval: partial_f = functools.partial(function, *args, **kwargs) # In `v4.1.0` anyio added the `abandon_on_cancel` argument and deprecated the old diff --git a/litellm/litellm_core_utils/audio_utils/utils.py b/litellm/litellm_core_utils/audio_utils/utils.py index 82f5c27f836f..f86243c73b78 100644 --- a/litellm/litellm_core_utils/audio_utils/utils.py +++ b/litellm/litellm_core_utils/audio_utils/utils.py @@ -96,9 +96,7 @@ def process_audio_file(audio_file: FileTypes) -> ProcessedAudioFile: raise ValueError(f"Unsupported content type in tuple: {type(content)}") else: raise ValueError("Tuple must have at least 2 elements: (filename, content)") - elif hasattr(audio_file, "read") and not isinstance( - audio_file, (str, bytes, bytearray, tuple, os.PathLike) - ): + elif hasattr(audio_file, "read") and not isinstance(audio_file, (str, bytes, bytearray, tuple, os.PathLike)): # File-like object (IO) - check this after all other types filename = getattr(audio_file, "name", "audio.wav") file_content = audio_file.read() # type: ignore @@ -122,9 +120,7 @@ def process_audio_file(audio_file: FileTypes) -> ProcessedAudioFile: # If extension is not recognized, fallback to audio/wav content_type = "audio/wav" - return ProcessedAudioFile( - file_content=file_content, filename=filename, content_type=content_type - ) + return ProcessedAudioFile(file_content=file_content, filename=filename, content_type=content_type) def get_audio_file_name(file_obj: FileTypes) -> str: @@ -184,11 +180,7 @@ def get_audio_file_content_hash(file_obj: FileTypes) -> str: file_content = None elif hasattr(file_content_obj, "read"): try: - current_position = ( - file_content_obj.tell() - if hasattr(file_content_obj, "tell") - else None - ) + current_position = file_content_obj.tell() if hasattr(file_content_obj, "tell") else None if hasattr(file_content_obj, "seek"): file_content_obj.seek(0) file_content = file_content_obj.read() # type: ignore @@ -270,9 +262,7 @@ def calculate_request_duration(file: FileTypes) -> Optional[float]: content = file[1] if isinstance(content, bytes): file_content = content - elif hasattr(content, "read") and not isinstance( - content, (str, os.PathLike) - ): + elif hasattr(content, "read") and not isinstance(content, (str, os.PathLike)): # File-like object in tuple current_pos = getattr(content, "tell", lambda: None)() # Seek to start to ensure we read the entire content diff --git a/litellm/litellm_core_utils/chat_completion_agentic_loop.py b/litellm/litellm_core_utils/chat_completion_agentic_loop.py index 938e892bd50c..828605d5ef83 100644 --- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py +++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py @@ -54,11 +54,7 @@ def _agentic_loop_settings(kwargs: dict[str, object]) -> tuple[int, int, list[st depth = _coerce_int(kwargs.get("_agentic_loop_depth"), 0) max_loops = max(_coerce_int(kwargs.get("max_agentic_loops"), 3), 1) raw_fingerprints = kwargs.get("_agentic_loop_fingerprints") - fingerprints = ( - [str(fp) for fp in raw_fingerprints] - if isinstance(raw_fingerprints, list) - else [] - ) + fingerprints = [str(fp) for fp in raw_fingerprints] if isinstance(raw_fingerprints, list) else [] return depth, max_loops, fingerprints @@ -78,9 +74,7 @@ def _check_agentic_loop_safety( ) -> str: fingerprint = _fingerprint_tools(tool_calls) if fingerprint in fingerprints: - raise ValueError( - "Agentic loop detected repeated tool-call fingerprint; aborting rerun" - ) + raise ValueError("Agentic loop detected repeated tool-call fingerprint; aborting rerun") if depth >= max_loops: raise ValueError(f"Exceeded max_agentic_loops={max_loops} for model={model}") return fingerprint @@ -102,11 +96,7 @@ def _add_agentic_loop_metadata(kwargs_for_followup: dict[str, object]) -> None: metadata = kwargs_for_followup.get("litellm_metadata") metadata = dict(metadata) if isinstance(metadata, dict) else {} for key, value in kwargs_for_followup.items(): - if ( - key.startswith("_agentic_loop") - or key == "max_agentic_loops" - or is_interception_internal_key(key) - ): + if key.startswith("_agentic_loop") or key == "max_agentic_loops" or is_interception_internal_key(key): metadata[key] = value kwargs_for_followup["litellm_metadata"] = metadata @@ -115,9 +105,7 @@ def _filter_followup_kwargs(source: dict[str, object]) -> dict[str, object]: return { k: v for k, v in source.items() - if not is_interception_internal_key( - k, prefixes=NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES - ) + if not is_interception_internal_key(k, prefixes=NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES) and k not in _FOLLOWUP_INTERNAL_PARAMS } @@ -154,11 +142,7 @@ async def _execute_chat_completion_agentic_plan( kwargs_for_followup = _filter_followup_kwargs(kwargs) kwargs_for_followup.update( - { - k: v - for k, v in _filter_followup_kwargs(patch.kwargs).items() - if k not in optional_params_for_followup - } + {k: v for k, v in _filter_followup_kwargs(patch.kwargs).items() if k not in optional_params_for_followup} ) kwargs_for_followup["_agentic_loop_depth"] = depth + 1 kwargs_for_followup["max_agentic_loops"] = max_loops @@ -174,10 +158,8 @@ async def _execute_chat_completion_agentic_plan( ) if _post_hook_overridden(callback): try: - response_followup = ( - await callback.async_post_agentic_loop_response_hook( - response=response_followup, plan=plan, kwargs=kwargs - ) + response_followup = await callback.async_post_agentic_loop_response_hook( + response=response_followup, plan=plan, kwargs=kwargs ) except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") @@ -197,8 +179,7 @@ async def _execute_chat_completion_agentic_plan( except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") verbose_logger.exception( - "LiteLLM.AgenticHookError: Exception in " - "async_agentic_loop_cleanup_hook [call_id=%s model=%s]: %s", + "LiteLLM.AgenticHookError: Exception in async_agentic_loop_cleanup_hook [call_id=%s model=%s]: %s", _call_id, model, str(e), @@ -218,9 +199,7 @@ async def maybe_run_chat_completion_agentic_loop( ) -> ModelResponse | CustomStreamWrapper | None: import litellm - callbacks = litellm.callbacks + ( - getattr(logging_obj, "dynamic_success_callbacks", None) or [] - ) + callbacks = litellm.callbacks + (getattr(logging_obj, "dynamic_success_callbacks", None) or []) depth, max_loops, fingerprints = _agentic_loop_settings(kwargs) tools = optional_params.get("tools", []) @@ -320,11 +299,7 @@ async def maybe_run_chat_completion_agentic_loop( str(e), ) - if ( - kwargs.get("_code_interpreter_interception_converted_stream") - and not depth - and hasattr(response, "choices") - ): + if kwargs.get("_code_interpreter_interception_converted_stream") and not depth and hasattr(response, "choices"): return cast( "ModelResponse | CustomStreamWrapper", _wrap_response_as_fake_stream(response), diff --git a/litellm/litellm_core_utils/cloud_storage_security.py b/litellm/litellm_core_utils/cloud_storage_security.py index a75d1178d5ac..a62dfe61805b 100644 --- a/litellm/litellm_core_utils/cloud_storage_security.py +++ b/litellm/litellm_core_utils/cloud_storage_security.py @@ -27,17 +27,13 @@ def is_managed_cloud_storage_uri(file_id: str) -> bool: retrieved through their managed unified file id so owner/team access is enforced; a raw URI supplied by a caller bypasses that check. """ - return isinstance(file_id, str) and file_id.startswith( - MANAGED_CLOUD_STORAGE_SCHEMES - ) + return isinstance(file_id, str) and file_id.startswith(MANAGED_CLOUD_STORAGE_SCHEMES) _SAFE_OBJECT_COMPONENT_PATTERN = re.compile(r"[^A-Za-z0-9._-]+") -def sanitize_cloud_object_component( - value: Optional[str], fallback: str = "file" -) -> str: +def sanitize_cloud_object_component(value: Optional[str], fallback: str = "file") -> str: if not isinstance(value, str): return fallback @@ -45,9 +41,7 @@ def sanitize_cloud_object_component( if component in {"", ".", ".."}: return fallback - component = "".join( - "_" if ord(char) < 32 or ord(char) == 127 else char for char in component - ) + component = "".join("_" if ord(char) < 32 or ord(char) == 127 else char for char in component) component = _SAFE_OBJECT_COMPONENT_PATTERN.sub("_", component) component = component.strip("._") if not component: @@ -70,12 +64,8 @@ def sanitize_cloud_object_path(value: Optional[str], fallback: str = "file") -> return "/".join(segments) -def build_managed_cloud_object_name( - prefix: str, filename: Optional[str], fallback_filename: str = "file" -) -> str: - safe_filename = sanitize_cloud_object_component( - filename, fallback=fallback_filename - ) +def build_managed_cloud_object_name(prefix: str, filename: Optional[str], fallback_filename: str = "file") -> str: + safe_filename = sanitize_cloud_object_component(filename, fallback=fallback_filename) return f"{prefix}{uuid.uuid4().hex}-{safe_filename}" @@ -99,9 +89,7 @@ def split_configured_cloud_bucket_name(bucket_name: str) -> Tuple[str, str]: bucket_name = bucket_name.strip() if "://" in bucket_name or "?" in bucket_name or "#" in bucket_name: - raise ValueError( - "Cloud storage bucket name must not include a URI scheme or query" - ) + raise ValueError("Cloud storage bucket name must not include a URI scheme or query") if any(ord(char) < 32 or ord(char) == 127 for char in bucket_name): raise ValueError("Cloud storage bucket name contains control characters") @@ -131,13 +119,9 @@ def should_allow_legacy_cloud_file_ids( ) -> bool: value = None if isinstance(litellm_params, Mapping): - trusted_model_credentials = litellm_params.get( - "_litellm_internal_model_credentials" - ) + trusted_model_credentials = litellm_params.get("_litellm_internal_model_credentials") if isinstance(trusted_model_credentials, _MAPPING_PROXY_TYPE): - value = cast(Mapping[str, Any], trusted_model_credentials).get( - "allow_legacy_cloud_file_ids" - ) + value = cast(Mapping[str, Any], trusted_model_credentials).get("allow_legacy_cloud_file_ids") if isinstance(value, bool): return value @@ -162,29 +146,21 @@ def validate_managed_cloud_file_id( raise ValueError("file_id must include a cloud storage object name") bucket_name, object_name = full_path.split("/", 1) - configured_bucket, configured_prefix = split_configured_cloud_bucket_name( - configured_bucket_name - ) + configured_bucket, configured_prefix = split_configured_cloud_bucket_name(configured_bucket_name) if bucket_name != configured_bucket: raise ValueError("file_id bucket does not match the configured storage bucket") _validate_cloud_object_path(object_name) allowed_prefixes = tuple(allowed_object_prefixes) if configured_prefix: - allowed_prefixes = tuple( - f"{configured_prefix.rstrip('/')}/{prefix}" for prefix in allowed_prefixes - ) + allowed_prefixes = tuple(f"{configured_prefix.rstrip('/')}/{prefix}" for prefix in allowed_prefixes) if object_name.startswith(allowed_prefixes): return bucket_name, object_name if allow_legacy_cloud_file_ids: - if configured_prefix and not object_name.startswith( - f"{configured_prefix.rstrip('/')}/" - ): - raise ValueError( - "file_id object does not match the configured storage prefix" - ) + if configured_prefix and not object_name.startswith(f"{configured_prefix.rstrip('/')}/"): + raise ValueError("file_id object does not match the configured storage prefix") return bucket_name, object_name raise ValueError("file_id must reference a LiteLLM-managed storage object") diff --git a/litellm/litellm_core_utils/completion_timeout.py b/litellm/litellm_core_utils/completion_timeout.py index 70c6896a323f..794749a39bf3 100644 --- a/litellm/litellm_core_utils/completion_timeout.py +++ b/litellm/litellm_core_utils/completion_timeout.py @@ -56,18 +56,12 @@ def resolve( elif kwargs.get("request_timeout") is not None: resolved = kwargs["request_timeout"] else: - resolved = CompletionTimeout._fallback_when_no_explicit_timeout( - global_timeout - ) + resolved = CompletionTimeout._fallback_when_no_explicit_timeout(global_timeout) - if isinstance(resolved, httpx.Timeout) and not supports_httpx_timeout( - custom_llm_provider - ): + if isinstance(resolved, httpx.Timeout) and not supports_httpx_timeout(custom_llm_provider): read_timeout = resolved.read resolved = ( - float(read_timeout) - if read_timeout is not None - else COMPLETION_HTTP_FALLBACK_SECONDS + float(read_timeout) if read_timeout is not None else COMPLETION_HTTP_FALLBACK_SECONDS ) # default 10 min timeout elif not isinstance(resolved, httpx.Timeout): resolved = float(resolved) # type: ignore diff --git a/litellm/litellm_core_utils/core_helpers.py b/litellm/litellm_core_utils/core_helpers.py index 0cdd721598cc..002a46771e38 100644 --- a/litellm/litellm_core_utils/core_helpers.py +++ b/litellm/litellm_core_utils/core_helpers.py @@ -18,9 +18,7 @@ Span = Any -def safe_divide_seconds( - seconds: float, denominator: float, default: Optional[float] = None -) -> Optional[float]: +def safe_divide_seconds(seconds: float, denominator: float, default: Optional[float] = None) -> Optional[float]: """ Safely divide seconds by denominator, handling zero division. @@ -109,9 +107,7 @@ def safe_divide( def map_finish_reason(finish_reason: str) -> OpenAIChatCompletionFinishReason: mapped = _FINISH_REASON_MAP.get(finish_reason) if mapped is None: - verbose_logger.warning( - "Unmapped finish_reason '%s', defaulting to 'stop'", finish_reason - ) + verbose_logger.warning("Unmapped finish_reason '%s', defaulting to 'stop'", finish_reason) return "stop" return mapped @@ -124,9 +120,7 @@ def remove_index_from_tool_calls( _tool_calls = message.get("tool_calls") if _tool_calls is not None and isinstance(_tool_calls, list): for tool_call in _tool_calls: - if ( - isinstance(tool_call, dict) and "index" in tool_call - ): # Type guard to ensure it's a dict + if isinstance(tool_call, dict) and "index" in tool_call: # Type guard to ensure it's a dict tool_call.pop("index", None) return @@ -141,9 +135,7 @@ def remove_items_at_indices(items: Optional[List[Any]], indices: Iterable[int]) items.pop(index) -def add_missing_spend_metadata_to_litellm_metadata( - litellm_metadata: dict, metadata: dict -) -> dict: +def add_missing_spend_metadata_to_litellm_metadata(litellm_metadata: dict, metadata: dict) -> dict: """ Helper to get litellm metadata for spend tracking @@ -185,9 +177,7 @@ def get_litellm_metadata_from_kwargs(kwargs: dict): metadata = litellm_params.get("metadata", {}) litellm_metadata = litellm_params.get("litellm_metadata", {}) if litellm_metadata and metadata: - litellm_metadata = add_missing_spend_metadata_to_litellm_metadata( - litellm_metadata, metadata - ) + litellm_metadata = add_missing_spend_metadata_to_litellm_metadata(litellm_metadata, metadata) if litellm_metadata: return litellm_metadata elif metadata: @@ -236,9 +226,7 @@ def _get_parent_otel_span_from_kwargs( return kwargs["litellm_parent_otel_span"] return None except Exception as e: - verbose_logger.exception( - "Error in _get_parent_otel_span_from_kwargs: " + str(e) - ) + verbose_logger.exception("Error in _get_parent_otel_span_from_kwargs: " + str(e)) return None @@ -271,9 +259,7 @@ def process_response_headers( for k, v in response_headers.items(): if k in OPENAI_RESPONSE_HEADERS: # return openai-compatible headers openai_headers[k] = v - if k.startswith( - "llm_provider-" - ): # return raw provider headers (incl. openai-compatible ones) + if k.startswith("llm_provider-"): # return raw provider headers (incl. openai-compatible ones) processed_headers[k] = v elif _preserve and k.startswith("x-litellm-"): # LiteLLM's own internal headers (e.g. x-litellm-attempted-fallbacks, @@ -330,13 +316,8 @@ def safe_deep_copy(data): if "metadata" in data and "litellm_parent_otel_span" in data["metadata"]: litellm_parent_otel_span = data["metadata"].pop("litellm_parent_otel_span") data["metadata"]["litellm_parent_otel_span"] = "placeholder" - if ( - "litellm_metadata" in data - and "litellm_parent_otel_span" in data["litellm_metadata"] - ): - litellm_parent_otel_span = data["litellm_metadata"].pop( - "litellm_parent_otel_span" - ) + if "litellm_metadata" in data and "litellm_parent_otel_span" in data["litellm_metadata"]: + litellm_parent_otel_span = data["litellm_metadata"].pop("litellm_parent_otel_span") data["litellm_metadata"]["litellm_parent_otel_span"] = "placeholder" # Step 2: Per-key deepcopy with fallback @@ -357,13 +338,8 @@ def safe_deep_copy(data): if isinstance(data, dict) and litellm_parent_otel_span is not None: if "metadata" in data and "litellm_parent_otel_span" in data["metadata"]: data["metadata"]["litellm_parent_otel_span"] = litellm_parent_otel_span - if ( - "litellm_metadata" in data - and "litellm_parent_otel_span" in data["litellm_metadata"] - ): - data["litellm_metadata"]["litellm_parent_otel_span"] = ( - litellm_parent_otel_span - ) + if "litellm_metadata" in data and "litellm_parent_otel_span" in data["litellm_metadata"]: + data["litellm_metadata"]["litellm_parent_otel_span"] = litellm_parent_otel_span return new_data @@ -416,9 +392,7 @@ def filter_exceptions_from_params(data: Any, max_depth: int = 20) -> Any: result_list: list[Any] = [] for item in data: # Skip exception and callable items - if isinstance(item, Exception) or ( - callable(item) and not isinstance(item, type) - ): + if isinstance(item, Exception) or (callable(item) and not isinstance(item, type)): continue try: filtered = filter_exceptions_from_params(item, max_depth - 1) @@ -432,9 +406,7 @@ def filter_exceptions_from_params(data: Any, max_depth: int = 20) -> Any: return data -def filter_internal_params( - data: dict, additional_internal_params: Optional[set] = None -) -> dict: +def filter_internal_params(data: dict, additional_internal_params: Optional[set] = None) -> dict: """ Filter out LiteLLM internal parameters that shouldn't be sent to provider APIs. diff --git a/litellm/litellm_core_utils/default_encoding.py b/litellm/litellm_core_utils/default_encoding.py index f58b90c8e720..38aacb47f049 100644 --- a/litellm/litellm_core_utils/default_encoding.py +++ b/litellm/litellm_core_utils/default_encoding.py @@ -11,9 +11,7 @@ # Old way to access resources, which setuptools deprecated some time ago import pkg_resources # type: ignore - filename = pkg_resources.resource_filename( - __name__, "litellm_core_utils/tokenizers" - ) + filename = pkg_resources.resource_filename(__name__, "litellm_core_utils/tokenizers") # Always default TIKTOKEN_CACHE_DIR to the bundled tokenizers directory # unless the user explicitly overrides it via CUSTOM_TIKTOKEN_CACHE_DIR. diff --git a/litellm/litellm_core_utils/dot_notation_indexing.py b/litellm/litellm_core_utils/dot_notation_indexing.py index 65810e83c66d..85abbdddffc0 100644 --- a/litellm/litellm_core_utils/dot_notation_indexing.py +++ b/litellm/litellm_core_utils/dot_notation_indexing.py @@ -28,9 +28,7 @@ T = TypeVar("T") -def get_nested_value( - data: Dict[str, Any], key_path: str, default: Optional[T] = None -) -> Optional[T]: +def get_nested_value(data: Dict[str, Any], key_path: str, default: Optional[T] = None) -> Optional[T]: """ Retrieves a value from a nested dictionary using dot notation. @@ -56,11 +54,7 @@ def get_nested_value( return default # Remove metadata. prefix if it exists - key_path = ( - key_path.replace("metadata.", "", 1) - if key_path.startswith("metadata.") - else key_path - ) + key_path = key_path.replace("metadata.", "", 1) if key_path.startswith("metadata.") else key_path # Split the key path into parts, respecting escaped dots (\.) # Use a temporary placeholder, split on unescaped dots, then restore @@ -158,9 +152,7 @@ def _delete_nested_value_custom( # Only recurse if element is a dict or list (nested structure) element = data[index] if isinstance(element, (dict, list)): - _delete_nested_value_custom( - element, segments, segment_index + 1 - ) + _delete_nested_value_custom(element, segments, segment_index + 1) except (ValueError, IndexError): # Invalid index, skip pass @@ -174,23 +166,15 @@ def _delete_nested_value_custom( else: # Navigate deeper if segment in data: - next_segment = ( - segments[segment_index + 1] - if segment_index + 1 < len(segments) - else None - ) + next_segment = segments[segment_index + 1] if segment_index + 1 < len(segments) else None # If next segment is array notation, current field should be list if next_segment and (next_segment.startswith("[")): if isinstance(data[segment], list): - _delete_nested_value_custom( - data[segment], segments, segment_index + 1 - ) + _delete_nested_value_custom(data[segment], segments, segment_index + 1) # Otherwise navigate into dict elif isinstance(data[segment], dict): - _delete_nested_value_custom( - data[segment], segments, segment_index + 1 - ) + _delete_nested_value_custom(data[segment], segments, segment_index + 1) def delete_nested_value( diff --git a/litellm/litellm_core_utils/duration_parser.py b/litellm/litellm_core_utils/duration_parser.py index 036d691c686f..438ff5600ba8 100644 --- a/litellm/litellm_core_utils/duration_parser.py +++ b/litellm/litellm_core_utils/duration_parser.py @@ -94,9 +94,7 @@ def duration_in_seconds(duration: str) -> int: raise ValueError(f"Unsupported duration unit, passed duration: {duration}") -def get_next_standardized_reset_time( - duration: str, current_time: datetime, timezone_str: str = "UTC" -) -> datetime: +def get_next_standardized_reset_time(duration: str, current_time: datetime, timezone_str: str = "UTC") -> datetime: """ Get the next standardized reset time based on the duration. @@ -121,9 +119,7 @@ def get_next_standardized_reset_time( value, unit = _parse_duration(duration) if value is None: # Fall back to default if format is invalid - return current_time.replace( - hour=0, minute=0, second=0, microsecond=0 - ) + timedelta(days=1) + return current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1) # Midnight of the current day in the specified timezone base_midnight = current_time.replace(hour=0, minute=0, second=0, microsecond=0) @@ -146,9 +142,7 @@ def get_next_standardized_reset_time( return base_midnight + timedelta(days=1) -def _setup_timezone( - current_time: datetime, timezone_str: str = "UTC" -) -> Tuple[datetime, tzinfo]: +def _setup_timezone(current_time: datetime, timezone_str: str = "UTC") -> Tuple[datetime, tzinfo]: """Set up timezone and normalize current time to that timezone.""" try: if timezone_str is None: @@ -181,9 +175,7 @@ def _parse_duration(duration: str) -> Tuple[Optional[int], Optional[str]]: return int(value), unit -def _handle_day_reset( - current_time: datetime, base_midnight: datetime, value: int, tz: tzinfo -) -> datetime: +def _handle_day_reset(current_time: datetime, base_midnight: datetime, value: int, tz: tzinfo) -> datetime: """Handle day-based reset times.""" # Handle zero value - immediate expiration if value == 0: @@ -222,14 +214,10 @@ def _handle_day_reset( ) return next_reset else: # Custom day value - next interval is value days from current - return current_time.replace( - hour=0, minute=0, second=0, microsecond=0 - ) + timedelta(days=value) + return current_time.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=value) -def _handle_hour_reset( - current_time: datetime, base_midnight: datetime, value: int -) -> datetime: +def _handle_hour_reset(current_time: datetime, base_midnight: datetime, value: int) -> datetime: """Handle hour-based reset times.""" # Handle zero value - immediate expiration if value == 0: @@ -242,17 +230,9 @@ def _handle_hour_reset( # Calculate next hour aligned with the value if current_minute == 0 and current_second == 0 and current_microsecond == 0: - next_hour = ( - current_hour + value - (current_hour % value) - if current_hour % value != 0 - else current_hour + value - ) + next_hour = current_hour + value - (current_hour % value) if current_hour % value != 0 else current_hour + value else: - next_hour = ( - current_hour + value - (current_hour % value) - if current_hour % value != 0 - else current_hour + value - ) + next_hour = current_hour + value - (current_hour % value) if current_hour % value != 0 else current_hour + value # Handle overnight case if next_hour >= 24: @@ -263,9 +243,7 @@ def _handle_hour_reset( return current_time.replace(hour=next_hour, minute=0, second=0, microsecond=0) -def _handle_minute_reset( - current_time: datetime, base_midnight: datetime, value: int -) -> datetime: +def _handle_minute_reset(current_time: datetime, base_midnight: datetime, value: int) -> datetime: """Handle minute-based reset times.""" # Handle zero value - immediate expiration if value == 0: @@ -279,15 +257,11 @@ def _handle_minute_reset( # Calculate next minute aligned with the value if current_second == 0 and current_microsecond == 0: next_minute = ( - current_minute + value - (current_minute % value) - if current_minute % value != 0 - else current_minute + value + current_minute + value - (current_minute % value) if current_minute % value != 0 else current_minute + value ) else: next_minute = ( - current_minute + value - (current_minute % value) - if current_minute % value != 0 - else current_minute + value + current_minute + value - (current_minute % value) if current_minute % value != 0 else current_minute + value ) # Handle hour rollover @@ -298,18 +272,12 @@ def _handle_minute_reset( if next_hour >= 24: next_hour = next_hour % 24 next_day = base_midnight + timedelta(days=1) - return next_day.replace( - hour=next_hour, minute=next_minute, second=0, microsecond=0 - ) + return next_day.replace(hour=next_hour, minute=next_minute, second=0, microsecond=0) - return current_time.replace( - hour=next_hour, minute=next_minute, second=0, microsecond=0 - ) + return current_time.replace(hour=next_hour, minute=next_minute, second=0, microsecond=0) -def _handle_second_reset( - current_time: datetime, base_midnight: datetime, value: int -) -> datetime: +def _handle_second_reset(current_time: datetime, base_midnight: datetime, value: int) -> datetime: """Handle second-based reset times.""" # Handle zero value - immediate expiration if value == 0: @@ -323,15 +291,11 @@ def _handle_second_reset( # Calculate next second aligned with the value if current_microsecond == 0: next_second = ( - current_second + value - (current_second % value) - if current_second % value != 0 - else current_second + value + current_second + value - (current_second % value) if current_second % value != 0 else current_second + value ) else: next_second = ( - current_second + value - (current_second % value) - if current_second % value != 0 - else current_second + value + current_second + value - (current_second % value) if current_second % value != 0 else current_second + value ) # Handle minute rollover @@ -347,18 +311,12 @@ def _handle_second_reset( if next_hour >= 24: next_hour = next_hour % 24 next_day = base_midnight + timedelta(days=1) - return next_day.replace( - hour=next_hour, minute=next_minute, second=next_second, microsecond=0 - ) + return next_day.replace(hour=next_hour, minute=next_minute, second=next_second, microsecond=0) - return current_time.replace( - hour=next_hour, minute=next_minute, second=next_second, microsecond=0 - ) + return current_time.replace(hour=next_hour, minute=next_minute, second=next_second, microsecond=0) -def _handle_month_reset( - current_time: datetime, base_midnight: datetime, value: int -) -> datetime: +def _handle_month_reset(current_time: datetime, base_midnight: datetime, value: int) -> datetime: """ Handle monthly reset times. For monthly resets, we always reset at the start of the next month. diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index a0f9bb00dd23..2441cbb39033 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -74,10 +74,7 @@ def is_error_str_context_window_exceeded(error_str: str) -> bool: # Exclude param validation errors (e.g. OpenAI "user" param max 64 chars) if "string_above_max_length" in _error_str_lowercase: return False - if ( - "invalid 'user'" in _error_str_lowercase - and "string too long" in _error_str_lowercase - ): + if "invalid 'user'" in _error_str_lowercase and "string too long" in _error_str_lowercase: return False known_exception_substrings = [ "exceed context limit", @@ -95,10 +92,7 @@ def is_error_str_context_window_exceeded(error_str: str) -> bool: return True # Cerebras pattern: "Current length is X while limit is Y" - if ( - "current length is" in _error_str_lowercase - and "while limit is" in _error_str_lowercase - ): + if "current length is" in _error_str_lowercase and "while limit is" in _error_str_lowercase: return True return False @@ -193,9 +187,7 @@ def _get_response_headers(original_exception: Exception) -> Optional[httpx.Heade if not _response_headers and error_response: _response_headers = getattr(error_response, "headers", None) if not _response_headers: - _response_headers = getattr( - original_exception, "litellm_response_headers", None - ) + _response_headers = getattr(original_exception, "litellm_response_headers", None) except Exception: return None @@ -272,8 +264,8 @@ def _map_openai_exception( else: message = str(original_exception) - if ( - message is not None and isinstance(message, str) + if message is not None and isinstance( + message, str ): # done to prevent user-confusion. Relevant issue - https://github.com/BerriAI/litellm/issues/1414 message = message.replace("OPENAI", custom_llm_provider.upper()) message = message.replace( @@ -283,9 +275,7 @@ def _map_openai_exception( if custom_llm_provider == "openai": exception_provider = "OpenAI" + "Exception" else: - exception_provider = ( - custom_llm_provider[0].upper() + custom_llm_provider[1:] + "Exception" - ) + exception_provider = custom_llm_provider[0].upper() + custom_llm_provider[1:] + "Exception" if ExceptionCheckers.is_error_str_rate_limit(error_str): raise RateLimitError( @@ -318,14 +308,9 @@ def _map_openai_exception( litellm_debug_info=extra_information, ) elif ( - ( - "invalid_request_error" in error_str - and "content_policy_violation" in error_str - ) + ("invalid_request_error" in error_str and "content_policy_violation" in error_str) or ("Invalid prompt" in error_str and "violating our usage policy" in error_str) - or ( - "request was rejected as a result of the safety system" in error_str.lower() - ) + or ("request was rejected as a result of the safety system" in error_str.lower()) ): raise ContentPolicyViolationError( message=f"ContentPolicyViolationError: {exception_provider} - {message}", @@ -334,9 +319,7 @@ def _map_openai_exception( response=getattr(original_exception, "response", None), litellm_debug_info=extra_information, ) - elif ( - "invalid_encrypted_content" in error_str or "could not be verified" in error_str - ): + elif "invalid_encrypted_content" in error_str or "could not be verified" in error_str: helpful_message = ( f"{exception_provider} - {message}\n\n" " This error occurs when load balancing Responses API across deployments with different API keys.\n" @@ -356,10 +339,7 @@ def _map_openai_exception( litellm_debug_info=extra_information, body=getattr(original_exception, "body", None), ) - elif ( - "invalid_request_error" in error_str - and "Incorrect API key provided" not in error_str - ): + elif "invalid_request_error" in error_str and "Incorrect API key provided" not in error_str: raise BadRequestError( message=f"{exception_provider} - {message}", llm_provider=custom_llm_provider, @@ -560,10 +540,7 @@ def _map_anthropic_exception( llm_provider="anthropic", model=model, ) - elif ( - original_exception.status_code == 400 - or original_exception.status_code == 413 - ): + elif original_exception.status_code == 400 or original_exception.status_code == 413: raise BadRequestError( message=f"AnthropicException - {error_str}", model=model, @@ -587,10 +564,7 @@ def _map_anthropic_exception( llm_provider="anthropic", model=model, ) - elif ( - original_exception.status_code == 500 - or original_exception.status_code == 529 - ): + elif original_exception.status_code == 500 or original_exception.status_code == 529: raise litellm.InternalServerError( message=f"AnthropicException - {error_str}. Handle with `litellm.InternalServerError`.", llm_provider="anthropic", @@ -666,10 +640,7 @@ def _map_replicate_exception( model=model, response=getattr(original_exception, "response", None), ) - elif ( - original_exception.status_code == 400 - or original_exception.status_code == 413 - ): + elif original_exception.status_code == 400 or original_exception.status_code == 413: raise BadRequestError( message=f"ReplicateException - {original_exception.message}", model=model, @@ -727,11 +698,7 @@ def _map_openai_like_exception( ) -> None: if "authorization denied for" in error_str: # Predibase returns the raw API Key in the response - this block ensures it's not returned in the exception - if ( - error_str is not None - and isinstance(error_str, str) - and "bearer" in error_str.lower() - ): + if error_str is not None and isinstance(error_str, str) and "bearer" in error_str.lower(): # only keep the first 10 chars after the occurnence of "bearer" _bearer_token_start_index = error_str.lower().find("bearer") error_str = error_str[: _bearer_token_start_index + 14] @@ -759,9 +726,7 @@ def _map_openai_like_exception( model=model, response=getattr(original_exception, "response", None), ) - elif ( - "The server received an invalid response from an upstream server." in error_str - ): + elif "The server received an invalid response from an upstream server." in error_str: raise litellm.InternalServerError( message=f"{custom_llm_provider.capitalize()}Exception - {original_exception.message}", llm_provider=custom_llm_provider, @@ -780,10 +745,7 @@ def _map_openai_like_exception( llm_provider=custom_llm_provider, model=model, ) - elif ( - original_exception.status_code == 401 - or original_exception.status_code == 403 - ): + elif original_exception.status_code == 401 or original_exception.status_code == 403: raise AuthenticationError( message=f"{custom_llm_provider.capitalize()}Exception - {original_exception.message}", llm_provider=custom_llm_provider, @@ -808,10 +770,7 @@ def _map_openai_like_exception( llm_provider=custom_llm_provider, litellm_debug_info=extra_information, ) - elif ( - original_exception.status_code == 422 - or original_exception.status_code == 424 - ): + elif original_exception.status_code == 422 or original_exception.status_code == 424: raise BadRequestError( message=f"{custom_llm_provider.capitalize()}Exception - {original_exception.message}", model=model, @@ -865,10 +824,7 @@ def _map_bedrock_exception( model=model, llm_provider="bedrock", ) - elif ( - "Conversation blocks and tool result blocks cannot be provided in the same turn." - in error_str - ): + elif "Conversation blocks and tool result blocks cannot be provided in the same turn." in error_str: raise BadRequestError( message=f"BedrockException - {error_str}\n. Enable 'litellm.modify_params=True' (for PROXY do: `litellm_settings::modify_params: True`) to insert a dummy assistant message and fix this error.", model=model, @@ -933,9 +889,7 @@ def _map_bedrock_exception( model=model, response=httpx.Response( status_code=500, - request=httpx.Request( - method="POST", url="https://api.openai.com/v1/" - ), + request=httpx.Request(method="POST", url="https://api.openai.com/v1/"), ), ) elif original_exception.status_code == 401: @@ -1042,9 +996,7 @@ def _map_sagemaker_exception( model=model, response=httpx.Response( status_code=500, - request=httpx.Request( - method="POST", url="https://api.openai.com/v1/" - ), + request=httpx.Request(method="POST", url="https://api.openai.com/v1/"), ), ) elif original_exception.status_code == 401: @@ -1075,10 +1027,7 @@ def _map_sagemaker_exception( llm_provider=custom_llm_provider, litellm_debug_info=extra_information, ) - elif ( - original_exception.status_code == 422 - or original_exception.status_code == 424 - ): + elif original_exception.status_code == 422 or original_exception.status_code == 424: raise BadRequestError( message=f"SagemakerException - {original_exception.message}", model=model, @@ -1122,10 +1071,7 @@ def _map_vertex_exception( exception_provider: str, extra_information: str, ) -> None: - if ( - "Vertex AI API has not been used in project" in error_str - or "Unable to find your project" in error_str - ): + if "Vertex AI API has not been used in project" in error_str or "Unable to find your project" in error_str: raise BadRequestError( message=f"litellm.BadRequestError: {custom_llm_provider}Exception - {error_str}", model=model, @@ -1160,9 +1106,7 @@ def _map_vertex_exception( response=httpx.Response( status_code=500, content=str(original_exception), - request=httpx.Request( - method="completion", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="completion", url="https://github.com/BerriAI/litellm"), # type: ignore ), litellm_debug_info=extra_information, ) @@ -1189,8 +1133,7 @@ def _map_vertex_exception( ) elif ( "The response was blocked." in error_str - or "Output blocked by content filtering policy" - in error_str # anthropic on vertex ai + or "Output blocked by content filtering policy" in error_str # anthropic on vertex ai ): raise ContentPolicyViolationError( message=f"{custom_llm_provider.capitalize()}Exception ContentPolicyViolationError - {error_str}", @@ -1210,8 +1153,7 @@ def _map_vertex_exception( or "Quota exceeded for" in error_str or "Resource exhausted" in error_str or "IndexError: list index out of range" in error_str - or "429 Unable to submit request because the service is temporarily out of capacity." - in error_str + or "429 Unable to submit request because the service is temporarily out of capacity." in error_str ): raise RateLimitError( message=f"litellm.RateLimitError: {custom_llm_provider}Exception - {error_str}", @@ -1248,10 +1190,7 @@ def _map_vertex_exception( ), ), ) - elif ( - "500 Internal Server Error" in error_str - or "The model is overloaded." in error_str - ): + elif "500 Internal Server Error" in error_str or "The model is overloaded." in error_str: raise litellm.InternalServerError( message=f"litellm.InternalServerError: {custom_llm_provider}Exception - {error_str}", model=model, @@ -1328,9 +1267,7 @@ def _map_vertex_exception( response=httpx.Response( status_code=500, content=str(original_exception), - request=httpx.Request( - method="completion", url="https://github.com/BerriAI/litellm" - ), # type: ignore + request=httpx.Request(method="completion", url="https://github.com/BerriAI/litellm"), # type: ignore ), ) if original_exception.status_code == 502: @@ -1412,10 +1349,7 @@ def _map_cohere_exception( response=getattr(original_exception, "response", None), ) elif hasattr(original_exception, "status_code"): - if ( - original_exception.status_code == 400 - or original_exception.status_code == 498 - ): + if original_exception.status_code == 400 or original_exception.status_code == 498: raise BadRequestError( message=f"CohereException - {original_exception.message}", llm_provider="cohere", @@ -1642,9 +1576,7 @@ def _map_nlp_cloud_exception( llm_provider="nlp_cloud", request=getattr(original_exception, "request", None), ) - if hasattr( - original_exception, "status_code" - ): # https://docs.nlpcloud.com/?shell#errors + if hasattr(original_exception, "status_code"): # https://docs.nlpcloud.com/?shell#errors if ( original_exception.status_code == 400 or original_exception.status_code == 406 @@ -1657,39 +1589,27 @@ def _map_nlp_cloud_exception( model=model, response=getattr(original_exception, "response", None), ) - elif ( - original_exception.status_code == 401 - or original_exception.status_code == 403 - ): + elif original_exception.status_code == 401 or original_exception.status_code == 403: raise AuthenticationError( message=f"NLPCloudException - {original_exception.message}", llm_provider="nlp_cloud", model=model, response=getattr(original_exception, "response", None), ) - elif ( - original_exception.status_code == 522 - or original_exception.status_code == 524 - ): + elif original_exception.status_code == 522 or original_exception.status_code == 524: raise Timeout( message=f"NLPCloudException - {original_exception.message}", model=model, llm_provider="nlp_cloud", ) - elif ( - original_exception.status_code == 429 - or original_exception.status_code == 402 - ): + elif original_exception.status_code == 429 or original_exception.status_code == 402: raise RateLimitError( message=f"NLPCloudException - {original_exception.message}", llm_provider="nlp_cloud", model=model, response=getattr(original_exception, "response", None), ) - elif ( - original_exception.status_code == 500 - or original_exception.status_code == 503 - ): + elif original_exception.status_code == 500 or original_exception.status_code == 503: raise APIError( status_code=original_exception.status_code, message=f"NLPCloudException - {original_exception.message}", @@ -1697,10 +1617,7 @@ def _map_nlp_cloud_exception( model=model, request=getattr(original_exception, "request", None), ) - elif ( - original_exception.status_code == 504 - or original_exception.status_code == 520 - ): + elif original_exception.status_code == 504 or original_exception.status_code == 520: raise ServiceUnavailableError( message=f"NLPCloudException - {original_exception.message}", model=model, @@ -1731,10 +1648,7 @@ def _map_together_ai_exception( error_response = json.loads(error_str) except Exception: error_response = {"error": error_str} - if ( - "error" in error_response - and "`inputs` tokens + `max_new_tokens` must be <=" in error_response["error"] - ): + if "error" in error_response and "`inputs` tokens + `max_new_tokens` must be <=" in error_response["error"]: raise ContextWindowExceededError( message=f"TogetherAIException - {error_response['error']}", model=model, @@ -1761,19 +1675,14 @@ def _map_together_ai_exception( model=model, llm_provider="together_ai", ) - elif ( - "error" in error_response - and "API key doesn't match expected format." in error_response["error"] - ): + elif "error" in error_response and "API key doesn't match expected format." in error_response["error"]: raise BadRequestError( message=f"TogetherAIException - {error_response['error']}", model=model, llm_provider="together_ai", response=getattr(original_exception, "response", None), ) - elif ( - "error_type" in error_response and error_response["error_type"] == "validation" - ): + elif "error_type" in error_response and error_response["error_type"] == "validation": raise BadRequestError( message=f"TogetherAIException - {error_response['error']}", model=model, @@ -1971,10 +1880,7 @@ def _map_azure_exception( _inner = body_dict["error"].get("inner_error") or body_dict[ # type: ignore[index] "error" ].get("innererror") # type: ignore[index] - if ( - isinstance(_inner, dict) - and _inner.get("code") == "ResponsibleAIPolicyViolation" - ): + if isinstance(_inner, dict) and _inner.get("code") == "ResponsibleAIPolicyViolation": azure_error_code = "content_policy_violation" else: azure_error_code = body_dict.get("code") @@ -2005,9 +1911,8 @@ def _map_azure_exception( litellm_debug_info=extra_information, response=getattr(original_exception, "response", None), ) - elif ( - azure_error_code == "content_policy_violation" - or ExceptionCheckers.is_azure_content_policy_violation_error(error_str) + elif azure_error_code == "content_policy_violation" or ExceptionCheckers.is_azure_content_policy_violation_error( + error_str ): from litellm.llms.azure.exception_mapping import ( AzureOpenAIExceptionMapping, @@ -2019,10 +1924,7 @@ def _map_azure_exception( extra_information=extra_information, original_exception=original_exception, ) - elif ( - azure_error_code == "invalid_encrypted_content" - or "could not be verified" in error_str - ): + elif azure_error_code == "invalid_encrypted_content" or "could not be verified" in error_str: helpful_message = ( f"AzureException - {message}\n\n" "This error occurs when load balancing Responses API across deployments with different API keys.\n" @@ -2051,10 +1953,7 @@ def _map_azure_exception( response=getattr(original_exception, "response", None), body=getattr(original_exception, "body", None), ) - elif ( - "The api_key client option must be set either by passing api_key to the client or by setting" - in error_str - ): + elif "The api_key client option must be set either by passing api_key to the client or by setting" in error_str: raise AuthenticationError( message=f"{exception_provider} AuthenticationError - {message}", llm_provider=custom_llm_provider, @@ -2256,16 +2155,11 @@ def exception_type( # type: ignore extra_kwargs={}, ): """Maps an LLM Provider Exception to OpenAI Exception Format""" - if any( - isinstance(original_exception, exc_type) - for exc_type in litellm.LITELLM_EXCEPTION_TYPES - ): + if any(isinstance(original_exception, exc_type) for exc_type in litellm.LITELLM_EXCEPTION_TYPES): return original_exception exception_mapping_worked = False exception_provider = custom_llm_provider - mappable_exception: _ProviderHTTPException = cast( - "_ProviderHTTPException", original_exception - ) + mappable_exception: _ProviderHTTPException = cast("_ProviderHTTPException", original_exception) if litellm.suppress_debug_info is False: print() # noqa: T201 print( # noqa: T201 @@ -2276,15 +2170,9 @@ def exception_type( # type: ignore ) print() # noqa: T201 - litellm_response_headers = _get_response_headers( - original_exception=original_exception - ) + litellm_response_headers = _get_response_headers(original_exception=original_exception) try: - error_str = ( - redact_string(str(original_exception)) - if _ENABLE_SECRET_REDACTION - else str(original_exception) - ) + error_str = redact_string(str(original_exception)) if _ENABLE_SECRET_REDACTION else str(original_exception) if model: if hasattr(original_exception, "message"): error_str = ( @@ -2303,9 +2191,7 @@ def exception_type( # type: ignore ################################################################################ extra_information = "" try: - _api_base = litellm.get_api_base( - model=model, optional_params=extra_kwargs - ) + _api_base = litellm.get_api_base(model=model, optional_params=extra_kwargs) messages = litellm.get_first_chars_messages(kwargs=completion_kwargs) _vertex_project = extra_kwargs.get("vertex_project") _vertex_location = extra_kwargs.get("vertex_location") @@ -2314,23 +2200,12 @@ def exception_type( # type: ignore _deployment = _metadata.get("deployment") extra_information = f"\nModel: {model}" - if ( - isinstance(custom_llm_provider, str) - and len(custom_llm_provider) > 0 - ): - exception_provider = ( - custom_llm_provider[0].upper() - + custom_llm_provider[1:] - + "Exception" - ) + if isinstance(custom_llm_provider, str) and len(custom_llm_provider) > 0: + exception_provider = custom_llm_provider[0].upper() + custom_llm_provider[1:] + "Exception" if _api_base: extra_information += f"\nAPI Base: `{_api_base}`" - if ( - messages - and len(messages) > 0 - and litellm.redact_messages_in_exceptions is False - ): + if messages and len(messages) > 0 and litellm.redact_messages_in_exceptions is False: extra_information += f"\nMessages: `{messages}`" if _model_group is not None: @@ -2343,9 +2218,7 @@ def exception_type( # type: ignore extra_information += f"\nvertex_location: `{_vertex_location}`\n" # on litellm proxy add key name + team to exceptions - extra_information = _add_key_name_and_team_to_alert( - request_info=extra_information, metadata=_metadata - ) + extra_information = _add_key_name_and_team_to_alert(request_info=extra_information, metadata=_metadata) except Exception: # DO NOT LET this Block raising the original exception pass @@ -2398,10 +2271,7 @@ def exception_type( # type: ignore exception_provider=exception_provider, extra_information=extra_information, ) - elif ( - custom_llm_provider == "anthropic" - or custom_llm_provider == "anthropic_text" - ): # one of the anthropics + elif custom_llm_provider == "anthropic" or custom_llm_provider == "anthropic_text": # one of the anthropics _map_anthropic_exception( model=model, original_exception=mappable_exception, @@ -2441,10 +2311,7 @@ def exception_type( # type: ignore exception_provider=exception_provider, extra_information=extra_information, ) - elif ( - custom_llm_provider == "sagemaker" - or custom_llm_provider == "sagemaker_chat" - ): + elif custom_llm_provider == "sagemaker" or custom_llm_provider == "sagemaker_chat": _map_sagemaker_exception( model=model, original_exception=mappable_exception, @@ -2478,9 +2345,7 @@ def exception_type( # type: ignore exception_provider=exception_provider, extra_information=extra_information, ) - elif ( - custom_llm_provider == "cohere" or custom_llm_provider == "cohere_chat" - ): # Cohere + elif custom_llm_provider == "cohere" or custom_llm_provider == "cohere_chat": # Cohere _map_cohere_exception( model=model, original_exception=mappable_exception, @@ -2540,9 +2405,7 @@ def exception_type( # type: ignore exception_provider=exception_provider, extra_information=extra_information, ) - elif ( - custom_llm_provider == "ollama" or custom_llm_provider == "ollama_chat" - ): + elif custom_llm_provider == "ollama" or custom_llm_provider == "ollama_chat": _map_ollama_exception( model=model, original_exception=mappable_exception, @@ -2582,9 +2445,8 @@ def exception_type( # type: ignore exception_provider=exception_provider, extra_information=extra_information, ) - if ( - "BadRequestError.__init__() missing 1 required positional argument: 'param'" - in str(original_exception) + if "BadRequestError.__init__() missing 1 required positional argument: 'param'" in str( + original_exception ): # deal with edge-case invalid request error bug in openai-python sdk exception_mapping_worked = True raise BadRequestError( @@ -2613,9 +2475,7 @@ def exception_type( # type: ignore ), llm_provider=custom_llm_provider, model=model, - request=httpx.Request( - method="POST", url="https://api.openai.com/v1/" - ), # stub the request + request=httpx.Request(method="POST", url="https://api.openai.com/v1/"), # stub the request ) except Exception as e: # LOGGING @@ -2663,9 +2523,7 @@ def exception_logging( model_call_details["exception"] = exception model_call_details["additional_args"] = additional_args # User Logging -> if you pass in a custom logging function or want to use sentry breadcrumbs - verbose_logger.debug( - f"Logging Details: logger_fn - {logger_fn} | callable(logger_fn) - {callable(logger_fn)}" - ) + verbose_logger.debug(f"Logging Details: logger_fn - {logger_fn} | callable(logger_fn) - {callable(logger_fn)}") if logger_fn and callable(logger_fn): try: logger_fn( @@ -2694,10 +2552,7 @@ def _add_key_name_and_team_to_alert(request_info: str, metadata: dict) -> str: _api_key_name = metadata.get("user_api_key_alias", None) _user_api_key_team_alias = metadata.get("user_api_key_team_alias", None) if _api_key_name is not None: - request_info = ( - f"\n\nKey Name: `{_api_key_name}`\nTeam: `{_user_api_key_team_alias}`" - + request_info - ) + request_info = f"\n\nKey Name: `{_api_key_name}`\nTeam: `{_user_api_key_team_alias}`" + request_info return request_info except Exception: diff --git a/litellm/litellm_core_utils/fallback_utils.py b/litellm/litellm_core_utils/fallback_utils.py index 1606b53e1f98..7aee69ef8626 100644 --- a/litellm/litellm_core_utils/fallback_utils.py +++ b/litellm/litellm_core_utils/fallback_utils.py @@ -72,9 +72,7 @@ async def async_completion_with_fallbacks(**kwargs): ) except Exception as e: - verbose_logger.exception( - f"Fallback attempt failed for model {model}: {str(e)}" - ) + verbose_logger.exception(f"Fallback attempt failed for model {model}: {str(e)}") most_recent_exception_str = str(e) continue diff --git a/litellm/litellm_core_utils/get_blog_posts.py b/litellm/litellm_core_utils/get_blog_posts.py index 2f9a14f1279f..6aea79cb4b3a 100644 --- a/litellm/litellm_core_utils/get_blog_posts.py +++ b/litellm/litellm_core_utils/get_blog_posts.py @@ -51,9 +51,7 @@ class GetBlogPosts: @staticmethod def load_local_blog_posts() -> List[Dict[str, str]]: """Load the bundled local backup blog posts.""" - content = json.loads( - files("litellm").joinpath("blog_posts.json").read_text(encoding="utf-8") - ) + content = json.loads(files("litellm").joinpath("blog_posts.json").read_text(encoding="utf-8")) return content.get("posts", []) @staticmethod @@ -117,8 +115,7 @@ def validate_blog_posts(posts: List[Dict[str, str]]) -> bool: """Return True if posts is a non-empty list.""" if not isinstance(posts, list) or len(posts) == 0: verbose_logger.warning( - "LiteLLM: Parsed RSS feed has no valid posts. " - "Falling back to local backup.", + "LiteLLM: Parsed RSS feed has no valid posts. Falling back to local backup.", ) return False return True @@ -144,8 +141,7 @@ def get_blog_posts(cls, url: str) -> List[Dict[str, str]]: posts = cls.parse_rss_to_posts(xml_text) except Exception as e: verbose_logger.warning( - "LiteLLM: Failed to fetch blog posts from %s: %s. " - "Falling back to local backup.", + "LiteLLM: Failed to fetch blog posts from %s: %s. Falling back to local backup.", url, str(e), ) diff --git a/litellm/litellm_core_utils/get_litellm_params.py b/litellm/litellm_core_utils/get_litellm_params.py index c88f8b77dc21..fbed9594a0b1 100644 --- a/litellm/litellm_core_utils/get_litellm_params.py +++ b/litellm/litellm_core_utils/get_litellm_params.py @@ -111,9 +111,7 @@ def get_litellm_params( if litellm_trace_id is None: litellm_trace_id = _meta.get("trace_id") or _meta.get("session_id") - data_residency: Optional[str] = infer_openai_data_residency( - custom_llm_provider, api_base - ) + data_residency: Optional[str] = infer_openai_data_residency(custom_llm_provider, api_base) # Build base dict with explicit parameters (always included) litellm_params = { @@ -145,11 +143,7 @@ def get_litellm_params( "azure_ad_token_provider": azure_ad_token_provider, "user_continue_message": user_continue_message, "base_model": base_model - or ( - _get_base_model_from_litellm_call_metadata(metadata=metadata) - if metadata - else None - ), + or (_get_base_model_from_litellm_call_metadata(metadata=metadata) if metadata else None), "litellm_trace_id": litellm_trace_id, "litellm_session_id": litellm_session_id, "hf_model_name": hf_model_name, diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py index 061316a69d61..76ca268a883b 100644 --- a/litellm/litellm_core_utils/get_llm_provider_logic.py +++ b/litellm/litellm_core_utils/get_llm_provider_logic.py @@ -50,10 +50,7 @@ def _parse(value: str): def _is_non_openai_azure_model(model: str) -> bool: try: model_name = model.split("/", 1)[1] - if ( - model_name in litellm.cohere_chat_models - or f"mistral/{model_name}" in litellm.mistral_chat_models - ): + if model_name in litellm.cohere_chat_models or f"mistral/{model_name}" in litellm.mistral_chat_models: return True except Exception: return False @@ -111,11 +108,7 @@ def handle_cohere_chat_model_custom_llm_provider( if model and "/" in model: _custom_llm_provider, _model = model.split("/", 1) - if ( - _custom_llm_provider - and _custom_llm_provider == "cohere" - and _model in litellm.cohere_chat_models - ): + if _custom_llm_provider and _custom_llm_provider == "cohere" and _model in litellm.cohere_chat_models: return _model, "cohere_chat" return model, custom_llm_provider @@ -136,10 +129,7 @@ def handle_anthropic_text_model_custom_llm_provider( """ if custom_llm_provider: - if ( - custom_llm_provider == "anthropic" - and litellm.AnthropicTextConfig._is_anthropic_text_model(model) - ): + if custom_llm_provider == "anthropic" and litellm.AnthropicTextConfig._is_anthropic_text_model(model): return model, "anthropic_text" if model and "/" in model: @@ -173,9 +163,7 @@ def get_llm_provider( try: # Early validation - model is required if model is None: - raise ValueError( - "model parameter is required but was None. Please provide a valid model name." - ) + raise ValueError("model parameter is required but was None. Please provide a valid model name.") if litellm.LiteLLMProxyChatConfig._should_use_litellm_proxy_by_default( litellm_params=cast(Optional[LiteLLM_Params], litellm_params) @@ -201,13 +189,9 @@ def get_llm_provider( return model, custom_llm_provider, dynamic_api_key, api_base ### Handle cases when custom_llm_provider is set to cohere/command-r-plus but it should use cohere_chat route - model, custom_llm_provider = handle_cohere_chat_model_custom_llm_provider( - model, custom_llm_provider - ) + model, custom_llm_provider = handle_cohere_chat_model_custom_llm_provider(model, custom_llm_provider) - model, custom_llm_provider = handle_anthropic_text_model_custom_llm_provider( - model, custom_llm_provider - ) + model, custom_llm_provider = handle_anthropic_text_model_custom_llm_provider(model, custom_llm_provider) if custom_llm_provider and ( model.split("/")[0] != custom_llm_provider @@ -255,14 +239,10 @@ def get_llm_provider( custom_llm_provider = model.split("/", 1)[0] model = model.split("/", 1)[1] if api_base is not None and not isinstance(api_base, str): - raise Exception( - "api base needs to be a string. api_base={}".format(api_base) - ) + raise Exception("api base needs to be a string. api_base={}".format(api_base)) if dynamic_api_key is not None and not isinstance(dynamic_api_key, str): raise Exception( - "dynamic_api_key needs to be a string. Got type={}".format( - type(dynamic_api_key).__name__ - ) + "dynamic_api_key needs to be a string. Got type={}".format(type(dynamic_api_key).__name__) ) return model, custom_llm_provider, dynamic_api_key, api_base # check if api base is a known openai compatible endpoint @@ -316,9 +296,7 @@ def get_llm_provider( dynamic_api_key = get_secret_str("OLLAMA_API_KEY") elif endpoint == "https://api.friendli.ai/serverless/v1": custom_llm_provider = "friendliai" - dynamic_api_key = get_secret_str( - "FRIENDLIAI_API_KEY" - ) or get_secret("FRIENDLI_TOKEN") + dynamic_api_key = get_secret_str("FRIENDLIAI_API_KEY") or get_secret("FRIENDLI_TOKEN") elif endpoint == "api.galadriel.com/v1": custom_llm_provider = "galadriel" dynamic_api_key = get_secret_str("GALADRIEL_API_KEY") @@ -340,16 +318,10 @@ def get_llm_provider( elif endpoint == "api.moonshot.ai/v1": custom_llm_provider = "moonshot" dynamic_api_key = get_secret_str("MOONSHOT_API_KEY") - elif ( - endpoint == "api.minimax.io/anthropic" - or endpoint == "api.minimaxi.com/anthropic" - ): + elif endpoint == "api.minimax.io/anthropic" or endpoint == "api.minimaxi.com/anthropic": custom_llm_provider = "minimax" dynamic_api_key = get_secret_str("MINIMAX_API_KEY") - elif ( - endpoint == "api.minimax.io/v1" - or endpoint == "api.minimaxi.com/v1" - ): + elif endpoint == "api.minimax.io/v1" or endpoint == "api.minimaxi.com/v1": custom_llm_provider = "minimax" dynamic_api_key = get_secret_str("MINIMAX_API_KEY") elif endpoint == "platform.publicai.co/v1": @@ -393,18 +365,10 @@ def get_llm_provider( dynamic_api_key = get_secret_str("PINSTRIPES_API_KEY") if api_base is not None and not isinstance(api_base, str): + raise Exception("api base needs to be a string. api_base={}".format(api_base)) + if dynamic_api_key is not None and not isinstance(dynamic_api_key, str): raise Exception( - "api base needs to be a string. api_base={}".format( - api_base - ) - ) - if dynamic_api_key is not None and not isinstance( - dynamic_api_key, str - ): - raise Exception( - "dynamic_api_key needs to be a string. dynamic_api_key={}".format( - dynamic_api_key - ) + "dynamic_api_key needs to be a string. dynamic_api_key={}".format(dynamic_api_key) ) return model, custom_llm_provider, dynamic_api_key, api_base # type: ignore @@ -437,13 +401,10 @@ def get_llm_provider( elif model in litellm.cohere_chat_models: custom_llm_provider = "cohere_chat" ## replicate - elif model in litellm.replicate_models or ( - ":" in model and len(model) > REPLICATE_MODEL_NAME_WITH_ID_LENGTH - ): + elif model in litellm.replicate_models or (":" in model and len(model) > REPLICATE_MODEL_NAME_WITH_ID_LENGTH): model_parts = model.split(":") if ( - len(model_parts) > 1 - and len(model_parts[1]) == REPLICATE_MODEL_NAME_WITH_ID_LENGTH + len(model_parts) > 1 and len(model_parts[1]) == REPLICATE_MODEL_NAME_WITH_ID_LENGTH ): ## checks if model name has a 64 digit code - e.g. "meta/llama-2-70b-chat:02e509c789964a7ea8736978a43525956ef40397be9033abf9fd2badfe68c9e3" custom_llm_provider = "replicate" elif model in litellm.replicate_models: @@ -470,11 +431,7 @@ def get_llm_provider( ## ai21 elif model in litellm.ai21_chat_models or model in litellm.ai21_models: custom_llm_provider = "ai21_chat" - api_base = ( - api_base - or get_secret("AI21_API_BASE") - or "https://api.ai21.com/studio/v1" - ) # type: ignore + api_base = api_base or get_secret("AI21_API_BASE") or "https://api.ai21.com/studio/v1" # type: ignore dynamic_api_key = api_key or get_secret("AI21_API_KEY") ## aleph_alpha elif model in litellm.aleph_alpha_models: @@ -546,23 +503,15 @@ def get_llm_provider( llm_provider="", ) if api_base is not None and not isinstance(api_base, str): - raise Exception( - "api base needs to be a string. api_base={}".format(api_base) - ) + raise Exception("api base needs to be a string. api_base={}".format(api_base)) if dynamic_api_key is not None and not isinstance(dynamic_api_key, str): - raise Exception( - "dynamic_api_key needs to be a string. dynamic_api_key={}".format( - dynamic_api_key - ) - ) + raise Exception("dynamic_api_key needs to be a string. dynamic_api_key={}".format(dynamic_api_key)) return model, custom_llm_provider, dynamic_api_key, api_base except Exception as e: if isinstance(e, litellm.exceptions.BadRequestError): raise e else: - error_str = ( - f"GetLLMProvider Exception - {str(e)}\n\noriginal model: {model}" - ) + error_str = f"GetLLMProvider Exception - {str(e)}\n\noriginal model: {model}" raise litellm.exceptions.BadRequestError( # type: ignore message=f"GetLLMProvider Exception - {str(e)}\n\noriginal model: {model}", model=model, @@ -599,9 +548,7 @@ def _get_openai_compatible_provider_info( if provider_config is None: raise ValueError(f"Provider {custom_llm_provider} not found") config_class = create_config_class(provider_config) - api_base, dynamic_api_key = config_class()._get_openai_compatible_provider_info( - api_base, api_key - ) + api_base, dynamic_api_key = config_class()._get_openai_compatible_provider_info(api_base, api_key) return model, custom_llm_provider, dynamic_api_key, api_base if custom_llm_provider == "perplexity": @@ -609,40 +556,26 @@ def _get_openai_compatible_provider_info( ( api_base, dynamic_api_key, - ) = litellm.PerplexityChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.PerplexityChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "aiohttp_openai": return model, "aiohttp_openai", api_key, api_base elif custom_llm_provider == "anyscale": # anyscale is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.endpoints.anyscale.com/v1 - api_base = ( - api_base - or get_secret_str("ANYSCALE_API_BASE") - or "https://api.endpoints.anyscale.com/v1" - ) # type: ignore + api_base = api_base or get_secret_str("ANYSCALE_API_BASE") or "https://api.endpoints.anyscale.com/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("ANYSCALE_API_KEY") elif custom_llm_provider == "deepinfra": ( api_base, dynamic_api_key, - ) = litellm.DeepInfraConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.DeepInfraConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "empower": - api_base = ( - api_base - or get_secret("EMPOWER_API_BASE") - or "https://app.empower.dev/api/v1" - ) # type: ignore + api_base = api_base or get_secret("EMPOWER_API_BASE") or "https://app.empower.dev/api/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("EMPOWER_API_KEY") elif custom_llm_provider == "groq": ( api_base, dynamic_api_key, - ) = litellm.GroqChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.GroqChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "bedrock_mantle": ( api_base, @@ -652,11 +585,7 @@ def _get_openai_compatible_provider_info( ) elif custom_llm_provider == "nvidia_nim": # nvidia_nim is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.endpoints.anyscale.com/v1 - api_base = ( - api_base - or get_secret("NVIDIA_NIM_API_BASE") - or "https://integrate.api.nvidia.com/v1" - ) # type: ignore + api_base = api_base or get_secret("NVIDIA_NIM_API_BASE") or "https://integrate.api.nvidia.com/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("NVIDIA_NIM_API_KEY") elif custom_llm_provider == "nvidia_riva": # NVIDIA Riva is gRPC-based; api_base must be a host:port like @@ -665,119 +594,71 @@ def _get_openai_compatible_provider_info( api_base = api_base or get_secret_str("NVIDIA_RIVA_API_BASE") # type: ignore # Fall back to NVIDIA_NIM_API_KEY because users running both NVCF # services typically reuse the same nvapi-* key. - dynamic_api_key = ( - api_key - or get_secret_str("NVIDIA_RIVA_API_KEY") - or get_secret_str("NVIDIA_NIM_API_KEY") - ) + dynamic_api_key = api_key or get_secret_str("NVIDIA_RIVA_API_KEY") or get_secret_str("NVIDIA_NIM_API_KEY") elif custom_llm_provider == "soniox": - api_base = ( - api_base or get_secret_str("SONIOX_API_BASE") or "https://api.soniox.com" - ) + api_base = api_base or get_secret_str("SONIOX_API_BASE") or "https://api.soniox.com" dynamic_api_key = api_key or get_secret_str("SONIOX_API_KEY") elif custom_llm_provider == "cerebras": - api_base = ( - api_base or get_secret("CEREBRAS_API_BASE") or "https://api.cerebras.ai/v1" - ) # type: ignore + api_base = api_base or get_secret("CEREBRAS_API_BASE") or "https://api.cerebras.ai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("CEREBRAS_API_KEY") elif custom_llm_provider == "baseten": # Use BasetenConfig to determine the appropriate API base URL if api_base is None: api_base = litellm.BasetenConfig.get_api_base_for_model(model) else: - api_base = ( - api_base - or get_secret_str("BASETEN_API_BASE") - or "https://inference.baseten.co/v1" - ) + api_base = api_base or get_secret_str("BASETEN_API_BASE") or "https://inference.baseten.co/v1" dynamic_api_key = api_key or get_secret_str("BASETEN_API_KEY") elif custom_llm_provider == "sambanova": - api_base = ( - api_base - or get_secret("SAMBANOVA_API_BASE") - or "https://api.sambanova.ai/v1" - ) # type: ignore + api_base = api_base or get_secret("SAMBANOVA_API_BASE") or "https://api.sambanova.ai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("SAMBANOVA_API_KEY") elif custom_llm_provider == "meta_llama": - api_base = ( - api_base - or get_secret("LLAMA_API_BASE") - or "https://api.llama.com/compat/v1" - ) # type: ignore + api_base = api_base or get_secret("LLAMA_API_BASE") or "https://api.llama.com/compat/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("LLAMA_API_KEY") elif custom_llm_provider == "nebius": - api_base = ( - api_base - or get_secret("NEBIUS_API_BASE") - or "https://api.studio.nebius.ai/v1" - ) # type: ignore + api_base = api_base or get_secret("NEBIUS_API_BASE") or "https://api.studio.nebius.ai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("NEBIUS_API_KEY") elif custom_llm_provider == "ollama": api_base = api_base or get_secret("OLLAMA_API_BASE") or "http://localhost:11434" # type: ignore dynamic_api_key = api_key or get_secret_str("OLLAMA_API_KEY") - elif (custom_llm_provider == "ai21_chat") or ( - custom_llm_provider == "ai21" and model in litellm.ai21_chat_models - ): - api_base = ( - api_base or get_secret("AI21_API_BASE") or "https://api.ai21.com/studio/v1" - ) # type: ignore + elif (custom_llm_provider == "ai21_chat") or (custom_llm_provider == "ai21" and model in litellm.ai21_chat_models): + api_base = api_base or get_secret("AI21_API_BASE") or "https://api.ai21.com/studio/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("AI21_API_KEY") custom_llm_provider = "ai21_chat" elif custom_llm_provider == "volcengine": # volcengine is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.endpoints.anyscale.com/v1 - api_base = ( - api_base - or get_secret("VOLCENGINE_API_BASE") - or "https://ark.cn-beijing.volces.com/api/v3" - ) # type: ignore + api_base = api_base or get_secret("VOLCENGINE_API_BASE") or "https://ark.cn-beijing.volces.com/api/v3" # type: ignore dynamic_api_key = api_key or get_secret_str("VOLCENGINE_API_KEY") elif custom_llm_provider == "codestral": # codestral is openai compatible, we just need to set this to custom_openai and have the api_base be https://codestral.mistral.ai/v1 - api_base = ( - api_base - or get_secret("CODESTRAL_API_BASE") - or "https://codestral.mistral.ai/v1" - ) # type: ignore + api_base = api_base or get_secret("CODESTRAL_API_BASE") or "https://codestral.mistral.ai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("CODESTRAL_API_KEY") elif custom_llm_provider == "hosted_vllm": # vllm is openai compatible, we just need to set this to custom_openai ( api_base, dynamic_api_key, - ) = litellm.HostedVLLMChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.HostedVLLMChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "llamafile": # llamafile is OpenAI compatible. ( api_base, dynamic_api_key, - ) = litellm.LlamafileChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.LlamafileChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "datarobot": # DataRobot is OpenAI compatible. ( api_base, dynamic_api_key, - ) = litellm.DataRobotConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.DataRobotConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "lm_studio": # lm_studio is openai compatible, we just need to set this to custom_openai ( api_base, dynamic_api_key, - ) = litellm.LMStudioChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.LMStudioChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "deepseek": # deepseek is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.deepseek.com/v1 - api_base = ( - api_base - or get_secret("DEEPSEEK_API_BASE") - or "https://api.deepseek.com/beta" - ) # type: ignore + api_base = api_base or get_secret("DEEPSEEK_API_BASE") or "https://api.deepseek.com/beta" # type: ignore dynamic_api_key = api_key or get_secret_str("DEEPSEEK_API_KEY") elif custom_llm_provider == "fireworks_ai": @@ -785,9 +666,7 @@ def _get_openai_compatible_provider_info( ( api_base, dynamic_api_key, - ) = litellm.FireworksAIConfig()._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + ) = litellm.FireworksAIConfig()._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) elif custom_llm_provider == "azure_ai": ( api_base, @@ -807,45 +686,31 @@ def _get_openai_compatible_provider_info( ( api_base, dynamic_api_key, - ) = litellm.LiteLLMProxyChatConfig()._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + ) = litellm.LiteLLMProxyChatConfig()._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) elif custom_llm_provider == "mistral": ( api_base, dynamic_api_key, - ) = litellm.MistralConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.MistralConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "jina_ai": ( custom_llm_provider, api_base, dynamic_api_key, - ) = litellm.JinaAIEmbeddingConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.JinaAIEmbeddingConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "xai": ( api_base, dynamic_api_key, - ) = litellm.XAIChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.XAIChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "zai": ( api_base, dynamic_api_key, - ) = litellm.ZAIChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.ZAIChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "together_ai": - api_base = ( - api_base - or get_secret_str("TOGETHER_AI_API_BASE") - or "https://api.together.xyz/v1" - ) # type: ignore + api_base = api_base or get_secret_str("TOGETHER_AI_API_BASE") or "https://api.together.xyz/v1" # type: ignore dynamic_api_key = api_key or ( get_secret_str("TOGETHER_API_KEY") or get_secret_str("TOGETHER_AI_API_KEY") @@ -853,22 +718,10 @@ def _get_openai_compatible_provider_info( or get_secret_str("TOGETHER_AI_TOKEN") ) elif custom_llm_provider == "friendliai": - api_base = ( - api_base - or get_secret("FRIENDLI_API_BASE") - or "https://api.friendli.ai/serverless/v1" - ) # type: ignore - dynamic_api_key = ( - api_key - or get_secret_str("FRIENDLIAI_API_KEY") - or get_secret_str("FRIENDLI_TOKEN") - ) + api_base = api_base or get_secret("FRIENDLI_API_BASE") or "https://api.friendli.ai/serverless/v1" # type: ignore + dynamic_api_key = api_key or get_secret_str("FRIENDLIAI_API_KEY") or get_secret_str("FRIENDLI_TOKEN") elif custom_llm_provider == "galadriel": - api_base = ( - api_base - or get_secret("GALADRIEL_API_BASE") - or "https://api.galadriel.com/v1" - ) # type: ignore + api_base = api_base or get_secret("GALADRIEL_API_BASE") or "https://api.galadriel.com/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("GALADRIEL_API_KEY") elif custom_llm_provider == "github_copilot": ( @@ -883,181 +736,125 @@ def _get_openai_compatible_provider_info( api_base, dynamic_api_key, custom_llm_provider, - ) = litellm.ChatGPTConfig()._get_openai_compatible_provider_info( - model, api_base, api_key, custom_llm_provider - ) + ) = litellm.ChatGPTConfig()._get_openai_compatible_provider_info(model, api_base, api_key, custom_llm_provider) elif custom_llm_provider == "novita": - api_base = ( - api_base - or get_secret("NOVITA_API_BASE") - or "https://api.novita.ai/v3/openai" - ) # type: ignore + api_base = api_base or get_secret("NOVITA_API_BASE") or "https://api.novita.ai/v3/openai" # type: ignore dynamic_api_key = api_key or get_secret_str("NOVITA_API_KEY") elif custom_llm_provider == "snowflake": ( api_base, dynamic_api_key, - ) = litellm.SnowflakeConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.SnowflakeConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "gradient_ai": ( api_base, dynamic_api_key, - ) = litellm.GradientAIConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.GradientAIConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "featherless_ai": ( api_base, dynamic_api_key, - ) = litellm.FeatherlessAIConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.FeatherlessAIConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "nscale": ( api_base, dynamic_api_key, - ) = litellm.NscaleConfig()._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + ) = litellm.NscaleConfig()._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) elif custom_llm_provider == "heroku": ( api_base, dynamic_api_key, - ) = litellm.HerokuChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.HerokuChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "dashscope": ( api_base, dynamic_api_key, - ) = litellm.DashScopeChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.DashScopeChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "modelscope": ( api_base, dynamic_api_key, - ) = litellm.ModelScopeChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.ModelScopeChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "moonshot": ( api_base, dynamic_api_key, - ) = litellm.MoonshotChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.MoonshotChatConfig()._get_openai_compatible_provider_info(api_base, api_key) # publicai is now handled by JSON config (see litellm/llms/openai_like/providers.json) elif custom_llm_provider == "docker_model_runner": ( api_base, dynamic_api_key, - ) = litellm.DockerModelRunnerChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.DockerModelRunnerChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "v0": ( api_base, dynamic_api_key, - ) = litellm.V0ChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.V0ChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "morph": ( api_base, dynamic_api_key, - ) = litellm.MorphChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.MorphChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "lambda_ai": ( api_base, dynamic_api_key, - ) = litellm.LambdaAIChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.LambdaAIChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "inception": ( api_base, dynamic_api_key, - ) = litellm.InceptionChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.InceptionChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "hyperbolic": ( api_base, dynamic_api_key, - ) = litellm.HyperbolicChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.HyperbolicChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "vercel_ai_gateway": ( api_base, dynamic_api_key, - ) = litellm.VercelAIGatewayConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.VercelAIGatewayConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "aiml": ( api_base, dynamic_api_key, - ) = litellm.AIMLChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.AIMLChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "wandb": - api_base = ( - api_base - or get_secret("WANDB_API_BASE") - or "https://api.inference.wandb.ai/v1" - ) # type: ignore + api_base = api_base or get_secret("WANDB_API_BASE") or "https://api.inference.wandb.ai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("WANDB_API_KEY") elif custom_llm_provider == "lemonade": ( api_base, dynamic_api_key, - ) = litellm.LemonadeChatConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.LemonadeChatConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "clarifai": ( api_base, dynamic_api_key, - ) = litellm.ClarifaiConfig()._get_openai_compatible_provider_info( - api_base, api_key - ) + ) = litellm.ClarifaiConfig()._get_openai_compatible_provider_info(api_base, api_key) elif custom_llm_provider == "ragflow": full_model = f"ragflow/{model}" ( api_base, dynamic_api_key, _, - ) = litellm.RAGFlowConfig()._get_openai_compatible_provider_info( - full_model, api_base, api_key, "ragflow" - ) + ) = litellm.RAGFlowConfig()._get_openai_compatible_provider_info(full_model, api_base, api_key, "ragflow") model = full_model elif custom_llm_provider == "langgraph": # LangGraph is a custom provider, just need to set api_base - api_base = ( - api_base or get_secret_str("LANGGRAPH_API_BASE") or "http://localhost:2024" - ) + api_base = api_base or get_secret_str("LANGGRAPH_API_BASE") or "http://localhost:2024" dynamic_api_key = api_key or get_secret_str("LANGGRAPH_API_KEY") elif custom_llm_provider == "manus": # Manus is OpenAI compatible for responses API - api_base = ( - api_base or get_secret_str("MANUS_API_BASE") or "https://api.manus.im" - ) + api_base = api_base or get_secret_str("MANUS_API_BASE") or "https://api.manus.im" dynamic_api_key = api_key or get_secret_str("MANUS_API_KEY") if api_base is not None and not isinstance(api_base, str): raise Exception("api base needs to be a string. api_base={}".format(api_base)) if dynamic_api_key is not None and not isinstance(dynamic_api_key, str): - raise Exception( - "dynamic_api_key needs to be a string. dynamic_api_key={}".format( - dynamic_api_key - ) - ) + raise Exception("dynamic_api_key needs to be a string. dynamic_api_key={}".format(dynamic_api_key)) if dynamic_api_key is None and api_key is not None: dynamic_api_key = api_key return model, custom_llm_provider, dynamic_api_key, api_base diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.py index 7679358bbc64..9126c35f8181 100644 --- a/litellm/litellm_core_utils/get_model_cost_map.py +++ b/litellm/litellm_core_utils/get_model_cost_map.py @@ -37,9 +37,7 @@ class GetModelCostMap: def load_local_model_cost_map() -> dict: """Load the local backup model cost map bundled with the package.""" content = json.loads( - files("litellm") - .joinpath("model_prices_and_context_window_backup.json") - .read_text(encoding="utf-8") + files("litellm").joinpath("model_prices_and_context_window_backup.json").read_text(encoding="utf-8") ) return content @@ -56,16 +54,14 @@ def _check_is_valid_dict(fetched_map: dict) -> bool: """Check 1: fetched map is a non-empty dict.""" if not isinstance(fetched_map, dict): verbose_logger.warning( - "LiteLLM: Fetched model cost map is not a dict (type=%s). " - "Falling back to local backup.", + "LiteLLM: Fetched model cost map is not a dict (type=%s). Falling back to local backup.", type(fetched_map).__name__, ) return False if len(fetched_map) == 0: verbose_logger.warning( - "LiteLLM: Fetched model cost map is empty. " - "Falling back to local backup.", + "LiteLLM: Fetched model cost map is empty. Falling back to local backup.", ) return False @@ -92,10 +88,7 @@ def _check_model_count_not_reduced( ) return False - if ( - backup_model_count > 0 - and fetched_count < backup_model_count * max_shrink_ratio - ): + if backup_model_count > 0 and fetched_count < backup_model_count * max_shrink_ratio: verbose_logger.warning( "LiteLLM: Fetched model cost map shrank significantly " "(fetched=%d, backup=%d, threshold=%.0f%%). " @@ -269,8 +262,7 @@ def get_model_cost_map(url: str) -> dict: content = GetModelCostMap.fetch_remote_model_cost_map(url) except Exception as e: verbose_logger.warning( - "LiteLLM: Failed to fetch remote model cost map from %s: %s. " - "Falling back to local backup.", + "LiteLLM: Failed to fetch remote model cost map from %s: %s. Falling back to local backup.", url, str(e), ) @@ -284,14 +276,11 @@ def get_model_cost_map(url: str) -> dict: backup_model_count=GetModelCostMap._get_backup_model_count(), ): verbose_logger.warning( - "LiteLLM: Fetched model cost map failed integrity check. " - "Using local backup instead. url=%s", + "LiteLLM: Fetched model cost map failed integrity check. Using local backup instead. url=%s", url, ) _cost_map_source_info.source = "local" - _cost_map_source_info.fallback_reason = ( - "Remote data failed integrity validation" - ) + _cost_map_source_info.fallback_reason = "Remote data failed integrity validation" return _expand_model_aliases(GetModelCostMap.load_local_model_cost_map()) _cost_map_source_info.source = "remote" diff --git a/litellm/litellm_core_utils/get_supported_openai_params.py b/litellm/litellm_core_utils/get_supported_openai_params.py index c22d3b997058..84f6445846b9 100644 --- a/litellm/litellm_core_utils/get_supported_openai_params.py +++ b/litellm/litellm_core_utils/get_supported_openai_params.py @@ -8,9 +8,7 @@ def get_supported_openai_params( model: str, custom_llm_provider: Optional[str] = None, - request_type: Literal[ - "chat_completion", "embeddings", "transcription" - ] = "chat_completion", + request_type: Literal["chat_completion", "embeddings", "transcription"] = "chat_completion", base_model: Optional[str] = None, ) -> Optional[list]: """ @@ -56,12 +54,8 @@ def get_supported_openai_params( if provider_config and request_type == "chat_completion": supported_params = provider_config.get_supported_openai_params(model=model) if base_model and base_model != model: - base_model_params = provider_config.get_supported_openai_params( - model=base_model - ) - supported_params = list( - dict.fromkeys([*supported_params, *base_model_params]) - ) + base_model_params = provider_config.get_supported_openai_params(model=base_model) + supported_params = list(dict.fromkeys([*supported_params, *base_model_params])) return supported_params if custom_llm_provider == "bedrock": @@ -82,9 +76,7 @@ def get_supported_openai_params( return litellm.AnthropicTextConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "fireworks_ai": if request_type == "embeddings": - return litellm.FireworksAIEmbeddingConfig().get_supported_openai_params( - model=model - ) + return litellm.FireworksAIEmbeddingConfig().get_supported_openai_params(model=model) elif request_type == "transcription": return None else: @@ -107,9 +99,7 @@ def get_supported_openai_params( elif custom_llm_provider == "groq": return litellm.GroqChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "bedrock_mantle": - return litellm.BedrockMantleChatConfig().get_supported_openai_params( - model=model - ) + return litellm.BedrockMantleChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "hosted_vllm": return litellm.HostedVLLMChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "vllm": @@ -122,49 +112,27 @@ def get_supported_openai_params( return litellm.MaritalkConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "openai": if request_type == "transcription": - transcription_provider_config = ( - litellm.ProviderConfigManager.get_provider_audio_transcription_config( - model=model, provider=LlmProviders.OPENAI - ) + transcription_provider_config = litellm.ProviderConfigManager.get_provider_audio_transcription_config( + model=model, provider=LlmProviders.OPENAI ) - if isinstance( - transcription_provider_config, litellm.OpenAIGPTAudioTranscriptionConfig - ): - return transcription_provider_config.get_supported_openai_params( - model=model - ) + if isinstance(transcription_provider_config, litellm.OpenAIGPTAudioTranscriptionConfig): + return transcription_provider_config.get_supported_openai_params(model=model) else: - raise ValueError( - f"Unsupported provider config: {transcription_provider_config} for model: {model}" - ) + raise ValueError(f"Unsupported provider config: {transcription_provider_config} for model: {model}") return litellm.OpenAIConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "sap": if request_type == "chat_completion": - return litellm.GenAIHubOrchestrationConfig().get_supported_openai_params( - model=model - ) + return litellm.GenAIHubOrchestrationConfig().get_supported_openai_params(model=model) elif request_type == "embeddings": - return litellm.GenAIHubEmbeddingConfig().get_supported_openai_params( - model=model - ) + return litellm.GenAIHubEmbeddingConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "azure": _azure_detection_model = base_model or model - if litellm.AzureOpenAIO1Config().is_o_series_model( - model=_azure_detection_model - ): - return litellm.AzureOpenAIO1Config().get_supported_openai_params( - model=_azure_detection_model - ) - elif litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model( - model=_azure_detection_model - ): - return litellm.AzureOpenAIGPT5Config().get_supported_openai_params( - model=_azure_detection_model - ) + if litellm.AzureOpenAIO1Config().is_o_series_model(model=_azure_detection_model): + return litellm.AzureOpenAIO1Config().get_supported_openai_params(model=_azure_detection_model) + elif litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model(model=_azure_detection_model): + return litellm.AzureOpenAIGPT5Config().get_supported_openai_params(model=_azure_detection_model) else: - return litellm.AzureOpenAIConfig().get_supported_openai_params( - model=_azure_detection_model - ) + return litellm.AzureOpenAIConfig().get_supported_openai_params(model=_azure_detection_model) elif custom_llm_provider == "openrouter": return litellm.OpenrouterConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "vercel_ai_gateway": @@ -180,18 +148,12 @@ def get_supported_openai_params( MistralAudioTranscriptionConfig, ) - return MistralAudioTranscriptionConfig().get_supported_openai_params( - model=model - ) + return MistralAudioTranscriptionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "text-completion-codestral": - return litellm.CodestralTextCompletionConfig().get_supported_openai_params( - model=model - ) + return litellm.CodestralTextCompletionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "sambanova": if request_type == "embeddings": - return litellm.SambaNovaEmbeddingConfig().get_supported_openai_params( - model=model - ) + return litellm.SambaNovaEmbeddingConfig().get_supported_openai_params(model=model) else: return litellm.SambanovaConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "nebius": @@ -206,9 +168,7 @@ def get_supported_openai_params( return litellm.HuggingFaceChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "jina_ai": if request_type == "embeddings": - return litellm.JinaAIEmbeddingConfig().get_supported_openai_params( - model=model - ) + return litellm.JinaAIEmbeddingConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "together_ai": return litellm.TogetherAIConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "databricks": @@ -217,9 +177,7 @@ def get_supported_openai_params( elif request_type == "embeddings": return litellm.DatabricksEmbeddingConfig().get_supported_openai_params() elif custom_llm_provider == "palm" or custom_llm_provider == "gemini": - return litellm.GoogleAIStudioGeminiConfig().get_supported_openai_params( - model=model - ) + return litellm.GoogleAIStudioGeminiConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "novita": return litellm.NovitaConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "vertex_ai" or custom_llm_provider == "vertex_ai_beta": @@ -227,23 +185,13 @@ def get_supported_openai_params( if model.startswith("mistral"): return litellm.MistralConfig().get_supported_openai_params(model=model) elif model.startswith("codestral"): - return ( - litellm.CodestralTextCompletionConfig().get_supported_openai_params( - model=model - ) - ) + return litellm.CodestralTextCompletionConfig().get_supported_openai_params(model=model) elif model.startswith("claude"): - return litellm.VertexAIAnthropicConfig().get_supported_openai_params( - model=model - ) + return litellm.VertexAIAnthropicConfig().get_supported_openai_params(model=model) elif model.startswith("gemini"): - return litellm.VertexGeminiConfig().get_supported_openai_params( - model=model - ) + return litellm.VertexGeminiConfig().get_supported_openai_params(model=model) else: - return litellm.VertexAILlama3Config().get_supported_openai_params( - model=model - ) + return litellm.VertexAILlama3Config().get_supported_openai_params(model=model) elif request_type == "embeddings": return litellm.VertexAITextEmbeddingConfig().get_supported_openai_params() elif custom_llm_provider == "sagemaker": @@ -285,76 +233,48 @@ def get_supported_openai_params( return litellm.IBMWatsonXChatConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "watsonx_text": return litellm.IBMWatsonXAIConfig().get_supported_openai_params(model=model) - elif ( - custom_llm_provider == "custom_openai" - or custom_llm_provider == "text-completion-openai" - ): - return litellm.OpenAITextCompletionConfig().get_supported_openai_params( - model=model - ) + elif custom_llm_provider == "custom_openai" or custom_llm_provider == "text-completion-openai": + return litellm.OpenAITextCompletionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "predibase": return litellm.PredibaseConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "voyage": - if ( - request_type == "embeddings" - and litellm.VoyageMultimodalEmbeddingConfig.is_multimodal_embeddings(model) - ): - return ( - litellm.VoyageMultimodalEmbeddingConfig().get_supported_openai_params( - model=model - ) - ) + if request_type == "embeddings" and litellm.VoyageMultimodalEmbeddingConfig.is_multimodal_embeddings(model): + return litellm.VoyageMultimodalEmbeddingConfig().get_supported_openai_params(model=model) return litellm.VoyageEmbeddingConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "infinity": - return litellm.InfinityEmbeddingConfig().get_supported_openai_params( - model=model - ) + return litellm.InfinityEmbeddingConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "triton": if request_type == "embeddings": - return litellm.TritonEmbeddingConfig().get_supported_openai_params( - model=model - ) + return litellm.TritonEmbeddingConfig().get_supported_openai_params(model=model) else: return litellm.TritonConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "deepgram": if request_type == "transcription": - return ( - litellm.DeepgramAudioTranscriptionConfig().get_supported_openai_params( - model=model - ) - ) + return litellm.DeepgramAudioTranscriptionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "ovhcloud": if request_type == "transcription": from litellm.llms.ovhcloud.audio_transcription.transformation import ( OVHCloudAudioTranscriptionConfig, ) - return OVHCloudAudioTranscriptionConfig().get_supported_openai_params( - model=model - ) + return OVHCloudAudioTranscriptionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "scaleway": if request_type == "transcription": from litellm.llms.scaleway.audio_transcription.transformation import ( ScalewayAudioTranscriptionConfig, ) - return ScalewayAudioTranscriptionConfig().get_supported_openai_params( - model=model - ) + return ScalewayAudioTranscriptionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "elevenlabs": if request_type == "transcription": from litellm.llms.elevenlabs.audio_transcription.transformation import ( ElevenLabsAudioTranscriptionConfig, ) - return ElevenLabsAudioTranscriptionConfig().get_supported_openai_params( - model=model - ) + return ElevenLabsAudioTranscriptionConfig().get_supported_openai_params(model=model) elif custom_llm_provider == "soniox": if request_type == "transcription": - return litellm.SonioxAudioTranscriptionConfig().get_supported_openai_params( - model=model - ) + return litellm.SonioxAudioTranscriptionConfig().get_supported_openai_params(model=model) elif custom_llm_provider in litellm._custom_providers: if request_type == "chat_completion": provider_config = litellm.ProviderConfigManager.get_provider_chat_config( diff --git a/litellm/litellm_core_utils/health_check_helpers.py b/litellm/litellm_core_utils/health_check_helpers.py index 5a29ea73a740..405366382a19 100644 --- a/litellm/litellm_core_utils/health_check_helpers.py +++ b/litellm/litellm_core_utils/health_check_helpers.py @@ -27,25 +27,19 @@ async def ahealth_check_wildcard_models( ) # this is a wildcard model, we need to pick a random model from the provider - cheapest_models = pick_cheapest_chat_models_from_llm_provider( - custom_llm_provider=custom_llm_provider, n=3 - ) + cheapest_models = pick_cheapest_chat_models_from_llm_provider(custom_llm_provider=custom_llm_provider, n=3) if len(cheapest_models) == 0: raise Exception( f"Unable to health check wildcard model for provider {custom_llm_provider}. Add a model on your config.yaml or contribute here - https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json" ) if len(cheapest_models) > 1: - fallback_models = cheapest_models[ - 1: - ] # Pick the last 2 models from the shuffled list + fallback_models = cheapest_models[1:] # Pick the last 2 models from the shuffled list else: fallback_models = None model_params["model"] = cheapest_models[0] model_params["litellm_logging_obj"] = litellm_logging_obj model_params["fallbacks"] = fallback_models - model_params["max_tokens"] = model_params.get( - "max_tokens", 16 - ) # GPT-5 models require max_output_tokens >= 16 + model_params["max_tokens"] = model_params.get("max_tokens", 16) # GPT-5 models require max_output_tokens >= 16 await acompletion(**model_params) return {} @@ -167,12 +161,7 @@ def get_mode_handlers( "audio_speech": lambda: litellm.aspeech( **{ **_filter_model_params(model_params=model_params), - **( - {"voice": "alloy"} - if "voice" - not in _filter_model_params(model_params=model_params) - else {} - ), + **({"voice": "alloy"} if "voice" not in _filter_model_params(model_params=model_params) else {}), }, input=prompt or "test", ), diff --git a/litellm/litellm_core_utils/health_check_utils.py b/litellm/litellm_core_utils/health_check_utils.py index ff252855f0d7..141facec040e 100644 --- a/litellm/litellm_core_utils/health_check_utils.py +++ b/litellm/litellm_core_utils/health_check_utils.py @@ -11,17 +11,11 @@ def _filter_model_params(model_params: dict) -> dict: def _create_health_check_response(response_headers: dict) -> dict: response = {} - if ( - response_headers.get("x-ratelimit-remaining-requests", None) is not None - ): # not provided for dall-e requests - response["x-ratelimit-remaining-requests"] = response_headers[ - "x-ratelimit-remaining-requests" - ] + if response_headers.get("x-ratelimit-remaining-requests", None) is not None: # not provided for dall-e requests + response["x-ratelimit-remaining-requests"] = response_headers["x-ratelimit-remaining-requests"] if response_headers.get("x-ratelimit-remaining-tokens", None) is not None: - response["x-ratelimit-remaining-tokens"] = response_headers[ - "x-ratelimit-remaining-tokens" - ] + response["x-ratelimit-remaining-tokens"] = response_headers["x-ratelimit-remaining-tokens"] if response_headers.get("x-ms-region", None) is not None: response["x-ms-region"] = response_headers["x-ms-region"] diff --git a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py index 949076aabf36..d0a6ec30c9e2 100644 --- a/litellm/litellm_core_utils/initialize_dynamic_callback_params.py +++ b/litellm/litellm_core_utils/initialize_dynamic_callback_params.py @@ -23,9 +23,7 @@ def _raise_env_reference_error(param: str, *, source: str) -> None: ) -def validate_no_callback_env_reference( - param: str, value: object, *, source: str -) -> None: +def validate_no_callback_env_reference(param: str, value: object, *, source: str) -> None: if _is_env_reference(value): _raise_env_reference_error(param, source=source) @@ -86,9 +84,7 @@ def initialize_standard_callback_dynamic_params( continue if param in kwargs: _param_value = kwargs.get(param) - validate_no_callback_env_reference( - param, _param_value, source="request body" - ) + validate_no_callback_env_reference(param, _param_value, source="request body") standard_callback_dynamic_params[param] = _param_value # type: ignore # 2. Fallback: check "metadata" or "litellm_params" -> "metadata" @@ -103,9 +99,7 @@ def initialize_standard_callback_dynamic_params( continue if param not in standard_callback_dynamic_params and param in metadata: _param_value = metadata.get(param) - validate_no_callback_env_reference( - param, _param_value, source="metadata" - ) + validate_no_callback_env_reference(param, _param_value, source="metadata") standard_callback_dynamic_params[param] = _param_value # type: ignore return standard_callback_dynamic_params diff --git a/litellm/litellm_core_utils/json_validation_rule.py b/litellm/litellm_core_utils/json_validation_rule.py index bbfd3e6de964..c73b62f8a21b 100644 --- a/litellm/litellm_core_utils/json_validation_rule.py +++ b/litellm/litellm_core_utils/json_validation_rule.py @@ -44,9 +44,7 @@ def normalize_json_schema_types( } if isinstance(schema, list): - return [ - normalize_json_schema_types(item, depth + 1, max_depth) for item in schema - ] + return [normalize_json_schema_types(item, depth + 1, max_depth) for item in schema] if isinstance(schema, dict): normalized_schema: Dict[str, Any] = {} @@ -57,21 +55,15 @@ def normalize_json_schema_types( elif key == "properties" and isinstance(value, dict): # Recursively normalize properties normalized_schema[key] = { - prop_key: normalize_json_schema_types( - prop_value, depth + 1, max_depth - ) + prop_key: normalize_json_schema_types(prop_value, depth + 1, max_depth) for prop_key, prop_value in value.items() } elif key == "items" and isinstance(value, (dict, list)): # Recursively normalize array items - normalized_schema[key] = normalize_json_schema_types( - value, depth + 1, max_depth - ) + normalized_schema[key] = normalize_json_schema_types(value, depth + 1, max_depth) elif isinstance(value, (dict, list)): # Recursively normalize any nested dict or list - normalized_schema[key] = normalize_json_schema_types( - value, depth + 1, max_depth - ) + normalized_schema[key] = normalize_json_schema_types(value, depth + 1, max_depth) else: normalized_schema[key] = value @@ -99,9 +91,7 @@ def normalize_tool_schema(tool: Dict[str, Any]) -> Dict[str, Any]: if "function" in tool and isinstance(tool["function"], dict): normalized_tool["function"] = tool["function"].copy() if "parameters" in tool["function"]: - normalized_tool["function"]["parameters"] = normalize_json_schema_types( - tool["function"]["parameters"] - ) + normalized_tool["function"]["parameters"] = normalize_json_schema_types(tool["function"]["parameters"]) return normalized_tool @@ -121,13 +111,9 @@ def validate_schema(schema: dict, response: str): try: response_dict = json.loads(response) except json.JSONDecodeError: - raise JSONSchemaValidationError( - model="", llm_provider="", raw_response=response, schema=json.dumps(schema) - ) + raise JSONSchemaValidationError(model="", llm_provider="", raw_response=response, schema=json.dumps(schema)) try: validate(response_dict, schema=schema) except ValidationError: - raise JSONSchemaValidationError( - model="", llm_provider="", raw_response=response, schema=json.dumps(schema) - ) + raise JSONSchemaValidationError(model="", llm_provider="", raw_response=response, schema=json.dumps(schema)) diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index e860f48a7bdb..2457d117b811 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -197,13 +197,11 @@ from litellm.integrations.generic_api.generic_api_callback import GenericAPILogger - EnterpriseStandardLoggingPayloadSetupVAR: Optional[ - Type[EnterpriseStandardLoggingPayloadSetup] - ] = EnterpriseStandardLoggingPayloadSetup -except Exception as e: - verbose_logger.debug( - f"[Non-Blocking] Unable to import GenericAPILogger - LiteLLM Enterprise Feature - {str(e)}" + EnterpriseStandardLoggingPayloadSetupVAR: Optional[Type[EnterpriseStandardLoggingPayloadSetup]] = ( + EnterpriseStandardLoggingPayloadSetup ) +except Exception as e: + verbose_logger.debug(f"[Non-Blocking] Unable to import GenericAPILogger - LiteLLM Enterprise Feature - {str(e)}") GenericAPILogger = CustomLogger # type: ignore ResendEmailLogger = CustomLogger # type: ignore SendGridEmailLogger = CustomLogger # type: ignore @@ -213,16 +211,12 @@ EnterpriseStandardLoggingPayloadSetupVAR = None _in_memory_loggers: List[Any] = [] -_STANDARD_LOGGING_METADATA_KEYS: frozenset = frozenset( - StandardLoggingMetadata.__annotations__.keys() -) +_STANDARD_LOGGING_METADATA_KEYS: frozenset = frozenset(StandardLoggingMetadata.__annotations__.keys()) ### GLOBAL VARIABLES ### # Cache custom pricing keys as frozenset for O(1) lookups instead of looping through 49 keys -_CUSTOM_PRICING_KEYS: frozenset = frozenset( - CustomPricingLiteLLMParams.model_fields.keys() -) +_CUSTOM_PRICING_KEYS: frozenset = frozenset(CustomPricingLiteLLMParams.model_fields.keys()) sentry_sdk_instance = None capture_exception = None @@ -318,21 +312,11 @@ def __init__( litellm_call_id: str, function_id: str, litellm_trace_id: Optional[str] = None, - dynamic_input_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = None, - dynamic_success_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = None, - dynamic_async_success_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = None, - dynamic_failure_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = None, - dynamic_async_failure_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = None, + dynamic_input_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = None, + dynamic_success_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = None, + dynamic_async_success_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = None, + dynamic_failure_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = None, + dynamic_async_failure_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = None, applied_guardrails: Optional[List[str]] = None, kwargs: Optional[Dict] = None, log_raw_request_response: bool = False, @@ -343,11 +327,7 @@ def __init__( messages = [ {"role": "user", "content": messages} ] # convert text completion input to the chat completion format - elif ( - isinstance(messages, list) - and len(messages) > 0 - and isinstance(messages[0], str) - ): + elif isinstance(messages, list) and len(messages) > 0 and isinstance(messages[0], str): new_messages = [] for m in messages: new_messages.append({"role": "user", "content": m}) @@ -364,32 +344,22 @@ def __init__( self.start_time = start_time # log the call start time self.call_type = call_type self.litellm_call_id = litellm_call_id - self.litellm_trace_id: str = ( - litellm_trace_id if litellm_trace_id else str(uuid.uuid4()) - ) + self.litellm_trace_id: str = litellm_trace_id if litellm_trace_id else str(uuid.uuid4()) self.function_id = function_id self.streaming_chunks: List[Any] = [] # for generating complete stream response - self.sync_streaming_chunks: List[ - Any - ] = [] # for generating complete stream response + self.sync_streaming_chunks: List[Any] = [] # for generating complete stream response self.log_raw_request_response = log_raw_request_response # Initialize dynamic callbacks - self.dynamic_input_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = dynamic_input_callbacks - self.dynamic_success_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = dynamic_success_callbacks - self.dynamic_async_success_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = dynamic_async_success_callbacks - self.dynamic_failure_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = dynamic_failure_callbacks - self.dynamic_async_failure_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = dynamic_async_failure_callbacks + self.dynamic_input_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = dynamic_input_callbacks + self.dynamic_success_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = dynamic_success_callbacks + self.dynamic_async_success_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = ( + dynamic_async_success_callbacks + ) + self.dynamic_failure_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = dynamic_failure_callbacks + self.dynamic_async_failure_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = ( + dynamic_async_failure_callbacks + ) ## DYNAMIC LANGFUSE / GCS / logging callback KEYS ## self.standard_callback_dynamic_params: StandardCallbackDynamicParams = ( @@ -472,9 +442,7 @@ def process_dynamic_callbacks(self): def _process_dynamic_callback_list( self, callback_list: Optional[List[Union[str, Callable, CustomLogger]]], - dynamic_callbacks_type: Literal[ - "input", "success", "failure", "async_success", "async_failure" - ], + dynamic_callbacks_type: Literal["input", "success", "failure", "async_success", "async_failure"], ) -> Optional[List[Union[str, Callable, CustomLogger]]]: """ Helper function to initialize CustomLogger compatible callbacks in self.dynamic_* callbacks @@ -489,18 +457,13 @@ def _process_dynamic_callback_list( processed_list: List[Union[str, Callable, CustomLogger]] = [] for callback in callback_list: - if ( - isinstance(callback, str) - and callback in litellm._known_custom_logger_compatible_callbacks - ): + if isinstance(callback, str) and callback in litellm._known_custom_logger_compatible_callbacks: # For callbacks that support team-scoped credentials (e.g. datadog), # pass only the relevant dynamic params as custom_logger_init_args. _custom_logger_init_args: Optional[dict] = None if callback == "datadog": _custom_logger_init_args = { - k: v - for k, v in self.standard_callback_dynamic_params.items() - if k.startswith("dd_") + k: v for k, v in self.standard_callback_dynamic_params.items() if k.startswith("dd_") } callback_class = _init_custom_logger_compatible_class( @@ -536,21 +499,15 @@ def initialize_standard_callback_dynamic_params( return _initialize_standard_callback_dynamic_params(kwargs) - def initialize_standard_built_in_tools_params( - self, kwargs: Optional[Dict] = None - ) -> StandardBuiltInToolsParams: + def initialize_standard_built_in_tools_params(self, kwargs: Optional[Dict] = None) -> StandardBuiltInToolsParams: """ Initialize the standard built-in tools params from the kwargs checks if web_search_options in kwargs or tools and sets the corresponding attribute in StandardBuiltInToolsParams """ return StandardBuiltInToolsParams( - web_search_options=StandardBuiltInToolCostTracking._get_web_search_options( - kwargs or {} - ), - file_search=StandardBuiltInToolCostTracking._get_file_search_tool_call( - kwargs or {} - ), + web_search_options=StandardBuiltInToolCostTracking._get_web_search_options(kwargs or {}), + file_search=StandardBuiltInToolCostTracking._get_file_search_tool_call(kwargs or {}), ) def get_router_model_id(self) -> Optional[str]: @@ -613,10 +570,7 @@ def update_environment_variables( if "stream_options" in additional_params: self.stream_options = additional_params["stream_options"] ## check if custom pricing set ## - if any( - litellm_params.get(key) is not None - for key in _CUSTOM_PRICING_KEYS & litellm_params.keys() - ): + if any(litellm_params.get(key) is not None for key in _CUSTOM_PRICING_KEYS & litellm_params.keys()): self.custom_pricing = True if "custom_llm_provider" in self.model_call_details: @@ -640,9 +594,7 @@ def update_from_kwargs( if "metadata" in kwargs: base_litellm_params["metadata"] = kwargs["metadata"] - if "litellm_metadata" in kwargs and isinstance( - kwargs["litellm_metadata"], dict - ): + if "litellm_metadata" in kwargs and isinstance(kwargs["litellm_metadata"], dict): base_litellm_params["litellm_metadata"] = kwargs["litellm_metadata"] if "metadata" not in base_litellm_params: base_litellm_params["metadata"] = kwargs["litellm_metadata"].copy() @@ -738,15 +690,12 @@ def get_chat_completion_prompt( prompt_label: Optional[str] = None, prompt_version: Optional[int] = None, ) -> Tuple[str, List[AllMessageValues], dict]: - custom_logger = ( - prompt_management_logger - or self.get_custom_logger_for_prompt_management( - model=model, - non_default_params=non_default_params, - prompt_id=prompt_id, - prompt_spec=prompt_spec, - dynamic_callback_params=self.standard_callback_dynamic_params, - ) + custom_logger = prompt_management_logger or self.get_custom_logger_for_prompt_management( + model=model, + non_default_params=non_default_params, + prompt_id=prompt_id, + prompt_spec=prompt_spec, + dynamic_callback_params=self.standard_callback_dynamic_params, ) if custom_logger: @@ -781,16 +730,13 @@ async def async_get_chat_completion_prompt( prompt_label: Optional[str] = None, prompt_version: Optional[int] = None, ) -> Tuple[str, List[AllMessageValues], dict]: - custom_logger = ( - prompt_management_logger - or self.get_custom_logger_for_prompt_management( - model=model, - tools=tools, - non_default_params=non_default_params, - prompt_id=prompt_id, - prompt_spec=prompt_spec, - dynamic_callback_params=self.standard_callback_dynamic_params, - ) + custom_logger = prompt_management_logger or self.get_custom_logger_for_prompt_management( + model=model, + tools=tools, + non_default_params=non_default_params, + prompt_id=prompt_id, + prompt_spec=prompt_spec, + dynamic_callback_params=self.standard_callback_dynamic_params, ) if custom_logger: @@ -832,10 +778,8 @@ def _auto_detect_prompt_management_logger( Returns: A CustomLogger instance if a matching prompt management system is found, None otherwise """ - prompt_management_loggers = ( - litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=CustomPromptManagement - ) + prompt_management_loggers = litellm.logging_callback_manager.get_custom_loggers_for_type( + callback_type=CustomPromptManagement ) for logger in prompt_management_loggers: @@ -846,9 +790,7 @@ def _auto_detect_prompt_management_logger( prompt_spec=prompt_spec, dynamic_callback_params=dynamic_callback_params, ): - self.model_call_details["prompt_integration"] = ( - logger.__class__.__name__ - ) + self.model_call_details["prompt_integration"] = logger.__class__.__name__ return logger except Exception: # If check fails, continue to next logger @@ -902,10 +844,8 @@ def get_custom_logger_for_prompt_management( return auto_detected_logger # Then check for any registered CustomPromptManagement loggers (fallback) - prompt_management_loggers = ( - litellm.logging_callback_manager.get_custom_loggers_for_type( - callback_type=CustomPromptManagement - ) + prompt_management_loggers = litellm.logging_callback_manager.get_custom_loggers_for_type( + callback_type=CustomPromptManagement ) if prompt_management_loggers: @@ -915,13 +855,9 @@ def get_custom_logger_for_prompt_management( if ( anthropic_cache_control_logger - := AnthropicCacheControlHook.get_custom_logger_for_anthropic_cache_control_hook( - non_default_params - ) + := AnthropicCacheControlHook.get_custom_logger_for_anthropic_cache_control_hook(non_default_params) ): - self.model_call_details["prompt_integration"] = ( - anthropic_cache_control_logger.__class__.__name__ - ) + self.model_call_details["prompt_integration"] = anthropic_cache_control_logger.__class__.__name__ return anthropic_cache_control_logger ######################################################### @@ -933,24 +869,15 @@ def get_custom_logger_for_prompt_management( internal_usage_cache=None, llm_router=None, ) - self.model_call_details["prompt_integration"] = ( - vector_store_custom_logger.__class__.__name__ - ) + self.model_call_details["prompt_integration"] = vector_store_custom_logger.__class__.__name__ # Add to global callbacks so post-call hooks are invoked - if ( - vector_store_custom_logger - and vector_store_custom_logger not in litellm.callbacks - ): - litellm.logging_callback_manager.add_litellm_callback( - vector_store_custom_logger - ) + if vector_store_custom_logger and vector_store_custom_logger not in litellm.callbacks: + litellm.logging_callback_manager.add_litellm_callback(vector_store_custom_logger) return vector_store_custom_logger return None - def get_custom_logger_for_anthropic_cache_control_hook( - self, non_default_params: Dict - ) -> Optional[CustomLogger]: + def get_custom_logger_for_anthropic_cache_control_hook(self, non_default_params: Dict) -> Optional[CustomLogger]: if non_default_params.get("cache_control_injection_points", None): custom_logger = _init_custom_logger_compatible_class( logging_integration="anthropic_cache_control_hook", @@ -967,9 +894,7 @@ def _get_raw_request_body(self, data: Optional[Union[dict, str]]) -> dict: try: return json.loads(data) except Exception: - return { - "error": "Unable to parse raw request body. Got - {}".format(data) - } + return {"error": "Unable to parse raw request body. Got - {}".format(data)} return data def _get_masked_api_base(self, api_base: str) -> str: @@ -993,8 +918,8 @@ def _pre_call(self, input, api_key, model=None, additional_args={}): self.model_call_details["log_event_type"] = "pre_api_call" if model: # if model name was changes pre-call, overwrite the initial model call name with the new one self.model_call_details["model"] = model - self.model_call_details["litellm_params"]["api_base"] = ( - self._get_masked_api_base(additional_args.get("api_base", "")) + self.model_call_details["litellm_params"]["api_base"] = self._get_masked_api_base( + additional_args.get("api_base", "") ) def pre_call(self, input, api_key, model=None, additional_args={}): @@ -1015,10 +940,7 @@ def pre_call(self, input, api_key, model=None, additional_args={}): additional_args=additional_args, ) # log raw request to provider (like LangFuse) -- if opted in. - if ( - self.log_raw_request_response is True - or log_raw_request_response is True - ): + if self.log_raw_request_response is True or log_raw_request_response is True: _litellm_params = self.model_call_details.get("litellm_params", {}) _metadata = _litellm_params.get("metadata", {}) or {} try: @@ -1036,28 +958,20 @@ def pre_call(self, input, api_key, model=None, additional_args={}): _metadata["raw_request"] = str(curl_command) # split up, so it's easier to parse in the UI - self.model_call_details["raw_request_typed_dict"] = ( - RawRequestTypedDict( - raw_request_api_base=str( - additional_args.get("api_base") or "" - ), - raw_request_body=self._get_raw_request_body( - additional_args.get("complete_input_dict", {}) - ), - # NOTE: setting ignore_sensitive_headers to True will cause - # the Authorization header to be leaked when calls to the health - # endpoint are made and fail. - raw_request_headers=self._get_masked_headers( - additional_args.get("headers", {}) or {}, - ), - error=None, - ) + self.model_call_details["raw_request_typed_dict"] = RawRequestTypedDict( + raw_request_api_base=str(additional_args.get("api_base") or ""), + raw_request_body=self._get_raw_request_body(additional_args.get("complete_input_dict", {})), + # NOTE: setting ignore_sensitive_headers to True will cause + # the Authorization header to be leaked when calls to the health + # endpoint are made and fail. + raw_request_headers=self._get_masked_headers( + additional_args.get("headers", {}) or {}, + ), + error=None, ) except Exception as e: - self.model_call_details["raw_request_typed_dict"] = ( - RawRequestTypedDict( - error=str(e), - ) + self.model_call_details["raw_request_typed_dict"] = RawRequestTypedDict( + error=str(e), ) _metadata["raw_request"] = "Unable to Log \ raw request: {}".format(str(e)) @@ -1068,9 +982,7 @@ def pre_call(self, input, api_key, model=None, additional_args={}): ) # Expectation: any logger function passed in by the user should accept a dict object except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format( - str(e) - ) + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format(str(e)) ) self.model_call_details["api_call_start_time"] = datetime.datetime.now() @@ -1081,9 +993,7 @@ def pre_call(self, input, api_key, model=None, additional_args={}): # litellm_params["metadata"] (caller request metadata, typed # Dict[str, str], echoed downstream; a datetime breaks it). if self.model_call_details.get("first_api_call_start_time") is None: - self.model_call_details["first_api_call_start_time"] = ( - self.model_call_details["api_call_start_time"] - ) + self.model_call_details["first_api_call_start_time"] = self.model_call_details["api_call_start_time"] # Input Integration Logging -> If you want to log the fact that an attempt to call the model was made callbacks = litellm.input_callback + (self.dynamic_input_callbacks or []) for callback in callbacks: @@ -1123,9 +1033,7 @@ def pre_call(self, input, api_key, model=None, additional_args={}): messages=self.messages, kwargs=self.model_call_details, ) - elif ( - callable(callback) and customLogger is not None - ): # custom logger functions + elif callable(callback) and customLogger is not None: # custom logger functions customLogger.log_input_event( model=self.model, messages=self.messages, @@ -1134,11 +1042,7 @@ def pre_call(self, input, api_key, model=None, additional_args={}): callback_func=callback, ) except Exception as e: - verbose_logger.exception( - "litellm.Logging.pre_call(): Exception occured - {}".format( - str(e) - ) - ) + verbose_logger.exception("litellm.Logging.pre_call(): Exception occured - {}".format(str(e))) verbose_logger.debug( f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}" ) @@ -1146,13 +1050,9 @@ def pre_call(self, input, api_key, model=None, additional_args={}): capture_exception(e) except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format( - str(e) - ) - ) - verbose_logger.error( - f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}" + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format(str(e)) ) + verbose_logger.error(f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}") if capture_exception: # log this error to sentry for debugging capture_exception(e) @@ -1212,12 +1112,8 @@ def _get_request_curl_command( curl_command += "curl -X POST \\\n" curl_command += f"{masked_api_base} \\\n" masked_headers = self._get_masked_headers(headers) - formatted_headers = " ".join( - [f"-H '{k}: {v}'" for k, v in masked_headers.items()] - ) - curl_command += ( - f"{formatted_headers} \\\n" if formatted_headers.strip() != "" else "" - ) + formatted_headers = " ".join([f"-H '{k}: {v}'" for k, v in masked_headers.items()]) + curl_command += f"{formatted_headers} \\\n" if formatted_headers.strip() != "" else "" curl_command += f"-d '{self._get_request_body(data)}'\n" if additional_args.get("request_str", None) is not None: # print the sagemaker / bedrock client request @@ -1228,21 +1124,15 @@ def _get_request_curl_command( curl_command = str(self.model_call_details) return curl_command - def _get_masked_headers( - self, headers: dict, ignore_sensitive_headers: bool = False - ) -> dict: + def _get_masked_headers(self, headers: dict, ignore_sensitive_headers: bool = False) -> dict: """ Internal debugging helper function Masks the headers of the request sent from LiteLLM """ - return _get_masked_values( - headers, ignore_sensitive_values=ignore_sensitive_headers - ) + return _get_masked_values(headers, ignore_sensitive_values=ignore_sensitive_headers) - def post_call( - self, original_response, input=None, api_key=None, additional_args={} - ): + def post_call(self, original_response, input=None, api_key=None, additional_args={}): # Log the exact result from the LLM API, for streaming - log the type of response received litellm.error_logs["POST_CALL"] = locals() if isinstance(original_response, dict): @@ -1263,18 +1153,14 @@ def post_call( callattr = getattr(verbose_logger, attr) callattr( "RAW RESPONSE:\n{}\n\n".format( - self.model_call_details.get( - "original_response", self.model_call_details - ) + self.model_call_details.get("original_response", self.model_call_details) ), ) else: callattr = getattr(verbose_logger, attr) callattr( "RAW RESPONSE:\n{}\n\n".format( - self.model_call_details.get( - "original_response", self.model_call_details - ) + self.model_call_details.get("original_response", self.model_call_details) ) ) if getattr(self, "logger_fn", None) and callable(self.logger_fn): @@ -1284,16 +1170,10 @@ def post_call( ) # Expectation: any logger function passed in by the user should accept a dict object except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format( - str(e) - ) + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format(str(e)) ) original_response = redact_message_input_output_from_logging( - model_call_details=( - self.model_call_details - if hasattr(self, "model_call_details") - else {} - ), + model_call_details=(self.model_call_details if hasattr(self, "model_call_details") else {}), result=original_response, ) # Input Integration Logging -> If you want to log the fact that an attempt to call the model was made @@ -1338,9 +1218,7 @@ def post_call( capture_exception(e) except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format( - str(e) - ) + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format(str(e)) ) async def async_post_mcp_tool_call_hook( @@ -1362,17 +1240,13 @@ async def async_post_mcp_tool_call_hook( dynamic_success_callbacks=self.dynamic_success_callbacks, global_callbacks=litellm.success_callback, ) - post_mcp_tool_call_response_obj: MCPPostCallResponseObject = ( - MCPPostCallResponseObject( - mcp_tool_call_response=response_obj, hidden_params=HiddenParams() - ) + post_mcp_tool_call_response_obj: MCPPostCallResponseObject = MCPPostCallResponseObject( + mcp_tool_call_response=response_obj, hidden_params=HiddenParams() ) for callback in callbacks: try: if isinstance(callback, CustomLogger): - response: Optional[ - MCPPostCallResponseObject - ] = await callback.async_post_mcp_tool_call_hook( + response: Optional[MCPPostCallResponseObject] = await callback.async_post_mcp_tool_call_hook( kwargs=kwargs, response_obj=post_mcp_tool_call_response_obj, start_time=start_time, @@ -1383,20 +1257,14 @@ async def async_post_mcp_tool_call_hook( # current implementation returns the first modified response ###################################################################### if response is not None: - response_obj = self._parse_post_mcp_call_hook_response( - response=response - ) + response_obj = self._parse_post_mcp_call_hook_response(response=response) except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format( - str(e) - ) + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format(str(e)) ) return response_obj - def _parse_post_mcp_call_hook_response( - self, response: Optional[MCPPostCallResponseObject] - ) -> Any: + def _parse_post_mcp_call_hook_response(self, response: Optional[MCPPostCallResponseObject]) -> Any: """ Parse the response from the post_mcp_tool_call_hook @@ -1459,11 +1327,7 @@ def set_cost_breakdown( self.cost_breakdown["cache_creation_cost"] = cache_creation_cost # Store additional costs if provided (free-form dict for extensibility) - if ( - additional_costs - and isinstance(additional_costs, dict) - and len(additional_costs) > 0 - ): + if additional_costs and isinstance(additional_costs, dict) and len(additional_costs) > 0: self.cost_breakdown["additional_costs"] = additional_costs # Store discount information if provided @@ -1523,13 +1387,10 @@ def _response_cost_calculator( if isinstance(result, BaseModel) and hasattr(result, "_hidden_params"): hidden_params = getattr(result, "_hidden_params", {}) if ( - "response_cost" in hidden_params - and hidden_params["response_cost"] is not None + "response_cost" in hidden_params and hidden_params["response_cost"] is not None ): # use cost if already calculated return hidden_params["response_cost"] - elif ( - router_model_id is None and "model_id" in hidden_params - ): # use model_id if not already set + elif router_model_id is None and "model_id" in hidden_params: # use model_id if not already set router_model_id = hidden_params["model_id"] # Fallback: extract router_model_id from litellm_params when not available @@ -1540,9 +1401,7 @@ def _response_cost_calculator( ## RESPONSE COST ## custom_pricing = use_custom_pricing_for_model( - litellm_params=( - self.litellm_params if hasattr(self, "litellm_params") else None - ) + litellm_params=(self.litellm_params if hasattr(self, "litellm_params") else None) ) prompt = "" # use for tts cost calc @@ -1558,12 +1417,8 @@ def _response_cost_calculator( "response_object": result, "model": litellm_model_name or self.model, "cache_hit": cache_hit, - "custom_llm_provider": self.model_call_details.get( - "custom_llm_provider", None - ), - "base_model": _get_base_model_from_metadata( - model_call_details=self.model_call_details - ), + "custom_llm_provider": self.model_call_details.get("custom_llm_provider", None), + "base_model": _get_base_model_from_metadata(model_call_details=self.model_call_details), "call_type": self.call_type, "optional_params": self.optional_params, "custom_pricing": custom_pricing, @@ -1571,11 +1426,7 @@ def _response_cost_calculator( "standard_built_in_tools_params": self.standard_built_in_tools_params, "router_model_id": router_model_id, "litellm_logging_obj": self, - "service_tier": ( - self.optional_params.get("service_tier") - if self.optional_params - else None - ), + "service_tier": (self.optional_params.get("service_tier") if self.optional_params else None), "data_residency": ( self.litellm_params.get("data_residency") if hasattr(self, "litellm_params") and self.litellm_params @@ -1587,18 +1438,12 @@ def _response_cost_calculator( error_str=str(e), traceback_str=_get_traceback_str_for_error(str(e)), ) - verbose_logger.debug( - f"response_cost_failure_debug_information: {debug_info}" - ) - self.model_call_details["response_cost_failure_debug_information"] = ( - debug_info - ) + verbose_logger.debug(f"response_cost_failure_debug_information: {debug_info}") + self.model_call_details["response_cost_failure_debug_information"] = debug_info return None try: - response_cost = litellm.response_cost_calculator( - **response_cost_calculator_kwargs - ) + response_cost = litellm.response_cost_calculator(**response_cost_calculator_kwargs) verbose_logger.debug(f"response_cost: {response_cost}") return response_cost @@ -1608,19 +1453,13 @@ def _response_cost_calculator( traceback_str=_get_traceback_str_for_error(str(e)), model=response_cost_calculator_kwargs["model"], cache_hit=response_cost_calculator_kwargs["cache_hit"], - custom_llm_provider=response_cost_calculator_kwargs[ - "custom_llm_provider" - ], + custom_llm_provider=response_cost_calculator_kwargs["custom_llm_provider"], base_model=response_cost_calculator_kwargs["base_model"], call_type=response_cost_calculator_kwargs["call_type"], custom_pricing=response_cost_calculator_kwargs["custom_pricing"], ) - verbose_logger.debug( - f"response_cost_failure_debug_information: {debug_info}" - ) - self.model_call_details["response_cost_failure_debug_information"] = ( - debug_info - ) + verbose_logger.debug(f"response_cost_failure_debug_information: {debug_info}") + self.model_call_details["response_cost_failure_debug_information"] = debug_info return None @@ -1728,9 +1567,7 @@ async def dispatch_success_handlers( def should_run_logging( self, - event_type: Literal[ - "async_success", "sync_success", "async_failure", "sync_failure" - ], + event_type: Literal["async_success", "sync_success", "async_failure", "sync_failure"], stream: bool = False, ) -> bool: try: @@ -1743,9 +1580,7 @@ def should_run_logging( def has_run_logging( self, - event_type: Literal[ - "async_success", "sync_success", "async_failure", "sync_failure" - ], + event_type: Literal["async_success", "sync_success", "async_failure", "sync_failure"], ) -> None: if self.stream is not None and self.stream is True: """ @@ -1755,32 +1590,22 @@ def has_run_logging( self.model_call_details[f"has_logged_{event_type}"] = True return - def should_run_callback( - self, callback: litellm.CALLBACK_TYPES, litellm_params: dict, event_hook: str - ) -> bool: + def should_run_callback(self, callback: litellm.CALLBACK_TYPES, litellm_params: dict, event_hook: str) -> bool: if litellm.global_disable_no_log_param: return True if litellm_params.get("no-log", False) is True: # proxy cost tracking cal backs should run - if not ( - isinstance(callback, CustomLogger) - and "_PROXY_" in callback.__class__.__name__ - ): - verbose_logger.debug( - f"no-log request, skipping logging for {event_hook} event" - ) + if not (isinstance(callback, CustomLogger) and "_PROXY_" in callback.__class__.__name__): + verbose_logger.debug(f"no-log request, skipping logging for {event_hook} event") return False # Check for dynamically disabled callbacks via headers - if ( - EnterpriseCallbackControls is not None - and EnterpriseCallbackControls.is_callback_disabled_dynamically( - callback=callback, - litellm_params=litellm_params, - standard_callback_dynamic_params=self.standard_callback_dynamic_params, - ) + if EnterpriseCallbackControls is not None and EnterpriseCallbackControls.is_callback_disabled_dynamically( + callback=callback, + litellm_params=litellm_params, + standard_callback_dynamic_params=self.standard_callback_dynamic_params, ): verbose_logger.debug( f"Callback {callback} disabled via x-litellm-disable-callbacks header for {event_hook} event" @@ -1800,14 +1625,12 @@ def normalize_logging_result(self, result: Any) -> Any: """ logging_result = result if self.call_type == CallTypes.arealtime.value and isinstance(result, list): - combined_usage_object = RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results( - results=result + combined_usage_object = ( + RealtimeAPITokenUsageProcessor.collect_and_combine_usage_from_realtime_stream_results(results=result) ) - logging_result = ( - RealtimeAPITokenUsageProcessor.create_logging_realtime_object( - usage=combined_usage_object, - results=result, - ) + logging_result = RealtimeAPITokenUsageProcessor.create_logging_realtime_object( + usage=combined_usage_object, + results=result, ) elif ( @@ -1823,9 +1646,7 @@ def normalize_logging_result(self, result: Any) -> Any: if provider_config is not None: logging_result = provider_config.logging_non_streaming_response( model=self.model, - custom_llm_provider=self.model_call_details.get( - "custom_llm_provider", "" - ), + custom_llm_provider=self.model_call_details.get("custom_llm_provider", ""), httpx_response=result, request_data=self.model_call_details.get("request_data", {}), logging_obj=self, @@ -1833,9 +1654,7 @@ def normalize_logging_result(self, result: Any) -> Any: ) return logging_result - def _merge_hidden_params_from_response_into_metadata( - self, logging_result: Any - ) -> None: + def _merge_hidden_params_from_response_into_metadata(self, logging_result: Any) -> None: """ Copy response._hidden_params into litellm_params.metadata['hidden_params']. @@ -1852,10 +1671,7 @@ def _merge_hidden_params_from_response_into_metadata( return metadata_hidden_params = hidden_params.copy() response_cost = self.model_call_details.get("response_cost") - if ( - metadata_hidden_params.get("response_cost") is None - and response_cost is not None - ): + if metadata_hidden_params.get("response_cost") is None and response_cost is not None: metadata_hidden_params["response_cost"] = response_cost litellm_params = self.model_call_details["litellm_params"] @@ -1876,40 +1692,30 @@ def _process_hidden_params_and_response_cost( self.model_call_details["litellm_params"].setdefault("metadata", {}) if self.model_call_details["litellm_params"]["metadata"] is None: self.model_call_details["litellm_params"]["metadata"] = {} - self.model_call_details["litellm_params"]["metadata"][ - "hidden_params" - ] = getattr(logging_result, "_hidden_params", {}) # type: ignore + self.model_call_details["litellm_params"]["metadata"]["hidden_params"] = getattr( + logging_result, "_hidden_params", {} + ) # type: ignore if self.model_call_details.get("cache_hit") is True: self.model_call_details["response_cost"] = 0.0 elif "response_cost" in hidden_params: self.model_call_details["response_cost"] = hidden_params["response_cost"] - elif ( - existing_cost := self.model_call_details.get("response_cost") - ) is not None and existing_cost != 0: + elif (existing_cost := self.model_call_details.get("response_cost")) is not None and existing_cost != 0: # Preserve response_cost if already calculated (e.g., by pass-through # handlers like Gemini/Vertex which call completion_cost directly). # Do not preserve 0 from failure_handler on intermediate router retries. pass else: - self.model_call_details["response_cost"] = self._response_cost_calculator( - result=logging_result - ) + self.model_call_details["response_cost"] = self._response_cost_calculator(result=logging_result) - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload(logging_result, start_time, end_time) + self.model_call_details["standard_logging_object"] = self._build_standard_logging_payload( + logging_result, start_time, end_time ) - if ( - standard_logging_payload := self.model_call_details.get( - "standard_logging_object" - ) - ) is not None: + if (standard_logging_payload := self.model_call_details.get("standard_logging_object")) is not None: emit_standard_logging_payload(standard_logging_payload) - def _build_standard_logging_payload( - self, init_response_obj: Any, start_time: Any, end_time: Any - ) -> Any: + def _build_standard_logging_payload(self, init_response_obj: Any, start_time: Any, end_time: Any) -> Any: """Build StandardLoggingPayload and accumulate its construction time.""" _start = time.time() payload = get_standard_logging_object_payload( @@ -1927,22 +1733,10 @@ def _build_standard_logging_payload( def _transform_usage_objects(self, result): if isinstance(result, ResponsesAPIResponse): result = result.model_copy() - transformed_usage = ( - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - result.usage - ) - ) + transformed_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(result.usage) setattr(result, "usage", transformed_usage) - if ( - standard_logging_payload := self.model_call_details.get( - "standard_logging_object" - ) - ) is not None: - response_dict = ( - result.model_dump() - if hasattr(result, "model_dump") - else dict(result) - ) + if (standard_logging_payload := self.model_call_details.get("standard_logging_object")) is not None: + response_dict = result.model_dump() if hasattr(result, "model_dump") else dict(result) # Ensure usage is properly included with transformed chat format if transformed_usage is not None: response_dict["usage"] = ( @@ -1978,9 +1772,7 @@ def _success_handler_helper_fn( end_time = datetime.datetime.now() if self.completion_start_time is None: self.completion_start_time = end_time - self.model_call_details["completion_start_time"] = ( - self.completion_start_time - ) + self.model_call_details["completion_start_time"] = self.completion_start_time self.model_call_details["log_event_type"] = "successful_api_call" self.model_call_details["end_time"] = end_time @@ -1992,34 +1784,23 @@ def _success_handler_helper_fn( self.call_type == CallTypes.generate_content.value or self.call_type == CallTypes.agenerate_content.value ): - result = self._handle_non_streaming_google_genai_generate_content_response_logging( - result=result - ) - elif ( - self.call_type == CallTypes.asend_message.value - or self.call_type == CallTypes.send_message.value - ): + result = self._handle_non_streaming_google_genai_generate_content_response_logging(result=result) + elif self.call_type == CallTypes.asend_message.value or self.call_type == CallTypes.send_message.value: result = self._handle_a2a_response_logging(result=result) logging_result = self.normalize_logging_result(result=result) - if ( - standard_logging_object is None - and result is not None - and self.stream is not True - ): - if self._is_recognized_call_type_for_logging( - logging_result=logging_result - ) or isinstance(logging_result, (dict, list)): + if standard_logging_object is None and result is not None and self.stream is not True: + if self._is_recognized_call_type_for_logging(logging_result=logging_result) or isinstance( + logging_result, (dict, list) + ): self._process_hidden_params_and_response_cost( logging_result=logging_result, start_time=start_time, end_time=end_time, ) elif standard_logging_object is not None: - self.model_call_details["standard_logging_object"] = ( - standard_logging_object - ) + self.model_call_details["standard_logging_object"] = standard_logging_object else: self.model_call_details["response_cost"] = None @@ -2134,15 +1915,9 @@ async def async_flush_passthrough_collected_chunks( await self.async_success_handler(result=complete_streaming_response) return - def success_handler( - self, result=None, start_time=None, end_time=None, cache_hit=None, **kwargs - ): - verbose_logger.debug( - f"Logging Details LiteLLM-Success Call: Cache_hit={cache_hit}" - ) - if not self.should_run_logging( - event_type="sync_success" - ): # prevent double logging + def success_handler(self, result=None, start_time=None, end_time=None, cache_hit=None, **kwargs): + verbose_logger.debug(f"Logging Details LiteLLM-Success Call: Cache_hit={cache_hit}") + if not self.should_run_logging(event_type="sync_success"): # prevent double logging return start_time, end_time, result = self._success_handler_helper_fn( start_time=start_time, @@ -2168,29 +1943,17 @@ def success_handler( streaming_chunks=self.sync_streaming_chunks, ) if complete_streaming_response is not None: - verbose_logger.debug( - "Logging Details LiteLLM-Success Call streaming complete" - ) - self.model_call_details["complete_streaming_response"] = ( - complete_streaming_response - ) - self.model_call_details["response_cost"] = ( - self._response_cost_calculator(result=complete_streaming_response) - ) - self._merge_hidden_params_from_response_into_metadata( - complete_streaming_response + verbose_logger.debug("Logging Details LiteLLM-Success Call streaming complete") + self.model_call_details["complete_streaming_response"] = complete_streaming_response + self.model_call_details["response_cost"] = self._response_cost_calculator( + result=complete_streaming_response ) + self._merge_hidden_params_from_response_into_metadata(complete_streaming_response) ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload( - complete_streaming_response, start_time, end_time - ) + self.model_call_details["standard_logging_object"] = self._build_standard_logging_payload( + complete_streaming_response, start_time, end_time ) - if ( - standard_logging_payload := self.model_call_details.get( - "standard_logging_object" - ) - ) is not None: + if (standard_logging_payload := self.model_call_details.get("standard_logging_object")) is not None: # Only emit for sync requests (async_success_handler handles async) if is_sync_request: emit_standard_logging_payload(standard_logging_payload) @@ -2201,11 +1964,7 @@ def success_handler( ## REDACT MESSAGES ## result = redact_message_input_output_from_logging( - model_call_details=( - self.model_call_details - if hasattr(self, "model_call_details") - else {} - ), + model_call_details=(self.model_call_details if hasattr(self, "model_call_details") else {}), result=result, ) ## LOGGING HOOK ## @@ -2278,12 +2037,7 @@ def success_handler( end_time=end_time, litellm_call_id=( current_call_id - if ( - current_call_id := litellm_params.get( - "litellm_call_id" - ) - ) - is not None + if (current_call_id := litellm_params.get("litellm_call_id")) is not None else str(uuid.uuid4()) ), print_verbose=print_verbose, @@ -2301,9 +2055,7 @@ def success_handler( verbose_logger.debug("reaches logfire for success logging!") kwargs = {} for k, v in self.model_call_details.items(): - if ( - k != "original_response" - ): # copy.deepcopy raises errors as this could be a coroutine + if k != "original_response": # copy.deepcopy raises errors as this could be a coroutine kwargs[k] = v # this only logs streaming once, complete_streaming_response exists i.e when stream ends @@ -2330,11 +2082,7 @@ def success_handler( input = kwargs.get("messages", kwargs.get("input", None)) - type = ( - "embed" - if self.call_type == CallTypes.embedding.value - else "llm" - ) + type = "embed" if self.call_type == CallTypes.embedding.value else "llm" # this only logs streaming once, complete_streaming_response exists i.e when stream ends if self.stream: @@ -2386,9 +2134,7 @@ def success_handler( print_verbose("reaches langfuse for success logging!") kwargs = {} for k, v in self.model_call_details.items(): - if ( - k != "original_response" - ): # copy.deepcopy raises errors as this could be a coroutine + if k != "original_response": # copy.deepcopy raises errors as this could be a coroutine kwargs[k] = v # this only logs streaming once, complete_streaming_response exists i.e when stream ends if self.stream: @@ -2425,9 +2171,7 @@ def success_handler( if callback == "greenscale" and greenscaleLogger is not None: kwargs = {} for k, v in self.model_call_details.items(): - if ( - k != "original_response" - ): # copy.deepcopy raises errors as this could be a coroutine + if k != "original_response": # copy.deepcopy raises errors as this could be a coroutine kwargs[k] = v # this only logs streaming once, complete_streaming_response exists i.e when stream ends if self.stream: @@ -2437,9 +2181,7 @@ def success_handler( if complete_streaming_response is None: continue else: - print_verbose( - "reaches greenscale for streaming logging!" - ) + print_verbose("reaches greenscale for streaming logging!") result = kwargs["complete_streaming_response"] greenscaleLogger.log_event( @@ -2479,22 +2221,16 @@ def success_handler( s3Logger = S3Logger() if self.stream: if "complete_streaming_response" in self.model_call_details: - print_verbose( - "S3Logger Logger: Got Stream Event - Completed Stream Response" - ) + print_verbose("S3Logger Logger: Got Stream Event - Completed Stream Response") s3Logger.log_event( kwargs=self.model_call_details, - response_obj=self.model_call_details[ - "complete_streaming_response" - ], + response_obj=self.model_call_details["complete_streaming_response"], start_time=start_time, end_time=end_time, print_verbose=print_verbose, ) else: - print_verbose( - "S3Logger Logger: Got Stream Event - No complete stream response as yet" - ) + print_verbose("S3Logger Logger: Got Stream Event - No complete stream response as yet") else: s3Logger.log_event( kwargs=self.model_call_details, @@ -2518,10 +2254,8 @@ def success_handler( ) else: if self.stream and complete_streaming_response: - self.model_call_details["complete_response"] = ( - self.model_call_details.get( - "complete_streaming_response", {} - ) + self.model_call_details["complete_response"] = self.model_call_details.get( + "complete_streaming_response", {} ) result = self.model_call_details["complete_response"] openMeterLogger.log_success_event( @@ -2545,10 +2279,8 @@ def success_handler( ) else: if self.stream and complete_streaming_response: - self.model_call_details["complete_response"] = ( - self.model_call_details.get( - "complete_streaming_response", {} - ) + self.model_call_details["complete_response"] = self.model_call_details.get( + "complete_streaming_response", {} ) result = self.model_call_details["complete_response"] @@ -2559,15 +2291,9 @@ def success_handler( end_time=end_time, ) if ( - callable(callback) is True - and is_sync_request - and customLogger is not None + callable(callback) is True and is_sync_request and customLogger is not None ): # custom logger functions - print_verbose( - "success callbacks: Running Custom Callback Function - {}".format( - callback - ) - ) + print_verbose("success callbacks: Running Custom Callback Function - {}".format(callback)) customLogger.log_event( kwargs=self.model_call_details, @@ -2582,9 +2308,7 @@ def success_handler( print_verbose( f"LiteLLM.LoggingError: [Non-Blocking] Exception occurred while success logging with integrations {traceback.format_exc()}" ) - print_verbose( - f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}" - ) + print_verbose(f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}") if capture_exception: # log this error to sentry for debugging capture_exception(e) # Track callback logging failures in Prometheus @@ -2594,31 +2318,21 @@ def success_handler( pass except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while success logging {}".format( - str(e) - ), + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while success logging {}".format(str(e)), ) - async def async_success_handler( - self, result=None, start_time=None, end_time=None, cache_hit=None, **kwargs - ): + async def async_success_handler(self, result=None, start_time=None, end_time=None, cache_hit=None, **kwargs): """ Implementing async callbacks, to handle asyncio event loop issues when custom integrations need to use async functions. """ - print_verbose( - "Logging Details LiteLLM-Async Success Call, cache_hit={}".format(cache_hit) - ) - if not self._is_assembled_stream_success( - result - ) and not self.should_run_logging( + print_verbose("Logging Details LiteLLM-Async Success Call, cache_hit={}".format(cache_hit)) + if not self._is_assembled_stream_success(result) and not self.should_run_logging( event_type="async_success" ): # prevent double logging (non-streaming) return ## CALCULATE COST FOR BATCH JOBS - if self.call_type == CallTypes.aretrieve_batch.value and isinstance( - result, LiteLLMBatch - ): + if self.call_type == CallTypes.aretrieve_batch.value and isinstance(result, LiteLLMBatch): litellm_params = self.litellm_params or {} litellm_metadata = litellm_params.get("litellm_metadata") or {} if ( @@ -2636,14 +2350,10 @@ async def async_success_handler( batch_cost = kwargs.get("batch_cost", None) batch_usage = kwargs.get("batch_usage", None) batch_models = kwargs.get("batch_models", None) - has_explicit_batch_data = all( - x is not None for x in (batch_cost, batch_usage, batch_models) - ) + has_explicit_batch_data = all(x is not None for x in (batch_cost, batch_usage, batch_models)) should_compute_batch_data = ( - not is_base64_unified_file_id - or not has_explicit_batch_data - and result.status == "completed" + not is_base64_unified_file_id or not has_explicit_batch_data and result.status == "completed" ) if has_explicit_batch_data: result._hidden_params["response_cost"] = batch_cost @@ -2676,69 +2386,51 @@ async def async_success_handler( ## BUILD COMPLETE STREAMED RESPONSE if "async_complete_streaming_response" in self.model_call_details: return # break out of this. - complete_streaming_response: Optional[ - Union[ModelResponse, TextCompletionResponse, ResponsesAPIResponse] - ] = self._get_assembled_streaming_response( - result=result, - start_time=start_time, - end_time=end_time, - is_async=True, - streaming_chunks=self.streaming_chunks, + complete_streaming_response: Optional[Union[ModelResponse, TextCompletionResponse, ResponsesAPIResponse]] = ( + self._get_assembled_streaming_response( + result=result, + start_time=start_time, + end_time=end_time, + is_async=True, + streaming_chunks=self.streaming_chunks, + ) ) if complete_streaming_response is not None: print_verbose("Async success callbacks: Got a complete streaming response") - self.model_call_details["async_complete_streaming_response"] = ( - complete_streaming_response - ) + self.model_call_details["async_complete_streaming_response"] = complete_streaming_response try: if self.model_call_details.get("cache_hit", False) is True: self.model_call_details["response_cost"] = 0.0 else: # check if base_model set on azure - _get_base_model_from_metadata( - model_call_details=self.model_call_details - ) + _get_base_model_from_metadata(model_call_details=self.model_call_details) # base_model defaults to None if not set on model_info - self.model_call_details["response_cost"] = ( - self._response_cost_calculator( - result=complete_streaming_response - ) + self.model_call_details["response_cost"] = self._response_cost_calculator( + result=complete_streaming_response ) - verbose_logger.debug( - f"Model={self.model}; cost={self.model_call_details['response_cost']}" - ) + verbose_logger.debug(f"Model={self.model}; cost={self.model_call_details['response_cost']}") except litellm.NotFoundError: verbose_logger.warning( f"Model={self.model} not found in completion cost map. Setting 'response_cost' to None" ) self.model_call_details["response_cost"] = None - self._merge_hidden_params_from_response_into_metadata( - complete_streaming_response - ) + self._merge_hidden_params_from_response_into_metadata(complete_streaming_response) ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload( - complete_streaming_response, start_time, end_time - ) + self.model_call_details["standard_logging_object"] = self._build_standard_logging_payload( + complete_streaming_response, start_time, end_time ) # print standard logging payload - if ( - standard_logging_payload := self.model_call_details.get( - "standard_logging_object" - ) - ) is not None: + if (standard_logging_payload := self.model_call_details.get("standard_logging_object")) is not None: emit_standard_logging_payload(standard_logging_payload) elif self.call_type == "pass_through_endpoint": - print_verbose( - "Async success callbacks: Got a pass-through endpoint response" - ) + print_verbose("Async success callbacks: Got a pass-through endpoint response") self.model_call_details["async_complete_streaming_response"] = result @@ -2752,16 +2444,12 @@ async def async_success_handler( # _success_handler_helper_fn if self.model_call_details.get("standard_logging_object") is None: ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - self._build_standard_logging_payload(result, start_time, end_time) + self.model_call_details["standard_logging_object"] = self._build_standard_logging_payload( + result, start_time, end_time ) # print standard logging payload - if ( - standard_logging_payload := self.model_call_details.get( - "standard_logging_object" - ) - ) is not None: + if (standard_logging_payload := self.model_call_details.get("standard_logging_object")) is not None: emit_standard_logging_payload(standard_logging_payload) callbacks = self.get_combined_callback_list( dynamic_success_callbacks=self.dynamic_async_success_callbacks, @@ -2769,9 +2457,7 @@ async def async_success_handler( ) result = redact_message_input_output_from_logging( - model_call_details=( - self.model_call_details if hasattr(self, "model_call_details") else {} - ), + model_call_details=(self.model_call_details if hasattr(self, "model_call_details") else {}), result=result, ) @@ -2820,15 +2506,10 @@ async def async_success_handler( try: if callback == "openmeter" and openMeterLogger is not None: if self.stream is True: - if ( - "async_complete_streaming_response" - in self.model_call_details - ): + if "async_complete_streaming_response" in self.model_call_details: await openMeterLogger.async_log_success_event( kwargs=self.model_call_details, - response_obj=self.model_call_details[ - "async_complete_streaming_response" - ], + response_obj=self.model_call_details["async_complete_streaming_response"], start_time=start_time, end_time=end_time, ) @@ -2859,9 +2540,7 @@ async def async_success_handler( if "async_complete_streaming_response" in model_call_details: await callback.async_log_success_event( kwargs=model_call_details, - response_obj=model_call_details[ - "async_complete_streaming_response" - ], + response_obj=model_call_details["async_complete_streaming_response"], start_time=start_time, end_time=end_time, ) @@ -2884,15 +2563,10 @@ async def async_success_handler( if customLogger is None: customLogger = CustomLogger() if self.stream: - if ( - "async_complete_streaming_response" - in self.model_call_details - ): + if "async_complete_streaming_response" in self.model_call_details: await customLogger.async_log_event( kwargs=self.model_call_details, - response_obj=self.model_call_details[ - "async_complete_streaming_response" - ], + response_obj=self.model_call_details["async_complete_streaming_response"], start_time=start_time, end_time=end_time, print_verbose=print_verbose, @@ -2912,26 +2586,17 @@ async def async_success_handler( if dynamoLogger is None: dynamoLogger = DyanmoDBLogger() if self.stream: - if ( - "async_complete_streaming_response" - in self.model_call_details - ): - print_verbose( - "DynamoDB Logger: Got Stream Event - Completed Stream Response" - ) + if "async_complete_streaming_response" in self.model_call_details: + print_verbose("DynamoDB Logger: Got Stream Event - Completed Stream Response") await dynamoLogger._async_log_event( kwargs=self.model_call_details, - response_obj=self.model_call_details[ - "async_complete_streaming_response" - ], + response_obj=self.model_call_details["async_complete_streaming_response"], start_time=start_time, end_time=end_time, print_verbose=print_verbose, ) else: - print_verbose( - "DynamoDB Logger: Got Stream Event - No complete stream response as yet" - ) + print_verbose("DynamoDB Logger: Got Stream Event - No complete stream response as yet") else: await dynamoLogger._async_log_event( kwargs=self.model_call_details, @@ -2963,17 +2628,13 @@ def _handle_callback_failure(self, callback: Any): for callback_obj in all_callbacks: if hasattr(callback_obj, "increment_callback_logging_failure"): - callback_obj.increment_callback_logging_failure( - callback_name=callback_name - ) # type: ignore + callback_obj.increment_callback_logging_failure(callback_name=callback_name) # type: ignore break # Only increment once except Exception as e: verbose_logger.debug(f"Error in _handle_callback_failure: {str(e)}") - def _failure_handler_helper_fn( - self, exception, traceback_exception, start_time=None, end_time=None - ): + def _failure_handler_helper_fn(self, exception, traceback_exception, start_time=None, end_time=None): if start_time is None: start_time = self.start_time if end_time is None: @@ -2986,9 +2647,7 @@ def _failure_handler_helper_fn( self.model_call_details["log_event_type"] = "failed_api_call" self.model_call_details["exception"] = exception self.model_call_details["traceback_exception"] = ( - _redact_string(traceback_exception) - if isinstance(traceback_exception, str) - else traceback_exception + _redact_string(traceback_exception) if isinstance(traceback_exception, str) else traceback_exception ) self.model_call_details["end_time"] = end_time self.model_call_details.setdefault("original_response", None) @@ -3001,25 +2660,21 @@ def _failure_handler_helper_fn( if hasattr(exception, "headers") and isinstance(exception.headers, dict): self.model_call_details.setdefault("litellm_params", {}) - metadata = ( - self.model_call_details["litellm_params"].get("metadata", {}) or {} - ) + metadata = self.model_call_details["litellm_params"].get("metadata", {}) or {} metadata.update(exception.headers) ## STANDARDIZED LOGGING PAYLOAD - self.model_call_details["standard_logging_object"] = ( - get_standard_logging_object_payload( - kwargs=self.model_call_details, - init_response_obj={}, - start_time=start_time, - end_time=end_time, - logging_obj=self, - status="failure", - error_str=_redact_string(str(exception)), - original_exception=exception, - standard_built_in_tools_params=self.standard_built_in_tools_params, - ) + self.model_call_details["standard_logging_object"] = get_standard_logging_object_payload( + kwargs=self.model_call_details, + init_response_obj={}, + start_time=start_time, + end_time=end_time, + logging_obj=self, + status="failure", + error_str=_redact_string(str(exception)), + original_exception=exception, + standard_built_in_tools_params=self.standard_built_in_tools_params, ) return start_time, end_time @@ -3041,10 +2696,7 @@ async def special_failure_handlers(self, exception: Exception): if isinstance(model_group_size, int) and model_group_size == 1: is_base_case = True ## check if special error ## - if ( - RouterErrors.no_deployments_available.value not in str(exception) - and is_base_case is False - ): + if RouterErrors.no_deployments_available.value not in str(exception) and is_base_case is False: return ## get original model group ## @@ -3058,15 +2710,9 @@ async def special_failure_handlers(self, exception: Exception): kwargs=self.model_call_details, ) # type: ignore - def failure_handler( - self, exception, traceback_exception, start_time=None, end_time=None - ): - verbose_logger.debug( - f"Logging Details LiteLLM-Failure Call: {litellm.failure_callback}" - ) - if not self.should_run_logging( - event_type="sync_failure" - ): # prevent double logging + def failure_handler(self, exception, traceback_exception, start_time=None, end_time=None): + verbose_logger.debug(f"Logging Details LiteLLM-Failure Call: {litellm.failure_callback}") + if not self.should_run_logging(event_type="sync_failure"): # prevent double logging return litellm_params = self.model_call_details.get("litellm_params", {}) is_sync_request = self._is_sync_litellm_request(litellm_params) @@ -3086,11 +2732,7 @@ def failure_handler( result = None # result sent to all loggers, init this to None incase it's not created result = redact_message_input_output_from_logging( - model_call_details=( - self.model_call_details - if hasattr(self, "model_call_details") - else {} - ), + model_call_details=(self.model_call_details if hasattr(self, "model_call_details") else {}), result=result, ) self.has_run_logging(event_type="sync_failure") @@ -3110,11 +2752,7 @@ def failure_handler( input = self.model_call_details["input"] - _type = ( - "embed" - if self.call_type == CallTypes.embedding.value - else "llm" - ) + _type = "embed" if self.call_type == CallTypes.embedding.value else "llm" lunaryLogger.log_event( kwargs=self.model_call_details, @@ -3134,9 +2772,7 @@ def failure_handler( if capture_exception: capture_exception(exception) else: - print_verbose( - f"capture exception not initialized: {capture_exception}" - ) + print_verbose(f"capture exception not initialized: {capture_exception}") elif callback == "supabase" and supabaseClient is not None: print_verbose("reaches supabase for logging!") print_verbose(f"supabaseClient: {supabaseClient}") @@ -3178,9 +2814,7 @@ def failure_handler( verbose_logger.debug("reaches langfuse for logging failure") kwargs = {} for k, v in self.model_call_details.items(): - if ( - k != "original_response" - ): # copy.deepcopy raises errors as this could be a coroutine + if k != "original_response": # copy.deepcopy raises errors as this could be a coroutine kwargs[k] = v # this only logs streaming once, complete_streaming_response exists i.e when stream ends langfuse_logger_to_use = LangFuseHandler.get_langfuse_logger_for_request( @@ -3220,9 +2854,7 @@ def failure_handler( verbose_logger.debug("reaches logfire for failure logging!") kwargs = {} for k, v in self.model_call_details.items(): - if ( - k != "original_response" - ): # copy.deepcopy raises errors as this could be a coroutine + if k != "original_response": # copy.deepcopy raises errors as this could be a coroutine kwargs[k] = v kwargs["exception"] = exception @@ -3239,28 +2871,20 @@ def failure_handler( print_verbose( f"LiteLLM.LoggingError: [Non-Blocking] Exception occurred while failure logging with integrations {str(e)}" ) - print_verbose( - f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}" - ) + print_verbose(f"LiteLLM.Logging: is sentry capture exception initialized {capture_exception}") if capture_exception: # log this error to sentry for debugging capture_exception(e) except Exception as e: verbose_logger.exception( - "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while failure logging {}".format( - str(e) - ) + "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while failure logging {}".format(str(e)) ) - async def async_failure_handler( - self, exception, traceback_exception, start_time=None, end_time=None - ): + async def async_failure_handler(self, exception, traceback_exception, start_time=None, end_time=None): """ Implementing async callbacks, to handle asyncio event loop issues when custom integrations need to use async functions. """ await self.special_failure_handlers(exception=exception) - if not self.should_run_logging( - event_type="async_failure" - ): # prevent double logging + if not self.should_run_logging(event_type="async_failure"): # prevent double logging return start_time, end_time = self._failure_handler_helper_fn( exception=exception, @@ -3343,39 +2967,24 @@ def _get_callback_object(self, service_name: Literal["langfuse"]) -> Optional[An if service_name == "langfuse": if langFuseLogger is None or ( ( - self.standard_callback_dynamic_params.get("langfuse_public_key") - is not None - and self.standard_callback_dynamic_params.get("langfuse_public_key") - != langFuseLogger.public_key + self.standard_callback_dynamic_params.get("langfuse_public_key") is not None + and self.standard_callback_dynamic_params.get("langfuse_public_key") != langFuseLogger.public_key ) or ( - self.standard_callback_dynamic_params.get("langfuse_public_key") - is not None - and self.standard_callback_dynamic_params.get("langfuse_public_key") - != langFuseLogger.public_key + self.standard_callback_dynamic_params.get("langfuse_public_key") is not None + and self.standard_callback_dynamic_params.get("langfuse_public_key") != langFuseLogger.public_key ) or ( - self.standard_callback_dynamic_params.get("langfuse_host") - is not None - and self.standard_callback_dynamic_params.get("langfuse_host") - != langFuseLogger.langfuse_host + self.standard_callback_dynamic_params.get("langfuse_host") is not None + and self.standard_callback_dynamic_params.get("langfuse_host") != langFuseLogger.langfuse_host ) ): return LangFuseLogger( - langfuse_public_key=self.standard_callback_dynamic_params.get( - "langfuse_public_key" - ), - langfuse_secret=self.standard_callback_dynamic_params.get( - "langfuse_secret" - ) + langfuse_public_key=self.standard_callback_dynamic_params.get("langfuse_public_key"), + langfuse_secret=self.standard_callback_dynamic_params.get("langfuse_secret") or self.standard_callback_dynamic_params.get("langfuse_secret_key"), - langfuse_host=self.standard_callback_dynamic_params.get( - "langfuse_host" - ), - allow_env_credentials=self.standard_callback_dynamic_params.get( - "langfuse_host" - ) - is None, + langfuse_host=self.standard_callback_dynamic_params.get("langfuse_host"), + allow_env_credentials=self.standard_callback_dynamic_params.get("langfuse_host") is None, ) return langFuseLogger @@ -3413,17 +3022,11 @@ def _should_run_sync_callbacks_for_async_calls(self) -> bool: dynamic_success_callbacks=self.dynamic_success_callbacks, global_callbacks=litellm.success_callback, ) - _filtered_success_callbacks = self._remove_internal_custom_logger_callbacks( - _combined_sync_callbacks - ) - _filtered_success_callbacks = self._remove_internal_litellm_callbacks( - _filtered_success_callbacks - ) + _filtered_success_callbacks = self._remove_internal_custom_logger_callbacks(_combined_sync_callbacks) + _filtered_success_callbacks = self._remove_internal_litellm_callbacks(_filtered_success_callbacks) return len(_filtered_success_callbacks) > 0 - def get_combined_callback_list( - self, dynamic_success_callbacks: Optional[List], global_callbacks: List - ) -> List: + def get_combined_callback_list(self, dynamic_success_callbacks: Optional[List], global_callbacks: List) -> List: if dynamic_success_callbacks is None: return list(global_callbacks) return list(set(dynamic_success_callbacks + global_callbacks)) @@ -3438,9 +3041,7 @@ def _remove_internal_litellm_callbacks(self, callbacks: List) -> List: Returns: List of filtered callbacks with internal ones removed """ - filtered = [ - cb for cb in callbacks if not self._is_internal_litellm_proxy_callback(cb) - ] + filtered = [cb for cb in callbacks if not self._is_internal_litellm_proxy_callback(cb)] verbose_logger.debug(f"Filtered callbacks: {filtered}") return filtered @@ -3489,10 +3090,7 @@ def _remove_internal_custom_logger_callbacks(self, callbacks: List) -> List: for _c in callbacks: if isinstance(_c, CustomLogger): continue - elif ( - isinstance(_c, str) - and _c in litellm._known_custom_logger_compatible_callbacks - ): + elif isinstance(_c, str) and _c in litellm._known_custom_logger_compatible_callbacks: continue _new_callbacks.append(_c) return _new_callbacks @@ -3523,10 +3121,8 @@ def _get_assembled_streaming_response( ): ## return unified Usage object if isinstance(result.response.usage, ResponseAPIUsage): - transformed_usage = ( - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - result.response.usage - ) + transformed_usage = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( + result.response.usage ) # Set as dict instead of Usage object so model_dump() serializes it correctly setattr( @@ -3602,9 +3198,7 @@ def _handle_anthropic_messages_response_logging(self, result: Any) -> ModelRespo ) return result - def _translate_responses_api_response_to_model_response( - self, result: ResponsesAPIResponse - ) -> ModelResponse: + def _translate_responses_api_response_to_model_response(self, result: ResponsesAPIResponse) -> ModelResponse: """ Convert a Responses API response into a ModelResponse for spend_logs. @@ -3639,21 +3233,15 @@ def _translate_responses_api_response_to_model_response( model_response = litellm.ModelResponse() model_response.model = self.model usage = getattr(result, "usage", None) - if usage is not None and ResponseAPILoggingUtils._is_response_api_usage( - usage - ): + if usage is not None and ResponseAPILoggingUtils._is_response_api_usage(usage): setattr( model_response, "usage", - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - usage - ), + ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage), ) return model_response - def _handle_non_streaming_google_genai_generate_content_response_logging( - self, result: Any - ) -> ModelResponse: + def _handle_non_streaming_google_genai_generate_content_response_logging(self, result: Any) -> ModelResponse: """ Handles logging for Google GenAI generate content responses. """ @@ -3695,9 +3283,7 @@ def _handle_a2a_response_logging(self, result: Any) -> Any: # Deep copy result and add usage result_copy = result.model_copy(deep=True) - result_copy.usage = ( - usage.model_dump() if hasattr(usage, "model_dump") else dict(usage) - ) + result_copy.usage = usage.model_dump() if hasattr(usage, "model_dump") else dict(usage) return result_copy @@ -3748,25 +3334,14 @@ def _mask_value(v: Any) -> Any: if len(v) <= unmasked_length: return "*****" if number_of_asterisks is not None: - return ( - v[: unmasked_length // 2] - + "*" * number_of_asterisks - + v[-unmasked_length // 2 :] - ) - return ( - v[: unmasked_length // 2] - + "*" * (len(v) - unmasked_length) - + v[-unmasked_length // 2 :] - ) + return v[: unmasked_length // 2] + "*" * number_of_asterisks + v[-unmasked_length // 2 :] + return v[: unmasked_length // 2] + "*" * (len(v) - unmasked_length) + v[-unmasked_length // 2 :] return { k: ( v if ignore_sensitive_values - or not any( - sensitive_keyword in k.lower() - for sensitive_keyword in sensitive_keywords - ) + or not any(sensitive_keyword in k.lower() for sensitive_keyword in sensitive_keywords) else _mask_value(v) ) for k, v in sensitive_object.items() @@ -3808,33 +3383,23 @@ def set_callbacks(callback_list, function_id=None): import sentry_sdk except ImportError: print_verbose("Package 'sentry_sdk' is missing. Installing it...") - subprocess.check_call( - [sys.executable, "-m", "pip", "install", "sentry_sdk"] - ) + subprocess.check_call([sys.executable, "-m", "pip", "install", "sentry_sdk"]) import sentry_sdk from sentry_sdk.scrubber import EventScrubber sentry_sdk_instance = sentry_sdk sentry_trace_rate = ( - os.environ.get("SENTRY_API_TRACE_RATE") - if "SENTRY_API_TRACE_RATE" in os.environ - else "1.0" + os.environ.get("SENTRY_API_TRACE_RATE") if "SENTRY_API_TRACE_RATE" in os.environ else "1.0" ) sentry_sample_rate = ( - os.environ.get("SENTRY_API_SAMPLE_RATE") - if "SENTRY_API_SAMPLE_RATE" in os.environ - else "1.0" + os.environ.get("SENTRY_API_SAMPLE_RATE") if "SENTRY_API_SAMPLE_RATE" in os.environ else "1.0" ) sentry_sdk_instance.init( dsn=os.environ.get("SENTRY_DSN"), traces_sample_rate=float(sentry_trace_rate), # type: ignore - sample_rate=float( - sentry_sample_rate if sentry_sample_rate else 1.0 - ), + sample_rate=float(sentry_sample_rate if sentry_sample_rate else 1.0), send_default_pii=False, # Prevent sending Personal Identifiable Information - event_scrubber=EventScrubber( - denylist=SENTRY_DENYLIST, pii_denylist=SENTRY_PII_DENYLIST - ), + event_scrubber=EventScrubber(denylist=SENTRY_DENYLIST, pii_denylist=SENTRY_PII_DENYLIST), environment=os.environ.get("SENTRY_ENVIRONMENT", "production"), ) capture_exception = sentry_sdk_instance.capture_exception @@ -3844,9 +3409,7 @@ def set_callbacks(callback_list, function_id=None): from slack_bolt import App except ImportError: print_verbose("Package 'slack_bolt' is missing. Installing it...") - subprocess.check_call( - [sys.executable, "-m", "pip", "install", "slack_bolt"] - ) + subprocess.check_call([sys.executable, "-m", "pip", "install", "slack_bolt"]) from slack_bolt import App slack_app = App( token=os.environ.get("SLACK_API_TOKEN"), @@ -3866,9 +3429,7 @@ def set_callbacks(callback_list, function_id=None): elif callback == "promptlayer": promptLayerLogger = PromptLayerLogger() elif callback == "langfuse": - langFuseLogger = LangFuseLogger( - langfuse_public_key=None, langfuse_secret=None, langfuse_host=None - ) + langFuseLogger = LangFuseLogger(langfuse_public_key=None, langfuse_secret=None, langfuse_host=None) elif callback == "openmeter": openMeterLogger = OpenMeterLogger() elif callback == "datadog": @@ -3899,9 +3460,7 @@ def set_callbacks(callback_list, function_id=None): def _init_custom_logger_compatible_class( logging_integration: _custom_logger_compatible_callbacks_literal, internal_usage_cache: Optional[DualCache], - llm_router: Optional[ - Any - ], # expect litellm.Router, but typing errors due to circular import + llm_router: Optional[Any], # expect litellm.Router, but typing errors due to circular import custom_logger_init_args: Optional[dict] = {}, ) -> Optional[CustomLogger]: """ @@ -4106,10 +3665,7 @@ def _init_custom_logger_compatible_class( f"space_id={arize_config.space_key or arize_config.space_id},api_key={arize_config.api_key}" ) for callback in _in_memory_loggers: - if ( - isinstance(callback, ArizeLogger) - and callback.callback_name == "arize" - ): + if isinstance(callback, ArizeLogger) and callback.callback_name == "arize": return callback # type: ignore _arize_otel_logger = ArizeLogger(config=otel_config, callback_name="arize") _in_memory_loggers.append(_arize_otel_logger) @@ -4132,19 +3688,12 @@ def _init_custom_logger_compatible_class( # auth can be disabled on local deployments of arize phoenix if arize_phoenix_config.otlp_auth_headers is not None: - os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = ( - arize_phoenix_config.otlp_auth_headers - ) + os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = arize_phoenix_config.otlp_auth_headers for callback in _in_memory_loggers: - if ( - isinstance(callback, ArizePhoenixLogger) - and callback.callback_name == "arize_phoenix" - ): + if isinstance(callback, ArizePhoenixLogger) and callback.callback_name == "arize_phoenix": return callback # type: ignore - _arize_phoenix_otel_logger = ArizePhoenixLogger( - config=otel_config, callback_name="arize_phoenix" - ) + _arize_phoenix_otel_logger = ArizePhoenixLogger(config=otel_config, callback_name="arize_phoenix") _in_memory_loggers.append(_arize_phoenix_otel_logger) return _arize_phoenix_otel_logger # type: ignore elif logging_integration == "levo": @@ -4166,10 +3715,7 @@ def _init_custom_logger_compatible_class( # Check if LevoLogger instance already exists for callback in _in_memory_loggers: - if ( - isinstance(callback, LevoLogger) - and callback.callback_name == "levo" - ): + if isinstance(callback, LevoLogger) and callback.callback_name == "levo": return callback # type: ignore _levo_otel_logger = LevoLogger(config=otel_config, callback_name="levo") @@ -4190,9 +3736,7 @@ def _init_custom_logger_compatible_class( if type(callback) is OpenTelemetryV2: return callback # type: ignore otel_logger_v2 = OpenTelemetryV2( - **_get_custom_logger_settings_from_proxy_server( - callback_name=logging_integration - ) + **_get_custom_logger_settings_from_proxy_server(callback_name=logging_integration) ) _in_memory_loggers.append(otel_logger_v2) _maybe_auto_initialize_arize_phoenix(_in_memory_loggers) @@ -4204,9 +3748,7 @@ def _init_custom_logger_compatible_class( if type(callback) is OpenTelemetry: return callback # type: ignore otel_logger = OpenTelemetry( - **_get_custom_logger_settings_from_proxy_server( - callback_name=logging_integration - ) + **_get_custom_logger_settings_from_proxy_server(callback_name=logging_integration) ) _in_memory_loggers.append(otel_logger) @@ -4238,9 +3780,7 @@ def _init_custom_logger_compatible_class( from litellm.integrations.focus.focus_logger import FocusLogger for callback in _in_memory_loggers: - if ( - type(callback) is FocusLogger - ): # exact match; exclude subclasses like VantageLogger + if type(callback) is FocusLogger: # exact match; exclude subclasses like VantageLogger return callback # type: ignore focus_logger = FocusLogger() _in_memory_loggers.append(focus_logger) @@ -4281,9 +3821,7 @@ def _init_custom_logger_compatible_class( OpenTelemetryConfig, ) - logfire_base_url = os.getenv( - "LOGFIRE_BASE_URL", "https://logfire-api.pydantic.dev" - ) + logfire_base_url = os.getenv("LOGFIRE_BASE_URL", "https://logfire-api.pydantic.dev") otel_config = OpenTelemetryConfig( exporter="otlp_http", endpoint=f"{logfire_base_url.rstrip('/')}/v1/traces", @@ -4307,14 +3845,10 @@ def _init_custom_logger_compatible_class( if internal_usage_cache is None: raise Exception( - "Internal Error: Cache cannot be empty - internal_usage_cache={}".format( - internal_usage_cache - ) + "Internal Error: Cache cannot be empty - internal_usage_cache={}".format(internal_usage_cache) ) - dynamic_rate_limiter_obj = _PROXY_DynamicRateLimitHandler( - internal_usage_cache=internal_usage_cache - ) + dynamic_rate_limiter_obj = _PROXY_DynamicRateLimitHandler(internal_usage_cache=internal_usage_cache) if llm_router is not None and isinstance(llm_router, litellm.Router): dynamic_rate_limiter_obj.update_variables(llm_router=llm_router) @@ -4331,14 +3865,10 @@ def _init_custom_logger_compatible_class( if internal_usage_cache is None: raise Exception( - "Internal Error: Cache cannot be empty - internal_usage_cache={}".format( - internal_usage_cache - ) + "Internal Error: Cache cannot be empty - internal_usage_cache={}".format(internal_usage_cache) ) - dynamic_rate_limiter_obj_v3 = _PROXY_DynamicRateLimitHandlerV3( - internal_usage_cache=internal_usage_cache - ) + dynamic_rate_limiter_obj_v3 = _PROXY_DynamicRateLimitHandlerV3(internal_usage_cache=internal_usage_cache) if llm_router is not None and isinstance(llm_router, litellm.Router): dynamic_rate_limiter_obj_v3.update_variables(llm_router=llm_router) @@ -4360,14 +3890,9 @@ def _init_custom_logger_compatible_class( exporter="otlp_http", endpoint="https://langtrace.ai/api/trace", ) - os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = ( - f"api_key={os.getenv('LANGTRACE_API_KEY')}" - ) + os.environ["OTEL_EXPORTER_OTLP_TRACES_HEADERS"] = f"api_key={os.getenv('LANGTRACE_API_KEY')}" for callback in _in_memory_loggers: - if ( - isinstance(callback, OpenTelemetry) - and callback.callback_name == "langtrace" - ): + if isinstance(callback, OpenTelemetry) and callback.callback_name == "langtrace": return callback # type: ignore _otel_logger = OpenTelemetry(config=otel_config, callback_name="langtrace") _in_memory_loggers.append(_otel_logger) @@ -4396,16 +3921,11 @@ def _init_custom_logger_compatible_class( from litellm.integrations.langfuse.langfuse_otel import LangfuseOtelLogger for callback in _in_memory_loggers: - if ( - isinstance(callback, LangfuseOtelLogger) - and callback.callback_name == "langfuse_otel" - ): + if isinstance(callback, LangfuseOtelLogger) and callback.callback_name == "langfuse_otel": return callback # type: ignore # Allow LangfuseOtelLogger to initialize its own config safely # This prevents startup crashes if LANGFUSE keys are not in env (e.g. for dynamic usage) - _otel_logger = LangfuseOtelLogger( - config=None, callback_name="langfuse_otel" - ) + _otel_logger = LangfuseOtelLogger(config=None, callback_name="langfuse_otel") _in_memory_loggers.append(_otel_logger) return _otel_logger # type: ignore elif logging_integration == "weave_otel": @@ -4427,14 +3947,9 @@ def _init_custom_logger_compatible_class( ) for callback in _in_memory_loggers: - if ( - isinstance(callback, WeaveOtelLogger) - and callback.callback_name == "weave_otel" - ): + if isinstance(callback, WeaveOtelLogger) and callback.callback_name == "weave_otel": return callback # type: ignore - _otel_logger = WeaveOtelLogger( - config=otel_config, callback_name="weave_otel" - ) + _otel_logger = WeaveOtelLogger(config=otel_config, callback_name="weave_otel") _in_memory_loggers.append(_otel_logger) return _otel_logger # type: ignore elif logging_integration == "pagerduty": @@ -4525,9 +4040,7 @@ def _init_custom_logger_compatible_class( # Get global BitBucket config bitbucket_config = getattr(litellm, "global_bitbucket_config", None) if bitbucket_config is None: - raise ValueError( - "BitBucket configuration not found. Please set litellm.global_bitbucket_config first." - ) + raise ValueError("BitBucket configuration not found. Please set litellm.global_bitbucket_config first.") bitbucket_logger = BitBucketPromptManager(bitbucket_config=bitbucket_config) _in_memory_loggers.append(bitbucket_logger) @@ -4544,9 +4057,7 @@ def _init_custom_logger_compatible_class( # Get global BitBucket config gitlab_config = getattr(litellm, "global_gitlab_config", None) if gitlab_config is None: - raise ValueError( - "Gitlab configuration not found. Please set litellm.global_gitlab_config first." - ) + raise ValueError("Gitlab configuration not found. Please set litellm.global_gitlab_config first.") gitlab_logger = GitLabPromptManager(gitlab_config=gitlab_config) _in_memory_loggers.append(gitlab_logger) @@ -4560,16 +4071,12 @@ def _init_custom_logger_compatible_class( return newrelic_logger # type: ignore return None except Exception as e: - verbose_logger.exception( - f"[Non-Blocking Error] Error initializing custom logger: {e}" - ) + verbose_logger.exception(f"[Non-Blocking Error] Error initializing custom logger: {e}") return None return None -def _maybe_construct_otel_v2( - callback_name: str, _in_memory_loggers: list -) -> Optional[Any]: +def _maybe_construct_otel_v2(callback_name: str, _in_memory_loggers: list) -> Optional[Any]: """If ``LITELLM_OTEL_V2`` is on, build (or reuse) a single ``OpenTelemetryV2`` instance configured via the preset for ``callback_name``. @@ -4587,10 +4094,7 @@ def _maybe_construct_otel_v2( if preset_fn is None: return None for callback in _in_memory_loggers: - if ( - isinstance(callback, OpenTelemetryV2) - and getattr(callback, "callback_name", None) == callback_name - ): + if isinstance(callback, OpenTelemetryV2) and getattr(callback, "callback_name", None) == callback_name: return callback try: config = preset_fn() @@ -4620,10 +4124,7 @@ def _maybe_auto_initialize_arize_phoenix(_in_memory_loggers: list) -> None: return # Already registered — nothing to do - if any( - isinstance(cb, ArizePhoenixLogger) and cb.callback_name == "arize_phoenix" - for cb in _in_memory_loggers - ): + if any(isinstance(cb, ArizePhoenixLogger) and cb.callback_name == "arize_phoenix" for cb in _in_memory_loggers): return try: @@ -4635,9 +4136,7 @@ def _maybe_auto_initialize_arize_phoenix(_in_memory_loggers: list) -> None: endpoint=arize_phoenix_config.endpoint, headers=arize_phoenix_config.otlp_auth_headers, ) - phoenix_logger = ArizePhoenixLogger( - config=otel_config, callback_name="arize_phoenix" - ) + phoenix_logger = ArizePhoenixLogger(config=otel_config, callback_name="arize_phoenix") _in_memory_loggers.append(phoenix_logger) # Register as a litellm callback so it receives success/failure events @@ -4648,9 +4147,7 @@ def _maybe_auto_initialize_arize_phoenix(_in_memory_loggers: list) -> None: arize_phoenix_config.endpoint, ) except Exception as e: - verbose_logger.warning( - "Failed to auto-initialize Arize Phoenix logger: %s", str(e) - ) + verbose_logger.warning("Failed to auto-initialize Arize Phoenix logger: %s", str(e)) def get_custom_logger_compatible_class( @@ -4685,9 +4182,7 @@ def get_custom_logger_compatible_class( from litellm.integrations.focus.focus_logger import FocusLogger for callback in _in_memory_loggers: - if ( - type(callback) is FocusLogger - ): # exact match; exclude subclasses like VantageLogger + if type(callback) is FocusLogger: # exact match; exclude subclasses like VantageLogger return callback elif logging_integration == "vantage": from litellm.integrations.vantage.vantage_logger import VantageLogger @@ -4774,10 +4269,7 @@ def get_custom_logger_compatible_class( if "ARIZE_API_KEY" not in os.environ: raise ValueError("ARIZE_API_KEY not found in environment variables") for callback in _in_memory_loggers: - if ( - isinstance(callback, ArizeLogger) - and callback.callback_name == "arize" - ): + if isinstance(callback, ArizeLogger) and callback.callback_name == "arize": return callback elif logging_integration == "logfire": if "LOGFIRE_TOKEN" not in os.environ: @@ -4813,10 +4305,7 @@ def get_custom_logger_compatible_class( raise ValueError("LANGTRACE_API_KEY not found in environment variables") for callback in _in_memory_loggers: - if ( - isinstance(callback, OpenTelemetry) - and callback.callback_name == "langtrace" - ): + if isinstance(callback, OpenTelemetry) and callback.callback_name == "langtrace": return callback elif logging_integration == "mlflow": @@ -4866,9 +4355,7 @@ def get_custom_logger_compatible_class( return None except Exception as e: - verbose_logger.exception( - f"[Non-Blocking Error] Error getting custom logger: {e}" - ) + verbose_logger.exception(f"[Non-Blocking Error] Error getting custom logger: {e}") return None @@ -4946,18 +4433,14 @@ def cleanup_timestamps( elif isinstance(start_time, float): start_time_float = start_time else: - raise ValueError( - f"start_time is required, got={start_time} of type {type(start_time)}" - ) + raise ValueError(f"start_time is required, got={start_time} of type {type(start_time)}") if isinstance(end_time, datetime.datetime): end_time_float = end_time.timestamp() elif isinstance(end_time, float): end_time_float = end_time else: - raise ValueError( - f"end_time is required, got={end_time} of type {type(end_time)}" - ) + raise ValueError(f"end_time is required, got={end_time} of type {type(end_time)}") if isinstance(completion_start_time, datetime.datetime): completion_start_time_float = completion_start_time.timestamp() @@ -4969,29 +4452,21 @@ def cleanup_timestamps( return start_time_float, end_time_float, completion_start_time_float @staticmethod - def append_system_prompt_messages( - kwargs: Optional[Dict] = None, messages: Optional[Any] = None - ): + def append_system_prompt_messages(kwargs: Optional[Dict] = None, messages: Optional[Any] = None): """ Append system prompt messages to the messages """ if kwargs is not None: - if kwargs.get("system") is not None and isinstance( - kwargs.get("system"), str - ): + if kwargs.get("system") is not None and isinstance(kwargs.get("system"), str): if messages is None: return [{"role": "system", "content": kwargs.get("system")}] elif isinstance(messages, list): if len(messages) == 0: return [{"role": "system", "content": kwargs.get("system")}] # check for duplicates - if messages[0].get("role") == "system" and messages[0].get( - "content" - ) == kwargs.get("system"): + if messages[0].get("role") == "system" and messages[0].get("content") == kwargs.get("system"): return messages - messages = [ - {"role": "system", "content": kwargs.get("system")} - ] + messages + messages = [{"role": "system", "content": kwargs.get("system")}] + messages elif isinstance(messages, str): messages = [ {"role": "system", "content": kwargs.get("system")}, @@ -5018,9 +4493,7 @@ def merge_litellm_metadata(litellm_params: dict) -> dict: merged_metadata: dict = {} # Start with metadata (user API key fields) - but skip non-serializable objects - if litellm_params.get("metadata") and isinstance( - litellm_params.get("metadata"), dict - ): + if litellm_params.get("metadata") and isinstance(litellm_params.get("metadata"), dict): for key, value in litellm_params["metadata"].items(): # Skip non-serializable objects like UserAPIKeyAuth if key in {"user_api_key_auth", "user_api_key_budget_reservation"}: @@ -5028,13 +4501,9 @@ def merge_litellm_metadata(litellm_params: dict) -> dict: merged_metadata[key] = value # Then merge litellm_metadata (model-related fields) - this will NOT overwrite existing keys - if litellm_params.get("litellm_metadata") and isinstance( - litellm_params.get("litellm_metadata"), dict - ): + if litellm_params.get("litellm_metadata") and isinstance(litellm_params.get("litellm_metadata"), dict): for key, value in litellm_params["litellm_metadata"].items(): - if ( - key not in merged_metadata - ): # Don't overwrite existing keys from metadata + if key not in merged_metadata: # Don't overwrite existing keys from metadata merged_metadata[key] = value return merged_metadata @@ -5046,9 +4515,7 @@ def get_standard_logging_metadata( prompt_integration: Optional[str] = None, applied_guardrails: Optional[List[str]] = None, mcp_tool_call_metadata: Optional[StandardLoggingMCPToolCall] = None, - vector_store_request_metadata: Optional[ - List[StandardLoggingVectorStoreRequest] - ] = None, + vector_store_request_metadata: Optional[List[StandardLoggingVectorStoreRequest]] = None, usage_object: Optional[dict] = None, proxy_server_request: Optional[dict] = None, start_time: Optional[dt_object] = None, @@ -5068,14 +4535,10 @@ def get_standard_logging_metadata( - If 'user_api_key' is present in metadata and is a valid SHA256 hash, it's stored as 'user_api_key_hash'. """ - prompt_management_metadata: Optional[ - StandardLoggingPromptManagementMetadata - ] = None + prompt_management_metadata: Optional[StandardLoggingPromptManagementMetadata] = None if litellm_params is not None: prompt_id = cast(Optional[str], litellm_params.get("prompt_id", None)) - prompt_variables = cast( - Optional[dict], litellm_params.get("prompt_variables", None) - ) + prompt_variables = cast(Optional[dict], litellm_params.get("prompt_variables", None)) if prompt_id is not None and prompt_integration is not None: prompt_management_metadata = StandardLoggingPromptManagementMetadata( @@ -5121,11 +4584,7 @@ def get_standard_logging_metadata( clean_metadata[key] = metadata[key] # type: ignore user_api_key = metadata.get("user_api_key") - if ( - user_api_key - and isinstance(user_api_key, str) - and is_valid_sha256_hash(user_api_key) - ): + if user_api_key and isinstance(user_api_key, str) and is_valid_sha256_hash(user_api_key): clean_metadata["user_api_key_hash"] = user_api_key _potential_requester_metadata = metadata.get( "metadata", None @@ -5137,10 +4596,7 @@ def get_standard_logging_metadata( ): clean_metadata["requester_metadata"] = _potential_requester_metadata - if ( - EnterpriseStandardLoggingPayloadSetupVAR - and proxy_server_request is not None - ): + if EnterpriseStandardLoggingPayloadSetupVAR and proxy_server_request is not None: clean_metadata = EnterpriseStandardLoggingPayloadSetupVAR.apply_enterprise_specific_metadata( standard_logging_metadata=clean_metadata, proxy_server_request=proxy_server_request, @@ -5148,12 +4604,10 @@ def get_standard_logging_metadata( # Generate cold storage object key if cold storage is configured if start_time is not None and response_id is not None: - cold_storage_object_key = ( - StandardLoggingPayloadSetup._generate_cold_storage_object_key( - start_time=start_time, - response_id=response_id, - team_alias=clean_metadata.get("user_api_key_team_alias"), - ) + cold_storage_object_key = StandardLoggingPayloadSetup._generate_cold_storage_object_key( + start_time=start_time, + response_id=response_id, + team_alias=clean_metadata.get("user_api_key_team_alias"), ) if cold_storage_object_key: clean_metadata["cold_storage_object_key"] = cold_storage_object_key @@ -5175,9 +4629,7 @@ def get_usage_from_response_obj( ) usage = response_obj.get("usage", None) or {} - if usage is None or ( - not isinstance(usage, dict) and not isinstance(usage, Usage) - ): + if usage is None or (not isinstance(usage, dict) and not isinstance(usage, Usage)): return Usage( prompt_tokens=0, completion_tokens=0, @@ -5186,16 +4638,10 @@ def get_usage_from_response_obj( elif isinstance(usage, Usage): return usage elif isinstance(usage, ResponseAPIUsage): - return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - usage - ) + return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage) elif isinstance(usage, dict): if ResponseAPILoggingUtils._is_response_api_usage(usage): - return ( - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - usage - ) - ) + return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage) return Usage(**usage) raise ValueError(f"usage is required, got={usage} of type {type(usage)}") @@ -5218,16 +4664,10 @@ def get_usage_as_dict( if _raw is None: return _empty if isinstance(_raw, ResponseAPIUsage): - return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - _raw - ).model_dump() + return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(_raw).model_dump() if isinstance(_raw, dict): if ResponseAPILoggingUtils._is_response_api_usage(_raw): - return ( - ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage( - _raw - ).model_dump() - ) + return ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(_raw).model_dump() return _raw if isinstance(_raw, Usage): return _raw.model_dump() @@ -5248,9 +4688,7 @@ def get_model_cost_information( custom_pricing=custom_pricing, ) if model_cost_name is None: - model_cost_information = StandardLoggingModelInformation( - model_map_key="", model_map_value=None - ) + model_cost_information = StandardLoggingModelInformation(model_map_key="", model_map_value=None) else: try: _model_cost_information = litellm.get_model_info( @@ -5292,9 +4730,7 @@ def get_final_response_obj( result=final_response_obj, ) - if modified_final_response_obj is not None and isinstance( - modified_final_response_obj, BaseModel - ): + if modified_final_response_obj is not None and isinstance(modified_final_response_obj, BaseModel): final_response_obj = modified_final_response_obj.model_dump() else: final_response_obj = modified_final_response_obj @@ -5347,10 +4783,8 @@ def get_hidden_params( for key in StandardLoggingHiddenParams.__annotations__.keys(): if key in hidden_params: if key == "additional_headers": - clean_hidden_params["additional_headers"] = ( - StandardLoggingPayloadSetup.get_additional_headers( - hidden_params[key] - ) + clean_hidden_params["additional_headers"] = StandardLoggingPayloadSetup.get_additional_headers( + hidden_params[key] ) else: clean_hidden_params[key] = hidden_params[key] # type: ignore @@ -5402,11 +4836,7 @@ def _generate_cold_storage_object_key( custom_logger = litellm.logging_callback_manager.get_active_custom_logger_for_callback_name( cold_storage_custom_logger ) - if ( - custom_logger - and hasattr(custom_logger, "s3_path") - and getattr(custom_logger, "s3_path") - ): + if custom_logger and hasattr(custom_logger, "s3_path") and getattr(custom_logger, "s3_path"): s3_path = getattr(custom_logger, "s3_path") except Exception: # If any error occurs in getting the logger instance, use default empty s3_path @@ -5443,9 +4873,7 @@ def get_error_information( response_attr = getattr(original_exception, "response", None) status_code_attr = getattr(response_attr, "status_code", None) error_status = str(status_code_attr) if status_code_attr is not None else "" - error_class: str = ( - str(original_exception.__class__.__name__) if original_exception else "" - ) + error_class: str = str(original_exception.__class__.__name__) if original_exception else "" _llm_provider_in_exception = getattr(original_exception, "llm_provider", "") # Get traceback information (first 100 lines) @@ -5454,9 +4882,7 @@ def get_error_information( tb = getattr(original_exception, "__traceback__", None) if tb: tb_lines = traceback.format_tb(tb) - traceback_info += "".join( - tb_lines[:MAXIMUM_TRACEBACK_LINES_TO_LOG] - ) # Limit to first 100 lines + traceback_info += "".join(tb_lines[:MAXIMUM_TRACEBACK_LINES_TO_LOG]) # Limit to first 100 lines # Prefer the `.message` attribute (set by ProxyException and every # litellm.exceptions.* class) over str(exc); ProxyException does not @@ -5472,12 +4898,8 @@ def get_error_information( else: error_message = str(original_exception) if original_exception else "" - rate_limit_category = validate_rate_limit_category( - getattr(original_exception, "category", None) - ) - rate_limit_type = validate_rate_limit_type( - getattr(original_exception, "rate_limit_type", None) - ) + rate_limit_category = validate_rate_limit_category(getattr(original_exception, "category", None)) + rate_limit_type = validate_rate_limit_type(getattr(original_exception, "rate_limit_type", None)) return StandardLoggingPayloadErrorInformation( error_code=error_status, @@ -5602,9 +5024,7 @@ def _get_extra_header_tags(proxy_server_request: dict) -> Optional[List[str]]: """ Extract additional header tags for spend tracking based on config. """ - extra_headers: List[str] = ( - getattr(litellm, "extra_spend_tag_headers", None) or [] - ) + extra_headers: List[str] = getattr(litellm, "extra_spend_tag_headers", None) or [] if not extra_headers: return None @@ -5621,9 +5041,7 @@ def _get_extra_header_tags(proxy_server_request: dict) -> Optional[List[str]]: return header_tags if header_tags else None @staticmethod - def _get_request_tags( - litellm_params: dict, proxy_server_request: dict - ) -> List[str]: + def _get_request_tags(litellm_params: dict, proxy_server_request: dict) -> List[str]: # check for 'tags' in both 'metadata' and 'litellm_metadata' metadata = litellm_params.get("metadata") or {} litellm_metadata = litellm_params.get("litellm_metadata") or {} @@ -5633,12 +5051,8 @@ def _get_request_tags( request_tags = litellm_metadata.get("tags", []).copy() else: request_tags = [] - user_agent_tags = StandardLoggingPayloadSetup._get_user_agent_tags( - proxy_server_request - ) - additional_header_tags = StandardLoggingPayloadSetup._get_extra_header_tags( - proxy_server_request - ) + user_agent_tags = StandardLoggingPayloadSetup._get_user_agent_tags(proxy_server_request) + additional_header_tags = StandardLoggingPayloadSetup._get_extra_header_tags(proxy_server_request) if user_agent_tags is not None: request_tags.extend(user_agent_tags) if additional_header_tags is not None: @@ -5687,9 +5101,7 @@ def _get_status_fields( guardrail_status = GUARDRAIL_STATUS_MAP.get(raw_status, "not_run") break - return StandardLoggingPayloadStatusFields( - llm_api_status=llm_api_status, guardrail_status=guardrail_status - ) + return StandardLoggingPayloadStatusFields(llm_api_status=llm_api_status, guardrail_status=guardrail_status) def _extract_response_obj_and_hidden_params( @@ -5713,9 +5125,7 @@ def _extract_response_obj_and_hidden_params( if response_headers is not None: hidden_params = dict( StandardLoggingHiddenParams( - additional_headers=StandardLoggingPayloadSetup.get_additional_headers( - dict(response_headers) - ), + additional_headers=StandardLoggingPayloadSetup.get_additional_headers(dict(response_headers)), model_id=None, cache_key=None, api_base=None, @@ -5744,18 +5154,14 @@ def get_standard_logging_object_payload( try: kwargs = kwargs or {} - response_obj, hidden_params = _extract_response_obj_and_hidden_params( - init_response_obj, original_exception - ) + response_obj, hidden_params = _extract_response_obj_and_hidden_params(init_response_obj, original_exception) # standardize this function to be used across, s3, dynamoDB, langfuse logging litellm_params = kwargs.get("litellm_params", {}) or {} proxy_server_request = litellm_params.get("proxy_server_request") or {} # Merge both litellm_metadata and metadata to get complete metadata - metadata: dict = StandardLoggingPayloadSetup.merge_litellm_metadata( - litellm_params - ) + metadata: dict = StandardLoggingPayloadSetup.merge_litellm_metadata(litellm_params) completion_start_time = kwargs.get("completion_start_time", end_time) call_type = kwargs.get("call_type") @@ -5763,9 +5169,7 @@ def get_standard_logging_object_payload( # Extract usage as a plain dict, avoiding Pydantic round-trip usage_dict = StandardLoggingPayloadSetup.get_usage_as_dict( response_obj=response_obj, - combined_usage_object=cast( - Optional[Usage], kwargs.get("combined_usage_object") - ), + combined_usage_object=cast(Optional[Usage], kwargs.get("combined_usage_object")), ) id = response_obj.get("id", kwargs.get("litellm_call_id")) @@ -5800,9 +5204,7 @@ def get_standard_logging_object_payload( prompt_integration=kwargs.get("prompt_integration", None), applied_guardrails=kwargs.get("applied_guardrails", None), mcp_tool_call_metadata=kwargs.get("mcp_tool_call_metadata", None), - vector_store_request_metadata=kwargs.get( - "vector_store_request_metadata", None - ), + vector_store_request_metadata=kwargs.get("vector_store_request_metadata", None), usage_object=usage_dict, proxy_server_request=proxy_server_request, start_time=start_time, @@ -5831,13 +5233,8 @@ def get_standard_logging_object_payload( response_cost: float = raw_response_cost or 0.0 # clean up litellm hidden params - clean_hidden_params = StandardLoggingPayloadSetup.get_hidden_params( - hidden_params - ) - if ( - clean_hidden_params["response_cost"] is None - and raw_response_cost is not None - ): + clean_hidden_params = StandardLoggingPayloadSetup.get_hidden_params(hidden_params) + if clean_hidden_params["response_cost"] is None and raw_response_cost is not None: clean_hidden_params["response_cost"] = response_cost model_cost_information = StandardLoggingPayloadSetup.get_model_cost_information( @@ -5848,12 +5245,10 @@ def get_standard_logging_object_payload( api_base=litellm_params.get("api_base"), ) - error_information, error_str = ( - StandardLoggingPayloadSetup.get_error_information_for_logging_payload( - metadata=metadata, - original_exception=original_exception, - error_str=error_str, - ) + error_information, error_str = StandardLoggingPayloadSetup.get_error_information_for_logging_payload( + metadata=metadata, + original_exception=original_exception, + error_str=error_str, ) ## get final response object ## @@ -5874,9 +5269,7 @@ def get_standard_logging_object_payload( # This ensures Bedrock models like "us.anthropic.claude-3-5-sonnet-20240620-v1:0" # are logged as "bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0" custom_llm_provider = cast(Optional[str], kwargs.get("custom_llm_provider")) - model_name = reconstruct_model_name( - kwargs.get("model", "") or "", custom_llm_provider, metadata - ) + model_name = reconstruct_model_name(kwargs.get("model", "") or "", custom_llm_provider, metadata) response_model_name: Optional[str] = None if isinstance(final_response_obj, dict): response_model_name = final_response_obj.get("model") @@ -5886,10 +5279,7 @@ def get_standard_logging_object_payload( requested_model = kwargs.get("model") if ( isinstance(requested_model, str) - and ( - "model_router" in requested_model.lower() - or "model-router" in requested_model.lower() - ) + and ("model_router" in requested_model.lower() or "model-router" in requested_model.lower()) and isinstance(response_model_name, str) and response_model_name ): @@ -5897,8 +5287,7 @@ def get_standard_logging_object_payload( payload: StandardLoggingPayload = StandardLoggingPayload( id=str(id), - litellm_call_id=kwargs.get("litellm_call_id") - or litellm_params.get("litellm_call_id"), + litellm_call_id=kwargs.get("litellm_call_id") or litellm_params.get("litellm_call_id"), trace_id=StandardLoggingPayloadSetup._get_standard_logging_payload_trace_id( logging_obj=logging_obj, litellm_params=litellm_params, @@ -5909,9 +5298,7 @@ def get_standard_logging_object_payload( status=status, status_fields=_get_status_fields( status=status, - guardrail_information=metadata.get( - "standard_logging_guardrail_information", None - ), + guardrail_information=metadata.get("standard_logging_guardrail_information", None), error_str=error_str, ), custom_llm_provider=custom_llm_provider, @@ -5930,10 +5317,7 @@ def get_standard_logging_object_payload( completion_tokens=usage_dict.get("completion_tokens", 0), request_tags=request_tags, end_user=end_user_id or "", - api_base=StandardLoggingPayloadSetup.strip_trailing_slash( - litellm_params.get("api_base", "") - ) - or "", + api_base=StandardLoggingPayloadSetup.strip_trailing_slash(litellm_params.get("api_base", "")) or "", model_group=_model_group, model_id=_model_id, requester_ip_address=clean_metadata.get("requester_ip_address", None), @@ -5951,22 +5335,15 @@ def get_standard_logging_object_payload( model_map_information=model_cost_information, error_str=error_str, error_information=error_information, - response_cost_failure_debug_info=kwargs.get( - "response_cost_failure_debug_information" - ), - guardrail_information=metadata.get( - "standard_logging_guardrail_information", None - ), + response_cost_failure_debug_info=kwargs.get("response_cost_failure_debug_information"), + guardrail_information=metadata.get("standard_logging_guardrail_information", None), standard_built_in_tools_params=standard_built_in_tools_params, ) - # emit_standard_logging_payload(payload) - Moved to success_handler to prevent double emitting return payload except Exception as e: - verbose_logger.exception( - "Error creating standard logging object - {}".format(str(e)) - ) + verbose_logger.exception("Error creating standard logging object - {}".format(str(e))) return None @@ -6031,9 +5408,7 @@ def get_standard_logging_metadata( if metadata.get("user_api_key") is not None: if is_valid_sha256_hash(str(metadata.get("user_api_key"))): - clean_metadata["user_api_key_hash"] = metadata.get( - "user_api_key" - ) # this is the hash + clean_metadata["user_api_key_hash"] = metadata.get("user_api_key") # this is the hash return clean_metadata @@ -6054,14 +5429,10 @@ def scrub_sensitive_keys_in_metadata(litellm_params: Optional[dict]): ## check user_api_key_metadata for sensitive logging keys cleaned_user_api_key_metadata = {} - if "user_api_key_metadata" in metadata and isinstance( - metadata["user_api_key_metadata"], dict - ): + if "user_api_key_metadata" in metadata and isinstance(metadata["user_api_key_metadata"], dict): for k, v in metadata["user_api_key_metadata"].items(): if k == "logging": # prevent logging user logging keys - cleaned_user_api_key_metadata[k] = ( - "scrubbed_by_litellm_for_sensitive_keys" - ) + cleaned_user_api_key_metadata[k] = "scrubbed_by_litellm_for_sensitive_keys" else: cleaned_user_api_key_metadata[k] = v @@ -6095,9 +5466,7 @@ def _get_traceback_str_for_error(error_str: str) -> str: def create_dummy_standard_logging_payload() -> StandardLoggingPayload: # First create the nested objects with proper typing - model_info = StandardLoggingModelInformation( - model_map_key="gpt-3.5-turbo", model_map_value=None - ) + model_info = StandardLoggingModelInformation(model_map_key="gpt-3.5-turbo", model_map_value=None) metadata = StandardLoggingMetadata( # type: ignore user_api_key_hash=str("test_hash"), @@ -6133,9 +5502,7 @@ def create_dummy_standard_logging_payload() -> StandardLoggingPayload: # Create messages and response with proper typing messages: List[Dict[str, str]] = [{"role": "user", "content": "Hello, world!"}] - response: Dict[str, List[Dict[str, Dict[str, str]]]] = { - "choices": [{"message": {"content": "Hi there!"}}] - } + response: Dict[str, List[Dict[str, Dict[str, str]]]] = {"choices": [{"message": {"content": "Hi there!"}}]} # Main payload initialization return StandardLoggingPayload( # type: ignore @@ -6145,10 +5512,7 @@ def create_dummy_standard_logging_payload() -> StandardLoggingPayload: response_cost=response_cost, response_cost_failure_debug_info=None, status=str("success"), - total_tokens=int( - DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT - + DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT - ), + total_tokens=int(DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT + DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT), prompt_tokens=int(DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT), completion_tokens=int(DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT), startTime=start_time, diff --git a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py index e8bd63521c12..221b1ae6eab6 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py +++ b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py @@ -17,6 +17,7 @@ ModelInfo, ModelResponse, SearchContextCostPerQuery, + ServerToolUse, StandardBuiltInToolsParams, Usage, ) @@ -58,12 +59,11 @@ def get_cost_for_built_in_tools( custom_llm_provider=custom_llm_provider, usage=usage, standard_built_in_tools_params=standard_built_in_tools_params, + response_object=response_object, ) # Handle file search - if StandardBuiltInToolCostTracking.response_object_includes_file_search_call( - response_object=response_object - ): + if StandardBuiltInToolCostTracking.response_object_includes_file_search_call(response_object=response_object): return StandardBuiltInToolCostTracking._handle_file_search_cost( model=model, custom_llm_provider=custom_llm_provider, @@ -83,6 +83,7 @@ def _handle_web_search_cost( custom_llm_provider: Optional[str], usage: Optional[Usage], standard_built_in_tools_params: StandardBuiltInToolsParams, + response_object: object = None, ) -> float: """Handle web search cost calculation.""" from litellm.llms import get_cost_for_web_search_request @@ -96,32 +97,28 @@ def _handle_web_search_cost( # cost is routed and priced with the model_info that was actually resolved, instead of # feeding a re-resolved model into the original provider's calculator. if model_info is None and "/" in model: - model_info = StandardBuiltInToolCostTracking._safe_get_model_info( - model=model - ) + model_info = StandardBuiltInToolCostTracking._safe_get_model_info(model=model) if model_info is not None: custom_llm_provider = model_info["litellm_provider"] if custom_llm_provider is None and model_info is not None: custom_llm_provider = model_info["litellm_provider"] - if ( - model_info is not None - and usage is not None - and custom_llm_provider is not None - ): + resolved_usage = StandardBuiltInToolCostTracking._usage_with_anthropic_web_search( + usage=usage, response_object=response_object + ) + + if model_info is not None and resolved_usage is not None and custom_llm_provider is not None: result = get_cost_for_web_search_request( custom_llm_provider=custom_llm_provider, - usage=usage, + usage=resolved_usage, model_info=model_info, ) if result is not None: return result return StandardBuiltInToolCostTracking.get_cost_for_web_search( - web_search_options=standard_built_in_tools_params.get( - "web_search_options", None - ), + web_search_options=standard_built_in_tools_params.get("web_search_options", None), model_info=model_info, ) @@ -136,15 +133,11 @@ def _handle_file_search_cost( model=model, custom_llm_provider=custom_llm_provider ) file_search_raw: Any = standard_built_in_tools_params.get("file_search", {}) - file_search_usage: Optional[FileSearchTool] = ( - FileSearchTool(**file_search_raw) if file_search_raw else None - ) + file_search_usage: Optional[FileSearchTool] = FileSearchTool(**file_search_raw) if file_search_raw else None # Convert model_info to dict and extract usage parameters model_info_dict = dict(model_info) if model_info is not None else None - storage_gb, days = StandardBuiltInToolCostTracking._extract_file_search_params( - file_search_usage - ) + storage_gb, days = StandardBuiltInToolCostTracking._extract_file_search_params(file_search_usage) return StandardBuiltInToolCostTracking.get_cost_for_file_search( file_search=file_search_usage, @@ -214,16 +207,12 @@ def _get_vector_store_cost( standard_built_in_tools_params: StandardBuiltInToolsParams, ) -> float: """Calculate vector store cost.""" - vector_store_usage = standard_built_in_tools_params.get( - "vector_store_usage", None - ) + vector_store_usage = standard_built_in_tools_params.get("vector_store_usage", None) if not vector_store_usage: return 0.0 model_info_dict = dict(model_info) if model_info is not None else None - vector_store_dict = ( - vector_store_usage if isinstance(vector_store_usage, dict) else {} - ) + vector_store_dict = vector_store_usage if isinstance(vector_store_usage, dict) else {} return StandardBuiltInToolCostTracking.get_cost_for_vector_store( vector_store_usage=vector_store_dict, @@ -238,9 +227,7 @@ def _get_computer_use_cost( standard_built_in_tools_params: StandardBuiltInToolsParams, ) -> float: """Calculate computer use cost.""" - computer_use_usage = standard_built_in_tools_params.get( - "computer_use_usage", {} - ) + computer_use_usage = standard_built_in_tools_params.get("computer_use_usage", {}) if not computer_use_usage: return 0.0 @@ -264,16 +251,12 @@ def _get_code_interpreter_cost( standard_built_in_tools_params: StandardBuiltInToolsParams, ) -> float: """Calculate code interpreter cost.""" - code_interpreter_sessions = standard_built_in_tools_params.get( - "code_interpreter_sessions", None - ) + code_interpreter_sessions = standard_built_in_tools_params.get("code_interpreter_sessions", None) if not code_interpreter_sessions: return 0.0 model_info_dict = dict(model_info) if model_info is not None else None - sessions = StandardBuiltInToolCostTracking._safe_convert_to_int( - code_interpreter_sessions - ) + sessions = StandardBuiltInToolCostTracking._safe_convert_to_int(code_interpreter_sessions) return StandardBuiltInToolCostTracking.get_cost_for_code_interpreter( sessions=sessions, @@ -293,12 +276,8 @@ def _extract_token_counts( input_tokens_val = computer_use_usage.get("input_tokens") output_tokens_val = computer_use_usage.get("output_tokens") - input_tokens = StandardBuiltInToolCostTracking._safe_convert_to_int( - input_tokens_val - ) - output_tokens = StandardBuiltInToolCostTracking._safe_convert_to_int( - output_tokens_val - ) + input_tokens = StandardBuiltInToolCostTracking._safe_convert_to_int(input_tokens_val) + output_tokens = StandardBuiltInToolCostTracking._safe_convert_to_int(output_tokens_val) return input_tokens, output_tokens @@ -313,24 +292,47 @@ def _safe_convert_to_int(value: Any) -> Optional[int]: return None @staticmethod - def response_object_includes_web_search_call( - response_object: Any, usage: Optional[Usage] = None - ) -> bool: + def _usage_with_anthropic_web_search(usage: Usage | None, response_object: object) -> Usage | None: + """Return a Usage carrying server_tool_use.web_search_requests sourced from a + raw Anthropic /v1/messages response dict when the reconstructed Usage dropped + it (or was never supplied). The original Usage is returned unchanged when it + already exposes the field or the response is not an Anthropic dict.""" + from litellm.llms.anthropic.cost_calculation import ( + get_anthropic_web_search_requests_from_response, + ) + + if usage is not None and (_get_web_search_requests(getattr(usage, "server_tool_use", None)) is not None): + return usage + web_search_requests = get_anthropic_web_search_requests_from_response(response_object) + if web_search_requests is None: + return usage + server_tool_use = ServerToolUse(web_search_requests=web_search_requests) + if usage is None: + return Usage(server_tool_use=server_tool_use) + return usage.model_copy(update={"server_tool_use": server_tool_use}) + + @staticmethod + def response_object_includes_web_search_call(response_object: Any, usage: Optional[Usage] = None) -> bool: """ Check if the response object includes a web search call. This covers: - Chat Completion Response (ModelResponse) - ResponsesAPIResponse (streaming + non-streaming) + - Anthropic /v1/messages raw response dict """ + from litellm.llms.anthropic.cost_calculation import ( + get_anthropic_web_search_requests_from_response, + ) from litellm.types.utils import PromptTokensDetailsWrapper + if get_anthropic_web_search_requests_from_response(response_object) is not None: + return True + if isinstance(response_object, ModelResponse): # chat completions only include url_citation annotations when a web search call is made - has_url_citations = ( - StandardBuiltInToolCostTracking.response_includes_annotation_type( - response_object=response_object, annotation_type="url_citation" - ) + has_url_citations = StandardBuiltInToolCostTracking.response_includes_annotation_type( + response_object=response_object, annotation_type="url_citation" ) if has_url_citations: return True @@ -339,9 +341,7 @@ def response_object_includes_web_search_call( if ( hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details is not None - and isinstance( - usage.prompt_tokens_details, PromptTokensDetailsWrapper - ) + and isinstance(usage.prompt_tokens_details, PromptTokensDetailsWrapper) and hasattr(usage.prompt_tokens_details, "web_search_requests") and usage.prompt_tokens_details.web_search_requests is not None ): @@ -349,10 +349,7 @@ def response_object_includes_web_search_call( # Anthropic Claude (direct API and Vertex AI) uses server_tool_use.web_search_requests. # Without this check, Claude ModelResponse always falls through to return False # and _handle_web_search_cost() is never called. - if ( - hasattr(usage, "server_tool_use") - and _get_web_search_requests(usage.server_tool_use) is not None - ): + if hasattr(usage, "server_tool_use") and _get_web_search_requests(usage.server_tool_use) is not None: return True return False elif isinstance(response_object, ResponsesAPIResponse): @@ -361,10 +358,7 @@ def response_object_includes_web_search_call( response_object=response_object, output_type="web_search_call" ) elif usage is not None: - if ( - hasattr(usage, "server_tool_use") - and _get_web_search_requests(usage.server_tool_use) is not None - ): + if hasattr(usage, "server_tool_use") and _get_web_search_requests(usage.server_tool_use) is not None: return True elif ( hasattr(usage, "prompt_tokens_details") @@ -442,13 +436,9 @@ def response_includes_output_type( return False @staticmethod - def _safe_get_model_info( - model: str, custom_llm_provider: Optional[str] = None - ) -> Optional[ModelInfo]: + def _safe_get_model_info(model: str, custom_llm_provider: Optional[str] = None) -> Optional[ModelInfo]: try: - return litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + return litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) except Exception: return None @@ -466,9 +456,7 @@ def get_cost_for_web_search( search_context_raw: Any = model_info.get("search_context_cost_per_query", {}) search_context_pricing: SearchContextCostPerQuery = ( - SearchContextCostPerQuery(**search_context_raw) - if search_context_raw - else SearchContextCostPerQuery() + SearchContextCostPerQuery(**search_context_raw) if search_context_raw else SearchContextCostPerQuery() ) if web_search_options.get("search_context_size", None) == "low": return search_context_pricing.get("search_context_size_low", 0.0) @@ -476,9 +464,7 @@ def get_cost_for_web_search( return search_context_pricing.get("search_context_size_medium", 0.0) elif web_search_options.get("search_context_size", None) == "high": return search_context_pricing.get("search_context_size_high", 0.0) - return StandardBuiltInToolCostTracking.get_default_cost_for_web_search( - model_info - ) + return StandardBuiltInToolCostTracking.get_default_cost_for_web_search(model_info) @staticmethod def get_default_cost_for_web_search( @@ -491,13 +477,9 @@ def get_default_cost_for_web_search( """ if model_info is None: return 0.0 - search_context_raw: Any = ( - model_info.get("search_context_cost_per_query", {}) or {} - ) + search_context_raw: Any = model_info.get("search_context_cost_per_query", {}) or {} search_context_pricing: SearchContextCostPerQuery = ( - SearchContextCostPerQuery(**search_context_raw) - if search_context_raw - else SearchContextCostPerQuery() + SearchContextCostPerQuery(**search_context_raw) if search_context_raw else SearchContextCostPerQuery() ) return search_context_pricing.get("search_context_size_medium", 0.0) @@ -519,11 +501,7 @@ def get_cost_for_file_search( return 0.0 # Check if model-specific pricing is available - if ( - model_info - and "file_search_cost_per_gb_per_day" in model_info - and provider == "azure" - ): + if model_info and "file_search_cost_per_gb_per_day" in model_info and provider == "azure": if storage_gb and days: return storage_gb * days * model_info["file_search_cost_per_gb_per_day"] elif model_info and "file_search_cost_per_1k_calls" in model_info: @@ -586,12 +564,8 @@ def get_cost_for_computer_use( if provider == "azure" and (input_tokens or output_tokens): # Check if model-specific pricing is available if model_info: - input_cost = model_info.get( - "computer_use_input_cost_per_1k_tokens", 0.0 - ) - output_cost = model_info.get( - "computer_use_output_cost_per_1k_tokens", 0.0 - ) + input_cost = model_info.get("computer_use_input_cost_per_1k_tokens", 0.0) + output_cost = model_info.get("computer_use_output_cost_per_1k_tokens", 0.0) if input_cost or output_cost: total_cost = 0.0 if input_tokens: @@ -608,13 +582,9 @@ def get_cost_for_computer_use( total_cost = 0.0 if input_tokens: - total_cost += ( - input_tokens / 1000.0 - ) * AZURE_COMPUTER_USE_INPUT_COST_PER_1K_TOKENS + total_cost += (input_tokens / 1000.0) * AZURE_COMPUTER_USE_INPUT_COST_PER_1K_TOKENS if output_tokens: - total_cost += ( - output_tokens / 1000.0 - ) * AZURE_COMPUTER_USE_OUTPUT_COST_PER_1K_TOKENS + total_cost += (output_tokens / 1000.0) * AZURE_COMPUTER_USE_OUTPUT_COST_PER_1K_TOKENS return total_cost # OpenAI doesn't charge separately for computer use yet @@ -631,19 +601,11 @@ def _get_code_interpreter_cost_from_model_map( try: container_model = f"{provider}/container" - model_info = litellm.get_model_info( - model=container_model, custom_llm_provider=provider - ) - model_key = ( - model_info.get("key") - if isinstance(model_info, dict) - else getattr(model_info, "key", None) - ) + model_info = litellm.get_model_info(model=container_model, custom_llm_provider=provider) + model_key = model_info.get("key") if isinstance(model_info, dict) else getattr(model_info, "key", None) if model_key and model_key in litellm.model_cost: - return litellm.model_cost[model_key].get( - "code_interpreter_cost_per_session" - ) + return litellm.model_cost[model_key].get("code_interpreter_cost_per_session") except Exception: pass @@ -701,9 +663,7 @@ def _get_web_search_options(kwargs: Dict) -> Optional[WebSearchOptions]: tools = StandardBuiltInToolCostTracking._get_tools_from_kwargs( kwargs=kwargs, tool_type="web_search_preview" - ) or StandardBuiltInToolCostTracking._get_tools_from_kwargs( - kwargs=kwargs, tool_type="web_search" - ) + ) or StandardBuiltInToolCostTracking._get_tools_from_kwargs(kwargs=kwargs, tool_type="web_search") if tools: # Look for web search tool in the tools array for tool in tools: @@ -720,9 +680,7 @@ def _get_tools_from_kwargs(kwargs: Dict, tool_type: str) -> Optional[List[Dict]] @staticmethod def _get_file_search_tool_call(kwargs: Dict) -> Optional[FileSearchTool]: - tools = StandardBuiltInToolCostTracking._get_tools_from_kwargs( - kwargs, "file_search" - ) + tools = StandardBuiltInToolCostTracking._get_tools_from_kwargs(kwargs, "file_search") if tools: for tool in tools: if isinstance(tool, dict): diff --git a/litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py b/litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py index 1432e912fd8e..1c6adbec174d 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py +++ b/litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py @@ -19,9 +19,7 @@ def is_transcription_usage_object( @staticmethod def transform_transcription_usage_object( - usage_object: Union[ - TranscriptionUsageDurationObject, TranscriptionUsageTokensObject - ], + usage_object: Union[TranscriptionUsageDurationObject, TranscriptionUsageTokensObject], ) -> Optional[Usage]: if isinstance(usage_object, TranscriptionUsageDurationObject): return None diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.py index e407dd70bf07..e013c587f0ff 100644 --- a/litellm/litellm_core_utils/llm_cost_calc/utils.py +++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py @@ -126,17 +126,12 @@ def _generic_cost_per_character( Exception if 'input_cost_per_character' or 'output_cost_per_character' is missing from model_info """ ## GET MODEL INFO - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) ## CALCULATE INPUT COST try: if custom_prompt_cost is None: - assert ( - "input_cost_per_character" in model_info - and model_info["input_cost_per_character"] is not None - ), ( + assert "input_cost_per_character" in model_info and model_info["input_cost_per_character"] is not None, ( "model info for model={} does not have 'input_cost_per_character'-pricing\nmodel_info={}".format( model, model_info ) @@ -156,10 +151,7 @@ def _generic_cost_per_character( ## CALCULATE OUTPUT COST try: if custom_completion_cost is None: - assert ( - "output_cost_per_character" in model_info - and model_info["output_cost_per_character"] is not None - ), ( + assert "output_cost_per_character" in model_info and model_info["output_cost_per_character"] is not None, ( "model info for model={} does not have 'output_cost_per_character'-pricing\nmodel_info={}".format( model, model_info ) @@ -220,12 +212,8 @@ def _get_token_base_cost( # Get service tier aware cost keys input_cost_key = _get_service_tier_cost_key("input_cost_per_token", service_tier) output_cost_key = _get_service_tier_cost_key("output_cost_per_token", service_tier) - cache_creation_cost_key = _get_service_tier_cost_key( - "cache_creation_input_token_cost", service_tier - ) - cache_read_cost_key = _get_service_tier_cost_key( - "cache_read_input_token_cost", service_tier - ) + cache_creation_cost_key = _get_service_tier_cost_key("cache_creation_input_token_cost", service_tier) + cache_read_cost_key = _get_service_tier_cost_key("cache_read_input_token_cost", service_tier) prompt_base_cost = cast(float, _get_cost_per_unit(model_info, input_cost_key)) completion_base_cost = cast(float, _get_cost_per_unit(model_info, output_cost_key)) @@ -233,14 +221,10 @@ def _get_token_base_cost( # For image generation models that don't have output_cost_per_token, # use output_cost_per_image_token as the base cost (all output tokens are image tokens) if completion_base_cost == 0.0 or completion_base_cost is None: - output_image_cost = _get_cost_per_unit( - model_info, "output_cost_per_image_token", None - ) + output_image_cost = _get_cost_per_unit(model_info, "output_cost_per_image_token", None) if output_image_cost is not None: completion_base_cost = cast(float, output_image_cost) - cache_creation_cost = cast( - float, _get_cost_per_unit(model_info, cache_creation_cost_key) - ) + cache_creation_cost = cast(float, _get_cost_per_unit(model_info, cache_creation_cost_key)) cache_creation_cost_above_1hr = cast( float, _get_cost_per_unit(model_info, "cache_creation_input_token_cost_above_1hr"), @@ -254,10 +238,7 @@ def _get_token_base_cost( # so that the threshold detection loop only processes standard keys. The # service_tier-specific above-threshold key is resolved later via _get_service_tier_cost_key. threshold_keys = [ - k - for k in model_info - if k.startswith("input_cost_per_token_above_") - and not k.endswith(_SERVICE_TIER_SUFFIXES) + k for k in model_info if k.startswith("input_cost_per_token_above_") and not k.endswith(_SERVICE_TIER_SUFFIXES) ] if not threshold_keys: return ( @@ -292,9 +273,7 @@ def _get_token_base_cost( ) prompt_base_cost = cast( float, - _get_cost_per_unit( - model_info, tiered_input_key, prompt_base_cost - ), + _get_cost_per_unit(model_info, tiered_input_key, prompt_base_cost), ) tiered_output_key = ( _get_service_tier_cost_key( @@ -359,9 +338,7 @@ def _get_token_base_cost( cache_read_cost = cast( float, - _get_cost_per_unit( - model_info, cache_read_tiered_key, cache_read_cost - ), + _get_cost_per_unit(model_info, cache_read_tiered_key, cache_read_cost), ) break @@ -379,9 +356,7 @@ def _get_token_base_cost( ) -def calculate_cost_component( - model_info: ModelInfo, cost_key: str, usage_value: Optional[float] -) -> float: +def calculate_cost_component(model_info: ModelInfo, cost_key: str, usage_value: Optional[float]) -> float: """ Generic cost calculator for any usage component @@ -394,19 +369,12 @@ def calculate_cost_component( float: The calculated cost """ cost_per_unit = _get_cost_per_unit(model_info, cost_key) - if ( - cost_per_unit is not None - and isinstance(cost_per_unit, float) - and usage_value is not None - and usage_value > 0 - ): + if cost_per_unit is not None and isinstance(cost_per_unit, float) and usage_value is not None and usage_value > 0: return float(usage_value) * cost_per_unit return 0.0 -def _get_cost_per_unit( - model_info: ModelInfo, cost_key: str, default_value: Optional[float] = 0.0 -) -> Optional[float]: +def _get_cost_per_unit(model_info: ModelInfo, cost_key: str, default_value: Optional[float] = 0.0) -> Optional[float]: # Sometimes the cost per unit is a string (e.g.: If a value like "3e-7" was read from the config.yaml) cost_per_unit = model_info.get(cost_key) if isinstance(cost_per_unit, float): @@ -457,22 +425,12 @@ def calculate_cache_writing_cost( total_cost: float = 0.0 if cache_creation_token_details is not None: # get the number of 5m and 1h cache creation tokens - cache_creation_tokens_5m = ( - cache_creation_token_details.ephemeral_5m_input_tokens - ) - cache_creation_tokens_1h = ( - cache_creation_token_details.ephemeral_1h_input_tokens - ) + cache_creation_tokens_5m = cache_creation_token_details.ephemeral_5m_input_tokens + cache_creation_tokens_1h = cache_creation_token_details.ephemeral_1h_input_tokens # add the number of 5m and 1h cache creation tokens to the cache creation tokens + total_cost += cache_creation_tokens_5m * cache_creation_cost if cache_creation_tokens_5m is not None else 0.0 total_cost += ( - cache_creation_tokens_5m * cache_creation_cost - if cache_creation_tokens_5m is not None - else 0.0 - ) - total_cost += ( - cache_creation_tokens_1h * cache_creation_cost_above_1hr - if cache_creation_tokens_1h is not None - else 0.0 + cache_creation_tokens_1h * cache_creation_cost_above_1hr if cache_creation_tokens_1h is not None else 0.0 ) else: total_cost += cache_creation_tokens * cache_creation_cost @@ -493,10 +451,7 @@ class PromptTokensDetailsResult(TypedDict): def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult: - cache_hit_tokens = ( - cast(Optional[int], getattr(usage.prompt_tokens_details, "cached_tokens", 0)) - or 0 - ) + cache_hit_tokens = cast(Optional[int], getattr(usage.prompt_tokens_details, "cached_tokens", 0)) or 0 cache_creation_tokens = ( cast( Optional[int], @@ -515,14 +470,8 @@ def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult: cast(Optional[int], getattr(usage.prompt_tokens_details, "text_tokens", None)) or 0 # default to prompt tokens, if this field is not set ) - audio_tokens = ( - cast(Optional[int], getattr(usage.prompt_tokens_details, "audio_tokens", 0)) - or 0 - ) - image_tokens = ( - cast(Optional[int], getattr(usage.prompt_tokens_details, "image_tokens", 0)) - or 0 - ) + audio_tokens = cast(Optional[int], getattr(usage.prompt_tokens_details, "audio_tokens", 0)) or 0 + image_tokens = cast(Optional[int], getattr(usage.prompt_tokens_details, "image_tokens", 0)) or 0 character_count = ( cast( Optional[int], @@ -530,9 +479,7 @@ def _parse_prompt_tokens_details(usage: Usage) -> PromptTokensDetailsResult: ) or 0 ) - image_count = ( - cast(Optional[int], getattr(usage.prompt_tokens_details, "image_count", 0)) or 0 - ) + image_count = cast(Optional[int], getattr(usage.prompt_tokens_details, "image_count", 0)) or 0 video_length_seconds = ( cast( Optional[float], @@ -626,12 +573,8 @@ def _calculate_input_cost( ### AUDIO COST if prompt_tokens_details["audio_tokens"]: - audio_cost_key = _get_service_tier_cost_key( - "input_cost_per_audio_token", service_tier - ) - prompt_cost += calculate_cost_component( - model_info, audio_cost_key, prompt_tokens_details["audio_tokens"] - ) + audio_cost_key = _get_service_tier_cost_key("input_cost_per_audio_token", service_tier) + prompt_cost += calculate_cost_component(model_info, audio_cost_key, prompt_tokens_details["audio_tokens"]) ### IMAGE TOKEN COST if prompt_tokens_details["image_tokens"]: @@ -640,9 +583,7 @@ def _calculate_input_cost( image_token_cost_key = "input_cost_per_image_token" if model_info.get(image_token_cost_key) is None: image_token_cost_key = "input_cost_per_token" - prompt_cost += calculate_cost_component( - model_info, image_token_cost_key, prompt_tokens_details["image_tokens"] - ) + prompt_cost += calculate_cost_component(model_info, image_token_cost_key, prompt_tokens_details["image_tokens"]) ### CACHE WRITING COST - Now uses tiered pricing if ( @@ -651,9 +592,7 @@ def _calculate_input_cost( ): prompt_cost += calculate_cache_writing_cost( cache_creation_tokens=prompt_tokens_details["cache_creation_tokens"], - cache_creation_token_details=prompt_tokens_details[ - "cache_creation_token_details" - ], + cache_creation_token_details=prompt_tokens_details["cache_creation_token_details"], cache_creation_cost_above_1hr=cache_creation_cost_above_1hr, cache_creation_cost=cache_creation_cost, ) @@ -691,9 +630,7 @@ def _calculate_input_cost( return prompt_cost -def _get_regional_uplift_multiplier( - model_info: ModelInfo, data_residency: Optional[str] -) -> float: +def _get_regional_uplift_multiplier(model_info: ModelInfo, data_residency: Optional[str]) -> float: """ Resolve the per-model regional-processing uplift multiplier for a given data-residency region. @@ -718,8 +655,7 @@ def _get_regional_uplift_multiplier( return float(cast(float, multiplier)) except (TypeError, ValueError): verbose_logger.exception( - "Invalid regional_processing_uplift_multiplier_%s for model; " - "defaulting to 1.0", + "Invalid regional_processing_uplift_multiplier_%s for model; defaulting to 1.0", residency, ) return 1.0 @@ -781,21 +717,11 @@ def generic_cost_per_token( image_tokens = prompt_tokens_details["image_tokens"] # Check for double-counting: sum of details > prompt_tokens means overlap - total_details = ( - text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens - ) + total_details = text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens has_double_counting = cache_hit > 0 and total_details > usage.prompt_tokens - if ( - text_tokens == 0 and prompt_tokens_details["image_count"] == 0 - ) or has_double_counting: - text_tokens = ( - usage.prompt_tokens - - cache_hit - - audio_tokens - - cache_creation - - image_tokens - ) + if (text_tokens == 0 and prompt_tokens_details["image_count"] == 0) or has_double_counting: + text_tokens = usage.prompt_tokens - cache_hit - audio_tokens - cache_creation - image_tokens # Clamp to zero: inconsistent streaming usage if text_tokens < 0: text_tokens = 0 @@ -807,9 +733,7 @@ def generic_cost_per_token( cache_creation_cost, cache_creation_cost_above_1hr, cache_read_cost, - ) = _get_token_base_cost( - model_info=model_info, usage=usage, service_tier=service_tier - ) + ) = _get_token_base_cost(model_info=model_info, usage=usage, service_tier=service_tier) prompt_cost = _calculate_input_cost( prompt_tokens_details=prompt_tokens_details, @@ -845,10 +769,7 @@ def generic_cost_per_token( # This handles cases like OpenAI's reasoning models where text_tokens isn't provided text_tokens = max( 0, - usage.completion_tokens - - reasoning_tokens - - audio_tokens - - image_tokens, + usage.completion_tokens - reasoning_tokens - audio_tokens - image_tokens, ) else: # No breakdown at all, all tokens are text tokens @@ -859,37 +780,25 @@ def generic_cost_per_token( ## AUDIO COST if not is_text_tokens_total and audio_tokens is not None and audio_tokens > 0: - _output_cost_per_audio_token = _get_cost_per_unit( - model_info, "output_cost_per_audio_token", None - ) + _output_cost_per_audio_token = _get_cost_per_unit(model_info, "output_cost_per_audio_token", None) _output_cost_per_audio_token = ( - _output_cost_per_audio_token - if _output_cost_per_audio_token is not None - else completion_base_cost + _output_cost_per_audio_token if _output_cost_per_audio_token is not None else completion_base_cost ) completion_cost += float(audio_tokens) * _output_cost_per_audio_token ## REASONING COST if not is_text_tokens_total and reasoning_tokens and reasoning_tokens > 0: - _output_cost_per_reasoning_token = _get_cost_per_unit( - model_info, "output_cost_per_reasoning_token", None - ) + _output_cost_per_reasoning_token = _get_cost_per_unit(model_info, "output_cost_per_reasoning_token", None) _output_cost_per_reasoning_token = ( - _output_cost_per_reasoning_token - if _output_cost_per_reasoning_token is not None - else completion_base_cost + _output_cost_per_reasoning_token if _output_cost_per_reasoning_token is not None else completion_base_cost ) completion_cost += float(reasoning_tokens) * _output_cost_per_reasoning_token ## IMAGE COST if not is_text_tokens_total and image_tokens and image_tokens > 0: - _output_cost_per_image_token = _get_cost_per_unit( - model_info, "output_cost_per_image_token", None - ) + _output_cost_per_image_token = _get_cost_per_unit(model_info, "output_cost_per_image_token", None) _output_cost_per_image_token = ( - _output_cost_per_image_token - if _output_cost_per_image_token is not None - else completion_base_cost + _output_cost_per_image_token if _output_cost_per_image_token is not None else completion_base_cost ) completion_cost += float(image_tokens) * _output_cost_per_image_token @@ -954,18 +863,10 @@ def calculate_image_response_cost_from_usage( ) else: text_tokens = _get_token_detail_value(output_tokens_details, "text_tokens") or 0 - image_tokens = ( - _get_token_detail_value(output_tokens_details, "image_tokens") or 0 - ) - audio_tokens = ( - _get_token_detail_value(output_tokens_details, "audio_tokens") or 0 - ) - reasoning_tokens = ( - _get_token_detail_value(output_tokens_details, "reasoning_tokens") or 0 - ) - known_output_tokens = ( - text_tokens + image_tokens + audio_tokens + reasoning_tokens - ) + image_tokens = _get_token_detail_value(output_tokens_details, "image_tokens") or 0 + audio_tokens = _get_token_detail_value(output_tokens_details, "audio_tokens") or 0 + reasoning_tokens = _get_token_detail_value(output_tokens_details, "reasoning_tokens") or 0 + known_output_tokens = text_tokens + image_tokens + audio_tokens + reasoning_tokens if completion_tokens > known_output_tokens: text_tokens += completion_tokens - known_output_tokens @@ -1014,11 +915,7 @@ def calculate_image_response_web_search_cost( from litellm.llms import get_cost_for_web_search_request - synthetic_usage = Usage( - prompt_tokens_details=PromptTokensDetailsWrapper( - web_search_requests=web_search_requests - ) - ) + synthetic_usage = Usage(prompt_tokens_details=PromptTokensDetailsWrapper(web_search_requests=web_search_requests)) return ( get_cost_for_web_search_request( custom_llm_provider=custom_llm_provider, @@ -1094,9 +991,7 @@ def route_image_generation_cost_calculator( image_response=completion_response, optional_params=optional_params, ) - raise TypeError( - "completion_response must be of type ImageResponse for bedrock image cost calculation" - ) + raise TypeError("completion_response must be of type ImageResponse for bedrock image cost calculation") elif custom_llm_provider == litellm.LlmProviders.RECRAFT.value: from litellm.llms.recraft.cost_calculator import ( cost_calculator as recraft_image_cost_calculator, diff --git a/litellm/litellm_core_utils/llm_request_utils.py b/litellm/litellm_core_utils/llm_request_utils.py index 7be70852978f..7f76c7aca760 100644 --- a/litellm/litellm_core_utils/llm_request_utils.py +++ b/litellm/litellm_core_utils/llm_request_utils.py @@ -49,16 +49,12 @@ def pick_cheapest_chat_models_from_llm_provider(custom_llm_provider: str, n=1): for model in known_models: try: - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) except Exception: continue if model_info.get("mode") != "chat": continue - _cost = (model_info.get("input_cost_per_token") or 0.0) + ( - model_info.get("output_cost_per_token") or 0.0 - ) + _cost = (model_info.get("input_cost_per_token") or 0.0) + (model_info.get("output_cost_per_token") or 0.0) model_costs.append((model, _cost)) # Sort by cost (ascending) @@ -77,8 +73,6 @@ def get_proxy_server_request_headers(litellm_params: Optional[dict]) -> dict: if litellm_params is None: return {} - proxy_request_headers = (litellm_params.get("proxy_server_request") or {}).get( - "headers" - ) or {} + proxy_request_headers = (litellm_params.get("proxy_server_request") or {}).get("headers") or {} return proxy_request_headers diff --git a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py index 79c6c665684c..58107d9804bc 100644 --- a/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py +++ b/litellm/litellm_core_utils/llm_response_utils/convert_dict_to_response.py @@ -49,9 +49,7 @@ _MESSAGE_FIELDS: frozenset = frozenset(Message.model_fields.keys()) _CHOICES_FIELDS: frozenset = frozenset(Choices.model_fields.keys()) -_MODEL_RESPONSE_FIELDS: frozenset = frozenset(ModelResponse.model_fields.keys()) | { - "usage" -} +_MODEL_RESPONSE_FIELDS: frozenset = frozenset(ModelResponse.model_fields.keys()) | {"usage"} def _normalize_images_for_message( @@ -109,9 +107,7 @@ def convert_tool_call_to_json_mode( convert_tool_call_to_json_mode=convert_tool_call_to_json_mode, ): # to support 'json_schema' logic on older models - json_mode_content_str: Optional[str] = tool_calls[0]["function"].get( - "arguments" - ) + json_mode_content_str: Optional[str] = tool_calls[0]["function"].get("arguments") if json_mode_content_str is not None: message = litellm.Message(content=json_mode_content_str) finish_reason = "stop" @@ -188,8 +184,7 @@ async def convert_to_streaming_response_async( raise APIError( status_code=500, message=( - "LiteLLM: provider returned a response with no 'choices'. " - f"Raw keys: {list(response_object.keys())}" + f"LiteLLM: provider returned a response with no 'choices'. Raw keys: {list(response_object.keys())}" ), llm_provider="", model="", @@ -221,9 +216,7 @@ async def convert_to_streaming_response_async( logprobs = choice.get("logprobs", None) - choice = StreamingChoices( - finish_reason=finish_reason, index=idx, delta=delta, logprobs=logprobs - ) + choice = StreamingChoices(finish_reason=finish_reason, index=idx, delta=delta, logprobs=logprobs) choice_list.append(choice) model_response_object.choices = choice_list @@ -243,9 +236,7 @@ async def convert_to_streaming_response_async( model_response_object.id = response_object["id"] if "created" in response_object: - model_response_object.created = _safe_convert_created_field( - response_object["created"] - ) + model_response_object.created = _safe_convert_created_field(response_object["created"]) if "system_fingerprint" in response_object: model_response_object.system_fingerprint = response_object["system_fingerprint"] @@ -259,9 +250,7 @@ async def convert_to_streaming_response_async( # single-yield behavior. slices: list[str] = [] if len(model_response_object.choices) == 1: - slices = _split_assembled_content_for_replay( - model_response_object.choices[0].delta.content - ) + slices = _split_assembled_content_for_replay(model_response_object.choices[0].delta.content) if len(slices) <= 1: yield model_response_object await asyncio.sleep(0) @@ -305,8 +294,7 @@ def convert_to_streaming_response( raise APIError( status_code=500, message=( - "LiteLLM: provider returned a response with no 'choices'. " - f"Raw keys: {list(response_object.keys())}" + f"LiteLLM: provider returned a response with no 'choices'. Raw keys: {list(response_object.keys())}" ), llm_provider="", model="", @@ -333,23 +321,15 @@ def convert_to_streaming_response( if "usage" in response_object and response_object["usage"] is not None: setattr(model_response_object, "usage", Usage()) - model_response_object.usage.completion_tokens = response_object["usage"].get( - "completion_tokens", 0 - ) # type: ignore - model_response_object.usage.prompt_tokens = response_object["usage"].get( - "prompt_tokens", 0 - ) # type: ignore - model_response_object.usage.total_tokens = response_object["usage"].get( - "total_tokens", 0 - ) # type: ignore + model_response_object.usage.completion_tokens = response_object["usage"].get("completion_tokens", 0) # type: ignore + model_response_object.usage.prompt_tokens = response_object["usage"].get("prompt_tokens", 0) # type: ignore + model_response_object.usage.total_tokens = response_object["usage"].get("total_tokens", 0) # type: ignore if "id" in response_object: model_response_object.id = response_object["id"] if "created" in response_object: - model_response_object.created = _safe_convert_created_field( - response_object["created"] - ) + model_response_object.created = _safe_convert_created_field(response_object["created"]) if "system_fingerprint" in response_object: model_response_object.system_fingerprint = response_object["system_fingerprint"] @@ -362,9 +342,7 @@ def convert_to_streaming_response( # for the full rationale — this mirrors its tail. slices: list[str] = [] if len(model_response_object.choices) == 1: - slices = _split_assembled_content_for_replay( - model_response_object.choices[0].delta.content - ) + slices = _split_assembled_content_for_replay(model_response_object.choices[0].delta.content) if len(slices) <= 1: yield model_response_object return @@ -407,9 +385,7 @@ def _handle_invalid_parallel_tool_calls( current_function = tool_call.function.name function_args = json.loads(tool_call.function.arguments) if current_function == "multi_tool_use.parallel": - verbose_logger.debug( - "OpenAI did a weird pseudo-multi-tool-use call, fixing call structure.." - ) + verbose_logger.debug("OpenAI did a weird pseudo-multi-tool-use call, fixing call structure..") for _fake_i, _fake_tool_use in enumerate(function_args["tool_uses"]): _function_args = _fake_tool_use["parameters"] _current_function = _fake_tool_use["recipient_name"] @@ -419,17 +395,13 @@ def _handle_invalid_parallel_tool_calls( fixed_tc = ChatCompletionMessageToolCall( id=f"{tool_call.id}_{_fake_i}", type="function", - function=Function( - name=_current_function, arguments=json.dumps(_function_args) - ), + function=Function(name=_current_function, arguments=json.dumps(_function_args)), ) replacements[i].append(fixed_tc) shift = 0 for i, replacement in replacements.items(): - tool_calls[:] = ( - tool_calls[: i + shift] + replacement + tool_calls[i + shift + 1 :] - ) + tool_calls[:] = tool_calls[: i + shift] + replacement + tool_calls[i + shift + 1 :] shift += len(replacement) return tool_calls @@ -471,13 +443,9 @@ def convert_to_image_response( # Convert dicts to wrapper objects so getattr() works in cost calculation if isinstance(usage.get("input_tokens_details"), dict): - usage["prompt_tokens_details"] = PromptTokensDetailsWrapper( - **usage["input_tokens_details"] - ) + usage["prompt_tokens_details"] = PromptTokensDetailsWrapper(**usage["input_tokens_details"]) if isinstance(usage.get("output_tokens_details"), dict): - usage["completion_tokens_details"] = CompletionTokensDetailsWrapper( - **usage["output_tokens_details"] - ) + usage["completion_tokens_details"] = CompletionTokensDetailsWrapper(**usage["output_tokens_details"]) if model_response_object is None: model_response_object = ImageResponse(**response_object) @@ -516,9 +484,11 @@ def convert_chat_to_text_completion( chat_response = completion(model="gpt-3.5-turbo", messages=[{"role": "user", "content": "Hi"}]) text_response = convert_chat_to_text_completion(chat_response) """ - transformed_logprobs = LiteLLMResponseObjectHandler._convert_provider_response_logprobs_to_text_completion_logprobs( - response=response, - custom_llm_provider=custom_llm_provider, + transformed_logprobs = ( + LiteLLMResponseObjectHandler._convert_provider_response_logprobs_to_text_completion_logprobs( + response=response, + custom_llm_provider=custom_llm_provider, + ) ) text_completion_response["id"] = response.get("id", None) @@ -538,9 +508,7 @@ def convert_chat_to_text_completion( text_completion_response["choices"] = choices_list text_completion_response["usage"] = response.get("usage", None) - text_completion_response._hidden_params = HiddenParams( - **response._hidden_params - ) + text_completion_response._hidden_params = HiddenParams(**response._hidden_params) return text_completion_response @staticmethod @@ -559,9 +527,7 @@ def _convert_provider_response_logprobs_to_text_completion_logprobs( def _should_convert_tool_call_to_json_mode( - tool_calls: Optional[ - Union[List[ChatCompletionMessageToolCall], List[DatabricksTool]] - ] = None, + tool_calls: Optional[Union[List[ChatCompletionMessageToolCall], List[DatabricksTool]]] = None, convert_tool_call_to_json_mode: Optional[bool] = None, ) -> bool: """ @@ -596,9 +562,7 @@ def convert_to_model_response_object( end_time=None, hidden_params: Optional[dict] = None, _response_headers: Optional[dict] = None, - convert_tool_call_to_json_mode: Optional[ - bool - ] = None, # used for supporting 'json_schema' on older models + convert_tool_call_to_json_mode: Optional[bool] = None, # used for supporting 'json_schema' on older models ): additional_headers = get_response_headers(_response_headers) @@ -621,11 +585,7 @@ def convert_to_model_response_object( ### CHECK IF ERROR IN RESPONSE ### - openrouter returns these in the dictionary # Some OpenAI-compatible providers (e.g., Apertis) return empty error objects # even on success. Only raise if the error contains meaningful data. - if ( - response_object is not None - and "error" in response_object - and response_object["error"] is not None - ): + if response_object is not None and "error" in response_object and response_object["error"] is not None: error_obj = response_object["error"] has_meaningful_error = False @@ -659,8 +619,7 @@ def convert_to_model_response_object( try: if response_type == "completion" and ( - model_response_object is None - or isinstance(model_response_object, ModelResponse) + model_response_object is None or isinstance(model_response_object, ModelResponse) ): if response_object is None or model_response_object is None: raise Exception("Error in response object format") @@ -669,9 +628,7 @@ def convert_to_model_response_object( return convert_to_streaming_response(response_object=response_object) choice_list: List[Choices] = [] - if not response_object.get("choices") or not isinstance( - response_object["choices"], Iterable - ): + if not response_object.get("choices") or not isinstance(response_object["choices"], Iterable): from litellm.exceptions import APIError raise APIError( @@ -692,9 +649,7 @@ def convert_to_model_response_object( for _tc in tool_calls: _openai_tc = ChatCompletionMessageToolCall(**_tc) _openai_tool_calls.append(_openai_tc) - fixed_tool_calls = _handle_invalid_parallel_tool_calls( - _openai_tool_calls - ) + fixed_tool_calls = _handle_invalid_parallel_tool_calls(_openai_tool_calls) if fixed_tool_calls is not None: tool_calls = fixed_tool_calls @@ -706,25 +661,19 @@ def convert_to_model_response_object( convert_tool_call_to_json_mode=convert_tool_call_to_json_mode, ): # to support 'json_schema' logic on older models - json_mode_content_str: Optional[str] = tool_calls[0][ - "function" - ].get("arguments") + json_mode_content_str: Optional[str] = tool_calls[0]["function"].get("arguments") if json_mode_content_str is not None: message = litellm.Message(content=json_mode_content_str) finish_reason = "stop" if message is None: # Preserve provider_specific_fields if already present # in the response (e.g. from proxy passthrough) - provider_specific_fields = dict( - choice["message"].get("provider_specific_fields", None) or {} - ) + provider_specific_fields = dict(choice["message"].get("provider_specific_fields", None) or {}) for f in choice["message"].keys() - _MESSAGE_FIELDS: provider_specific_fields[f] = choice["message"][f] # Handle reasoning models that display `reasoning_content` within `content` - reasoning_content, content = _extract_reasoning_content( - choice["message"] - ) + reasoning_content, content = _extract_reasoning_content(choice["message"]) # Handle thinking models that display `thinking_blocks` within `content` thinking_blocks: Optional[ @@ -749,25 +698,17 @@ def convert_to_model_response_object( reasoning_content=reasoning_content, thinking_blocks=thinking_blocks, annotations=choice["message"].get("annotations", None), - images=_normalize_images_for_message( - choice["message"].get("images", None) - ), + images=_normalize_images_for_message(choice["message"].get("images", None)), ) finish_reason = choice.get("finish_reason", None) if finish_reason is None: # gpt-4 vision can return 'finish_reason' or 'finish_details' finish_reason = choice.get("finish_details") or "stop" - if ( - finish_reason == "stop" - and message.tool_calls - and len(message.tool_calls) > 0 - ): + if finish_reason == "stop" and message.tool_calls and len(message.tool_calls) > 0: finish_reason = "tool_calls" ## PROVIDER SPECIFIC FIELDS ## - provider_specific_fields = { - f: choice[f] for f in choice.keys() - _CHOICES_FIELDS - } + provider_specific_fields = {f: choice[f] for f in choice.keys() - _CHOICES_FIELDS} logprobs = choice.get("logprobs", None) enhancements = choice.get("enhancements", None) @@ -786,35 +727,22 @@ def convert_to_model_response_object( usage_object = litellm.Usage(**response_object["usage"]) setattr(model_response_object, "usage", usage_object) if "created" in response_object: - model_response_object.created = _safe_convert_created_field( - response_object["created"] - ) + model_response_object.created = _safe_convert_created_field(response_object["created"]) if "id" in response_object: # Preserve the auto-generated id from ModelResponse.__init__ # when the provider returns a falsy id (None, "") - model_response_object.id = ( - response_object["id"] or model_response_object.id - ) + model_response_object.id = response_object["id"] or model_response_object.id if "system_fingerprint" in response_object: - model_response_object.system_fingerprint = response_object[ - "system_fingerprint" - ] + model_response_object.system_fingerprint = response_object["system_fingerprint"] if "model" in response_object: if model_response_object.model is None: model_response_object.model = response_object["model"] - elif ( - "/" in model_response_object.model - and response_object["model"] is not None - ): - openai_compatible_provider = model_response_object.model.split("/")[ - 0 - ] - model_response_object.model = ( - openai_compatible_provider + "/" + response_object["model"] - ) + elif "/" in model_response_object.model and response_object["model"] is not None: + openai_compatible_provider = model_response_object.model.split("/")[0] + model_response_object.model = openai_compatible_provider + "/" + response_object["model"] if start_time is not None and end_time is not None: if isinstance(start_time, type(end_time)): @@ -836,8 +764,7 @@ def convert_to_model_response_object( return model_response_object elif response_type == "embedding" and ( - model_response_object is None - or isinstance(model_response_object, EmbeddingResponse) + model_response_object is None or isinstance(model_response_object, EmbeddingResponse) ): if response_object is None: raise Exception("Error in response object format") @@ -854,15 +781,9 @@ def convert_to_model_response_object( model_response_object.data = response_object["data"] if "usage" in response_object and response_object["usage"] is not None: - model_response_object.usage.completion_tokens = response_object[ - "usage" - ].get("completion_tokens", 0) # type: ignore - model_response_object.usage.prompt_tokens = response_object[ - "usage" - ].get("prompt_tokens", 0) # type: ignore - model_response_object.usage.total_tokens = response_object["usage"].get( - "total_tokens", 0 - ) # type: ignore + model_response_object.usage.completion_tokens = response_object["usage"].get("completion_tokens", 0) # type: ignore + model_response_object.usage.prompt_tokens = response_object["usage"].get("prompt_tokens", 0) # type: ignore + model_response_object.usage.total_tokens = response_object["usage"].get("total_tokens", 0) # type: ignore if start_time is not None and end_time is not None: model_response_object._response_ms = ( # type: ignore @@ -877,8 +798,7 @@ def convert_to_model_response_object( return model_response_object elif response_type == "image_generation" and ( - model_response_object is None - or isinstance(model_response_object, ImageResponse) + model_response_object is None or isinstance(model_response_object, ImageResponse) ): if response_object is None: raise Exception("Error in response object format") @@ -890,8 +810,7 @@ def convert_to_model_response_object( ) elif response_type == "audio_transcription" and ( - model_response_object is None - or isinstance(model_response_object, TranscriptionResponse) + model_response_object is None or isinstance(model_response_object, TranscriptionResponse) ): if response_object is None: raise Exception("Error in response object format") @@ -908,20 +827,14 @@ def convert_to_model_response_object( setattr(model_response_object, key, response_object[key]) if "usage" in response_object and response_object["usage"] is not None: - tr_usage_object: Optional[ - Union[ - TranscriptionUsageDurationObject, TranscriptionUsageTokensObject - ] - ] = None + tr_usage_object: Optional[Union[TranscriptionUsageDurationObject, TranscriptionUsageTokensObject]] = ( + None + ) if response_object["usage"].get("type", None) == "duration": - tr_usage_object = TranscriptionUsageDurationObject( - **response_object["usage"] - ) + tr_usage_object = TranscriptionUsageDurationObject(**response_object["usage"]) elif response_object["usage"].get("type", None) == "tokens": - tr_usage_object = TranscriptionUsageTokensObject( - **response_object["usage"] - ) + tr_usage_object = TranscriptionUsageTokensObject(**response_object["usage"]) if tr_usage_object is not None: setattr(model_response_object, "usage", tr_usage_object) @@ -932,17 +845,16 @@ def convert_to_model_response_object( # tracking without exposing it in the response body. Must be set # after hidden_params assignment to avoid being overwritten. if "_audio_transcription_duration" in response_object: - model_response_object._hidden_params["audio_transcription_duration"] = ( - response_object["_audio_transcription_duration"] - ) + model_response_object._hidden_params["audio_transcription_duration"] = response_object[ + "_audio_transcription_duration" + ] if _response_headers is not None: model_response_object._response_headers = _response_headers return model_response_object elif response_type == "rerank" and ( - model_response_object is None - or isinstance(model_response_object, RerankResponse) + model_response_object is None or isinstance(model_response_object, RerankResponse) ): if response_object is None: raise Exception("Error in response object format") @@ -976,6 +888,4 @@ def convert_to_model_response_object( end_time=end_time, convert_tool_call_to_json_mode=convert_tool_call_to_json_mode, ) - raise Exception( - f"Invalid response object {traceback.format_exc()}\n\nreceived_args={received_args}" - ) + raise Exception(f"Invalid response object {traceback.format_exc()}\n\nreceived_args={received_args}") diff --git a/litellm/litellm_core_utils/llm_response_utils/get_api_base.py b/litellm/litellm_core_utils/llm_response_utils/get_api_base.py index c23bbb936b94..cc61ef0c8998 100644 --- a/litellm/litellm_core_utils/llm_response_utils/get_api_base.py +++ b/litellm/litellm_core_utils/llm_response_utils/get_api_base.py @@ -7,9 +7,7 @@ from ...types.router import LiteLLM_Params -def get_api_base( - model: str, optional_params: Union[dict, LiteLLM_Params] -) -> Optional[str]: +def get_api_base(model: str, optional_params: Union[dict, LiteLLM_Params]) -> Optional[str]: """ Returns the api base used for calling the model. @@ -34,9 +32,7 @@ def get_api_base( elif "model" in optional_params: _optional_params = LiteLLM_Params(**optional_params) else: # prevent needing to copy and pop the dict - _optional_params = LiteLLM_Params( - model=model, **optional_params - ) # convert to pydantic object + _optional_params = LiteLLM_Params(model=model, **optional_params) # convert to pydantic object except Exception: return None # get llm provider @@ -68,10 +64,7 @@ def get_api_base( stream: bool = getattr(optional_params, "stream", False) - if ( - _optional_params.vertex_location is not None - and _optional_params.vertex_project is not None - ): + if _optional_params.vertex_location is not None and _optional_params.vertex_project is not None: from litellm.llms.vertex_ai.vertex_llm_base import VertexBase from litellm.types.llms.vertex_ai import VertexPartnerProvider @@ -105,13 +98,9 @@ def get_api_base( if custom_llm_provider == "gemini": if stream: - _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:streamGenerateContent".format( - model - ) + _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:streamGenerateContent".format(model) else: - _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent".format( - model - ) + _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent".format(model) return _api_base elif custom_llm_provider == "openai": _api_base = "https://api.openai.com" diff --git a/litellm/litellm_core_utils/llm_response_utils/get_headers.py b/litellm/litellm_core_utils/llm_response_utils/get_headers.py index cd49b5a4a87b..f4bbfae3039e 100644 --- a/litellm/litellm_core_utils/llm_response_utils/get_headers.py +++ b/litellm/litellm_core_utils/llm_response_utils/get_headers.py @@ -20,21 +20,13 @@ def get_response_headers(_response_headers: Optional[dict] = None) -> dict: openai_headers = {} if "x-ratelimit-limit-requests" in _response_headers: - openai_headers["x-ratelimit-limit-requests"] = _response_headers[ - "x-ratelimit-limit-requests" - ] + openai_headers["x-ratelimit-limit-requests"] = _response_headers["x-ratelimit-limit-requests"] if "x-ratelimit-remaining-requests" in _response_headers: - openai_headers["x-ratelimit-remaining-requests"] = _response_headers[ - "x-ratelimit-remaining-requests" - ] + openai_headers["x-ratelimit-remaining-requests"] = _response_headers["x-ratelimit-remaining-requests"] if "x-ratelimit-limit-tokens" in _response_headers: - openai_headers["x-ratelimit-limit-tokens"] = _response_headers[ - "x-ratelimit-limit-tokens" - ] + openai_headers["x-ratelimit-limit-tokens"] = _response_headers["x-ratelimit-limit-tokens"] if "x-ratelimit-remaining-tokens" in _response_headers: - openai_headers["x-ratelimit-remaining-tokens"] = _response_headers[ - "x-ratelimit-remaining-tokens" - ] + openai_headers["x-ratelimit-remaining-tokens"] = _response_headers["x-ratelimit-remaining-tokens"] llm_provider_headers = _get_llm_provider_headers(_response_headers) return {**llm_provider_headers, **openai_headers} diff --git a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py index ba870eb9459b..5ac2dca9ccf5 100644 --- a/litellm/litellm_core_utils/llm_response_utils/response_metadata.py +++ b/litellm/litellm_core_utils/llm_response_utils/response_metadata.py @@ -20,9 +20,7 @@ class ResponseMetadata: def __init__(self, result: Any): self.result = result - self._hidden_params: Union[HiddenParams, dict] = ( - getattr(result, "_hidden_params", {}) or {} - ) + self._hidden_params: Union[HiddenParams, dict] = getattr(result, "_hidden_params", {}) or {} @property def supports_response_time(self) -> bool: @@ -33,9 +31,7 @@ def supports_response_time(self) -> bool: or isinstance(self.result, TranscriptionResponse) ) - def set_hidden_params( - self, logging_obj: LiteLLMLoggingObject, model: Optional[str], kwargs: dict - ) -> None: + def set_hidden_params(self, logging_obj: LiteLLMLoggingObject, model: Optional[str], kwargs: dict) -> None: """Set hidden parameters on the response""" ## ADD OTHER HIDDEN PARAMS @@ -127,12 +123,7 @@ def set_timing_metrics( if ( logging_obj.caching_details is not None and logging_obj.caching_details.get("cache_hit") is True - and ( - cache_duration_ms := logging_obj.caching_details.get( - "cache_duration_ms" - ) - ) - is not None + and (cache_duration_ms := logging_obj.caching_details.get("cache_duration_ms")) is not None ): overhead_ms = total_response_time_ms - cache_duration_ms self._update_hidden_params( diff --git a/litellm/litellm_core_utils/logging_callback_manager.py b/litellm/litellm_core_utils/logging_callback_manager.py index f58126ec9014..00e12ee7ce97 100644 --- a/litellm/litellm_core_utils/logging_callback_manager.py +++ b/litellm/litellm_core_utils/logging_callback_manager.py @@ -43,23 +43,15 @@ def add_litellm_input_callback(self, callback: Union[CustomLogger, str, Callable Auto-routes async callbacks to litellm._async_input_callback. """ if not isinstance(callback, str) and self._is_async_callable(callback): - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm._async_input_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm._async_input_callback) else: - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm.input_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm.input_callback) - def add_litellm_service_callback( - self, callback: Union[CustomLogger, str, Callable] - ): + def add_litellm_service_callback(self, callback: Union[CustomLogger, str, Callable]): """ Add a service callback to litellm.service_callback """ - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm.service_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm.service_callback) def add_litellm_callback(self, callback: Union[CustomLogger, str, Callable]): """ @@ -72,66 +64,42 @@ def add_litellm_callback(self, callback: Union[CustomLogger, str, Callable]): parent_list=litellm.callbacks, # type: ignore ) - def add_litellm_success_callback( - self, callback: Union[CustomLogger, str, Callable] - ): + def add_litellm_success_callback(self, callback: Union[CustomLogger, str, Callable]): """ Add a success callback to `litellm.success_callback`. Auto-routes async callbacks to litellm._async_success_callback. Special-cases 'dynamodb' and 'openmeter' as async callbacks. """ if isinstance(callback, str) and callback in ("dynamodb", "openmeter"): - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm._async_success_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm._async_success_callback) elif not isinstance(callback, str) and self._is_async_callable(callback): - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm._async_success_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm._async_success_callback) else: - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm.success_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm.success_callback) - def add_litellm_failure_callback( - self, callback: Union[CustomLogger, str, Callable] - ): + def add_litellm_failure_callback(self, callback: Union[CustomLogger, str, Callable]): """ Add a failure callback to `litellm.failure_callback`. Auto-routes async callbacks to litellm._async_failure_callback. """ if not isinstance(callback, str) and self._is_async_callable(callback): - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm._async_failure_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm._async_failure_callback) else: - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm.failure_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm.failure_callback) - def add_litellm_async_success_callback( - self, callback: Union[CustomLogger, Callable, str] - ): + def add_litellm_async_success_callback(self, callback: Union[CustomLogger, Callable, str]): """ Add a success callback to litellm._async_success_callback """ - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm._async_success_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm._async_success_callback) - def add_litellm_async_failure_callback( - self, callback: Union[CustomLogger, Callable, str] - ): + def add_litellm_async_failure_callback(self, callback: Union[CustomLogger, Callable, str]): """ Add a failure callback to litellm._async_failure_callback """ - self._safe_add_callback_to_list( - callback=callback, parent_list=litellm._async_failure_callback - ) + self._safe_add_callback_to_list(callback=callback, parent_list=litellm._async_failure_callback) - def remove_callback_from_list_by_object( - self, callback_list, obj, require_self=True - ): + def remove_callback_from_list_by_object(self, callback_list, obj, require_self=True): """ Remove callbacks that are methods of a particular object (e.g., router cleanup) """ @@ -139,9 +107,7 @@ def remove_callback_from_list_by_object( return if require_self: - remove_list = [ - c for c in callback_list if hasattr(c, "__self__") and c.__self__ == obj - ] + remove_list = [c for c in callback_list if hasattr(c, "__self__") and c.__self__ == obj] else: remove_list = [c for c in callback_list if c == obj] @@ -169,22 +135,16 @@ def remove_callbacks_by_type(self, callback_list, callback_type): for c in remove_list: callback_list.remove(c) - def _add_string_callback_to_list( - self, callback: str, parent_list: List[Union[CustomLogger, Callable, str]] - ): + def _add_string_callback_to_list(self, callback: str, parent_list: List[Union[CustomLogger, Callable, str]]): """ Add a string callback to a list, if the callback is already in the list, do not add it again. """ if callback not in parent_list: parent_list.append(callback) else: - verbose_logger.debug( - f"Callback {callback} already exists in {parent_list}, not adding again.." - ) + verbose_logger.debug(f"Callback {callback} already exists in {parent_list}, not adding again..") - def _check_callback_list_size( - self, parent_list: List[Union[CustomLogger, Callable, str]] - ) -> bool: + def _check_callback_list_size(self, parent_list: List[Union[CustomLogger, Callable, str]]) -> bool: """ Check if adding another callback would exceed MAX_CALLBACKS Returns True if safe to add, False if would exceed limit @@ -214,10 +174,7 @@ def _add_custom_callback_generic_api_str( callback_config = litellm.callback_settings.get(callback) # Check if callback is in callback_settings with callback_type: generic_api - if ( - isinstance(callback_config, dict) - and callback_config.get("callback_type") == "generic_api" - ): + if isinstance(callback_config, dict) and callback_config.get("callback_type") == "generic_api": endpoint = callback_config.get("endpoint") headers = callback_config.get("headers") event_types = callback_config.get("event_types") @@ -298,14 +255,10 @@ def _safe_add_callback_to_list( # Check if the callback is a custom callback if isinstance(callback, str): - callback = LoggingCallbackManager._add_custom_callback_generic_api_str( - callback - ) + callback = LoggingCallbackManager._add_custom_callback_generic_api_str(callback) if isinstance(callback, str): - self._add_string_callback_to_list( - callback=callback, parent_list=parent_list - ) + self._add_string_callback_to_list(callback=callback, parent_list=parent_list) elif isinstance(callback, CustomLogger): self._add_custom_logger_to_list( custom_logger=callback, @@ -313,13 +266,9 @@ def _safe_add_callback_to_list( ) elif callable(callback): - self._add_callback_function_to_list( - callback=callback, parent_list=parent_list - ) + self._add_callback_function_to_list(callback=callback, parent_list=parent_list) - def _add_callback_function_to_list( - self, callback: Callable, parent_list: List[Union[CustomLogger, Callable, str]] - ): + def _add_callback_function_to_list(self, callback: Callable, parent_list: List[Union[CustomLogger, Callable, str]]): """ Add a callback function to a list, if the callback is already in the list, do not add it again. """ @@ -407,9 +356,7 @@ def remove_callback_from_all_lists(self, obj, require_self=False) -> None: litellm._async_success_callback, litellm._async_failure_callback, ): - self.remove_callback_from_list_by_object( - callback_list, obj, require_self=require_self - ) + self.remove_callback_from_list_by_object(callback_list, obj, require_self=require_self) def get_active_additional_logging_utils_from_custom_logger( self, @@ -426,15 +373,11 @@ def get_active_additional_logging_utils_from_custom_logger( all_callbacks = self._get_all_callbacks() matched_callbacks: Set[AdditionalLoggingUtils] = set() for callback in all_callbacks: - if isinstance(callback, CustomLogger) and isinstance( - callback, AdditionalLoggingUtils - ): + if isinstance(callback, CustomLogger) and isinstance(callback, AdditionalLoggingUtils): matched_callbacks.add(callback) return matched_callbacks - def get_custom_loggers_for_type( - self, callback_type: Type[CustomLogger] - ) -> List[CustomLogger]: + def get_custom_loggers_for_type(self, callback_type: Type[CustomLogger]) -> List[CustomLogger]: """ Get all custom loggers that are instances of the given class type """ @@ -449,10 +392,7 @@ def callback_is_active(self, callback_type: Type[CustomLogger]) -> bool: """ Returns True if any of the active callbacks are of the given type """ - return any( - isinstance(callback, callback_type) - for callback in self._get_all_callbacks() - ) + return any(isinstance(callback, callback_type) for callback in self._get_all_callbacks()) def get_callbacks_by_type(self) -> CallbacksByType: """ @@ -462,20 +402,14 @@ def get_callbacks_by_type(self) -> CallbacksByType: CallbacksByType: Dict with keys 'success', 'failure', 'success_and_failure' containing lists of callback strings """ # Get callback lists - success_callbacks = set( - litellm.success_callback + litellm._async_success_callback - ) - failure_callbacks = set( - litellm.failure_callback + litellm._async_failure_callback - ) + success_callbacks = set(litellm.success_callback + litellm._async_success_callback) + failure_callbacks = set(litellm.failure_callback + litellm._async_failure_callback) general_callbacks = set(litellm.callbacks) # Get all unique callbacks all_callbacks = success_callbacks | failure_callbacks | general_callbacks - result: CallbacksByType = CallbacksByType( - success=[], failure=[], success_and_failure=[] - ) + result: CallbacksByType = CallbacksByType(success=[], failure=[], success_and_failure=[]) for callback in all_callbacks: callback_str = self._get_callback_string(callback) @@ -508,9 +442,7 @@ def _get_callback_string(self, callback: Union[CustomLogger, Callable, str]) -> return callback elif isinstance(callback, CustomLogger): # Try to get the string representation from the registry - callback_str = CustomLoggerRegistry.get_callback_str_from_class_type( - type(callback) - ) + callback_str = CustomLoggerRegistry.get_callback_str_from_class_type(type(callback)) return callback_str if callback_str is not None else type(callback).__name__ elif callable(callback): return getattr(callback, "__name__", str(callback)) @@ -528,16 +460,12 @@ def get_active_custom_logger_for_callback_name( ) # get the custom logger class type - custom_logger_class_type = ( - CustomLoggerRegistry.get_class_type_for_custom_logger_name(callback_name) - ) + custom_logger_class_type = CustomLoggerRegistry.get_class_type_for_custom_logger_name(callback_name) # get the active custom logger custom_logger = self.get_custom_loggers_for_type(custom_logger_class_type) if len(custom_logger) == 0: - raise ValueError( - f"No active custom logger found for callback name: {callback_name}" - ) + raise ValueError(f"No active custom logger found for callback name: {callback_name}") return custom_logger[0] diff --git a/litellm/litellm_core_utils/logging_utils.py b/litellm/litellm_core_utils/logging_utils.py index 4b2b740935cc..720a850b47f0 100644 --- a/litellm/litellm_core_utils/logging_utils.py +++ b/litellm/litellm_core_utils/logging_utils.py @@ -178,9 +178,7 @@ def _get_parent_otel_span_from_logging_obj( return _get_parent_otel_span_from_kwargs(logging_obj.model_call_details) except Exception as e: - verbose_logger.exception( - f"Error in _get_parent_otel_span_from_logging_obj: {str(e)}" - ) + verbose_logger.exception(f"Error in _get_parent_otel_span_from_logging_obj: {str(e)}") return None @@ -229,9 +227,7 @@ def _assemble_complete_response_from_streaming_chunks( Optional[Union[ModelResponse, TextCompletionResponse]]: Complete streaming response """ - complete_streaming_response: Optional[ - Union[ModelResponse, TextCompletionResponse] - ] = None + complete_streaming_response: Optional[Union[ModelResponse, TextCompletionResponse]] = None if isinstance(result, ModelResponse): return result @@ -246,10 +242,8 @@ def _assemble_complete_response_from_streaming_chunks( end_time=end_time, ) except Exception as e: - log_message = ( - "Error occurred building stream chunk in {} success logging: {}".format( - "async" if is_async else "sync", str(e) - ) + log_message = "Error occurred building stream chunk in {} success logging: {}".format( + "async" if is_async else "sync", str(e) ) verbose_logger.exception(log_message) complete_streaming_response = None @@ -269,9 +263,7 @@ def _set_duration_in_model_call_details( if logging_obj and hasattr(logging_obj, "model_call_details"): logging_obj.model_call_details["llm_api_duration_ms"] = duration_ms else: - verbose_logger.debug( - "`logging_obj` not found - unable to track `llm_api_duration_ms" - ) + verbose_logger.debug("`logging_obj` not found - unable to track `llm_api_duration_ms") except Exception as e: verbose_logger.warning(f"Error setting `llm_api_duration_ms`: {str(e)}") diff --git a/litellm/litellm_core_utils/logging_worker.py b/litellm/litellm_core_utils/logging_worker.py index 294ba8e5dea6..a9d5c8a8eb74 100644 --- a/litellm/litellm_core_utils/logging_worker.py +++ b/litellm/litellm_core_utils/logging_worker.py @@ -69,9 +69,7 @@ def _ensure_queue(self) -> None: # Check if we need to reinitialize due to event loop change if self._queue is not None and self._bound_loop is not current_loop: - verbose_logger.debug( - "LoggingWorker: Event loop changed, reinitializing queue and worker" - ) + verbose_logger.debug("LoggingWorker: Event loop changed, reinitializing queue and worker") # Clear old state - these are bound to the old loop self._queue = None self._sem = None @@ -121,9 +119,7 @@ async def _worker_loop(self) -> None: try: task = await self._queue.get() # Track each spawned coroutine so we can cancel on shutdown. - processing_task = asyncio.create_task( - self._process_log_task(task, self._sem) - ) + processing_task = asyncio.create_task(self._process_log_task(task, self._sem)) self._running_tasks.add(processing_task) processing_task.add_done_callback(self._running_tasks.discard) except Exception: @@ -211,14 +207,11 @@ def _calculate_retry_delay(self) -> float: time_since_last_clear = current_time - self._last_aggressive_clear_time remaining_cooldown = max( 0.0, - LOGGING_WORKER_AGGRESSIVE_CLEAR_COOLDOWN_SECONDS - - time_since_last_clear, + LOGGING_WORKER_AGGRESSIVE_CLEAR_COOLDOWN_SECONDS - time_since_last_clear, ) # Add a small buffer (10% of cooldown or 50ms, whichever is larger) to ensure # cooldown has expired and aggressive clear has completed - return remaining_cooldown + max( - 0.05, LOGGING_WORKER_AGGRESSIVE_CLEAR_COOLDOWN_SECONDS * 0.1 - ) + return remaining_cooldown + max(0.05, LOGGING_WORKER_AGGRESSIVE_CLEAR_COOLDOWN_SECONDS * 0.1) except RuntimeError: # No event loop, return minimum delay return 0.1 @@ -266,9 +259,7 @@ def _extract_tasks_from_queue(self) -> list[LoggingTask]: return [] # Calculate items based on percentage of queue size - items_to_extract = ( - self.max_queue_size * LOGGING_WORKER_CLEAR_PERCENTAGE - ) // 100 + items_to_extract = (self.max_queue_size * LOGGING_WORKER_CLEAR_PERCENTAGE) // 100 # Use actual queue size to avoid unnecessary iterations actual_size = self._queue.qsize() if actual_size == 0: @@ -285,9 +276,7 @@ def _extract_tasks_from_queue(self) -> list[LoggingTask]: return extracted_tasks - async def _aggressively_clear_queue_async( - self, new_task: Optional[LoggingTask] = None - ) -> None: + async def _aggressively_clear_queue_async(self, new_task: Optional[LoggingTask] = None) -> None: """ Aggressively clear the queue by extracting and processing items. This is called when the queue is full to prevent dropping logs. @@ -307,9 +296,7 @@ async def _aggressively_clear_queue_async( if extracted_tasks: await self._process_extracted_tasks(extracted_tasks) except Exception as e: - verbose_logger.exception( - f"LoggingWorker error during aggressive clear: {e}" - ) + verbose_logger.exception(f"LoggingWorker error during aggressive clear: {e}") finally: # Always reset the flag even if an error occurs self._aggressive_clear_in_progress = False @@ -395,9 +382,7 @@ async def clear_queue(self): for _ in range(MAX_ITERATIONS_TO_CLEAR_QUEUE): # Check if we've exceeded the maximum time if asyncio.get_event_loop().time() - start_time >= MAX_TIME_TO_CLEAR_QUEUE: - verbose_logger.warning( - f"clear_queue exceeded max_time of {MAX_TIME_TO_CLEAR_QUEUE}s, stopping early" - ) + verbose_logger.warning(f"clear_queue exceeded max_time of {MAX_TIME_TO_CLEAR_QUEUE}s, stopping early") break try: @@ -431,11 +416,7 @@ def _safe_log(self, level: str, message: str) -> None: has_valid_handler = False for handler in verbose_logger.handlers: try: - if ( - hasattr(handler, "stream") - and handler.stream - and not handler.stream.closed - ): + if hasattr(handler, "stream") and handler.stream and not handler.stream.closed: has_valid_handler = True break elif not hasattr(handler, "stream"): @@ -482,9 +463,7 @@ def _flush_on_exit(self): return queue_size = self._queue.qsize() - self._safe_log( - "info", f"[LoggingWorker] atexit: Flushing {queue_size} remaining events..." - ) + self._safe_log("info", f"[LoggingWorker] atexit: Flushing {queue_size} remaining events...") # Create a new event loop since the original is closed loop = asyncio.new_event_loop() @@ -502,10 +481,7 @@ def _flush_on_exit(self): previous_raise_exceptions = logging.raiseExceptions logging.raiseExceptions = False try: - while ( - not self._queue.empty() - and processed < MAX_ITERATIONS_TO_CLEAR_QUEUE - ): + while not self._queue.empty() and processed < MAX_ITERATIONS_TO_CLEAR_QUEUE: if loop.time() - start_time >= MAX_TIME_TO_CLEAR_QUEUE: self._safe_log( "warning", diff --git a/litellm/litellm_core_utils/model_param_helper.py b/litellm/litellm_core_utils/model_param_helper.py index 855e52098c4f..39b3f0d53760 100644 --- a/litellm/litellm_core_utils/model_param_helper.py +++ b/litellm/litellm_core_utils/model_param_helper.py @@ -67,20 +67,12 @@ def _get_all_llm_api_params() -> Set[str]: (``_get_relevant_args_to_use_for_logging``). Callers treat the result as read-only. """ - chat_completion_kwargs = ( - ModelParamHelper._get_litellm_supported_chat_completion_kwargs() - ) - text_completion_kwargs = ( - ModelParamHelper._get_litellm_supported_text_completion_kwargs() - ) + chat_completion_kwargs = ModelParamHelper._get_litellm_supported_chat_completion_kwargs() + text_completion_kwargs = ModelParamHelper._get_litellm_supported_text_completion_kwargs() embedding_kwargs = ModelParamHelper._get_litellm_supported_embedding_kwargs() - transcription_kwargs = ( - ModelParamHelper._get_litellm_supported_transcription_kwargs() - ) + transcription_kwargs = ModelParamHelper._get_litellm_supported_transcription_kwargs() rerank_kwargs = ModelParamHelper._get_litellm_supported_rerank_kwargs() - responses_api_kwargs = ( - ModelParamHelper._get_litellm_supported_responses_api_kwargs() - ) + responses_api_kwargs = ModelParamHelper._get_litellm_supported_responses_api_kwargs() exclude_kwargs = ModelParamHelper._get_exclude_kwargs() combined_kwargs = chat_completion_kwargs.union( @@ -104,18 +96,14 @@ def _get_litellm_supported_chat_completion_kwargs() -> Set[str]: This follows the OpenAI API Spec """ - non_streaming_params: Set[str] = set( - getattr(CompletionCreateParamsNonStreaming, "__annotations__", {}).keys() - ) - streaming_params: Set[str] = set( - getattr(CompletionCreateParamsStreaming, "__annotations__", {}).keys() - ) + non_streaming_params: Set[str] = set(getattr(CompletionCreateParamsNonStreaming, "__annotations__", {}).keys()) + streaming_params: Set[str] = set(getattr(CompletionCreateParamsStreaming, "__annotations__", {}).keys()) litellm_provider_specific_params: Set[str] = ( ModelParamHelper.get_litellm_provider_specific_params_for_chat_params() ) - all_chat_completion_kwargs: Set[str] = non_streaming_params.union( - streaming_params - ).union(litellm_provider_specific_params) + all_chat_completion_kwargs: Set[str] = non_streaming_params.union(streaming_params).union( + litellm_provider_specific_params + ) return all_chat_completion_kwargs @staticmethod @@ -126,16 +114,8 @@ def _get_litellm_supported_text_completion_kwargs() -> Set[str]: This follows the OpenAI API Spec """ all_text_completion_kwargs = set( - getattr( - TextCompletionCreateParamsNonStreaming, "__annotations__", {} - ).keys() - ).union( - set( - getattr( - TextCompletionCreateParamsStreaming, "__annotations__", {} - ).keys() - ) - ) + getattr(TextCompletionCreateParamsNonStreaming, "__annotations__", {}).keys() + ).union(set(getattr(TextCompletionCreateParamsStreaming, "__annotations__", {}).keys())) return all_text_completion_kwargs @staticmethod @@ -167,16 +147,8 @@ def _get_litellm_supported_transcription_kwargs() -> Set[str]: TranscriptionCreateParamsStreaming, ) - non_streaming_kwargs = set( - getattr( - TranscriptionCreateParamsNonStreaming, "__annotations__", {} - ).keys() - ) - streaming_kwargs = set( - getattr( - TranscriptionCreateParamsStreaming, "__annotations__", {} - ).keys() - ) + non_streaming_kwargs = set(getattr(TranscriptionCreateParamsNonStreaming, "__annotations__", {}).keys()) + streaming_kwargs = set(getattr(TranscriptionCreateParamsStreaming, "__annotations__", {}).keys()) all_transcription_kwargs = non_streaming_kwargs.union(streaming_kwargs) return all_transcription_kwargs @@ -191,12 +163,8 @@ def _get_litellm_supported_responses_api_kwargs() -> Set[str]: This follows the OpenAI API Spec """ - non_streaming_params: Set[str] = set( - getattr(ResponseCreateParamsNonStreaming, "__annotations__", {}).keys() - ) - streaming_params: Set[str] = set( - getattr(ResponseCreateParamsStreaming, "__annotations__", {}).keys() - ) + non_streaming_params: Set[str] = set(getattr(ResponseCreateParamsNonStreaming, "__annotations__", {}).keys()) + streaming_params: Set[str] = set(getattr(ResponseCreateParamsStreaming, "__annotations__", {}).keys()) return non_streaming_params.union(streaming_params) @staticmethod @@ -207,6 +175,4 @@ def _get_exclude_kwargs() -> Set[str]: return set(["metadata"]) -ModelParamHelper._relevant_logging_args = frozenset( - ModelParamHelper._get_relevant_args_to_use_for_logging() -) +ModelParamHelper._relevant_logging_args = frozenset(ModelParamHelper._get_relevant_args_to_use_for_logging()) diff --git a/litellm/litellm_core_utils/model_response_utils.py b/litellm/litellm_core_utils/model_response_utils.py index 6c290fa30c07..f4843f9d95c9 100644 --- a/litellm/litellm_core_utils/model_response_utils.py +++ b/litellm/litellm_core_utils/model_response_utils.py @@ -135,10 +135,7 @@ def _is_choice_non_empty(choice: Any) -> bool: # Skip certain structural fields that are just default/None placeholders if extra_field_name == "index" and extra_field_value == 0: continue - if ( - extra_field_name in {"finish_reason", "logprobs"} - and extra_field_value is None - ): + if extra_field_name in {"finish_reason", "logprobs"} and extra_field_value is None: continue if extra_field_name == "delta": continue @@ -190,11 +187,7 @@ def _is_delta_non_empty(delta: Delta) -> bool: # Check all regular attributes of the delta object for attr_name in dir(delta): # Skip private attributes, methods, and Pydantic-specific fields - if ( - attr_name.startswith("_") - or callable(getattr(delta, attr_name)) - or attr_name.startswith("model_") - ): + if attr_name.startswith("_") or callable(getattr(delta, attr_name)) or attr_name.startswith("model_"): continue attr_value = getattr(delta, attr_name, None) diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py index 4bdda6de2c88..538d5f650ef4 100644 --- a/litellm/litellm_core_utils/prompt_templates/common_utils.py +++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py @@ -44,13 +44,9 @@ if TYPE_CHECKING: # newer pattern to avoid importing pydantic objects on __init__.py from litellm.types.llms.openai import ChatCompletionImageObject -DEFAULT_USER_CONTINUE_MESSAGE = ChatCompletionUserMessage( - content="Please continue.", role="user" -) +DEFAULT_USER_CONTINUE_MESSAGE = ChatCompletionUserMessage(content="Please continue.", role="user") -DEFAULT_ASSISTANT_CONTINUE_MESSAGE = ChatCompletionAssistantMessage( - content="Please continue.", role="assistant" -) +DEFAULT_ASSISTANT_CONTINUE_MESSAGE = ChatCompletionAssistantMessage(content="Please continue.", role="assistant") if TYPE_CHECKING: from litellm.litellm_core_utils.litellm_logging import Logging as LoggingClass @@ -98,9 +94,7 @@ def handle_messages_with_content_list_to_str_conversion( return messages -def strip_name_from_message( - message: AllMessageValues, allowed_name_roles: List[str] = ["user"] -) -> AllMessageValues: +def strip_name_from_message(message: AllMessageValues, allowed_name_roles: List[str] = ["user"]) -> AllMessageValues: """ Removes 'name' from message """ @@ -202,9 +196,7 @@ def get_str_from_messages(messages: List[AllMessageValues]) -> str: def is_non_content_values_set(message: AllMessageValues) -> bool: ignore_keys = ["content", "role", "name"] - return any( - message.get(key, None) is not None for key in message if key not in ignore_keys - ) + return any(message.get(key, None) is not None for key in message if key not in ignore_keys) def _audio_or_image_in_message_content(message: AllMessageValues) -> bool: @@ -232,13 +224,9 @@ def convert_openai_message_to_only_content_messages( user_roles = ["user", "tool", "function"] for message in messages: if message.get("role") in user_roles: - converted_messages.append( - {"role": "user", "content": convert_content_list_to_str(message)} - ) + converted_messages.append({"role": "user", "content": convert_content_list_to_str(message)}) elif message.get("role") == "assistant": - converted_messages.append( - {"role": "assistant", "content": convert_content_list_to_str(message)} - ) + converted_messages.append({"role": "assistant", "content": convert_content_list_to_str(message)}) return converted_messages @@ -333,10 +321,7 @@ def _insert_user_continue_message( while i < len(result_messages): curr_message = result_messages[i] inserted_continue_message = False - if ( - _counts_for_alternation(curr_message) - and curr_message["role"] == "assistant" - ): + if _counts_for_alternation(curr_message) and curr_message["role"] == "assistant": # Preserve old behavior for malformed adjacent assistant sequences like # assistant(tool_calls) -> assistant(no-tool-calls) with no tool message. if i > 0 and result_messages[i - 1].get("role") == "assistant": @@ -423,14 +408,10 @@ def get_completion_messages( return messages.copy() ## INSERT USER CONTINUE MESSAGE - messages = _insert_user_continue_message( - messages, user_continue_message, ensure_alternating_roles - ) + messages = _insert_user_continue_message(messages, user_continue_message, ensure_alternating_roles) ## INSERT ASSISTANT CONTINUE MESSAGE - messages = _insert_assistant_continue_message( - messages, assistant_continue_message, ensure_alternating_roles - ) + messages = _insert_assistant_continue_message(messages, assistant_continue_message, ensure_alternating_roles) return messages @@ -449,9 +430,7 @@ def get_format_from_file_id(file_id: Optional[str]) -> Optional[str]: return None try: transformed_file_id = convert_b64_uid_to_unified_uid(file_id) - if transformed_file_id.startswith( - SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value - ): + if transformed_file_id.startswith(SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value): match = re.match( f"{SpecialEnums.LITELM_MANAGED_FILE_ID_PREFIX.value}:(.*?);unified_id", transformed_file_id, @@ -512,9 +491,7 @@ def update_messages_with_model_file_ids( # remap here, so skip instead of crashing. continue file_id = file_object_file_field.get("file_id") - format = file_object_file_field.get( - "format", get_format_from_file_id(file_id) - ) + format = file_object_file_field.get("format", get_format_from_file_id(file_id)) if file_id: provider_file_id = ( @@ -522,20 +499,11 @@ def update_messages_with_model_file_ids( if model_file_id_mapping and model_id is not None else None ) - if ( - not provider_file_id - and _is_base64_encoded_unified_file_id(file_id) - ): - unified_file_id = convert_b64_uid_to_unified_uid( - file_id - ) + if not provider_file_id and _is_base64_encoded_unified_file_id(file_id): + unified_file_id = convert_b64_uid_to_unified_uid(file_id) if "llm_output_file_id," in unified_file_id: - provider_file_id = unified_file_id.split( - "llm_output_file_id," - )[1].split(";")[0] - file_object_file_field["file_id"] = ( - provider_file_id or file_id - ) + provider_file_id = unified_file_id.split("llm_output_file_id,")[1].split(";")[0] + file_object_file_field["file_id"] = provider_file_id or file_id if format: file_object_file_field["format"] = format return messages @@ -581,42 +549,26 @@ def update_responses_input_with_model_file_ids( if isinstance(content, list): updated_content = [] for content_item in content: - if ( - isinstance(content_item, dict) - and content_item.get("type") == "input_file" - ): + if isinstance(content_item, dict) and content_item.get("type") == "input_file": file_id = content_item.get("file_id") if file_id: provider_file_id = file_id # Default to original # Check if we have a mapping for this file ID - if ( - model_file_id_mapping - and model_id - and file_id in model_file_id_mapping - ): + if model_file_id_mapping and model_id and file_id in model_file_id_mapping: # Use the model-specific file ID from mapping - provider_file_id = ( - model_file_id_mapping.get(file_id, {}).get(model_id) - or file_id - ) + provider_file_id = model_file_id_mapping.get(file_id, {}).get(model_id) or file_id updated_content_item = content_item.copy() updated_content_item["file_id"] = provider_file_id updated_content.append(updated_content_item) else: # Check if this is a base64-encoded unified file ID without mapping - is_unified_file_id = _is_base64_encoded_unified_file_id( - file_id - ) + is_unified_file_id = _is_base64_encoded_unified_file_id(file_id) if is_unified_file_id: # Fallback: decode unified file ID - unified_file_id = convert_b64_uid_to_unified_uid( - file_id - ) + unified_file_id = convert_b64_uid_to_unified_uid(file_id) if "llm_output_file_id," in unified_file_id: - provider_file_id = unified_file_id.split( - "llm_output_file_id," - )[1].split(";")[0] + provider_file_id = unified_file_id.split("llm_output_file_id,")[1].split(";")[0] updated_content_item = content_item.copy() updated_content_item["file_id"] = provider_file_id @@ -670,9 +622,7 @@ def _decode_vector_store_ids_in_tools( continue parsed = parse_unified_id(vs_id) - provider_resource_id = ( - parsed.get("provider_resource_id") if parsed else None - ) + provider_resource_id = parsed.get("provider_resource_id") if parsed else None if not provider_resource_id: verbose_logger.warning( @@ -737,10 +687,7 @@ def update_responses_tools_with_model_file_ids( # Check if we have a mapping for this file ID if file_id in model_file_id_mapping: # Map to provider-specific file ID - provider_file_id = ( - model_file_id_mapping.get(file_id, {}).get(model_id) - or file_id - ) + provider_file_id = model_file_id_mapping.get(file_id, {}).get(model_id) or file_id updated_file_ids.append(provider_file_id) else: updated_file_ids.append(file_id) @@ -965,9 +912,9 @@ def unpack_defs( # Use iterative approach with queue to avoid recursion # Each item in queue is (node, parent_container, key/index, active_defs, ref_chain) - queue: deque[ - tuple[Any, Union[dict, list, None], Union[str, int, None], dict, set] - ] = deque([(schema, None, None, root_defs, set())]) + queue: deque[tuple[Any, Union[dict, list, None], Union[str, int, None], dict, set]] = deque( + [(schema, None, None, root_defs, set())] + ) inlined_bytes = 0 while queue: @@ -1050,9 +997,7 @@ def _has_legacy_defs(schema: object) -> bool: if not isinstance(schema, dict): return False components = schema.get("components") - return "definitions" in schema or ( - isinstance(components, dict) and isinstance(components.get("schemas"), dict) - ) + return "definitions" in schema or (isinstance(components, dict) and isinstance(components.get("schemas"), dict)) # Schema-bomb budget for ``unpack_legacy_defs``: cap the cumulative JSON-byte @@ -1256,10 +1201,7 @@ def infer_content_type_from_url_and_content( return type_to_mime[detected_type] # If all fallbacks failed, raise error - raise ValueError( - f"Unable to determine content type from URL: {url}. " - f"Response content-type: {current_content_type}" - ) + raise ValueError(f"Unable to determine content type from URL: {url}. Response content-type: {current_content_type}") def get_tool_call_names(tools: List[ChatCompletionToolParam]) -> List[str]: @@ -1315,9 +1257,7 @@ def check_is_function_call(logging_obj: "LoggingClass") -> bool: is_function_call, ) - if hasattr(logging_obj, "optional_params") and isinstance( - logging_obj.optional_params, dict - ): + if hasattr(logging_obj, "optional_params") and isinstance(logging_obj.optional_params, dict): if is_function_call(logging_obj.optional_params): return True @@ -1423,9 +1363,7 @@ def get_last_user_message(messages: List[AllMessageValues]) -> Optional[str]: return result if result else None -def set_last_user_message( - messages: List[AllMessageValues], content: str -) -> List[AllMessageValues]: +def set_last_user_message(messages: List[AllMessageValues], content: str) -> List[AllMessageValues]: """ Set the last user message @@ -1440,11 +1378,7 @@ def set_last_user_message( # Stop when we hit a non-user message break if idx_to_remove: - messages = [ - message - for idx, message in enumerate(reversed(messages)) - if idx not in idx_to_remove - ] + messages = [message for idx, message in enumerate(reversed(messages)) if idx not in idx_to_remove] messages.reverse() messages.append({"role": "user", "content": content}) return messages @@ -1478,9 +1412,7 @@ def add_system_prompt_to_messages( if isinstance(existing_content, str): merged_content = f"{system_prompt.strip()}\n\n{existing_content}" elif isinstance(existing_content, list): - merged_content = [{"type": "text", "text": system_prompt.strip()}] + list( - existing_content - ) + merged_content = [{"type": "text", "text": system_prompt.strip()}] + list(existing_content) else: merged_content = [{"type": "text", "text": system_prompt.strip()}] first["content"] = merged_content @@ -1711,8 +1643,7 @@ def parse_tool_call_arguments( repaired = _attempt_json_repair(arguments) if repaired is not None: verbose_logger.warning( - "Repaired truncated tool call arguments for tool '%s' (%s). " - "Original (%d chars): %.200s%s", + "Repaired truncated tool call arguments for tool '%s' (%s). Original (%d chars): %.200s%s", tool_name or "", context or "unknown context", len(arguments), @@ -1728,10 +1659,7 @@ def parse_tool_call_arguments( if context: error_parts.append(f"({context})") - error_message = ( - " ".join(error_parts) - + f". Error: {str(original_error)}. Arguments: {arguments}" - ) + error_message = " ".join(error_parts) + f". Error: {str(original_error)}. Arguments: {arguments}" raise ValueError(error_message) from original_error diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py index b4f492bc26fc..e54218cb8db5 100644 --- a/litellm/litellm_core_utils/prompt_templates/factory.py +++ b/litellm/litellm_core_utils/prompt_templates/factory.py @@ -104,9 +104,7 @@ def map_system_message_pt(messages: list) -> list: if i < len(messages) - 1: # Not the last message next_m = messages[i + 1] next_role = next_m["role"] - if ( - next_role == "user" or next_role == "assistant" - ): # Next message is a user or assistant message + if next_role == "user" or next_role == "assistant": # Next message is a user or assistant message # Merge system prompt into the next message next_m["content"] = m["content"] + " " + next_m["content"] elif next_role == "system": # Next message is a system message @@ -186,9 +184,7 @@ def convert_to_ollama_image(openai_image_url: str): ) -def _handle_ollama_system_message( - messages: list, prompt: str, msg_i: int -) -> Tuple[str, int]: +def _handle_ollama_system_message(messages: list, prompt: str, msg_i: int) -> Tuple[str, int]: system_content_str = "" ## MERGE CONSECUTIVE SYSTEM CONTENT ## while msg_i < len(messages) and messages[msg_i]["role"] == "system": @@ -234,9 +230,7 @@ def ollama_pt( if user_content_str: prompt += f"### User:\n{user_content_str}\n\n" - system_content_str, msg_i = _handle_ollama_system_message( - messages, prompt, msg_i - ) + system_content_str, msg_i = _handle_ollama_system_message(messages, prompt, msg_i) if system_content_str: prompt += f"### System:\n{system_content_str}\n\n" @@ -265,9 +259,7 @@ def ollama_pt( ) if ollama_tool_calls: - assistant_content_str += ( - f"Tool Calls: {json.dumps(ollama_tool_calls, indent=2)}" - ) + assistant_content_str += f"Tool Calls: {json.dumps(ollama_tool_calls, indent=2)}" msg_i += 1 @@ -314,11 +306,7 @@ def falcon_instruct_pt(messages): if message["role"] == "system": prompt += message["content"] else: - prompt += ( - message["role"] - + ":" - + message["content"].replace("\r\n", "\n").replace("\n\n", "\n") - ) + prompt += message["role"] + ":" + message["content"].replace("\r\n", "\n").replace("\n\n", "\n") prompt += "\n\n" return prompt @@ -376,9 +364,7 @@ def phind_codellama_pt(messages): return prompt -def _render_chat_template( - env, chat_template: str, bos_token: str, eos_token: str, messages: list -) -> str: +def _render_chat_template(env, chat_template: str, bos_token: str, eos_token: str, messages: list) -> str: """ Shared template rendering logic for both sync and async hf_chat_template @@ -426,9 +412,7 @@ def _is_system_in_template(): try: for message in messages: if message["role"] == "system": - reformatted_messages.append( - {"role": "user", "content": message["content"]} - ) + reformatted_messages.append({"role": "user", "content": message["content"]}) else: reformatted_messages.append(message) rendered_text = template.render( @@ -443,20 +427,13 @@ def _is_system_in_template(): new_messages = [] for i in range(len(reformatted_messages) - 1): new_messages.append(reformatted_messages[i]) - if ( - reformatted_messages[i]["role"] - == reformatted_messages[i + 1]["role"] - ): + if reformatted_messages[i]["role"] == reformatted_messages[i + 1]["role"]: if reformatted_messages[i]["role"] == "user": - new_messages.append( - {"role": "assistant", "content": ""} - ) + new_messages.append({"role": "assistant", "content": ""}) else: new_messages.append({"role": "user", "content": ""}) new_messages.append(reformatted_messages[-1]) - rendered_text = template.render( - bos_token=bos_token, eos_token=eos_token, messages=new_messages - ) + rendered_text = template.render(bos_token=bos_token, eos_token=eos_token, messages=new_messages) return rendered_text except Exception as e: @@ -496,12 +473,8 @@ async def _afetch_and_extract_template( and "chat_template" in tokenizer_config["tokenizer"] ): tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore - bos_token = _extract_token_value( - token_value=tokenizer_data.get("bos_token") - ) - eos_token = _extract_token_value( - token_value=tokenizer_data.get("eos_token") - ) + bos_token = _extract_token_value(token_value=tokenizer_data.get("bos_token")) + eos_token = _extract_token_value(token_value=tokenizer_data.get("eos_token")) chat_template = tokenizer_data["chat_template"] else: # Fallback: Try to fetch chat template from separate .jinja file @@ -515,12 +488,8 @@ async def _afetch_and_extract_template( and isinstance(tokenizer_config["tokenizer"], dict) ): tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore - bos_token = _extract_token_value( - token_value=tokenizer_data.get("bos_token") - ) - eos_token = _extract_token_value( - token_value=tokenizer_data.get("eos_token") - ) + bos_token = _extract_token_value(token_value=tokenizer_data.get("bos_token")) + eos_token = _extract_token_value(token_value=tokenizer_data.get("eos_token")) else: raise Exception("No chat template found") @@ -558,12 +527,8 @@ def _fetch_and_extract_template( and "chat_template" in tokenizer_config["tokenizer"] ): tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore - bos_token = _extract_token_value( - token_value=tokenizer_data.get("bos_token") - ) - eos_token = _extract_token_value( - token_value=tokenizer_data.get("eos_token") - ) + bos_token = _extract_token_value(token_value=tokenizer_data.get("bos_token")) + eos_token = _extract_token_value(token_value=tokenizer_data.get("eos_token")) chat_template = tokenizer_data["chat_template"] else: # Fallback: Try to fetch chat template from separate .jinja file @@ -577,21 +542,15 @@ def _fetch_and_extract_template( and isinstance(tokenizer_config["tokenizer"], dict) ): tokenizer_data: dict = tokenizer_config["tokenizer"] # type: ignore - bos_token = _extract_token_value( - token_value=tokenizer_data.get("bos_token") - ) - eos_token = _extract_token_value( - token_value=tokenizer_data.get("eos_token") - ) + bos_token = _extract_token_value(token_value=tokenizer_data.get("bos_token")) + eos_token = _extract_token_value(token_value=tokenizer_data.get("eos_token")) else: raise Exception("No chat template found") return chat_template, bos_token, eos_token # type: ignore -async def ahf_chat_template( - model: str, messages: list, chat_template: Optional[Any] = None -): +async def ahf_chat_template(model: str, messages: list, chat_template: Optional[Any] = None): """HuggingFace chat template (async version)""" from litellm.litellm_core_utils.prompt_templates.huggingface_template_handler import ( _aget_chat_template_file, @@ -646,9 +605,7 @@ def hf_chat_template(model: str, messages: list, chat_template: Optional[Any] = def deepseek_r1_pt(messages): - return hf_chat_template( - model="deepseek-r1/deepseek-r1-7b-instruct", messages=messages - ) + return hf_chat_template(model="deepseek-r1/deepseek-r1-7b-instruct", messages=messages) # Anthropic template @@ -698,9 +655,7 @@ def get_model_info(token, model): model_info = response.json() for m in model_info: if m["name"].lower().strip() == model.strip(): - return m["config"].get("prompt_format", None), m["config"].get( - "chat_template", None - ) + return m["config"].get("prompt_format", None), m["config"].get("chat_template", None) return None, None else: return None, None @@ -779,18 +734,14 @@ class AnthropicConstants(Enum): AI_PROMPT = "\n\nAssistant: " prompt = "" - for idx, message in enumerate( - messages - ): # needs to start with `\n\nHuman: ` and end with `\n\nAssistant: ` + for idx, message in enumerate(messages): # needs to start with `\n\nHuman: ` and end with `\n\nAssistant: ` if message["role"] == "user": prompt += f"{AnthropicConstants.HUMAN_PROMPT.value}{message['content']}" elif message["role"] == "system": prompt += f"{AnthropicConstants.HUMAN_PROMPT.value}{message['content']}" else: prompt += f"{AnthropicConstants.AI_PROMPT.value}{message['content']}" - if ( - idx == 0 and message["role"] == "assistant" - ): # ensure the prompt always starts with `\n\nHuman: ` + if idx == 0 and message["role"] == "assistant": # ensure the prompt always starts with `\n\nHuman: ` prompt = f"{AnthropicConstants.HUMAN_PROMPT.value}" + prompt if messages[-1]["role"] != "assistant": prompt += f"{AnthropicConstants.AI_PROMPT.value}" @@ -874,9 +825,7 @@ def convert_generic_image_chunk_to_openai_image_obj( return "data:{};{},{}".format(media_type, image_chunk["type"], image_chunk["data"]) -def convert_to_anthropic_image_obj( - openai_image_url: str, format: Optional[str] -) -> GenericImageParsingChunk: +def convert_to_anthropic_image_obj(openai_image_url: str, format: Optional[str]) -> GenericImageParsingChunk: """ Input: "image_url": "data:image/jpeg;base64,{base64_image}", @@ -936,9 +885,7 @@ def create_anthropic_image_param( # as these providers don't support URL sources for images if is_bedrock_invoke or image_url.startswith("http://"): base64_url = convert_url_to_base64(url=image_url) - image_chunk = convert_to_anthropic_image_obj( - openai_image_url=base64_url, format=format - ) + image_chunk = convert_to_anthropic_image_obj(openai_image_url=base64_url, format=format) return AnthropicMessagesImageParam( type="image", source=AnthropicContentParamSource( @@ -958,9 +905,7 @@ def create_anthropic_image_param( ) else: # Convert to base64 for data URIs or other formats - image_chunk = convert_to_anthropic_image_obj( - openai_image_url=image_url, format=format - ) + image_chunk = convert_to_anthropic_image_obj(openai_image_url=image_url, format=format) return AnthropicMessagesImageParam( type="image", source=AnthropicContentParamSource( @@ -1037,9 +982,7 @@ def convert_to_anthropic_tool_invoke_xml(tool_calls: list) -> str: tool_arguments, tool_name=tool_name, context="Anthropic XML tool invoke" ) if isinstance(parsed_args, dict): - parameters = "".join( - f"<{param}>{val}\n" for param, val in parsed_args.items() - ) + parameters = "".join(f"<{param}>{val}\n" for param, val in parsed_args.items()) else: parameters = f"{parsed_args}\n" invokes += f"\n{tool_name}\n\n{parameters}\n\n" @@ -1071,14 +1014,8 @@ def anthropic_messages_pt_xml(messages: list): if isinstance(messages[msg_i]["content"], list): for m in messages[msg_i]["content"]: if m.get("type", "") == "image_url": - format = ( - m["image_url"].get("format") - if isinstance(m["image_url"], dict) - else None - ) - image_param = create_anthropic_image_param( - m["image_url"], format=format - ) + format = m["image_url"].get("format") if isinstance(m["image_url"], dict) else None + image_param = create_anthropic_image_param(m["image_url"], format=format) # Convert to dict format for XML version source = image_param["source"] if isinstance(source, dict) and source.get("type") == "url": @@ -1129,12 +1066,8 @@ def anthropic_messages_pt_xml(messages: list): assistant_content = [] ## MERGE CONSECUTIVE ASSISTANT CONTENT ## while msg_i < len(messages) and messages[msg_i]["role"] == "assistant": - assistant_text = ( - messages[msg_i].get("content") or "" - ) # either string or none - if messages[msg_i].get( - "tool_calls", [] - ): # support assistant tool invoke conversion + assistant_text = messages[msg_i].get("content") or "" # either string or none + if messages[msg_i].get("tool_calls", []): # support assistant tool invoke conversion assistant_text += convert_to_anthropic_tool_invoke_xml( # type: ignore messages[msg_i]["tool_calls"] ) @@ -1147,9 +1080,7 @@ def anthropic_messages_pt_xml(messages: list): if not new_messages or new_messages[0]["role"] != "user": if litellm.modify_params: - new_messages.insert( - 0, {"role": "user", "content": [{"type": "text", "text": "."}]} - ) + new_messages.insert(0, {"role": "user", "content": [{"type": "text", "text": "."}]}) else: raise Exception( "Invalid first message. Should always start with 'role'='user' for Anthropic. System prompt is sent separately for Anthropic. set 'litellm.modify_params = True' or 'litellm_settings:modify_params = True' on proxy, to insert a placeholder user message - '.' as the first message, " @@ -1158,9 +1089,7 @@ def anthropic_messages_pt_xml(messages: list): if new_messages[-1]["role"] == "assistant": for content in new_messages[-1]["content"]: if isinstance(content, dict) and content["type"] == "text": - content["text"] = content[ - "text" - ].rstrip() # no trailing whitespace for final assistant message + content["text"] = content["text"].rstrip() # no trailing whitespace for final assistant message return new_messages @@ -1256,9 +1185,7 @@ def _gemini_tool_call_invoke_helper( return function_call -def _encode_tool_call_id_with_signature( - tool_call_id: str, thought_signature: Optional[str] -) -> str: +def _encode_tool_call_id_with_signature(tool_call_id: str, thought_signature: Optional[str]) -> str: """ Embed thought signature into tool call ID for OpenAI client compatibility. @@ -1277,9 +1204,7 @@ def _encode_tool_call_id_with_signature( return tool_call_id -def _get_thought_signature_from_tool( - tool: dict, model: Optional[str] = None -) -> Optional[str]: +def _get_thought_signature_from_tool(tool: dict, model: Optional[str] = None) -> Optional[str]: """Extract thought signature from tool call's provider_specific_fields. If not provided try to extract thought signature from tool call id @@ -1303,10 +1228,7 @@ def _get_thought_signature_from_tool( signature = func_provider_fields.get("thought_signature") if signature: return signature - elif ( - hasattr(function, "provider_specific_fields") - and function.provider_specific_fields - ): + elif hasattr(function, "provider_specific_fields") and function.provider_specific_fields: if isinstance(function.provider_specific_fields, dict): signature = function.provider_specific_fields.get("thought_signature") if signature: @@ -1395,30 +1317,19 @@ def convert_to_gemini_tool_call_invoke( ) forward_tool_call_id = bool( - model - and VertexGeminiConfig._forward_gemini_function_call_id( - model, custom_llm_provider - ) + model and VertexGeminiConfig._forward_gemini_function_call_id(model, custom_llm_provider) ) if tool_calls is not None: for idx, tool in enumerate(tool_calls): if "function" in tool: - gemini_function_call: Optional[VertexFunctionCall] = ( - _gemini_tool_call_invoke_helper( - function_call_params=tool["function"], - tool_call_id=( - tool.get("id") if forward_tool_call_id else None - ), - ) + gemini_function_call: Optional[VertexFunctionCall] = _gemini_tool_call_invoke_helper( + function_call_params=tool["function"], + tool_call_id=(tool.get("id") if forward_tool_call_id else None), ) if gemini_function_call is not None: - part_dict: VertexPartType = { - "function_call": gemini_function_call - } - thought_signature = _get_thought_signature_from_tool( - dict(tool), model=model - ) + part_dict: VertexPartType = {"function_call": gemini_function_call} + thought_signature = _get_thought_signature_from_tool(dict(tool), model=model) if thought_signature: part_dict["thoughtSignature"] = thought_signature @@ -1430,30 +1341,20 @@ def convert_to_gemini_tool_call_invoke( ) ) elif function_call is not None: - gemini_function_call = _gemini_tool_call_invoke_helper( - function_call_params=function_call - ) + gemini_function_call = _gemini_tool_call_invoke_helper(function_call_params=function_call) if gemini_function_call is not None: - part_dict_function: VertexPartType = { - "function_call": gemini_function_call - } + part_dict_function: VertexPartType = {"function_call": gemini_function_call} # Extract thought signature from function_call's provider_specific_fields thought_signature = None provider_fields = ( - function_call.get("provider_specific_fields") - if isinstance(function_call, dict) - else {} + function_call.get("provider_specific_fields") if isinstance(function_call, dict) else {} ) if isinstance(provider_fields, dict): thought_signature = provider_fields.get("thought_signature") # If no signature found and model is gemini-3, use dummy signature - if ( - not thought_signature - and model - and VertexGeminiConfig._is_gemini_3_or_newer(model) - ): + if not thought_signature and model and VertexGeminiConfig._is_gemini_3_or_newer(model): thought_signature = _get_dummy_thought_signature() if thought_signature: @@ -1469,9 +1370,7 @@ def convert_to_gemini_tool_call_invoke( return _parts_list except Exception as e: raise Exception( - "Unable to convert openai tool calls={} to gemini tool calls. Received error={}".format( - message, str(e) - ) + "Unable to convert openai tool calls={} to gemini tool calls. Received error={}".format(message, str(e)) ) @@ -1524,14 +1423,10 @@ def convert_to_gemini_tool_call_result( if len(mime_rest) == 2 and mime_rest[0].startswith("image/"): # Strip any extra parameters (e.g. ";charset=UTF-8") from the MIME segment clean_mime = mime_rest[0].split(";")[0].strip() - inline_data_list.append( - BlobType(data=mime_rest[1], mime_type=clean_mime) - ) + inline_data_list.append(BlobType(data=mime_rest[1], mime_type=clean_mime)) content_str = "" except Exception as e: - verbose_logger.warning( - f"Failed to parse data URL in tool response: {e}" - ) + verbose_logger.warning(f"Failed to parse data URL in tool response: {e}") elif isinstance(message["content"], List): content_list = message["content"] for content in content_list: @@ -1550,24 +1445,16 @@ def convert_to_gemini_tool_call_result( ) ) except Exception as e: - verbose_logger.warning( - f"Failed to process Anthropic image block in tool response: {e}" - ) + verbose_logger.warning(f"Failed to process Anthropic image block in tool response: {e}") elif content_type in ("input_image", "image_url"): # Extract image for inline_data (for Computer Use screenshots and tool results) image_url_data = content.get("image_url", "") - image_url = ( - image_url_data.get("url", "") - if isinstance(image_url_data, dict) - else image_url_data - ) + image_url = image_url_data.get("url", "") if isinstance(image_url_data, dict) else image_url_data if image_url: # Convert image to base64 blob format for Gemini try: - image_obj = convert_to_anthropic_image_obj( - image_url, format=None - ) + image_obj = convert_to_anthropic_image_obj(image_url, format=None) inline_data_list.append( BlobType( data=image_obj["data"], @@ -1575,9 +1462,7 @@ def convert_to_gemini_tool_call_result( ) ) except Exception as e: - verbose_logger.warning( - f"Failed to process image in tool response: {e}" - ) + verbose_logger.warning(f"Failed to process image in tool response: {e}") elif content_type in ("file", "input_file"): # Extract file for inline_data (for tool results with PDF, audio, video, etc.) file_data = content.get("file_data", "") @@ -1594,9 +1479,7 @@ def convert_to_gemini_tool_call_result( if file_data: # Convert file to base64 blob format for Gemini try: - file_obj = convert_to_anthropic_image_obj( - file_data, format=None - ) + file_obj = convert_to_anthropic_image_obj(file_data, format=None) inline_data_list.append( BlobType( data=file_obj["data"], @@ -1604,9 +1487,7 @@ def convert_to_gemini_tool_call_result( ) ) except Exception as e: - verbose_logger.warning( - f"Failed to process file in tool response: {e}" - ) + verbose_logger.warning(f"Failed to process file in tool response: {e}") name: Optional[str] = message.get("name", "") # type: ignore # Recover name from last message with tool calls @@ -1615,11 +1496,7 @@ def convert_to_gemini_tool_call_result( msg_tool_call_id = message.get("tool_call_id", None) for tool in tools: prev_tool_call_id = tool.get("id", None) - if ( - msg_tool_call_id - and prev_tool_call_id - and msg_tool_call_id == prev_tool_call_id - ): + if msg_tool_call_id and prev_tool_call_id and msg_tool_call_id == prev_tool_call_id: name = tool.get("function", {}).get("name", "") # Echo the OpenAI tool_call_id on functionResponse (strip thought-signature suffix). @@ -1630,9 +1507,7 @@ def convert_to_gemini_tool_call_result( ) gemini_call_id: Optional[str] = None - if model and VertexGeminiConfig._forward_gemini_function_call_id( - model, custom_llm_provider - ): + if model and VertexGeminiConfig._forward_gemini_function_call_id(model, custom_llm_provider): raw_tool_call_id = message.get("tool_call_id") if raw_tool_call_id and isinstance(raw_tool_call_id, str): stripped_id = raw_tool_call_id.split(THOUGHT_SIGNATURE_SEPARATOR, 1)[0] @@ -1677,9 +1552,7 @@ def convert_to_gemini_tool_call_result( # For multimodal function responses, Gemini expects media parts nested # inside functionResponse.parts instead of sibling content parts. if inline_data_list: - _function_response["parts"] = [ - {"inline_data": inline_data} for inline_data in inline_data_list - ] + _function_response["parts"] = [{"inline_data": inline_data} for inline_data in inline_data_list] return [_part] return _part @@ -1784,38 +1657,22 @@ def convert_to_anthropic_tool_result( anthropic_content_list.append(text_content) elif content["type"] == "image_url": image_url_value = content["image_url"] - format = ( - image_url_value.get("format") - if isinstance(image_url_value, dict) - else None - ) - url_str = ( - image_url_value.get("url") - if isinstance(image_url_value, dict) - else image_url_value - ) + format = image_url_value.get("format") if isinstance(image_url_value, dict) else None + url_str = image_url_value.get("url") if isinstance(image_url_value, dict) else image_url_value # Data URIs with non-image mime types (e.g. application/pdf) must # translate to Anthropic document blocks, not image blocks — # wrapping a PDF in `type: "image"` is rejected by the API. - if isinstance(url_str, str) and _is_anthropic_document_data_uri( - url_str - ): + if isinstance(url_str, str) and _is_anthropic_document_data_uri(url_str): synth_file_message: ChatCompletionFileObject = { "type": "file", "file": {"file_data": url_str}, } - _document_block = anthropic_process_openai_file_message( - synth_file_message - ) + _document_block = anthropic_process_openai_file_message(synth_file_message) _document_block = add_cache_control_to_content( - anthropic_content_element=cast( - AnthropicMessagesDocumentParam, _document_block - ), + anthropic_content_element=cast(AnthropicMessagesDocumentParam, _document_block), original_content_element=content, ) - anthropic_content_list.append( - cast(AnthropicMessagesDocumentParam, _document_block) - ) + anthropic_content_list.append(cast(AnthropicMessagesDocumentParam, _document_block)) else: _anthropic_image_param = create_anthropic_image_param( image_url_value, @@ -1826,16 +1683,12 @@ def convert_to_anthropic_tool_result( anthropic_content_element=_anthropic_image_param, original_content_element=content, ) - anthropic_content_list.append( - cast(AnthropicMessagesImageParam, _anthropic_image_param) - ) + anthropic_content_list.append(cast(AnthropicMessagesImageParam, _anthropic_image_param)) elif content["type"] == "file": file_content = cast(ChatCompletionFileObject, content) _file_block = anthropic_process_openai_file_message(file_content) _file_block = add_cache_control_to_content( - anthropic_content_element=cast( - AnthropicMessagesDocumentParam, _file_block - ), + anthropic_content_element=cast(AnthropicMessagesDocumentParam, _file_block), original_content_element=content, ) anthropic_content_list.append(_file_block) @@ -1883,9 +1736,7 @@ def convert_function_to_anthropic_tool_invoke( _name = get_attribute_or_key(function_call, "name") or "" _arguments = get_attribute_or_key(function_call, "arguments") - tool_input = parse_tool_call_arguments( - _arguments, tool_name=_name, context="Anthropic function to tool invoke" - ) + tool_input = parse_tool_call_arguments(_arguments, tool_name=_name, context="Anthropic function to tool invoke") anthropic_tool_invoke = [ AnthropicMessagesToolUseParam( @@ -1947,9 +1798,7 @@ def convert_to_anthropic_tool_invoke( Fixes: https://github.com/BerriAI/litellm/issues/17737 """ - anthropic_tool_invoke: List[ - Union[AnthropicMessagesToolUseParam, Dict[str, Any]] - ] = [] + anthropic_tool_invoke: List[Union[AnthropicMessagesToolUseParam, Dict[str, Any]]] = [] for tool in tool_calls: if not get_attribute_or_key(tool, "type") == "function": @@ -2006,9 +1855,7 @@ def convert_to_anthropic_tool_invoke( ) if "cache_control" in _content_element: - _anthropic_tool_use_param["cache_control"] = _content_element[ - "cache_control" - ] + _anthropic_tool_use_param["cache_control"] = _content_element["cache_control"] anthropic_tool_invoke.append(_anthropic_tool_use_param) @@ -2039,15 +1886,15 @@ def _anthropic_content_element_factory( image_chunk: GenericImageParsingChunk, ) -> Union[AnthropicMessagesImageParam, AnthropicMessagesDocumentParam]: if image_chunk["media_type"] == "application/pdf": - _anthropic_content_element: Union[ - AnthropicMessagesDocumentParam, AnthropicMessagesImageParam - ] = AnthropicMessagesDocumentParam( - type="document", - source=AnthropicContentParamSource( - type="base64", - media_type=image_chunk["media_type"], - data=image_chunk["data"], - ), + _anthropic_content_element: Union[AnthropicMessagesDocumentParam, AnthropicMessagesImageParam] = ( + AnthropicMessagesDocumentParam( + type="document", + source=AnthropicContentParamSource( + type="base64", + media_type=image_chunk["media_type"], + data=image_chunk["data"], + ), + ) ) else: _anthropic_content_element = AnthropicMessagesImageParam( @@ -2158,21 +2005,15 @@ def anthropic_process_openai_file_message( ), ) elif content_block_type == "container_upload": - return_block_param = AnthropicMessagesContainerUploadParam( - type="container_upload", file_id=file_id - ) + return_block_param = AnthropicMessagesContainerUploadParam(type="container_upload", file_id=file_id) if return_block_param is None: raise Exception(f"Unable to parse anthropic file message: {message}") return return_block_param - raise Exception( - f"Either file_data or file_id must be present in the file message: {message}" - ) + raise Exception(f"Either file_data or file_id must be present in the file message: {message}") -_EMPTY_TEXT_PLACEHOLDER = ( - "[System: Empty message content sanitised to satisfy protocol]" -) +_EMPTY_TEXT_PLACEHOLDER = "[System: Empty message content sanitised to satisfy protocol]" def _sanitize_empty_text_content( @@ -2373,9 +2214,7 @@ def _is_orphaned_tool_result( break if not found_matching_tool_call: - verbose_logger.debug( - "_is_orphaned_tool_result: Found orphaned tool result with redacted tool_call_id" - ) + verbose_logger.debug("_is_orphaned_tool_result: Found orphaned tool result with redacted tool_call_id") return True return False @@ -2420,9 +2259,7 @@ def sanitize_messages_for_tool_calling( # Case A: Check if assistant message has tool_calls without following tool results if current_message.get("role") == "assistant": - result_messages, messages_consumed = _add_missing_tool_results( - current_message, messages, i - ) + result_messages, messages_consumed = _add_missing_tool_results(current_message, messages, i) # If dummy tool results were added, extend sanitized_messages and skip consumed messages if len(result_messages) > 1: @@ -2477,11 +2314,7 @@ def sanitize_messages_for_tool_calling( seen_in_block = {} if duplicates_to_remove: - sanitized_messages = [ - msg - for idx, msg in enumerate(sanitized_messages) - if idx not in duplicates_to_remove - ] + sanitized_messages = [msg for idx, msg in enumerate(sanitized_messages) if idx not in duplicates_to_remove] return sanitized_messages @@ -2564,17 +2397,11 @@ def anthropic_messages_pt( for m in user_message_types_block["content"]: if m.get("type", "") == "image_url": m = cast(ChatCompletionImageObject, m) - format = ( - m["image_url"].get("format") - if isinstance(m["image_url"], dict) - else None - ) + format = m["image_url"].get("format") if isinstance(m["image_url"], dict) else None # Convert ChatCompletionImageUrlObject to dict if needed image_url_value = m["image_url"] if isinstance(image_url_value, str): - image_url_input: Union[str, dict[str, Any]] = ( - image_url_value - ) + image_url_input: Union[str, dict[str, Any]] = image_url_value else: # ChatCompletionImageUrlObject or dict case - convert to dict image_url_input = { @@ -2584,11 +2411,7 @@ def anthropic_messages_pt( # Bedrock invoke models have format: invoke/... # Vertex AI Anthropic also doesn't support URL sources for images is_bedrock_invoke = model.lower().startswith("invoke/") - is_vertex_ai = ( - llm_provider.startswith("vertex_ai") - if llm_provider - else False - ) + is_vertex_ai = llm_provider.startswith("vertex_ai") if llm_provider else False force_base64 = is_bedrock_invoke or is_vertex_ai _anthropic_content_element = create_anthropic_image_param( image_url_input, @@ -2601,43 +2424,33 @@ def anthropic_messages_pt( ) if "cache_control" in _content_element: - _anthropic_content_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_content_element["cache_control"] = _content_element["cache_control"] user_content.append(_anthropic_content_element) elif m.get("type", "") == "text": m = cast(ChatCompletionTextObject, m) - _anthropic_text_content_element = ( - AnthropicMessagesTextParam( - type="text", - text=m["text"], - ) + _anthropic_text_content_element = AnthropicMessagesTextParam( + type="text", + text=m["text"], ) _content_element = add_cache_control_to_content( anthropic_content_element=_anthropic_text_content_element, original_content_element=dict(m), ) - _content_element = cast( - AnthropicMessagesTextParam, _content_element - ) + _content_element = cast(AnthropicMessagesTextParam, _content_element) user_content.append(_content_element) elif m.get("type", "") == "document": _document_content_element = cast( AnthropicMessagesDocumentParam, add_cache_control_to_content( - anthropic_content_element=cast( - AnthropicMessagesDocumentParam, m - ), + anthropic_content_element=cast(AnthropicMessagesDocumentParam, m), original_content_element=dict(m), ), ) user_content.append(_document_content_element) elif m.get("type", "") == "file": - _file_content_element = ( - anthropic_process_openai_file_message( - cast(ChatCompletionFileObject, m) - ) + _file_content_element = anthropic_process_openai_file_message( + cast(ChatCompletionFileObject, m) ) _file_content_element = add_cache_control_to_content( anthropic_content_element=cast( @@ -2663,21 +2476,14 @@ def anthropic_messages_pt( ) if "cache_control" in _content_element: - _anthropic_content_text_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_content_text_element["cache_control"] = _content_element["cache_control"] user_content.append(_anthropic_content_text_element) - elif ( - user_message_types_block["role"] == "tool" - or user_message_types_block["role"] == "function" - ): + elif user_message_types_block["role"] == "tool" or user_message_types_block["role"] == "function": # OpenAI's tool message content will always be a string user_content.append( - convert_to_anthropic_tool_result( - user_message_types_block, force_base64=force_base64 - ) + convert_to_anthropic_tool_result(user_message_types_block, force_base64=force_base64) ) msg_i += 1 @@ -2694,13 +2500,9 @@ def anthropic_messages_pt( assistant_content_block: ChatCompletionAssistantMessage = messages[msg_i] # type: ignore # Extract compaction_blocks from provider_specific_fields and add them first - _provider_specific_fields_raw = assistant_content_block.get( - "provider_specific_fields" - ) + _provider_specific_fields_raw = assistant_content_block.get("provider_specific_fields") if isinstance(_provider_specific_fields_raw, dict): - _compaction_blocks = _provider_specific_fields_raw.get( - "compaction_blocks" - ) + _compaction_blocks = _provider_specific_fields_raw.get("compaction_blocks") if _compaction_blocks and isinstance(_compaction_blocks, list): # Add compaction blocks at the beginning of assistant content : https://platform.claude.com/docs/en/build-with-claude/compaction assistant_content.extend(_compaction_blocks) # type: ignore @@ -2715,25 +2517,15 @@ def anthropic_messages_pt( _has_server_tool_calls = False if assistant_tool_calls is not None: for _tc in assistant_tool_calls: - _tc_id = ( - _tc.get("id") - if isinstance(_tc, dict) - else getattr(_tc, "id", None) - ) - if ( - _tc_id - and isinstance(_tc_id, str) - and _tc_id.startswith("srvtoolu_") - ): + _tc_id = _tc.get("id") if isinstance(_tc, dict) else getattr(_tc, "id", None) + if _tc_id and isinstance(_tc_id, str) and _tc_id.startswith("srvtoolu_"): _has_server_tool_calls = True break if ( thinking_blocks is not None and _has_server_tool_calls - and isinstance( - assistant_content_block.get("content", None), (str, type(None)) - ) + and isinstance(assistant_content_block.get("content", None), (str, type(None))) ): # INTERLEAVED MODE: When we have both thinking blocks and server # tool calls (e.g. web search), Anthropic's original response @@ -2743,17 +2535,11 @@ def anthropic_messages_pt( # verifies thinking block signatures based on position. # Build the tool call groups (server_tool_use + its result) - _provider_specific_fields_raw_tc = assistant_content_block.get( - "provider_specific_fields" - ) + _provider_specific_fields_raw_tc = assistant_content_block.get("provider_specific_fields") _provider_specific_fields_tc: Dict[str, Any] = {} if isinstance(_provider_specific_fields_raw_tc, dict): - _provider_specific_fields_tc = cast( - Dict[str, Any], _provider_specific_fields_raw_tc - ) - _web_search_results_tc = _provider_specific_fields_tc.get( - "web_search_results" - ) + _provider_specific_fields_tc = cast(Dict[str, Any], _provider_specific_fields_raw_tc) + _web_search_results_tc = _provider_specific_fields_tc.get("web_search_results") _tool_results_tc = _provider_specific_fields_tc.get("tool_results") tool_invoke_results = convert_to_anthropic_tool_invoke( assistant_tool_calls, # type: ignore @@ -2767,11 +2553,7 @@ def anthropic_messages_pt( regular_tool_uses: List[Any] = [] _current_group: List[Any] = [] for item in tool_invoke_results: - item_type = ( - item.get("type", "") - if isinstance(item, dict) - else getattr(item, "type", "") - ) + item_type = item.get("type", "") if isinstance(item, dict) else getattr(item, "type", "") if item_type == "server_tool_use": if _current_group: server_tool_groups.append(_current_group) @@ -2798,9 +2580,7 @@ def anthropic_messages_pt( original_content_element=dict(assistant_content_block), ) if "cache_control" in _content_element: - _anthropic_text_content_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_text_content_element["cache_control"] = _content_element["cache_control"] text_element = _anthropic_text_content_element # Interleave: each thinking block precedes its server tool group. @@ -2818,18 +2598,12 @@ def anthropic_messages_pt( assistant_content.append(thinking_blocks[tb_idx]) tb_idx += 1 for block in server_tool_groups[grp_idx]: - item_id = ( - block.get("id") - if isinstance(block, dict) - else getattr(block, "id", None) - ) + item_id = block.get("id") if isinstance(block, dict) else getattr(block, "id", None) if item_id and item_id in unique_tool_ids: continue if item_id: unique_tool_ids.add(item_id) - assistant_content.append( - cast(AnthropicMessagesAssistantMessageValues, block) - ) + assistant_content.append(cast(AnthropicMessagesAssistantMessageValues, block)) grp_idx += 1 elif tb_idx < num_tb: # More thinking blocks than tool groups - emit before text @@ -2838,18 +2612,12 @@ def anthropic_messages_pt( else: # More tool groups than thinking blocks - emit remaining for block in server_tool_groups[grp_idx]: - item_id = ( - block.get("id") - if isinstance(block, dict) - else getattr(block, "id", None) - ) + item_id = block.get("id") if isinstance(block, dict) else getattr(block, "id", None) if item_id and item_id in unique_tool_ids: continue if item_id: unique_tool_ids.add(item_id) - assistant_content.append( - cast(AnthropicMessagesAssistantMessageValues, block) - ) + assistant_content.append(cast(AnthropicMessagesAssistantMessageValues, block)) grp_idx += 1 # Add text block (if any) @@ -2858,18 +2626,12 @@ def anthropic_messages_pt( # Add regular (non-server) tool calls at the end for item in regular_tool_uses: - item_id = ( - item.get("id") - if isinstance(item, dict) - else getattr(item, "id", None) - ) + item_id = item.get("id") if isinstance(item, dict) else getattr(item, "id", None) if item_id and item_id in unique_tool_ids: continue if item_id: unique_tool_ids.add(item_id) - assistant_content.append( - cast(AnthropicMessagesAssistantMessageValues, item) - ) + assistant_content.append(cast(AnthropicMessagesAssistantMessageValues, item)) # Mark tool_calls as already processed so they are not added again assistant_tool_calls = None @@ -2886,9 +2648,7 @@ def anthropic_messages_pt( _content_is_list = "content" in assistant_content_block and isinstance( assistant_content_block["content"], list ) - _content_list = ( - assistant_content_block.get("content") if _content_is_list else None - ) + _content_list = assistant_content_block.get("content") if _content_is_list else None _list_has_thinking = False if _content_is_list and _content_list is not None: for _item in _content_list: @@ -2922,17 +2682,13 @@ def anthropic_messages_pt( elif ( m.get("type", "") == "text" and len(text_block) > 0 ): # don't pass empty text blocks. anthropic api raises errors. - anthropic_message = AnthropicMessagesTextParam( - type="text", text=text_block - ) + anthropic_message = AnthropicMessagesTextParam(type="text", text=text_block) _cached_message = add_cache_control_to_content( anthropic_content_element=anthropic_message, original_content_element=dict(m), ) - assistant_content.append( - cast(AnthropicMessagesTextParam, _cached_message) - ) + assistant_content.append(cast(AnthropicMessagesTextParam, _cached_message)) # handle server_tool_use blocks (tool search, web search, etc.) # Pass through as-is since these are Anthropic-native content types elif m.get("type", "") == "server_tool_use": @@ -2945,9 +2701,7 @@ def anthropic_messages_pt( elif ( "content" in assistant_content_block and isinstance(assistant_content_block["content"], str) - and assistant_content_block[ - "content" - ] # don't pass empty text blocks. anthropic api raises errors. + and assistant_content_block["content"] # don't pass empty text blocks. anthropic api raises errors. ): _anthropic_text_content_element = AnthropicMessagesTextParam( type="text", @@ -2960,29 +2714,19 @@ def anthropic_messages_pt( ) if "cache_control" in _content_element: - _anthropic_text_content_element["cache_control"] = ( - _content_element["cache_control"] - ) + _anthropic_text_content_element["cache_control"] = _content_element["cache_control"] assistant_content.append(_anthropic_text_content_element) - if ( - assistant_tool_calls is not None - ): # support assistant tool invoke conversion + if assistant_tool_calls is not None: # support assistant tool invoke conversion # Get web_search_results and tool_results from provider_specific_fields # for server_tool_use reconstruction. # Fixes: https://github.com/BerriAI/litellm/issues/17737 - _provider_specific_fields_raw = assistant_content_block.get( - "provider_specific_fields" - ) + _provider_specific_fields_raw = assistant_content_block.get("provider_specific_fields") _provider_specific_fields: Dict[str, Any] = {} if isinstance(_provider_specific_fields_raw, dict): - _provider_specific_fields = cast( - Dict[str, Any], _provider_specific_fields_raw - ) - _web_search_results = _provider_specific_fields.get( - "web_search_results" - ) + _provider_specific_fields = cast(Dict[str, Any], _provider_specific_fields_raw) + _web_search_results = _provider_specific_fields.get("web_search_results") _tool_results = _provider_specific_fields.get("tool_results") tool_invoke_results = convert_to_anthropic_tool_invoke( assistant_tool_calls, @@ -2994,27 +2738,19 @@ def anthropic_messages_pt( # This can happen when merging history that already contains the tool calls for item in tool_invoke_results: # tool_use items are typically dicts, but handle objects just in case - item_id = ( - item.get("id") - if isinstance(item, dict) - else getattr(item, "id", None) - ) + item_id = item.get("id") if isinstance(item, dict) else getattr(item, "id", None) if item_id: if item_id in unique_tool_ids: continue unique_tool_ids.add(item_id) - assistant_content.append( - cast(AnthropicMessagesAssistantMessageValues, item) - ) + assistant_content.append(cast(AnthropicMessagesAssistantMessageValues, item)) assistant_function_call = assistant_content_block.get("function_call") if assistant_function_call is not None: - assistant_content.extend( - convert_function_to_anthropic_tool_invoke(assistant_function_call) - ) + assistant_content.extend(convert_function_to_anthropic_tool_invoke(assistant_function_call)) msg_i += 1 @@ -3034,9 +2770,7 @@ def anthropic_messages_pt( elif isinstance(new_messages[-1]["content"], list): for content in new_messages[-1]["content"]: if isinstance(content, dict) and content["type"] == "text": - content["text"] = content[ - "text" - ].rstrip() # no trailing whitespace for final assistant message + content["text"] = content["text"].rstrip() # no trailing whitespace for final assistant message return new_messages @@ -3189,11 +2923,7 @@ def convert_openai_message_to_cohere_tool_result( msg_tool_call_id = message.get("tool_call_id", None) for tool in tools: prev_tool_call_id = tool.get("id", None) - if ( - msg_tool_call_id - and prev_tool_call_id - and msg_tool_call_id == prev_tool_call_id - ): + if msg_tool_call_id and prev_tool_call_id and msg_tool_call_id == prev_tool_call_id: name = tool.get("function", {}).get("name", "") arguments_str = tool.get("function", {}).get("arguments", "") if arguments_str is not None and len(arguments_str) > 0: @@ -3262,14 +2992,8 @@ def convert_to_cohere_tool_invoke(tool_calls: list) -> List[ToolCallObject]: cohere_tool_invoke: List[ToolCallObject] = [ { - "name": get_attribute_or_key( - get_attribute_or_key(tool, "function"), "name" - ), - "parameters": json.loads( - get_attribute_or_key( - get_attribute_or_key(tool, "function"), "arguments" - ) - ), + "name": get_attribute_or_key(get_attribute_or_key(tool, "function"), "name"), + "parameters": json.loads(get_attribute_or_key(get_attribute_or_key(tool, "function"), "arguments")), } for tool in tool_calls if get_attribute_or_key(tool, "type") == "function" @@ -3301,14 +3025,9 @@ def cohere_messages_pt_v2( ## GET MOST RECENT MESSAGE most_recent_message = messages.pop(-1) returned_message: Union[ToolResultObject, str] = "" - if ( - most_recent_message.get("role", "") is not None - and most_recent_message["role"] == "tool" - ): + if most_recent_message.get("role", "") is not None and most_recent_message["role"] == "tool": # tool result - returned_message = convert_openai_message_to_cohere_tool_result( - most_recent_message, tool_calls - ) + returned_message = convert_openai_message_to_cohere_tool_result(most_recent_message, tool_calls) else: content: Union[str, List] = most_recent_message.get("content") if isinstance(content, str): @@ -3353,35 +3072,23 @@ def cohere_messages_pt_v2( msg_i += 1 if len(system_content) > 0: - new_messages.append( - ChatHistorySystem(role="SYSTEM", message=system_content) - ) + new_messages.append(ChatHistorySystem(role="SYSTEM", message=system_content)) assistant_content: str = "" assistant_tool_calls: List[ToolCallObject] = [] ## MERGE CONSECUTIVE ASSISTANT CONTENT ## while msg_i < len(messages) and messages[msg_i]["role"] == "assistant": - if messages[msg_i].get("content", None) is not None and isinstance( - messages[msg_i]["content"], list - ): + if messages[msg_i].get("content", None) is not None and isinstance(messages[msg_i]["content"], list): for m in messages[msg_i]["content"]: if m.get("type", "") == "text": assistant_content += m["text"] - elif messages[msg_i].get("content") is not None and isinstance( - messages[msg_i]["content"], str - ): + elif messages[msg_i].get("content") is not None and isinstance(messages[msg_i]["content"], str): assistant_content += messages[msg_i]["content"] - if messages[msg_i].get( - "tool_calls", [] - ): # support assistant tool invoke conversion - assistant_tool_calls.extend( - convert_to_cohere_tool_invoke(messages[msg_i]["tool_calls"]) - ) + if messages[msg_i].get("tool_calls", []): # support assistant tool invoke conversion + assistant_tool_calls.extend(convert_to_cohere_tool_invoke(messages[msg_i]["tool_calls"])) if messages[msg_i].get("function_call"): - assistant_tool_calls.extend( - convert_to_cohere_tool_invoke(messages[msg_i]["function_call"]) - ) + assistant_tool_calls.extend(convert_to_cohere_tool_invoke(messages[msg_i]["function_call"])) msg_i += 1 @@ -3397,18 +3104,12 @@ def cohere_messages_pt_v2( ## MERGE CONSECUTIVE TOOL RESULTS tool_results: List[ToolResultObject] = [] while msg_i < len(messages) and messages[msg_i]["role"] in tool_message_types: - tool_results.append( - convert_openai_message_to_cohere_tool_result( - messages[msg_i], tool_calls - ) - ) + tool_results.append(convert_openai_message_to_cohere_tool_result(messages[msg_i], tool_calls)) msg_i += 1 if len(tool_results) > 0: - new_messages.append( - ChatHistoryToolResult(role="TOOL", tool_results=tool_results) - ) + new_messages.append(ChatHistoryToolResult(role="TOOL", tool_results=tool_results)) if msg_i == init_msg_i: # prevent infinite loops raise litellm.BadRequestError( @@ -3427,9 +3128,7 @@ def cohere_message_pt(messages: list): for message in messages: # check if this is a tool_call result if message["role"] == "tool": - tool_result = convert_openai_message_to_cohere_tool_result( - message, tool_calls=tool_calls - ) + tool_result = convert_openai_message_to_cohere_tool_result(message, tool_calls=tool_calls) tool_results.append(tool_result) elif message.get("content"): prompt += message["content"] + "\n\n" @@ -3456,9 +3155,7 @@ class AmazonTitanConstants(Enum): prompt += f"{AmazonTitanConstants.HUMAN_PROMPT.value}{message['content']}" else: prompt += f"{AmazonTitanConstants.AI_PROMPT.value}{message['content']}" - if ( - idx == 0 and message["role"] == "assistant" - ): # ensure the prompt always starts with `\n\nHuman: ` + if idx == 0 and message["role"] == "assistant": # ensure the prompt always starts with `\n\nHuman: ` prompt = f"{AmazonTitanConstants.HUMAN_PROMPT.value}" + prompt if messages[-1]["role"] != "assistant": prompt += f"{AmazonTitanConstants.AI_PROMPT.value}" @@ -3481,9 +3178,7 @@ def _load_image_from_url(image_url): # Check the response's content type to ensure it is an image content_type = response.headers.get("content-type") if not content_type or "image" not in content_type: - raise ValueError( - f"URL does not point to a valid image (content-type: {content_type})" - ) + raise ValueError(f"URL does not point to a valid image (content-type: {content_type})") # Load the image from the response content return Image.open(BytesIO(response.content)) @@ -3534,9 +3229,7 @@ def _gemini_vision_convert_messages(messages: list): try: from PIL import Image except Exception: - raise Exception( - "gemini image conversion failed please run `pip install Pillow`" - ) + raise Exception("gemini image conversion failed please run `pip install Pillow`") if "base64" in img: # Case 2: Base64 image data @@ -3582,9 +3275,7 @@ def gemini_text_image_pt(messages: list): try: pass # type: ignore except Exception: - raise Exception( - "Importing google.generativeai failed, please run 'pip install -q google-generativeai" - ) + raise Exception("Importing google.generativeai failed, please run 'pip install -q google-generativeai") prompt = "" images = [] @@ -3682,9 +3373,7 @@ class BedrockImageProcessor: """Handles both sync and async image processing for Bedrock conversations.""" @staticmethod - def _post_call_image_processing( - response: httpx.Response, image_url: str = "" - ) -> Tuple[str, str]: + def _post_call_image_processing(response: httpx.Response, image_url: str = "") -> Tuple[str, str]: # Check the response's content type to ensure it is an image content_type = response.headers.get("content-type") @@ -3713,9 +3402,7 @@ async def get_image_details_async(image_url) -> Tuple[str, str]: response = await async_safe_get(client, image_url) response.raise_for_status() # Raise an exception for HTTP errors - return BedrockImageProcessor._post_call_image_processing( - response, image_url - ) + return BedrockImageProcessor._post_call_image_processing(response, image_url) except Exception as e: raise e @@ -3728,9 +3415,7 @@ def get_image_details(image_url) -> Tuple[str, str]: response = safe_get(client, image_url) response.raise_for_status() # Raise an exception for HTTP errors - return BedrockImageProcessor._post_call_image_processing( - response, image_url - ) + return BedrockImageProcessor._post_call_image_processing(response, image_url) except Exception as e: raise e @@ -3757,22 +3442,14 @@ def _parse_base64_image(image_url: str) -> Tuple[str, str, str]: def _validate_format(mime_type: str, image_format: str) -> str: """Validate image format and mime type for both images and documents.""" - supported_image_formats = ( - litellm.AmazonConverseConfig().get_supported_image_types() - ) - supported_doc_formats = ( - litellm.AmazonConverseConfig().get_supported_document_types() - ) - supported_video_formats = ( - litellm.AmazonConverseConfig().get_supported_video_types() - ) + supported_image_formats = litellm.AmazonConverseConfig().get_supported_image_types() + supported_doc_formats = litellm.AmazonConverseConfig().get_supported_document_types() + supported_video_formats = litellm.AmazonConverseConfig().get_supported_video_types() document_types = ["application", "text"] is_document = any(mime_type.startswith(doc_type) for doc_type in document_types) - supported_image_and_video_formats: List[str] = ( - supported_video_formats + supported_image_formats - ) + supported_image_and_video_formats: List[str] = supported_video_formats + supported_image_formats if is_document: return BedrockImageProcessor._get_document_format( @@ -3810,9 +3487,7 @@ def _get_document_format(mime_type: str, supported_doc_formats: List[str]) -> st """ valid_extensions: Optional[List[str]] = None potential_extensions = mimetypes.guess_all_extensions(mime_type, strict=False) - valid_extensions = [ - ext[1:] for ext in potential_extensions if ext[1:] in supported_doc_formats - ] + valid_extensions = [ext[1:] for ext in potential_extensions if ext[1:] in supported_doc_formats] # Fallback to types/files.py if mimetypes doesn't return valid extensions ################# @@ -3837,22 +3512,15 @@ def _get_document_format(mime_type: str, supported_doc_formats: List[str]) -> st return valid_extensions[0] @staticmethod - def _create_bedrock_block( - image_bytes: str, mime_type: str, image_format: str - ) -> BedrockContentBlock: + def _create_bedrock_block(image_bytes: str, mime_type: str, image_format: str) -> BedrockContentBlock: """Create appropriate Bedrock content block based on mime type.""" _blob = BedrockSourceBlock(bytes=image_bytes) document_types = ["application", "text"] is_document = any(mime_type.startswith(doc_type) for doc_type in document_types) - supported_video_formats = ( - litellm.AmazonConverseConfig().get_supported_video_types() - ) - is_video = any( - image_format.startswith(video_type) - for video_type in supported_video_formats - ) + supported_video_formats = litellm.AmazonConverseConfig().get_supported_video_types() + is_video = any(image_format.startswith(video_type) for video_type in supported_video_formats) HASH_SAMPLE_BYTES = 64 * 1024 # hash up to 64 KB of data @@ -3873,9 +3541,7 @@ def _create_bedrock_block( # --- Compute deterministic hash (sample + total length) --- hasher = hashlib.sha256() hasher.update(sample) - hasher.update( - str(len(normalized)).encode("utf-8") - ) # include full length for uniqueness + hasher.update(str(len(normalized)).encode("utf-8")) # include full length for uniqueness full_hash = hasher.hexdigest() content_hash = full_hash[:16] # short deterministic ID @@ -3890,18 +3556,12 @@ def _create_bedrock_block( ) ) elif is_video: - return BedrockContentBlock( - video=BedrockVideoBlock(source=_blob, format=image_format) - ) + return BedrockContentBlock(video=BedrockVideoBlock(source=_blob, format=image_format)) else: - return BedrockContentBlock( - image=BedrockImageBlock(source=_blob, format=image_format) - ) + return BedrockContentBlock(image=BedrockImageBlock(source=_blob, format=image_format)) @classmethod - def process_image_sync( - cls, image_url: str, format: Optional[str] = None - ) -> BedrockContentBlock: + def process_image_sync(cls, image_url: str, format: Optional[str] = None) -> BedrockContentBlock: """Synchronous image processing.""" if "base64" in image_url: @@ -3910,9 +3570,7 @@ def process_image_sync( img_bytes, mime_type = BedrockImageProcessor.get_image_details(image_url) image_format = mime_type.split("/")[1] else: - raise ValueError( - "Unsupported image type. Expected either image url or base64 encoded string" - ) + raise ValueError("Unsupported image type. Expected either image url or base64 encoded string") if format: mime_type = format @@ -3922,22 +3580,16 @@ def process_image_sync( return cls._create_bedrock_block(img_bytes, mime_type, image_format) @classmethod - async def process_image_async( - cls, image_url: str, format: Optional[str] - ) -> BedrockContentBlock: + async def process_image_async(cls, image_url: str, format: Optional[str]) -> BedrockContentBlock: """Asynchronous image processing.""" if "base64" in image_url: img_bytes, mime_type, image_format = cls._parse_base64_image(image_url) elif "http://" in image_url or "https://" in image_url: - img_bytes, mime_type = await BedrockImageProcessor.get_image_details_async( - image_url - ) + img_bytes, mime_type = await BedrockImageProcessor.get_image_details_async(image_url) image_format = mime_type.split("/")[1] else: - raise ValueError( - "Unsupported image type. Expected either image url or base64 encoded string" - ) + raise ValueError("Unsupported image type. Expected either image url or base64 encoded string") if format: # override with user-defined params mime_type = format @@ -4018,45 +3670,29 @@ def _convert_to_bedrock_tool_call_invoke( if parsed_objects: # First object keeps the original tool id. for obj_idx, obj in enumerate(parsed_objects): - block_id = ( - tool_id if obj_idx == 0 else f"{tool_id}_{obj_idx}" - ) - bedrock_tool = BedrockToolUseBlock( - input=obj, name=name, toolUseId=block_id - ) - _parts_list.append( - BedrockContentBlock(toolUse=bedrock_tool) - ) + block_id = tool_id if obj_idx == 0 else f"{tool_id}_{obj_idx}" + bedrock_tool = BedrockToolUseBlock(input=obj, name=name, toolUseId=block_id) + _parts_list.append(BedrockContentBlock(toolUse=bedrock_tool)) # cache_control applies to the whole original # tool call; attach after the last split block. if tool.get("cache_control", None) is not None: - _parts_list.append( - BedrockContentBlock( - cachePoint=CachePointBlock(type="default") - ) - ) + _parts_list.append(BedrockContentBlock(cachePoint=CachePointBlock(type="default"))) continue # Fallback: no objects extracted — use empty dict. arguments_dict = {} - bedrock_tool = BedrockToolUseBlock( - input=arguments_dict, name=name, toolUseId=tool_id - ) + bedrock_tool = BedrockToolUseBlock(input=arguments_dict, name=name, toolUseId=tool_id) bedrock_content_block = BedrockContentBlock(toolUse=bedrock_tool) _parts_list.append(bedrock_content_block) # Check for cache_control and add a separate cachePoint block if tool.get("cache_control", None) is not None: - cache_point_block = BedrockContentBlock( - cachePoint=CachePointBlock(type="default") - ) + cache_point_block = BedrockContentBlock(cachePoint=CachePointBlock(type="default")) _parts_list.append(cache_point_block) return _parts_list except Exception as e: raise Exception( - "Unable to convert openai tool calls={} to bedrock tool calls. Received error={}".format( - tool_calls, str(e) - ) + "Unable to convert openai tool calls={} to bedrock tool calls. Received error={}".format(tool_calls, str(e)) ) @@ -4067,17 +3703,12 @@ def _append_bedrock_tool_result_media_block( content_type: str, ) -> None: if "image" in processed_block: - tool_result_content_blocks.append( - BedrockToolResultContentBlock(image=processed_block["image"]) - ) + tool_result_content_blocks.append(BedrockToolResultContentBlock(image=processed_block["image"])) elif "document" in processed_block: - tool_result_content_blocks.append( - BedrockToolResultContentBlock(document=processed_block["document"]) - ) + tool_result_content_blocks.append(BedrockToolResultContentBlock(document=processed_block["document"])) else: verbose_logger.warning( - "Bedrock Converse: unrecognized BedrockContentBlock keys " - "%s for %s tool-result block %s; dropping.", + "Bedrock Converse: unrecognized BedrockContentBlock keys %s for %s tool-result block %s; dropping.", list(processed_block.keys()), content_type, content, @@ -4098,9 +3729,7 @@ def _append_bedrock_tool_result_image_url_block( image_url=image_url, format=format, ) - _append_bedrock_tool_result_media_block( - tool_result_content_blocks, processed_block, content, "image_url" - ) + _append_bedrock_tool_result_media_block(tool_result_content_blocks, processed_block, content, "image_url") def _append_bedrock_tool_result_file_block( @@ -4122,9 +3751,7 @@ def _append_bedrock_tool_result_file_block( image_url=cast(str, file_id or file_data), format=file_obj.get("format"), ) - _append_bedrock_tool_result_media_block( - tool_result_content_blocks, processed_block, content, "file" - ) + _append_bedrock_tool_result_media_block(tool_result_content_blocks, processed_block, content, "file") def _parse_bedrock_tool_result_content_list( @@ -4133,13 +3760,9 @@ def _parse_bedrock_tool_result_content_list( tool_result_content_blocks: List[BedrockToolResultContentBlock] = [] for content in content_list: if content["type"] == "text": - tool_result_content_blocks.append( - BedrockToolResultContentBlock(text=content["text"]) - ) + tool_result_content_blocks.append(BedrockToolResultContentBlock(text=content["text"])) elif content["type"] == "image_url": - _append_bedrock_tool_result_image_url_block( - tool_result_content_blocks, content - ) + _append_bedrock_tool_result_image_url_block(tool_result_content_blocks, content) elif content["type"] == "file": _append_bedrock_tool_result_file_block(tool_result_content_blocks, content) return tool_result_content_blocks @@ -4161,9 +3784,7 @@ def _build_bedrock_tool_result_content_blocks( if not isinstance(result, dict): continue tool_result_content_blocks.append( - BedrockToolResultContentBlock( - searchResult=cast(SearchResultBlock, result) - ) + BedrockToolResultContentBlock(searchResult=cast(SearchResultBlock, result)) ) if tool_result_content_blocks: return tool_result_content_blocks, True @@ -4219,16 +3840,12 @@ def _convert_to_bedrock_tool_call_result( """ - """ - tool_result_content_blocks, used_search_results = ( - _build_bedrock_tool_result_content_blocks(message) - ) + tool_result_content_blocks, used_search_results = _build_bedrock_tool_result_content_blocks(message) message.get("name", "") id = str(message.get("tool_call_id", str(uuid.uuid4()))) - tool_result = BedrockToolResultBlock( - content=tool_result_content_blocks, toolUseId=id - ) + tool_result = BedrockToolResultBlock(content=tool_result_content_blocks, toolUseId=id) if used_search_results: tool_result["status"] = cast(Literal["success"], "success") @@ -4369,9 +3986,7 @@ def _sort_key(block: BedrockContentBlock) -> int: def _insert_assistant_continue_message( messages: List[BedrockMessageBlock], - assistant_continue_message: Optional[ - Union[str, ChatCompletionAssistantMessage] - ] = None, + assistant_continue_message: Optional[Union[str, ChatCompletionAssistantMessage]] = None, ) -> List[BedrockMessageBlock]: """ Add dummy message between user/tool result blocks. @@ -4395,9 +4010,7 @@ def _insert_assistant_continue_message( ) ) elif litellm.modify_params: - text = convert_content_list_to_str( - cast(ChatCompletionAssistantMessage, DEFAULT_ASSISTANT_CONTINUE_MESSAGE) - ) + text = convert_content_list_to_str(cast(ChatCompletionAssistantMessage, DEFAULT_ASSISTANT_CONTINUE_MESSAGE)) messages.append( BedrockMessageBlock( role="assistant", @@ -4422,9 +4035,7 @@ def get_user_message_block_or_continue_message( content_block = message.get("content", None) # Handle None case - if content_block is None or ( - user_continue_message is None and litellm.modify_params is False - ): + if content_block is None or (user_continue_message is None and litellm.modify_params is False): return skip_empty_text_blocks(message=message) # Handle string case @@ -4475,9 +4086,7 @@ def get_user_message_block_or_continue_message( def return_assistant_continue_message( - assistant_continue_message: Optional[ - Union[str, ChatCompletionAssistantMessage] - ] = None, + assistant_continue_message: Optional[Union[str, ChatCompletionAssistantMessage]] = None, ) -> ChatCompletionAssistantMessage: if assistant_continue_message and isinstance(assistant_continue_message, str): return ChatCompletionAssistantMessage( @@ -4500,11 +4109,7 @@ def _skip_empty_dict_blocks(blocks: List[dict]) -> List[dict]: Returns: Filtered list of non-empty text blocks """ - return [ - item - for item in blocks - if not (item.get("type") == "text" and not item.get("text", "").strip()) - ] + return [item for item in blocks if not (item.get("type") == "text" and not item.get("text", "").strip())] @overload @@ -4542,9 +4147,7 @@ def skip_empty_text_blocks( modified_message["content"] = None # user message content cannot be None return modified_message elif isinstance(content_block, list): - modified_content_block = _skip_empty_dict_blocks( - cast(List[dict], content_block) - ) + modified_content_block = _skip_empty_dict_blocks(cast(List[dict], content_block)) # If no content remains and it's an assistant message, set content to None if not modified_content_block and message["role"] == "assistant": @@ -4572,9 +4175,7 @@ def skip_empty_text_blocks( def process_empty_text_blocks( message: ChatCompletionAssistantMessage, - assistant_continue_message: Optional[ - Union[str, ChatCompletionAssistantMessage] - ] = None, + assistant_continue_message: Optional[Union[str, ChatCompletionAssistantMessage]] = None, ) -> ChatCompletionAssistantMessage: modified_content_block = message.get("content", None) ## BASE CASE ## @@ -4582,14 +4183,9 @@ def process_empty_text_blocks( return message # Check if all items are empty text blocks - if all( - item["type"] == "text" and not item["text"].strip() - for item in modified_content_block - ): + if all(item["type"] == "text" and not item["text"].strip() for item in modified_content_block): # Replace with a single continue message - _assistant_continue_message = return_assistant_continue_message( - assistant_continue_message - ) + _assistant_continue_message = return_assistant_continue_message(assistant_continue_message) modified_content_block = [ { "type": "text", @@ -4599,9 +4195,7 @@ def process_empty_text_blocks( else: # Filter out only empty text blocks, keeping non-empty text and other block types modified_content_block = [ - item - for item in modified_content_block - if not (item["type"] == "text" and not item["text"].strip()) + item for item in modified_content_block if not (item["type"] == "text" and not item["text"].strip()) ] modified_message = message.copy() @@ -4614,9 +4208,7 @@ def process_empty_text_blocks( def get_assistant_message_block_or_continue_message( message: ChatCompletionAssistantMessage, - assistant_continue_message: Optional[ - Union[str, ChatCompletionAssistantMessage] - ] = None, + assistant_continue_message: Optional[Union[str, ChatCompletionAssistantMessage]] = None, ) -> ChatCompletionAssistantMessage: """ Returns the user content block @@ -4627,9 +4219,7 @@ def get_assistant_message_block_or_continue_message( content_block = message.get("content", None) # Handle Base case - if content_block is None or ( - assistant_continue_message is None and litellm.modify_params is False - ): + if content_block is None or (assistant_continue_message is None and litellm.modify_params is False): return skip_empty_text_blocks(message=message) # Handle string case @@ -4655,9 +4245,7 @@ def get_assistant_message_block_or_continue_message( } ], """ - return process_empty_text_blocks( - message=message, assistant_continue_message=assistant_continue_message - ) + return process_empty_text_blocks(message=message, assistant_continue_message=assistant_continue_message) # Handle unsupported type raise ValueError(f"Unsupported content type: {type(content_block)}") @@ -4679,8 +4267,7 @@ def _initial_message_setup( messages.append(DEFAULT_USER_CONTINUE_MESSAGE) else: raise litellm.BadRequestError( - message=BAD_MESSAGE_ERROR_STR - + "bedrock requires at least one non-system message", + message=BAD_MESSAGE_ERROR_STR + "bedrock requires at least one non-system message", model=model, llm_provider=llm_provider, ) @@ -4708,9 +4295,7 @@ async def _bedrock_converse_messages_pt_async( model: str, llm_provider: str, user_continue_message: Optional[ChatCompletionUserMessage] = None, - assistant_continue_message: Optional[ - Union[str, ChatCompletionAssistantMessage] - ] = None, + assistant_continue_message: Optional[Union[str, ChatCompletionAssistantMessage]] = None, ) -> List[BedrockMessageBlock]: contents: List[BedrockMessageBlock] = [] msg_i = 0 @@ -4737,9 +4322,7 @@ async def _bedrock_converse_messages_pt_async( _parts.append(_part) elif element["type"] == "guarded_text": # Wrap guarded_text in guardContent block - _part = BedrockContentBlock( - guardContent={"text": {"text": element["text"]}} - ) + _part = BedrockContentBlock(guardContent={"text": {"text": element["text"]}}) _parts.append(_part) elif element["type"] in ("grounding_source", "query"): # Contextual grounding tags are guardrail metadata; the @@ -4764,29 +4347,19 @@ async def _bedrock_converse_messages_pt_async( ) _parts.append(_part) elif element["type"] == "document": - _part = BedrockConverseMessagesProcessor._process_document_message( - element - ) + _part = BedrockConverseMessagesProcessor._process_document_message(element) _parts.append(_part) - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - message_block=cast( - OpenAIMessageContentListBlock, element - ), - block_type="content_block", - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + message_block=cast(OpenAIMessageContentListBlock, element), + block_type="content_block", ) if _cache_point_block is not None: _parts.append(_cache_point_block) user_content.extend(_parts) - elif message_block["content"] and isinstance( - message_block["content"], str - ): + elif message_block["content"] and isinstance(message_block["content"], str): _part = BedrockContentBlock(text=messages[msg_i]["content"]) - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - message_block, block_type="content_block" - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + message_block, block_type="content_block" ) user_content.append(_part) if _cache_point_block is not None: @@ -4795,27 +4368,20 @@ async def _bedrock_converse_messages_pt_async( msg_i += 1 if user_content: if len(contents) > 0 and contents[-1]["role"] == "user": - if ( - assistant_continue_message is not None - or litellm.modify_params is True - ): + if assistant_continue_message is not None or litellm.modify_params is True: # if last message was a 'user' message, then add a dummy assistant message (bedrock requires alternating roles) contents = _insert_assistant_continue_message( messages=contents, assistant_continue_message=assistant_continue_message, ) - contents.append( - BedrockMessageBlock(role="user", content=user_content) - ) + contents.append(BedrockMessageBlock(role="user", content=user_content)) else: verbose_logger.warning( "Potential consecutive user/tool blocks. Trying to merge. If error occurs, please set a 'assistant_continue_message' or set 'modify_params=True' to insert a dummy assistant message for bedrock calls." ) contents[-1]["content"].extend(user_content) else: - contents.append( - BedrockMessageBlock(role="user", content=user_content) - ) + contents.append(BedrockMessageBlock(role="user", content=user_content)) ## MERGE CONSECUTIVE TOOL CALL MESSAGES ## tool_content: List[BedrockContentBlock] = [] @@ -4833,18 +4399,13 @@ async def _bedrock_converse_messages_pt_async( # Check for content-level cache_control in list content elif isinstance(current_message.get("content"), list): for content_element in current_message["content"]: - if ( - isinstance(content_element, dict) - and content_element.get("cache_control", None) is not None - ): + if isinstance(content_element, dict) and content_element.get("cache_control", None) is not None: has_cache_control = True break # Add a separate cachePoint block if cache_control is present if has_cache_control: - cache_point_block = BedrockContentBlock( - cachePoint=CachePointBlock(type="default") - ) + cache_point_block = BedrockContentBlock(cachePoint=CachePointBlock(type="default")) tool_content.append(cache_point_block) msg_i += 1 @@ -4853,35 +4414,26 @@ async def _bedrock_converse_messages_pt_async( if tool_content: # if last message was a 'user' message, then add a blank assistant message (bedrock requires alternating roles) if len(contents) > 0 and contents[-1]["role"] == "user": - if ( - assistant_continue_message is not None - or litellm.modify_params is True - ): + if assistant_continue_message is not None or litellm.modify_params is True: # if last message was a 'user' message, then add a dummy assistant message (bedrock requires alternating roles) contents = _insert_assistant_continue_message( messages=contents, assistant_continue_message=assistant_continue_message, ) - contents.append( - BedrockMessageBlock(role="user", content=tool_content) - ) + contents.append(BedrockMessageBlock(role="user", content=tool_content)) else: verbose_logger.warning( "Potential consecutive user/tool blocks. Trying to merge. If error occurs, please set a 'assistant_continue_message' or set 'modify_params=True' to insert a dummy assistant message for bedrock calls." ) contents[-1]["content"].extend(tool_content) else: - contents.append( - BedrockMessageBlock(role="user", content=tool_content) - ) + contents.append(BedrockMessageBlock(role="user", content=tool_content)) assistant_content: List[BedrockContentBlock] = [] ## MERGE CONSECUTIVE ASSISTANT CONTENT ## while msg_i < len(messages) and messages[msg_i]["role"] == "assistant": - assistant_message_block = ( - get_assistant_message_block_or_continue_message( - message=messages[msg_i], - assistant_continue_message=assistant_continue_message, - ) + assistant_message_block = get_assistant_message_block_or_continue_message( + message=messages[msg_i], + assistant_continue_message=assistant_continue_message, ) _assistant_content = assistant_message_block.get("content", None) thinking_blocks = cast( @@ -4890,97 +4442,75 @@ async def _bedrock_converse_messages_pt_async( ) if thinking_blocks is not None: - converted_thinking_blocks = BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( - thinking_blocks + converted_thinking_blocks = ( + BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( + thinking_blocks + ) ) assistant_content = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content( thinking_blocks=converted_thinking_blocks, assistant_parts=assistant_content, ) - if _assistant_content is not None and isinstance( - _assistant_content, list - ): + if _assistant_content is not None and isinstance(_assistant_content, list): assistants_parts: List[BedrockContentBlock] = [] for element in _assistant_content: if isinstance(element, dict): if element["type"] == "thinking": thinking_block = BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( - thinking_blocks=[ - cast(ChatCompletionThinkingBlock, element) - ] + thinking_blocks=[cast(ChatCompletionThinkingBlock, element)] ) - assistants_parts = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content( - thinking_blocks=thinking_block, - assistant_parts=assistants_parts, + assistants_parts = ( + BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content( + thinking_blocks=thinking_block, + assistant_parts=assistants_parts, + ) ) elif element["type"] == "text": # Skip completely empty strings to avoid blank content blocks if element.get("text", "").strip(): - assistants_part = BedrockContentBlock( - text=element["text"] - ) + assistants_part = BedrockContentBlock(text=element["text"]) assistants_parts.append(assistants_part) elif element["type"] == "image_url": if isinstance(element["image_url"], dict): image_url = element["image_url"]["url"] else: image_url = element["image_url"] - assistants_part = ( - await BedrockImageProcessor.process_image_async( # type: ignore - image_url=image_url - ) + assistants_part = await BedrockImageProcessor.process_image_async( # type: ignore + image_url=image_url ) assistants_parts.append(assistants_part) # Add cache point block for assistant content elements - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - message_block=cast( - OpenAIMessageContentListBlock, element - ), - block_type="content_block", - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + message_block=cast(OpenAIMessageContentListBlock, element), + block_type="content_block", ) if _cache_point_block is not None: assistants_parts.append(_cache_point_block) assistant_content.extend(assistants_parts) - elif _assistant_content is not None and isinstance( - _assistant_content, str - ): + elif _assistant_content is not None and isinstance(_assistant_content, str): # Skip completely empty strings to avoid blank content blocks if _assistant_content.strip(): - assistant_content.append( - BedrockContentBlock(text=_assistant_content) - ) + assistant_content.append(BedrockContentBlock(text=_assistant_content)) # If content is empty/whitespace, skip it (don't add a placeholder) # Add cache point block for assistant string content - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - assistant_message_block, block_type="content_block" - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + assistant_message_block, block_type="content_block" ) if _cache_point_block is not None: assistant_content.append(_cache_point_block) _tool_calls = assistant_message_block.get("tool_calls", []) if _tool_calls: - assistant_content.extend( - _convert_to_bedrock_tool_call_invoke(_tool_calls) - ) + assistant_content.extend(_convert_to_bedrock_tool_call_invoke(_tool_calls)) msg_i += 1 - assistant_content = _deduplicate_bedrock_content_blocks( - assistant_content, "toolUse" - ) - assistant_content = _sort_bedrock_assistant_content_blocks( - assistant_content - ) + assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse") + assistant_content = _sort_bedrock_assistant_content_blocks(assistant_content) if assistant_content: - contents.append( - BedrockMessageBlock(role="assistant", content=assistant_content) - ) + contents.append(BedrockMessageBlock(role="assistant", content=assistant_content)) if msg_i == init_msg_i: # prevent infinite loops raise litellm.BadRequestError( @@ -5007,9 +4537,7 @@ def translate_thinking_blocks_to_reasoning_content_blocks( reasoning_content_block = BedrockConverseReasoningContentBlock( reasoningText=text_block, ) - bedrock_content_block = BedrockContentBlock( - reasoningContent=reasoning_content_block - ) + bedrock_content_block = BedrockContentBlock(reasoningContent=reasoning_content_block) reasoning_content_blocks.append(bedrock_content_block) return reasoning_content_blocks @@ -5027,16 +4555,12 @@ def _process_file_message(message: ChatCompletionFileObject) -> BedrockContentBl if file_data is None and file_id is None: raise litellm.BadRequestError( - message="file_data and file_id cannot both be None. Got={}".format( - message - ), + message="file_data and file_id cannot both be None. Got={}".format(message), model="", llm_provider="bedrock", ) format = file_message.get("format") - return BedrockImageProcessor.process_image_sync( - image_url=cast(str, file_id or file_data), format=format - ) + return BedrockImageProcessor.process_image_sync(image_url=cast(str, file_id or file_data), format=format) @staticmethod async def _async_process_file_message( @@ -5054,15 +4578,11 @@ async def _async_process_file_message( format = file_message.get("format") if file_data is None and file_id is None: raise litellm.BadRequestError( - message="file_data and file_id cannot both be None. Got={}".format( - message - ), + message="file_data and file_id cannot both be None. Got={}".format(message), model="", llm_provider="bedrock", ) - return await BedrockImageProcessor.process_image_async( - image_url=cast(str, file_id or file_data), format=format - ) + return await BedrockImageProcessor.process_image_async(image_url=cast(str, file_id or file_data), format=format) @staticmethod def _process_document_message(element: dict) -> BedrockContentBlock: @@ -5080,9 +4600,7 @@ def _process_document_message(element: dict) -> BedrockContentBlock: ) media_type: str = source["media_type"] data: str = source["data"] - doc_format = BedrockImageProcessor._validate_format( - mime_type=media_type, image_format=media_type.split("/")[1] - ) + doc_format = BedrockImageProcessor._validate_format(mime_type=media_type, image_format=media_type.split("/")[1]) # Deterministic name using the same hashing pattern as _create_bedrock_block HASH_SAMPLE_BYTES = 64 * 1024 @@ -5118,11 +4636,7 @@ def add_thinking_blocks_to_assistant_content( filtered_thinking_blocks = [] for block in thinking_blocks: reasoning_content = block.get("reasoningContent", None) - reasoning_text = ( - reasoning_content.get("reasoningText", None) - if reasoning_content is not None - else None - ) + reasoning_text = reasoning_content.get("reasoningText", None) if reasoning_content is not None else None if reasoning_text and not reasoning_text.get("signature"): reasoning_text_text = reasoning_text["text"] if reasoning_text_text.strip(): @@ -5140,9 +4654,7 @@ def _bedrock_converse_messages_pt( model: str, llm_provider: str, user_continue_message: Optional[ChatCompletionUserMessage] = None, - assistant_continue_message: Optional[ - Union[str, ChatCompletionAssistantMessage] - ] = None, + assistant_continue_message: Optional[Union[str, ChatCompletionAssistantMessage]] = None, ) -> List[BedrockMessageBlock]: """ Converts given messages from OpenAI format to Bedrock format @@ -5177,9 +4689,7 @@ def _bedrock_converse_messages_pt( _parts.append(_part) elif element["type"] == "guarded_text": # Wrap guarded_text in guardContent block - _part = BedrockContentBlock( - guardContent={"text": {"text": element["text"]}} - ) + _part = BedrockContentBlock(guardContent={"text": {"text": element["text"]}}) _parts.append(_part) elif element["type"] in ("grounding_source", "query"): # Contextual grounding tags are guardrail metadata; the @@ -5200,34 +4710,24 @@ def _bedrock_converse_messages_pt( ) _parts.append(_part) # type: ignore elif element["type"] == "file": - _part = ( - BedrockConverseMessagesProcessor._process_file_message( - message=cast(ChatCompletionFileObject, element) - ) + _part = BedrockConverseMessagesProcessor._process_file_message( + message=cast(ChatCompletionFileObject, element) ) _parts.append(_part) elif element["type"] == "document": - _part = BedrockConverseMessagesProcessor._process_document_message( - element - ) + _part = BedrockConverseMessagesProcessor._process_document_message(element) _parts.append(_part) - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - message_block=cast( - OpenAIMessageContentListBlock, element - ), - block_type="content_block", - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + message_block=cast(OpenAIMessageContentListBlock, element), + block_type="content_block", ) if _cache_point_block is not None: _parts.append(_cache_point_block) user_content.extend(_parts) elif message_block["content"] and isinstance(message_block["content"], str): _part = BedrockContentBlock(text=messages[msg_i]["content"]) - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - message_block, block_type="content_block" - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + message_block, block_type="content_block" ) user_content.append(_part) if _cache_point_block is not None: @@ -5236,18 +4736,13 @@ def _bedrock_converse_messages_pt( msg_i += 1 if user_content: if len(contents) > 0 and contents[-1]["role"] == "user": - if ( - assistant_continue_message is not None - or litellm.modify_params is True - ): + if assistant_continue_message is not None or litellm.modify_params is True: # if last message was a 'user' message, then add a dummy assistant message (bedrock requires alternating roles) contents = _insert_assistant_continue_message( messages=contents, assistant_continue_message=assistant_continue_message, ) - contents.append( - BedrockMessageBlock(role="user", content=user_content) - ) + contents.append(BedrockMessageBlock(role="user", content=user_content)) else: verbose_logger.warning( "Potential consecutive user/tool blocks. Trying to merge. If error occurs, please set a 'assistant_continue_message' or set 'modify_params=True' to insert a dummy assistant message for bedrock calls." @@ -5274,18 +4769,13 @@ def _bedrock_converse_messages_pt( # Check for content-level cache_control in list content elif isinstance(current_message.get("content"), list): for content_element in current_message["content"]: - if ( - isinstance(content_element, dict) - and content_element.get("cache_control", None) is not None - ): + if isinstance(content_element, dict) and content_element.get("cache_control", None) is not None: has_cache_control = True break # Add a separate cachePoint block if cache_control is present if has_cache_control: - cache_point_block = BedrockContentBlock( - cachePoint=CachePointBlock(type="default") - ) + cache_point_block = BedrockContentBlock(cachePoint=CachePointBlock(type="default")) tool_content.append(cache_point_block) msg_i += 1 @@ -5294,18 +4784,13 @@ def _bedrock_converse_messages_pt( if tool_content: # if last message was a 'user' message, then add a blank assistant message (bedrock requires alternating roles) if len(contents) > 0 and contents[-1]["role"] == "user": - if ( - assistant_continue_message is not None - or litellm.modify_params is True - ): + if assistant_continue_message is not None or litellm.modify_params is True: # if last message was a 'user' message, then add a dummy assistant message (bedrock requires alternating roles) contents = _insert_assistant_continue_message( messages=contents, assistant_continue_message=assistant_continue_message, ) - contents.append( - BedrockMessageBlock(role="user", content=tool_content) - ) + contents.append(BedrockMessageBlock(role="user", content=tool_content)) else: verbose_logger.warning( "Potential consecutive user/tool blocks. Trying to merge. If error occurs, please set a 'assistant_continue_message' or set 'modify_params=True' to insert a dummy assistant message for bedrock calls." @@ -5327,8 +4812,10 @@ def _bedrock_converse_messages_pt( ) if thinking_blocks is not None: - converted_thinking_blocks = BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( - thinking_blocks + converted_thinking_blocks = ( + BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( + thinking_blocks + ) ) assistant_content = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content( thinking_blocks=converted_thinking_blocks, @@ -5340,22 +4827,22 @@ def _bedrock_converse_messages_pt( for element in _assistant_content: if isinstance(element, dict): if element["type"] == "thinking": - thinking_block = BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( - thinking_blocks=[ - cast(ChatCompletionThinkingBlock, element) - ] + thinking_block = ( + BedrockConverseMessagesProcessor.translate_thinking_blocks_to_reasoning_content_blocks( + thinking_blocks=[cast(ChatCompletionThinkingBlock, element)] + ) ) - assistants_parts = BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content( - thinking_blocks=thinking_block, - assistant_parts=assistants_parts, + assistants_parts = ( + BedrockConverseMessagesProcessor.add_thinking_blocks_to_assistant_content( + thinking_blocks=thinking_block, + assistant_parts=assistants_parts, + ) ) elif element["type"] == "text": # AWS Bedrock doesn't allow empty or whitespace-only text content # Skip completely empty strings to avoid blank content blocks if element.get("text", "").strip(): - assistants_part = BedrockContentBlock( - text=element["text"] - ) + assistants_part = BedrockContentBlock(text=element["text"]) assistants_parts.append(assistants_part) elif element["type"] == "image_url": if isinstance(element["image_url"], dict): @@ -5367,13 +4854,9 @@ def _bedrock_converse_messages_pt( ) assistants_parts.append(assistants_part) # Add cache point block for assistant content elements - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - message_block=cast( - OpenAIMessageContentListBlock, element - ), - block_type="content_block", - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + message_block=cast(OpenAIMessageContentListBlock, element), + block_type="content_block", ) if _cache_point_block is not None: assistants_parts.append(_cache_point_block) @@ -5381,34 +4864,24 @@ def _bedrock_converse_messages_pt( elif _assistant_content is not None and isinstance(_assistant_content, str): # Skip completely empty strings to avoid blank content blocks if _assistant_content.strip(): - assistant_content.append( - BedrockContentBlock(text=_assistant_content) - ) + assistant_content.append(BedrockContentBlock(text=_assistant_content)) # Add cache point block for assistant string content - _cache_point_block = ( - litellm.AmazonConverseConfig()._get_cache_point_block( - assistant_message_block, block_type="content_block" - ) + _cache_point_block = litellm.AmazonConverseConfig()._get_cache_point_block( + assistant_message_block, block_type="content_block" ) if _cache_point_block is not None: assistant_content.append(_cache_point_block) _tool_calls = assistant_message_block.get("tool_calls", []) if _tool_calls: - assistant_content.extend( - _convert_to_bedrock_tool_call_invoke(_tool_calls) - ) + assistant_content.extend(_convert_to_bedrock_tool_call_invoke(_tool_calls)) msg_i += 1 - assistant_content = _deduplicate_bedrock_content_blocks( - assistant_content, "toolUse" - ) + assistant_content = _deduplicate_bedrock_content_blocks(assistant_content, "toolUse") assistant_content = _sort_bedrock_assistant_content_blocks(assistant_content) if assistant_content: - contents.append( - BedrockMessageBlock(role="assistant", content=assistant_content) - ) + contents.append(BedrockMessageBlock(role="assistant", content=assistant_content)) if msg_i == init_msg_i: # prevent infinite loops raise litellm.BadRequestError( @@ -5442,16 +4915,12 @@ def replace_invalid(char): if input_tool_name != valid_string: # passed tool name was formatted to become valid # store it internally so we can use for the response - litellm.bedrock_tool_name_mappings.set_cache( - key=valid_string, value=input_tool_name - ) + litellm.bedrock_tool_name_mappings.set_cache(key=valid_string, value=input_tool_name) return valid_string -def add_cache_point_tool_block( - tool: dict, model: Optional[str] = None -) -> Optional[BedrockToolBlock]: +def add_cache_point_tool_block(tool: dict, model: Optional[str] = None) -> Optional[BedrockToolBlock]: from litellm.llms.bedrock.common_utils import is_claude_4_5_on_bedrock cache_control = tool.get("cache_control", None) @@ -5461,11 +4930,7 @@ def add_cache_point_tool_block( cache_point_block: CachePointBlock = {"type": "default"} if isinstance(cache_control, dict) and "ttl" in cache_control: ttl = cache_control["ttl"] - if ( - ttl in ["5m", "1h"] - and model is not None - and is_claude_4_5_on_bedrock(model) - ): + if ttl in ["5m", "1h"] and model is not None and is_claude_4_5_on_bedrock(model): cache_point_block["ttl"] = ttl return {"cachePoint": cache_point_block} return None @@ -5492,14 +4957,10 @@ def _is_bedrock_tool_block(tool: dict) -> bool: >>> _is_bedrock_tool_block({"type": "function", "function": {...}}) False """ - return isinstance(tool, dict) and ( - "systemTool" in tool or "toolSpec" in tool or "cachePoint" in tool - ) + return isinstance(tool, dict) and ("systemTool" in tool or "toolSpec" in tool or "cachePoint" in tool) -def _bedrock_tools_pt( - tools: List, model: Optional[str] = None -) -> List[BedrockToolBlock]: +def _bedrock_tools_pt(tools: List, model: Optional[str] = None) -> List[BedrockToolBlock]: """ OpenAI tools looks like: tools = [ @@ -5554,14 +5015,10 @@ def _bedrock_tools_pt( ) from litellm.litellm_core_utils.prompt_templates.common_utils import unpack_defs - _valid_json_schema_root_types = frozenset( - ("array", "boolean", "integer", "null", "number", "object", "string") - ) + _valid_json_schema_root_types = frozenset(("array", "boolean", "integer", "null", "number", "object", "string")) # Only Claude on Bedrock honours strict tool schemas; other families # (Nova, Llama, GPT-OSS) reject the strict field outright. - supports_strict_tools = bool( - model and get_bedrock_base_model(model).startswith("anthropic") - ) + supports_strict_tools = bool(model and get_bedrock_base_model(model).startswith("anthropic")) tool_block_list: List[BedrockToolBlock] = [] for tool_idx, tool in enumerate(tools): # Check if tool is already a BedrockToolBlock (e.g., systemTool for Nova grounding) @@ -5572,17 +5029,11 @@ def _bedrock_tools_pt( # OpenAI function tools, or Anthropic Messages / Claude Code ({name, input_schema, type, ...}) if isinstance(tool, dict) and "input_schema" in tool and "function" not in tool: - parameters = copy.deepcopy( - tool.get("input_schema") or {"type": "object", "properties": {}} - ) + parameters = copy.deepcopy(tool.get("input_schema") or {"type": "object", "properties": {}}) raw_name = tool.get("name", "") or "" _tool_description = tool.get("description", None) else: - parameters = copy.deepcopy( - tool.get("function", {}).get( - "parameters", {"type": "object", "properties": {}} - ) - ) + parameters = copy.deepcopy(tool.get("function", {}).get("parameters", {"type": "object", "properties": {}})) raw_name = tool.get("function", {}).get("name", "") or "" _tool_description = tool.get("function", {}).get("description", None) @@ -5639,9 +5090,7 @@ def function_call_prompt(messages: list, functions: list): if isinstance(message["content"], str): message["content"] += f""" {function_prompt}""" else: - message["content"].append( - {"type": "text", "text": f""" {function_prompt}"""} - ) + message["content"].append({"type": "text", "text": f""" {function_prompt}"""}) function_added_to_prompt = True if function_added_to_prompt is False: @@ -5657,9 +5106,7 @@ def response_schema_prompt(model: str, response_schema: dict) -> str: Returns the prompt str that's passed to the model as a user message """ custom_prompt_details: Optional[dict] = None - response_schema_as_message = [ - {"role": "user", "content": "{}".format(response_schema)} - ] + response_schema_as_message = [{"role": "user", "content": "{}".format(response_schema)}] if f"{model}/response_schema_prompt" in litellm.custom_prompt_dict: custom_prompt_details = litellm.custom_prompt_dict[ f"{model}/response_schema_prompt" @@ -5712,23 +5159,17 @@ def custom_prompt( bos_open = True pre_message_str = ( - role_dict[role]["pre_message"] - if role in role_dict and "pre_message" in role_dict[role] - else "" + role_dict[role]["pre_message"] if role in role_dict and "pre_message" in role_dict[role] else "" ) post_message_str = ( - role_dict[role]["post_message"] - if role in role_dict and "post_message" in role_dict[role] - else "" + role_dict[role]["post_message"] if role in role_dict and "post_message" in role_dict[role] else "" ) if isinstance(message["content"], str): prompt += pre_message_str + message["content"] + post_message_str elif isinstance(message["content"], list): text_str = "" for content in message["content"]: - if content.get("text", None) is not None and isinstance( - content["text"], str - ): + if content.get("text", None) is not None and isinstance(content["text"], str): text_str += content["text"] prompt += pre_message_str + text_str + post_message_str @@ -5753,9 +5194,7 @@ def prompt_factory( elif custom_llm_provider == "anthropic": if litellm.AnthropicTextConfig._is_anthropic_text_model(model): return anthropic_pt(messages=messages) - return anthropic_messages_pt( - messages=messages, model=model, llm_provider=custom_llm_provider - ) + return anthropic_messages_pt(messages=messages, model=model, llm_provider=custom_llm_provider) elif custom_llm_provider == "anthropic_xml": return anthropic_messages_pt_xml(messages=messages) elif custom_llm_provider == "gemini": @@ -5768,9 +5207,7 @@ def prompt_factory( else: return gemini_text_image_pt(messages=messages) elif custom_llm_provider == "mistral": - return litellm.MistralConfig()._transform_messages( - messages=messages, model=model - ) + return litellm.MistralConfig()._transform_messages(messages=messages, model=model) elif custom_llm_provider == "bedrock": if "amazon.titan-text" in model: return amazon_titan_pt(messages=messages) @@ -5802,16 +5239,12 @@ def prompt_factory( elif custom_llm_provider == "watsonx": from litellm.llms.watsonx.chat.transformation import IBMWatsonXChatConfig - return IBMWatsonXChatConfig.apply_prompt_template( - model=model, messages=messages - ) + return IBMWatsonXChatConfig.apply_prompt_template(model=model, messages=messages) try: if "meta-llama/llama-2" in model and "chat" in model: return llama_2_chat_pt(messages=messages) - elif ( - "meta-llama/llama-3" in model or "meta-llama-3" in model - ) and "instruct" in model: + elif ("meta-llama/llama-3" in model or "meta-llama-3" in model) and "instruct" in model: return hf_chat_template( model="meta-llama/Meta-Llama-3-8B-Instruct", messages=messages, @@ -5835,9 +5268,7 @@ def prompt_factory( return wizardcoder_pt(messages=messages) elif "phind/phind-codellama" in model: return phind_codellama_pt(messages=messages) - elif "togethercomputer/llama-2" in model and ( - "instruct" in model or "chat" in model - ): + elif "togethercomputer/llama-2" in model and ("instruct" in model or "chat" in model): return llama_2_chat_pt(messages=messages) elif model in [ "gryphe/mythomax-l2-13b", @@ -5847,9 +5278,7 @@ def prompt_factory( return alpaca_pt(messages=messages) elif model.strip() == "meta-llama/llamaguard-7b": chat_template = "{% if messages|length % 2 == 0 %}{% set role = 'Agent' %}{% else %}{% set role = 'User' %}{% endif %}{{ \"[INST] Task: Check if there is unsafe content in '\" + role + \"' messages in conversations according our safety policy with the below categories.\n\n\nO1: Violence and Hate. \nShould not\n- Help people plan or engage in violence.\n- Encourage people to engage in violence.\n- Express hateful, derogatory, or demeaning sentiments against people based on sensitive personal characteristics like their race, color, religion, national origin, sexual orientation, gender, gender identity, or disability.\n- Encourage discrimination against people based on those characteristics and should not use slurs or create insults based on those characteristics.\nCan\n- Provide information on violence and discrimination.\n- Discuss the topics of hate and violence, and can discuss historical events involving violence.\nO2: Sexual Content.\nShould not\n- Engage in sexually explicit (i.e., erotic) conversations and should not encourage people to engage in sexual activities.\nCan\n- Discuss topics related to sexuality and sexual education.\n- Provide general information regarding sexual activities.\n- Provide guidance on topics related to sexual health.\nO3: Criminal Planning.\nShould not\n- Help people plan or engage in criminal activities like theft, kidnapping, or financial crimes, especially when the person indicates that they may act on the information provided to them.\n- Encourage people to engage in criminal activities or condone criminal behavior.\nCan\n- Help people understand how crimes are committed, provided that the response is not so detailed that it could be used to provide a roadmap for future crimes.\n- Help people understand how systems work that are used to prevent crimes, provided those descriptions do not provide detailed information on how to defeat those systems.\nO4: Guns and Illegal Weapons.\nShould not\n- Assist in the planning or execution of firearm or illegal weapons crimes, especially when the person indicates that they may act on the information provided to them.\n- Encourage people to engage in firearm or illegal weapons crimes or condone such behavior.\nCan\n- Discuss firearms and the arguments for and against firearm ownership.\nO5: Regulated or Controlled Substances.\nShould not\n- Encourage or assist people in the trafficking, consumption, or use of regulated or controlled substances, including but not limited to illegal drugs, tobacco, alcohol, and cannabis.\n- Assist or encourage people to create such substances when it is illegal to do so.\nCan\n- Discuss the use of regulated or controlled substances, and can provide general information on those substances (ex: what their chemical composition is and what their effects are).\n- Provide information on how those substances are manufactured, provided that the information is not so detailed as to provide step-by-step instructions for their creation.\nO6: Self-Harm.\nShould not\n- Encourage people to harm themselves.\n- Romanticize or condone self-harm or suicide.\n- Provide information regarding the methods of suicide or self-harm.\n- Provide any information or advice, other than information regarding appropriate health resources, to people who express or imply that they wish to harm themselves.\nCan\n- Provide general information regarding self-harm and suicide (ex: statistics, the mental health challenges faced by those who take these actions).\nShould\n- Provide information regarding appropriate health resources to people who imply or express the desire to harm themselves.\n\n\n\n\n\" }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% set content = message['content'] %}{% if message['role'] == 'user' %}{% set role = 'User' %}{% elif message['role'] == 'assistant' %}{% set role = 'Agent' %}{% endif %}{{ role + ': ' + content.strip() + '\n\n' }}{% endfor %}{{ \"\n\nProvide your safety assessment for \" + role + \" in the above conversation:\n- First line must read 'safe' or 'unsafe'.\n- If unsafe, a second line must include a comma-separated list of violated categories. [/INST]\" }}" - return hf_chat_template( - model=model, messages=messages, chat_template=chat_template - ) + return hf_chat_template(model=model, messages=messages, chat_template=chat_template) else: return hf_chat_template(original_model_name, messages) except Exception: diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.py index fd38bc9388d3..7129d6bba81b 100644 --- a/litellm/litellm_core_utils/prompt_templates/image_handling.py +++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py @@ -91,9 +91,7 @@ async def async_convert_url_to_base64(url: str) -> str: raise except Exception: pass - raise litellm.ImageFetchError( - f"Error: Unable to fetch image from URL after 3 attempts. url={url}" - ) + raise litellm.ImageFetchError(f"Error: Unable to fetch image from URL after 3 attempts. url={url}") def convert_url_to_base64(url: str) -> str: diff --git a/litellm/litellm_core_utils/realtime_streaming.py b/litellm/litellm_core_utils/realtime_streaming.py index e2ad3c13337c..4b1dc1a66d1a 100644 --- a/litellm/litellm_core_utils/realtime_streaming.py +++ b/litellm/litellm_core_utils/realtime_streaming.py @@ -69,9 +69,7 @@ def __init__( # Detect whether the client is explicitly opting into the beta protocol. self._client_wants_beta = self._detect_beta_header(websocket) self._backend_uses_beta_protocol = ( - self._client_wants_beta - if backend_uses_beta_protocol is None - else backend_uses_beta_protocol + self._client_wants_beta if backend_uses_beta_protocol is None else backend_uses_beta_protocol ) _logged_real_time_event_types = litellm.logged_real_time_event_types @@ -103,9 +101,7 @@ def __init__( self._guardrail_turn_detection_update_sent: bool = False # Deferred Gemini Live setup: Pipecat may stream audio before session.update. # Buffer client audio until the backend acknowledges setup (setupComplete). - self._backend_setup_complete: bool = ( - provider_config is None or provider_config.requires_session_configuration() - ) + self._backend_setup_complete: bool = provider_config is None or provider_config.requires_session_configuration() self._flushing_pending_messages_until_setup: bool = False self._pending_messages_until_setup: List[str] = [] self._pending_messages_byte_total: int = 0 @@ -133,9 +129,7 @@ def __init__( "input_audio_buffer.end", ] ) - _CLIENT_AUDIO_BUFFER_COMMIT_TYPES = frozenset( - ["input_audio_buffer.commit", "input_audio_buffer.end"] - ) + _CLIENT_AUDIO_BUFFER_COMMIT_TYPES = frozenset(["input_audio_buffer.commit", "input_audio_buffer.end"]) _AUDIO_FORMAT_MAP: Dict[str, Dict[str, Any]] = { "pcm16": {"type": "audio/pcm", "rate": 24000}, "g711_ulaw": {"type": "audio/G711-ulaw", "rate": 8000}, @@ -182,9 +176,7 @@ def store_message(self, message: Union[str, bytes, dict, OpenAIRealtimeEvents]): try: event_type = message_obj.get("type", "") if event_type in self._SESSION_EVENT_TYPES: - typed_obj: OpenAIRealtimeEvents = OpenAIRealtimeStreamSessionEvents( - **message_obj - ) # type: ignore + typed_obj: OpenAIRealtimeEvents = OpenAIRealtimeStreamSessionEvents(**message_obj) # type: ignore else: # Catch-all base object so unknown/new event names never raise. typed_obj = OpenAIRealtimeStreamResponseBaseObject(**message_obj) # type: ignore @@ -211,22 +203,15 @@ def _collect_user_input_from_client_event(self, message: Union[str, dict]) -> No if item.get("role") == "user": content_list = item.get("content", []) for content in content_list: - if ( - isinstance(content, dict) - and content.get("type") == "input_text" - ): + if isinstance(content, dict) and content.get("type") == "input_text": text = content.get("text", "") if text: - self.input_messages.append( - {"role": "user", "content": text} - ) + self.input_messages.append({"role": "user", "content": text}) elif msg_type == "session.update": session = msg_obj.get("session", {}) instructions = session.get("instructions", "") if instructions: - self.input_messages.append( - {"role": "system", "content": instructions} - ) + self.input_messages.append({"role": "system", "content": instructions}) tools = session.get("tools") if tools and isinstance(tools, list): self.session_tools = tools @@ -237,9 +222,7 @@ def _collect_user_input_from_client_event(self, message: Union[str, dict]) -> No except (json.JSONDecodeError, AttributeError, TypeError): pass - def _collect_user_input_from_backend_event( - self, event_obj: Union[dict, OpenAIRealtimeEvents] - ) -> None: + def _collect_user_input_from_backend_event(self, event_obj: Union[dict, OpenAIRealtimeEvents]) -> None: """Extract user voice transcription from backend events for spend logging.""" try: event_type = event_obj.get("type", "") @@ -250,9 +233,7 @@ def _collect_user_input_from_backend_event( except (AttributeError, TypeError): pass - def _detect_transcription_session_from_backend( - self, event_obj: Union[dict, OpenAIRealtimeEvents] - ) -> None: + def _detect_transcription_session_from_backend(self, event_obj: Union[dict, OpenAIRealtimeEvents]) -> None: """Flag transcription-only sessions from backend session events.""" try: event_type = event_obj.get("type", "") @@ -268,9 +249,7 @@ def _detect_transcription_session_from_backend( except (AttributeError, TypeError): pass - def _capture_transcription_usage( - self, event_obj: Union[dict, OpenAIRealtimeEvents] - ) -> None: + def _capture_transcription_usage(self, event_obj: Union[dict, OpenAIRealtimeEvents]) -> None: """ Append a usage-only transcription completed event to the logged results so the cost calculator can bill it by audio duration. The default logged event @@ -299,9 +278,7 @@ def _capture_transcription_usage( except (AttributeError, TypeError): pass - def _collect_tool_calls_from_response_done( - self, event_obj: Union[dict, OpenAIRealtimeEvents] - ) -> None: + def _collect_tool_calls_from_response_done(self, event_obj: Union[dict, OpenAIRealtimeEvents]) -> None: """Extract function_call items from response.done events for spend logging.""" try: if event_obj.get("type") != "response.done": @@ -335,12 +312,8 @@ async def log_messages(self): if self.input_messages: self.logging_obj.model_call_details["messages"] = self.input_messages if self.session_tools or self.tool_calls: - self.logging_obj.model_call_details["realtime_tools"] = ( - self.session_tools - ) - self.logging_obj.model_call_details["realtime_tool_calls"] = ( - self.tool_calls - ) + self.logging_obj.model_call_details["realtime_tools"] = self.session_tools + self.logging_obj.model_call_details["realtime_tool_calls"] = self.tool_calls ## ASYNC LOGGING # Create an event loop for the new thread asyncio.create_task(self.logging_obj.async_success_handler(self.messages)) @@ -370,21 +343,15 @@ async def _send_to_backend(self, message: str) -> bool: msg_obj = json.loads(msg) except (json.JSONDecodeError, TypeError): msg_obj = None - if isinstance(msg_obj, dict) and self.provider_config.is_setup_message( - msg_obj - ): + if isinstance(msg_obj, dict) and self.provider_config.is_setup_message(msg_obj): if self._content_sent_after_setup: - verbose_logger.debug( - "Dropping follow-up setup after content was already sent to backend" - ) + verbose_logger.debug("Dropping follow-up setup after content was already sent to backend") continue await self.backend_ws.send(msg) # type: ignore[union-attr, attr-defined] self._cache_session_configuration_request(msg) sent = True else: - is_content_message = isinstance( - msg_obj, dict - ) and self.provider_config.is_content_message(msg_obj) + is_content_message = isinstance(msg_obj, dict) and self.provider_config.is_content_message(msg_obj) # Send first, then mutate state, so a failed send leaves both # ``session_configuration_request`` and # ``_content_sent_after_setup`` untouched. Caching or marking @@ -439,10 +406,7 @@ def _enforce_transcription_session_model(self, message: str) -> str: changed = False transcription = session.get("input_audio_transcription") - if ( - isinstance(transcription, dict) - and transcription.get("model") != authorized_model - ): + if isinstance(transcription, dict) and transcription.get("model") != authorized_model: session["input_audio_transcription"] = { **transcription, "model": authorized_model, @@ -454,10 +418,7 @@ def _enforce_transcription_session_model(self, message: str) -> str: audio_input = audio.get("input") if isinstance(audio_input, dict): nested_transcription = audio_input.get("transcription") - if ( - isinstance(nested_transcription, dict) - and nested_transcription.get("model") != authorized_model - ): + if isinstance(nested_transcription, dict) and nested_transcription.get("model") != authorized_model: session["audio"] = { **audio, "input": { @@ -518,17 +479,13 @@ def _collapse_buffered_audio_messages(messages: List[str]) -> List[str]: def _sync_pending_messages_byte_total(self) -> None: self._pending_messages_byte_total = sum( - len(message.encode("utf-8")) - for message in self._pending_messages_until_setup + len(message.encode("utf-8")) for message in self._pending_messages_until_setup ) def _should_buffer_client_message_until_setup(self, message: str) -> bool: if not self._uses_deferred_backend_setup(): return False - if ( - self._backend_setup_complete - and not self._flushing_pending_messages_until_setup - ): + if self._backend_setup_complete and not self._flushing_pending_messages_until_setup: return False try: msg_obj = json.loads(message) @@ -551,10 +508,8 @@ def _buffer_pending_message_until_setup(self, message: str) -> None: msg_bytes = len(message.encode("utf-8")) if ( - len(self._pending_messages_until_setup) - < RealTimeStreaming._MAX_BUFFERED_MESSAGES - and self._pending_messages_byte_total + msg_bytes - <= RealTimeStreaming._MAX_BUFFERED_BYTES + len(self._pending_messages_until_setup) < RealTimeStreaming._MAX_BUFFERED_MESSAGES + and self._pending_messages_byte_total + msg_bytes <= RealTimeStreaming._MAX_BUFFERED_BYTES ): self._pending_messages_until_setup.append(message) self._pending_messages_byte_total += msg_bytes @@ -566,9 +521,7 @@ def _buffer_pending_message_until_setup(self, message: str) -> None: ) async def _flush_pending_messages_until_setup(self) -> bool: - pending = self._collapse_buffered_audio_messages( - self._pending_messages_until_setup - ) + pending = self._collapse_buffered_audio_messages(self._pending_messages_until_setup) self._pending_messages_until_setup = [] self._pending_messages_byte_total = 0 for idx, message in enumerate(pending): @@ -576,12 +529,9 @@ async def _flush_pending_messages_until_setup(self) -> bool: await self._send_to_backend(message) except Exception as e: unsent = pending[idx:] - self._pending_messages_until_setup = ( - unsent + self._pending_messages_until_setup - ) + self._pending_messages_until_setup = unsent + self._pending_messages_until_setup self._pending_messages_byte_total = sum( - len(msg.encode("utf-8")) - for msg in self._pending_messages_until_setup + len(msg.encode("utf-8")) for msg in self._pending_messages_until_setup ) verbose_logger.debug( "Failed to flush buffered client message after setup: %s (%d buffered message(s) retained)", @@ -713,9 +663,7 @@ def _has_audio_transcription_guardrails(self) -> bool: """ from litellm.types.guardrails import GuardrailEventHooks - return self._has_realtime_guardrails_for_event_hooks( - [GuardrailEventHooks.realtime_input_transcription] - ) + return self._has_realtime_guardrails_for_event_hooks([GuardrailEventHooks.realtime_input_transcription]) async def run_realtime_guardrails( self, @@ -755,10 +703,7 @@ async def run_realtime_guardrails( continue if id(callback) in _already_run: continue - if not any( - callback.should_run_guardrail(data=_check_data, event_type=et) - for et in _realtime_event_types - ): + if not any(callback.should_run_guardrail(data=_check_data, event_type=et) for et in _realtime_event_types): continue _already_run.add(id(callback)) try: @@ -770,9 +715,7 @@ async def run_realtime_guardrails( except Exception as e: # Re-raise unexpected errors (no status_code/detail = programming bug, not a block). # HTTPException and guardrail-raised exceptions have a status_code or detail attr. - is_guardrail_block = hasattr(e, "status_code") or isinstance( - e, ValueError - ) + is_guardrail_block = hasattr(e, "status_code") or isinstance(e, ValueError) if not is_guardrail_block: verbose_logger.exception( "[realtime guardrail] unexpected error in apply_guardrail: %s", @@ -787,15 +730,10 @@ async def run_realtime_guardrails( elif detail is not None: safe_msg = str(detail) else: - safe_msg = ( - str(e) - or "I'm sorry, that request was blocked by the content filter." - ) + safe_msg = str(e) or "I'm sorry, that request was blocked by the content filter." # Use realtime_violation_message if configured; fall back to guardrail error text. - error_msg = ( - getattr(callback, "realtime_violation_message", None) or safe_msg - ) + error_msg = getattr(callback, "realtime_violation_message", None) or safe_msg # Deliver any caller-supplied backend message FIRST so that # protocol contracts requiring a specific ordering (e.g. @@ -832,9 +770,7 @@ async def run_realtime_guardrails( "item": { "type": "message", "role": "user", - "content": [ - {"type": "input_text", "text": guardrail_prompt} - ], + "content": [{"type": "input_text", "text": guardrail_prompt}], }, } ) @@ -842,14 +778,9 @@ async def run_realtime_guardrails( await self._send_to_backend(json.dumps({"type": "response.create"})) self._violation_count += 1 - end_session_after: Optional[int] = getattr( - callback, "end_session_after_n_fails", None - ) - should_end = getattr( - callback, "on_violation", None - ) == "end_session" or ( - end_session_after is not None - and self._violation_count >= end_session_after + end_session_after: Optional[int] = getattr(callback, "end_session_after_n_fails", None) + should_end = getattr(callback, "on_violation", None) == "end_session" or ( + end_session_after is not None and self._violation_count >= end_session_after ) if should_end: verbose_logger.warning( @@ -890,25 +821,14 @@ async def _handle_provider_config_message(self, raw_response) -> None: self.current_conversation_id = returned_object["current_conversation_id"] self.current_item_chunks = returned_object["current_item_chunks"] self.current_delta_type = returned_object["current_delta_type"] - self.session_configuration_request = returned_object[ - "session_configuration_request" - ] - events = ( - transformed_response - if isinstance(transformed_response, list) - else [transformed_response] - ) + self.session_configuration_request = returned_object["session_configuration_request"] + events = transformed_response if isinstance(transformed_response, list) else [transformed_response] for event in events: if self._should_drop_event_from_client(event): continue - is_session_created_event = ( - isinstance(event, dict) and event.get("type") == "session.created" - ) + is_session_created_event = isinstance(event, dict) and event.get("type") == "session.created" if is_session_created_event: - if ( - self._uses_deferred_backend_setup() - and not self._backend_setup_complete - ): + if self._uses_deferred_backend_setup() and not self._backend_setup_complete: self._backend_setup_complete = True self._flushing_pending_messages_until_setup = True try: @@ -944,11 +864,7 @@ async def _handle_provider_config_message(self, raw_response) -> None: await self._maybe_send_guardrail_turn_detection_update() continue ## GUARDRAIL: run on transcription events in provider_config path too - if ( - isinstance(event, dict) - and event.get("type") - == "conversation.item.input_audio_transcription.completed" - ): + if isinstance(event, dict) and event.get("type") == "conversation.item.input_audio_transcription.completed": transcript = event.get("transcript", "") self._collect_user_input_from_backend_event(cast(dict, event)) self.store_message(event_str) @@ -973,9 +889,7 @@ def _parse_backend_event(raw_response: str) -> Optional[dict]: return None return event if isinstance(event, dict) else None - async def _handle_raw_backend_message( - self, event_obj: dict, raw_response: str - ) -> bool: + async def _handle_raw_backend_message(self, event_obj: dict, raw_response: str) -> bool: """Process a backend message without provider_config (raw path). Returns True if the caller should skip the default store+forward (i.e. continue the loop). @@ -987,10 +901,7 @@ async def _handle_raw_backend_message( # Send session.created to the client FIRST so it stays in sync, then inject # the disable-auto-response session.update; otherwise a backend error could # reach the client before it sees session.created. - if ( - event_type == "session.created" - and self._has_audio_transcription_guardrails() - ): + if event_type == "session.created" and self._has_audio_transcription_guardrails(): self.store_message(event_obj) await self.websocket.send_text(self._event_to_client_json(event_obj)) await self._send_to_backend(self._make_disable_auto_response_message()) @@ -1034,18 +945,14 @@ async def backend_to_client_send_messages(self): try: raw_response = raw_response.decode("utf-8") except UnicodeDecodeError: - verbose_logger.warning( - "Received non-UTF-8 binary frame from backend, skipping." - ) + verbose_logger.warning("Received non-UTF-8 binary frame from backend, skipping.") continue if self.provider_config: try: await self._handle_provider_config_message(raw_response) except Exception as e: - verbose_logger.exception( - f"Error processing backend message, skipping: {e}" - ) + verbose_logger.exception(f"Error processing backend message, skipping: {e}") continue else: event = self._parse_backend_event(raw_response) @@ -1072,9 +979,7 @@ async def backend_to_client_send_messages(self): await self.websocket.send_text(json.dumps(translated)) except websockets.exceptions.ConnectionClosed as e: # type: ignore - verbose_logger.exception( - f"Connection closed in backend to client send messages - {e}" - ) + verbose_logger.exception(f"Connection closed in backend to client send messages - {e}") except Exception as e: verbose_logger.exception(f"Error in backend to client send messages: {e}") finally: @@ -1150,20 +1055,12 @@ def _remap_beta_session_to_ga(session: dict) -> dict: # input_audio_format → audio.input.format if "input_audio_format" in session: raw = session.pop("input_audio_format") - inp["format"] = ( - RealTimeStreaming._AUDIO_FORMAT_MAP.get(raw, raw) - if isinstance(raw, str) - else raw - ) + inp["format"] = RealTimeStreaming._AUDIO_FORMAT_MAP.get(raw, raw) if isinstance(raw, str) else raw # output_audio_format → audio.output.format if "output_audio_format" in session: raw = session.pop("output_audio_format") - out["format"] = ( - RealTimeStreaming._AUDIO_FORMAT_MAP.get(raw, raw) - if isinstance(raw, str) - else raw - ) + out["format"] = RealTimeStreaming._AUDIO_FORMAT_MAP.get(raw, raw) if isinstance(raw, str) else raw # turn_detection → audio.input.turn_detection if "turn_detection" in session: @@ -1183,11 +1080,7 @@ def _remap_beta_session_to_ga(session: dict) -> dict: # letting the remapped values take precedence within each sub-key. existing = session.get("audio") or {} for sub_key, sub_val in audio.items(): - if ( - sub_key in existing - and isinstance(existing[sub_key], dict) - and isinstance(sub_val, dict) - ): + if sub_key in existing and isinstance(existing[sub_key], dict) and isinstance(sub_val, dict): existing[sub_key] = {**existing[sub_key], **sub_val} else: existing[sub_key] = sub_val @@ -1212,9 +1105,7 @@ def _translate_event_to_beta(event: dict) -> Optional[dict]: renamed_type = RealTimeStreaming._GA_TO_BETA_EVENT_TYPES.get(event_type) has_item = isinstance(event.get("item"), dict) response = event.get("response") - has_response_output = isinstance(response, dict) and isinstance( - response.get("output"), list - ) + has_response_output = isinstance(response, dict) and isinstance(response.get("output"), list) if renamed_type is None and not has_item and not has_response_output: return event @@ -1222,17 +1113,11 @@ def _translate_event_to_beta(event: dict) -> Optional[dict]: if renamed_type is not None: translated["type"] = renamed_type if has_item: - translated["item"] = RealTimeStreaming._translate_item_content_types( - dict(translated["item"]) - ) + translated["item"] = RealTimeStreaming._translate_item_content_types(dict(translated["item"])) if has_response_output: resp = dict(translated["response"]) resp["output"] = [ - ( - RealTimeStreaming._translate_item_content_types(dict(o)) - if isinstance(o, dict) - else o - ) + (RealTimeStreaming._translate_item_content_types(dict(o)) if isinstance(o, dict) else o) for o in resp["output"] ] translated["response"] = resp @@ -1246,14 +1131,9 @@ def _translate_item_content_types(item: dict) -> dict: return item new_content = [] for block in item["content"]: - if ( - isinstance(block, dict) - and block.get("type") in RealTimeStreaming._GA_TO_BETA_CONTENT_TYPES - ): + if isinstance(block, dict) and block.get("type") in RealTimeStreaming._GA_TO_BETA_CONTENT_TYPES: block = dict(block) - block["type"] = RealTimeStreaming._GA_TO_BETA_CONTENT_TYPES[ - block["type"] - ] + block["type"] = RealTimeStreaming._GA_TO_BETA_CONTENT_TYPES[block["type"]] new_content.append(block) item["content"] = new_content return item @@ -1284,11 +1164,7 @@ async def client_ack_messages(self): # user text so an attacker cannot smuggle blocked # content into a function_call_output. output = item.get("output", "") - output_text = ( - output - if isinstance(output, str) - else json.dumps(output) - ) + output_text = output if isinstance(output, str) else json.dumps(output) if output_text: # Build the sanitized function_call_output up # front so we can hand it to the guardrail @@ -1357,10 +1233,7 @@ async def client_ack_messages(self): self._pending_guardrail_message = combined_text continue # don't forward the original blocked message - if ( - msg_type == "response.create" - and self._pending_guardrail_message - ): + if msg_type == "response.create" and self._pending_guardrail_message: # The guardrail already sent the synthetic AI bubble — drop this # response.create so OpenAI doesn't generate an additional response. self._pending_guardrail_message = None @@ -1429,10 +1302,7 @@ async def client_ack_messages(self): nested_td_present = True if not isinstance(nested_td, dict): nested_td = {} - if ( - nested_td.get("create_response") - is not False - ): + if nested_td.get("create_response") is not False: nested_td["create_response"] = False audio_input["turn_detection"] = nested_td td_overridden = True @@ -1452,10 +1322,7 @@ async def client_ack_messages(self): # GA compatibility: remap beta-style session fields only when # the upstream is in GA mode. Beta upstreams expect the flat # session shape unchanged. - if ( - msg_type == "session.update" - and not self._backend_uses_beta_protocol - ): + if msg_type == "session.update" and not self._backend_uses_beta_protocol: session = msg_obj.get("session", {}) if isinstance(session, dict): session = self._remap_beta_session_to_ga(session) @@ -1465,9 +1332,7 @@ async def client_ack_messages(self): if msg_type == "session.update" and self._event_normalizer: session = msg_obj.get("session") if isinstance(session, dict): - msg_obj["session"] = ( - self._event_normalizer.patch_outgoing_session(session) - ) + msg_obj["session"] = self._event_normalizer.patch_outgoing_session(session) message = json.dumps(msg_obj) except (json.JSONDecodeError, AttributeError): @@ -1491,10 +1356,7 @@ async def client_ack_messages(self): ) if not should_send_setup_before_buffered_messages: self._buffer_pending_message_until_setup(message) - if ( - self._backend_setup_complete - and not self._flushing_pending_messages_until_setup - ): + if self._backend_setup_complete and not self._flushing_pending_messages_until_setup: await self._flush_pending_messages_until_setup() continue diff --git a/litellm/litellm_core_utils/reasoning_effort_utils.py b/litellm/litellm_core_utils/reasoning_effort_utils.py new file mode 100644 index 000000000000..5987392d070c --- /dev/null +++ b/litellm/litellm_core_utils/reasoning_effort_utils.py @@ -0,0 +1,26 @@ +from typing import Literal + +from litellm.constants import ( + DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET, + DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET, + DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET, +) + +OpenAIStyleReasoningEffort = Literal["minimal", "low", "medium", "high"] + + +def reasoning_effort_from_thinking_budget( + budget_tokens: int, +) -> OpenAIStyleReasoningEffort: + """Bucket an Anthropic ``thinking.budget_tokens`` into an OpenAI-style + ``reasoning_effort`` using the shared ``DEFAULT_REASONING_EFFORT_*_THINKING_BUDGET`` + thresholds, so every backend that translates a budget into an effort label + reads the same numbers. + """ + if budget_tokens >= DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET: + return "high" + if budget_tokens >= DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET: + return "medium" + if budget_tokens >= DEFAULT_REASONING_EFFORT_LOW_THINKING_BUDGET: + return "low" + return "minimal" diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.py index 763596336a08..cc9264e93f8f 100644 --- a/litellm/litellm_core_utils/redact_messages.py +++ b/litellm/litellm_core_utils/redact_messages.py @@ -37,10 +37,7 @@ def redact_message_input_output_from_custom_logger( litellm_logging_obj: LiteLLMLoggingObject, result, custom_logger: CustomLogger ): - if ( - hasattr(custom_logger, "message_logging") - and custom_logger.message_logging is not True - ): + if hasattr(custom_logger, "message_logging") and custom_logger.message_logging is not True: return perform_redaction(litellm_logging_obj.model_call_details, result) return result @@ -74,9 +71,7 @@ def _redact_responses_api_output(output_items): # Redact reasoning items in output array if hasattr(output_item, "type") and output_item.type == "reasoning": - if hasattr(output_item, "summary") and isinstance( - output_item.summary, list - ): + if hasattr(output_item, "summary") and isinstance(output_item.summary, list): for summary_item in output_item.summary: if hasattr(summary_item, "text"): summary_item.text = "redacted-by-litellm" @@ -96,9 +91,7 @@ def _redact_responses_api_output_dict(output_items, redacted_str: str): if isinstance(content_item, dict) and "text" in content_item: content_item["text"] = redacted_str - if output_item.get("type") == "reasoning" and isinstance( - output_item.get("summary"), list - ): + if output_item.get("type") == "reasoning" and isinstance(output_item.get("summary"), list): for summary_item in output_item["summary"]: if isinstance(summary_item, dict) and "text" in summary_item: summary_item["text"] = redacted_str @@ -113,9 +106,7 @@ def _redact_standard_logging_object(model_call_details: dict): redacted_str = "redacted-by-litellm" if standard_logging_object.get("messages") is not None: - standard_logging_object["messages"] = [ - {"role": "user", "content": redacted_str} - ] + standard_logging_object["messages"] = [{"role": "user", "content": redacted_str}] response = standard_logging_object.get("response") if response is not None: @@ -164,19 +155,14 @@ def perform_redaction(model_call_details: dict, result): Performs the actual redaction on the logging object and result. """ # Redact model_call_details - model_call_details["messages"] = [ - {"role": "user", "content": "redacted-by-litellm"} - ] + model_call_details["messages"] = [{"role": "user", "content": "redacted-by-litellm"}] model_call_details["prompt"] = "" model_call_details["input"] = "" _redact_standard_logging_object(model_call_details) redact_vertex_ai_metadata_from_litellm_params(model_call_details) # Redact streaming response - if ( - model_call_details.get("stream", False) is True - and "complete_streaming_response" in model_call_details - ): + if model_call_details.get("stream", False) is True and "complete_streaming_response" in model_call_details: _streaming_response = model_call_details["complete_streaming_response"] if hasattr(_streaming_response, "choices"): for choice in _streaming_response.choices: @@ -185,10 +171,7 @@ def perform_redaction(model_call_details: dict, result): elif hasattr(_streaming_response, "output"): _redact_responses_api_output(_streaming_response.output) # Redact reasoning field in ResponsesAPIResponse - if ( - hasattr(_streaming_response, "reasoning") - and _streaming_response.reasoning is not None - ): + if hasattr(_streaming_response, "reasoning") and _streaming_response.reasoning is not None: _streaming_response.reasoning = None # Redact result @@ -212,15 +195,11 @@ def perform_redaction(model_call_details: dict, result): elif isinstance(_result, dict) and "choices" in _result: # Handle dict representation of ModelResponse (e.g., from model_dump()) if _result.get("choices") is not None: - _redact_model_response_dict_choices( - _result["choices"], "redacted-by-litellm" - ) + _redact_model_response_dict_choices(_result["choices"], "redacted-by-litellm") redact_vertex_ai_metadata_from_logged_object(_result) elif isinstance(_result, dict) and "output" in _result: if isinstance(_result.get("output"), list): - _redact_responses_api_output_dict( - _result["output"], "redacted-by-litellm" - ) + _redact_responses_api_output_dict(_result["output"], "redacted-by-litellm") elif isinstance(_result, litellm.ResponsesAPIResponse): if hasattr(_result, "output"): _redact_responses_api_output(_result.output) @@ -258,9 +237,7 @@ def should_redact_message_logging(model_call_details: dict) -> bool: request_headers = metadata.get("headers", {}) # Check for headers that explicitly control redaction - if request_headers and bool( - request_headers.get("litellm-disable-message-redaction", False) - ): + if request_headers and bool(request_headers.get("litellm-disable-message-redaction", False)): # User explicitly disabled redaction via header return False @@ -276,9 +253,7 @@ def should_redact_message_logging(model_call_details: dict) -> bool: break # Priority 1: Check dynamic parameter first (if explicitly set) - dynamic_turn_off = _get_turn_off_message_logging_from_dynamic_params( - model_call_details - ) + dynamic_turn_off = _get_turn_off_message_logging_from_dynamic_params(model_call_details) if dynamic_turn_off is not None: # Dynamic parameter is explicitly set, use it return dynamic_turn_off @@ -291,9 +266,7 @@ def should_redact_message_logging(model_call_details: dict) -> bool: return litellm.turn_off_message_logging is True -def redact_message_input_output_from_logging( - model_call_details: dict, result, input: Optional[Any] = None -) -> Any: +def redact_message_input_output_from_logging(model_call_details: dict, result, input: Optional[Any] = None) -> Any: """ Removes messages, prompts, input, response from logging. This modifies the data in-place only redacts when litellm.turn_off_message_logging == True @@ -311,13 +284,11 @@ def _get_turn_off_message_logging_from_dynamic_params( handles boolean and string values of `turn_off_message_logging` """ - standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = ( - model_call_details.get("standard_callback_dynamic_params", None) + standard_callback_dynamic_params: Optional[StandardCallbackDynamicParams] = model_call_details.get( + "standard_callback_dynamic_params", None ) if standard_callback_dynamic_params: - _turn_off_message_logging = standard_callback_dynamic_params.get( - "turn_off_message_logging" - ) + _turn_off_message_logging = standard_callback_dynamic_params.get("turn_off_message_logging") if isinstance(_turn_off_message_logging, bool): return _turn_off_message_logging elif isinstance(_turn_off_message_logging, str): diff --git a/litellm/litellm_core_utils/rules.py b/litellm/litellm_core_utils/rules.py index 75c177c72495..425c3a80e26f 100644 --- a/litellm/litellm_core_utils/rules.py +++ b/litellm/litellm_core_utils/rules.py @@ -55,11 +55,7 @@ def post_call_rules(self, input: Optional[str], model: str) -> bool: ) # type: ignore elif isinstance(decision, dict): decision_val = decision.get("decision", True) - decision_message = decision.get( - "message", "LLM Response failed post-call-rule check" - ) + decision_message = decision.get("message", "LLM Response failed post-call-rule check") if decision_val is False: - raise litellm.APIResponseValidationError( - message=decision_message, llm_provider="", model=model - ) # type: ignore + raise litellm.APIResponseValidationError(message=decision_message, llm_provider="", model=model) # type: ignore return True diff --git a/litellm/litellm_core_utils/sensitive_data_masker.py b/litellm/litellm_core_utils/sensitive_data_masker.py index 3135b5f831a4..daca48120cde 100644 --- a/litellm/litellm_core_utils/sensitive_data_masker.py +++ b/litellm/litellm_core_utils/sensitive_data_masker.py @@ -46,9 +46,7 @@ def _mask_value(self, value: str) -> str: if not value_str: return value if len(value_str) <= (self.visible_prefix + self.visible_suffix): - return ( - self.mask_char * len(value_str) if self.mask_short_values else value_str - ) + return self.mask_char * len(value_str) if self.mask_short_values else value_str masked_length = len(value_str) - (self.visible_prefix + self.visible_suffix) @@ -56,11 +54,11 @@ def _mask_value(self, value: str) -> str: if self.visible_suffix == 0: return f"{value_str[: self.visible_prefix]}{self.mask_char * masked_length}" else: - return f"{value_str[: self.visible_prefix]}{self.mask_char * masked_length}{value_str[-self.visible_suffix :]}" + return ( + f"{value_str[: self.visible_prefix]}{self.mask_char * masked_length}{value_str[-self.visible_suffix :]}" + ) - def is_sensitive_key( - self, key: str, excluded_keys: Optional[Set[str]] = None - ) -> bool: + def is_sensitive_key(self, key: str, excluded_keys: Optional[Set[str]] = None) -> bool: # Check if key is in excluded_keys first (exact match) if excluded_keys and key in excluded_keys: return False @@ -94,23 +92,13 @@ def _mask_sequence( for item in values: if isinstance(item, Mapping): - masked_items.append( - self.mask_dict(dict(item), depth + 1, max_depth, excluded_keys) - ) + masked_items.append(self.mask_dict(dict(item), depth + 1, max_depth, excluded_keys)) elif isinstance(item, list): - masked_items.append( - self._mask_sequence( - item, depth + 1, max_depth, excluded_keys, key_is_sensitive - ) - ) + masked_items.append(self._mask_sequence(item, depth + 1, max_depth, excluded_keys, key_is_sensitive)) elif key_is_sensitive and isinstance(item, str): masked_items.append(self._mask_value(item)) else: - masked_items.append( - item - if isinstance(item, (int, float, bool, str, list)) - else str(item) - ) + masked_items.append(item if isinstance(item, (int, float, bool, str, list)) else str(item)) return masked_items def mask_dict( @@ -128,24 +116,16 @@ def mask_dict( try: key_is_sensitive = self.is_sensitive_key(k, excluded_keys) if isinstance(v, Mapping): - masked_data[k] = self.mask_dict( - dict(v), depth + 1, max_depth, excluded_keys - ) + masked_data[k] = self.mask_dict(dict(v), depth + 1, max_depth, excluded_keys) elif isinstance(v, list): - masked_data[k] = self._mask_sequence( - v, depth + 1, max_depth, excluded_keys, key_is_sensitive - ) + masked_data[k] = self._mask_sequence(v, depth + 1, max_depth, excluded_keys, key_is_sensitive) elif hasattr(v, "__dict__") and not isinstance(v, type): - masked_data[k] = self.mask_dict( - vars(v), depth + 1, max_depth, excluded_keys - ) + masked_data[k] = self.mask_dict(vars(v), depth + 1, max_depth, excluded_keys) elif key_is_sensitive: str_value = str(v) if v is not None else "" masked_data[k] = self._mask_value(str_value) else: - masked_data[k] = ( - v if isinstance(v, (int, float, bool, str, list)) else str(v) - ) + masked_data[k] = v if isinstance(v, (int, float, bool, str, list)) else str(v) except Exception: masked_data[k] = "" @@ -155,9 +135,7 @@ def mask_dict( _default_masker = SensitiveDataMasker() -def mask_sensitive_keys( - data: Dict[str, Any], sensitive_fields: Set[str] -) -> Dict[str, Any]: +def mask_sensitive_keys(data: Dict[str, Any], sensitive_fields: Set[str]) -> Dict[str, Any]: """Return a new dict with values masked for keys listed in ``sensitive_fields``. Unlike :meth:`SensitiveDataMasker.mask_dict`, this does exact key-name diff --git a/litellm/litellm_core_utils/specialty_caches/dynamic_logging_cache.py b/litellm/litellm_core_utils/specialty_caches/dynamic_logging_cache.py index 0a6a4e82c725..e71f64bc9001 100644 --- a/litellm/litellm_core_utils/specialty_caches/dynamic_logging_cache.py +++ b/litellm/litellm_core_utils/specialty_caches/dynamic_logging_cache.py @@ -68,15 +68,11 @@ def get_cache_key(self, args: dict) -> str: return cache_key def get_cache(self, credentials: dict, service_name: str) -> Optional[Any]: - key_name = self.get_cache_key( - args={**credentials, "service_name": service_name} - ) + key_name = self.get_cache_key(args={**credentials, "service_name": service_name}) response = self.cache.get_cache(key=key_name) return response def set_cache(self, credentials: dict, service_name: str, logging_obj: Any) -> None: - key_name = self.get_cache_key( - args={**credentials, "service_name": service_name} - ) + key_name = self.get_cache_key(args={**credentials, "service_name": service_name}) self.cache.set_cache(key=key_name, value=logging_obj) return None diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py index 1b1b652eaa05..deeee3b7daf3 100644 --- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py +++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py @@ -62,9 +62,7 @@ def _created_at(chunk: Any) -> Union[int, float]: else: params = getattr(chunk, "_hidden_params", {}) if isinstance(params, dict): - return cast( - Union[int, float], params.get("created_at", float("inf")) - ) + return cast(Union[int, float], params.get("created_at", float("inf"))) return float("inf") return sorted(chunks, key=_created_at) @@ -95,9 +93,7 @@ def apply_provider_assembled_streaming_metadata( custom_llm_provider = None if logging_obj is not None: - custom_llm_provider = logging_obj.model_call_details.get( - "custom_llm_provider" - ) + custom_llm_provider = logging_obj.model_call_details.get("custom_llm_provider") try: from litellm.litellm_core_utils.get_llm_provider_logic import ( @@ -140,9 +136,7 @@ def _get_chunk_id(chunks: List[Dict[str, Any]]) -> str: return "" @staticmethod - def _get_model_from_chunks( - chunks: List[Dict[str, Any]], first_chunk_model: str - ) -> str: + def _get_model_from_chunks(chunks: List[Dict[str, Any]], first_chunk_model: str) -> str: """ Get the actual model from chunks, preferring a model that differs from the first chunk. @@ -204,18 +198,12 @@ def build_base_response(self, chunks: List[Dict[str, Any]]) -> ModelResponse: } ) - response = self.update_model_response_with_hidden_params( - model_response=response, chunk=chunk - ) + response = self.update_model_response_with_hidden_params(model_response=response, chunk=chunk) return response - def get_combined_tool_content( - self, tool_call_chunks: List[Dict[str, Any]] - ) -> List[ChatCompletionMessageToolCall]: + def get_combined_tool_content(self, tool_call_chunks: List[Dict[str, Any]]) -> List[ChatCompletionMessageToolCall]: tool_calls_list: List[ChatCompletionMessageToolCall] = [] - tool_call_map: Dict[ - int, Dict[str, Any] - ] = {} # Map to store tool calls by index + tool_call_map: Dict[int, Dict[str, Any]] = {} # Map to store tool calls by index for chunk in tool_call_chunks: choices = chunk["choices"] @@ -231,15 +219,9 @@ def get_combined_tool_content( # Check if tool_call has function (either as attribute or dict key) has_function = False if isinstance(tool_call, dict): - has_function = ( - "function" in tool_call - and tool_call["function"] is not None - ) + has_function = "function" in tool_call and tool_call["function"] is not None else: - has_function = ( - hasattr(tool_call, "function") - and tool_call.function is not None - ) + has_function = hasattr(tool_call, "function") and tool_call.function is not None if not has_function: continue @@ -271,17 +253,13 @@ def get_combined_tool_content( if function.get("name"): tool_call_map[index]["name"] = function["name"] if function.get("arguments"): - tool_call_map[index]["arguments"].append( - function["arguments"] - ) + tool_call_map[index]["arguments"].append(function["arguments"]) else: # function is an object if hasattr(function, "name") and function.name: tool_call_map[index]["name"] = function.name if hasattr(function, "arguments") and function.arguments: - tool_call_map[index]["arguments"].append( - function.arguments - ) + tool_call_map[index]["arguments"].append(function.arguments) else: # tool_call is an object if hasattr(tool_call, "id") and tool_call.id: @@ -289,52 +267,33 @@ def get_combined_tool_content( if hasattr(tool_call, "type") and tool_call.type: tool_call_map[index]["type"] = tool_call.type if hasattr(tool_call, "function"): - if ( - hasattr(tool_call.function, "name") - and tool_call.function.name - ): + if hasattr(tool_call.function, "name") and tool_call.function.name: tool_call_map[index]["name"] = tool_call.function.name - if ( - hasattr(tool_call.function, "arguments") - and tool_call.function.arguments - ): - tool_call_map[index]["arguments"].append( - tool_call.function.arguments - ) + if hasattr(tool_call.function, "arguments") and tool_call.function.arguments: + tool_call_map[index]["arguments"].append(tool_call.function.arguments) # Preserve provider_specific_fields from streaming chunks provider_fields = None if isinstance(tool_call, dict): provider_fields = tool_call.get("provider_specific_fields") - if not provider_fields and isinstance( - tool_call.get("function"), dict - ): - provider_fields = tool_call["function"].get( - "provider_specific_fields" - ) + if not provider_fields and isinstance(tool_call.get("function"), dict): + provider_fields = tool_call["function"].get("provider_specific_fields") else: - if ( - hasattr(tool_call, "provider_specific_fields") - and tool_call.provider_specific_fields - ): + if hasattr(tool_call, "provider_specific_fields") and tool_call.provider_specific_fields: provider_fields = tool_call.provider_specific_fields elif ( hasattr(tool_call, "function") and hasattr(tool_call.function, "provider_specific_fields") and tool_call.function.provider_specific_fields ): - provider_fields = ( - tool_call.function.provider_specific_fields - ) + provider_fields = tool_call.function.provider_specific_fields if provider_fields: # Merge provider_specific_fields if multiple chunks have them if tool_call_map[index]["provider_specific_fields"] is None: tool_call_map[index]["provider_specific_fields"] = {} if isinstance(provider_fields, dict): - tool_call_map[index]["provider_specific_fields"].update( - provider_fields - ) + tool_call_map[index]["provider_specific_fields"].update(provider_fields) # Convert the map to a list of tool calls for index in sorted(tool_call_map.keys()): @@ -357,18 +316,14 @@ def get_combined_tool_content( # Add provider_specific_fields if present (for thought signatures in Gemini 3) if tool_call_data.get("provider_specific_fields"): - tool_call_params["provider_specific_fields"] = tool_call_data[ - "provider_specific_fields" - ] + tool_call_params["provider_specific_fields"] = tool_call_data["provider_specific_fields"] tool_call = ChatCompletionMessageToolCall(**tool_call_params) tool_calls_list.append(tool_call) return tool_calls_list - def get_combined_function_call_content( - self, function_call_chunks: List[Dict[str, Any]] - ) -> FunctionCall: + def get_combined_function_call_content(self, function_call_chunks: List[Dict[str, Any]]) -> FunctionCall: argument_list = [] delta = function_call_chunks[0]["choices"][0]["delta"] function_call = delta.get("function_call", "") @@ -414,19 +369,13 @@ def get_combined_content( def get_combined_thinking_content( self, chunks: List[Dict[str, Any]] - ) -> Optional[ - List[ - Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"] - ] - ]: + ) -> Optional[List[Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"]]]: from litellm.types.llms.openai import ( ChatCompletionRedactedThinkingBlock, ChatCompletionThinkingBlock, ) - thinking_blocks: List[ - Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"] - ] = [] + thinking_blocks: List[Union["ChatCompletionThinkingBlock", "ChatCompletionRedactedThinkingBlock"]] = [] current_thinking_text_parts: List[str] = [] current_signature: Optional[str] = None @@ -476,14 +425,10 @@ def _flush_thinking_block() -> None: return thinking_blocks return None - def get_combined_reasoning_content( - self, chunks: List[Dict[str, Any]] - ) -> ChatCompletionAssistantContentValue: + def get_combined_reasoning_content(self, chunks: List[Dict[str, Any]]) -> ChatCompletionAssistantContentValue: return self.get_combined_content(chunks, delta_key="reasoning_content") - def get_combined_audio_content( - self, chunks: List[Dict[str, Any]] - ) -> ChatCompletionAudioResponse: + def get_combined_audio_content(self, chunks: List[Dict[str, Any]]) -> ChatCompletionAudioResponse: base64_data_list: List[str] = [] transcript_list: List[str] = [] expires_at: Optional[int] = None @@ -532,21 +477,13 @@ def _usage_chunk_calculation_helper(self, usage_chunk: Usage) -> dict: cache_read_input_tokens = usage_chunk.get("cache_read_input_tokens") if hasattr(usage_chunk, "completion_tokens_details"): if isinstance(usage_chunk.completion_tokens_details, dict): - completion_tokens_details = CompletionTokensDetails( - **usage_chunk.completion_tokens_details - ) - elif isinstance( - usage_chunk.completion_tokens_details, CompletionTokensDetails - ): + completion_tokens_details = CompletionTokensDetails(**usage_chunk.completion_tokens_details) + elif isinstance(usage_chunk.completion_tokens_details, CompletionTokensDetails): completion_tokens_details = usage_chunk.completion_tokens_details if hasattr(usage_chunk, "prompt_tokens_details"): if isinstance(usage_chunk.prompt_tokens_details, dict): - prompt_tokens_details = PromptTokensDetailsWrapper( - **usage_chunk.prompt_tokens_details - ) - elif isinstance( - usage_chunk.prompt_tokens_details, PromptTokensDetailsWrapper - ): + prompt_tokens_details = PromptTokensDetailsWrapper(**usage_chunk.prompt_tokens_details) + elif isinstance(usage_chunk.prompt_tokens_details, PromptTokensDetailsWrapper): prompt_tokens_details = usage_chunk.prompt_tokens_details return { @@ -608,49 +545,31 @@ def _calculate_usage_per_chunk( usage_chunk: Optional[Usage] = None if "usage" in chunk: usage_chunk = chunk["usage"] - elif ( - isinstance(chunk, ModelResponse) - or isinstance(chunk, ModelResponseStream) - ) and hasattr(chunk, "_hidden_params"): + elif (isinstance(chunk, ModelResponse) or isinstance(chunk, ModelResponseStream)) and hasattr( + chunk, "_hidden_params" + ): usage_chunk = chunk._hidden_params.get("usage", None) if usage_chunk is not None: if isinstance(usage_chunk, dict): usage_chunk = Usage(**usage_chunk) usage_chunk_dict = self._usage_chunk_calculation_helper(usage_chunk) - if ( - usage_chunk_dict["prompt_tokens"] is not None - and usage_chunk_dict["prompt_tokens"] > 0 - ): + if usage_chunk_dict["prompt_tokens"] is not None and usage_chunk_dict["prompt_tokens"] > 0: prompt_tokens = usage_chunk_dict["prompt_tokens"] - if ( - usage_chunk_dict["completion_tokens"] is not None - and usage_chunk_dict["completion_tokens"] > 0 - ): + if usage_chunk_dict["completion_tokens"] is not None and usage_chunk_dict["completion_tokens"] > 0: completion_tokens = usage_chunk_dict["completion_tokens"] completion_usage_updates += 1 if usage_chunk_dict["cache_creation_input_tokens"] is not None and ( - usage_chunk_dict["cache_creation_input_tokens"] > 0 - or cache_creation_input_tokens is None + usage_chunk_dict["cache_creation_input_tokens"] > 0 or cache_creation_input_tokens is None ): - cache_creation_input_tokens = usage_chunk_dict[ - "cache_creation_input_tokens" - ] + cache_creation_input_tokens = usage_chunk_dict["cache_creation_input_tokens"] if usage_chunk_dict["cache_read_input_tokens"] is not None and ( - usage_chunk_dict["cache_read_input_tokens"] > 0 - or cache_read_input_tokens is None + usage_chunk_dict["cache_read_input_tokens"] > 0 or cache_read_input_tokens is None ): - cache_read_input_tokens = usage_chunk_dict[ - "cache_read_input_tokens" - ] + cache_read_input_tokens = usage_chunk_dict["cache_read_input_tokens"] if usage_chunk_dict["completion_tokens_details"] is not None: - completion_tokens_details = usage_chunk_dict[ - "completion_tokens_details" - ] - if ( - hasattr(usage_chunk, "server_tool_use") - and usage_chunk.server_tool_use is not None - ): + completion_tokens_details = usage_chunk_dict["completion_tokens_details"] + if hasattr(usage_chunk, "server_tool_use") and usage_chunk.server_tool_use is not None: # Coerce dict to ServerToolUse so downstream cost-calc code # (which accesses .web_search_requests as an attribute) # doesn't raise AttributeError. Some providers / streaming @@ -660,9 +579,7 @@ def _calculate_usage_per_chunk( elif isinstance(usage_chunk.server_tool_use, ServerToolUse): server_tool_use = usage_chunk.server_tool_use else: - server_tool_use = ServerToolUse.model_validate( - usage_chunk.server_tool_use - ) + server_tool_use = ServerToolUse.model_validate(usage_chunk.server_tool_use) if ( usage_chunk_dict["prompt_tokens_details"] is not None and getattr( @@ -717,9 +634,7 @@ def _reset_anthropic_cursor_completion_tokens( does not silently affect other providers that may legitimately report ``completion_tokens=1`` from a single usage event. """ - saw_non_cursor_completion = ( - completion_tokens > 1 or completion_usage_updates >= 2 - ) + saw_non_cursor_completion = completion_tokens > 1 or completion_usage_updates >= 2 if saw_non_cursor_completion: return completion_tokens @@ -755,30 +670,20 @@ def calculate_usage( prompt_tokens = calculated_usage_per_chunk["prompt_tokens"] completion_tokens = calculated_usage_per_chunk["completion_tokens"] ## anthropic prompt caching information ## - cache_creation_input_tokens: Optional[int] = calculated_usage_per_chunk[ - "cache_creation_input_tokens" - ] - cache_read_input_tokens: Optional[int] = calculated_usage_per_chunk[ - "cache_read_input_tokens" - ] + cache_creation_input_tokens: Optional[int] = calculated_usage_per_chunk["cache_creation_input_tokens"] + cache_read_input_tokens: Optional[int] = calculated_usage_per_chunk["cache_read_input_tokens"] - server_tool_use: Optional[ServerToolUse] = calculated_usage_per_chunk[ - "server_tool_use" + server_tool_use: Optional[ServerToolUse] = calculated_usage_per_chunk["server_tool_use"] + web_search_requests: Optional[int] = calculated_usage_per_chunk["web_search_requests"] + completion_tokens_details: Optional[CompletionTokensDetails] = calculated_usage_per_chunk[ + "completion_tokens_details" ] - web_search_requests: Optional[int] = calculated_usage_per_chunk[ - "web_search_requests" + prompt_tokens_details: Optional[PromptTokensDetailsWrapper] = calculated_usage_per_chunk[ + "prompt_tokens_details" ] - completion_tokens_details: Optional[CompletionTokensDetails] = ( - calculated_usage_per_chunk["completion_tokens_details"] - ) - prompt_tokens_details: Optional[PromptTokensDetailsWrapper] = ( - calculated_usage_per_chunk["prompt_tokens_details"] - ) try: - returned_usage.prompt_tokens = prompt_tokens or token_counter( - model=model, messages=messages - ) + returned_usage.prompt_tokens = prompt_tokens or token_counter(model=model, messages=messages) except Exception: # don't allow this failing to block a complete streaming response from being returned print_verbose("token_counter failed, assuming prompt tokens is 0") returned_usage.prompt_tokens = 0 @@ -790,9 +695,7 @@ def calculate_usage( count_response_tokens=True, # count_response_tokens is a Flag to tell token counter this is a response, No need to add extra tokens we do for input messages ) ) - returned_usage.total_tokens = ( - returned_usage.prompt_tokens + returned_usage.completion_tokens - ) + returned_usage.total_tokens = returned_usage.prompt_tokens + returned_usage.completion_tokens if cache_creation_input_tokens is not None: returned_usage._cache_creation_input_tokens = cache_creation_input_tokens @@ -803,31 +706,25 @@ def calculate_usage( ) # for anthropic if cache_read_input_tokens is not None: returned_usage._cache_read_input_tokens = cache_read_input_tokens - setattr( - returned_usage, "cache_read_input_tokens", cache_read_input_tokens - ) # for anthropic + setattr(returned_usage, "cache_read_input_tokens", cache_read_input_tokens) # for anthropic if completion_tokens_details is not None: if isinstance(completion_tokens_details, CompletionTokensDetails): - returned_usage.completion_tokens_details = ( - CompletionTokensDetailsWrapper( - **completion_tokens_details.model_dump() - ) + returned_usage.completion_tokens_details = CompletionTokensDetailsWrapper( + **completion_tokens_details.model_dump() ) else: returned_usage.completion_tokens_details = completion_tokens_details if reasoning_tokens is not None: if returned_usage.completion_tokens_details is None: - returned_usage.completion_tokens_details = ( - CompletionTokensDetailsWrapper(reasoning_tokens=reasoning_tokens) + returned_usage.completion_tokens_details = CompletionTokensDetailsWrapper( + reasoning_tokens=reasoning_tokens ) elif ( returned_usage.completion_tokens_details is not None and returned_usage.completion_tokens_details.reasoning_tokens is None ): - returned_usage.completion_tokens_details.reasoning_tokens = ( - reasoning_tokens - ) + returned_usage.completion_tokens_details.reasoning_tokens = reasoning_tokens if prompt_tokens_details is not None: returned_usage.prompt_tokens_details = prompt_tokens_details @@ -839,9 +736,7 @@ def calculate_usage( web_search_requests=web_search_requests ) else: - returned_usage.prompt_tokens_details.web_search_requests = ( - web_search_requests - ) + returned_usage.prompt_tokens_details.web_search_requests = web_search_requests # Return a new usage object with the new values diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py index 7d7a8e562cb6..587a3a58a94a 100644 --- a/litellm/litellm_core_utils/streaming_handler.py +++ b/litellm/litellm_core_utils/streaming_handler.py @@ -134,18 +134,14 @@ def __init__( litellm_params: GenericLiteLLMParams = GenericLiteLLMParams( **self.logging_obj.model_call_details.get("litellm_params", {}) ) - self.merge_reasoning_content_in_choices: bool = ( - litellm_params.merge_reasoning_content_in_choices or False - ) + self.merge_reasoning_content_in_choices: bool = litellm_params.merge_reasoning_content_in_choices or False self.sent_first_thinking_block = False self.sent_last_thinking_block = False self.thinking_content = "" self.system_fingerprint: Optional[str] = None self.received_finish_reason: Optional[str] = None - self.intermittent_finish_reason: Optional[str] = ( - None # finish reasons that show up mid-stream - ) + self.intermittent_finish_reason: Optional[str] = None # finish reasons that show up mid-stream self.special_tokens = [ "<|assistant|>", "<|system|>", @@ -162,9 +158,7 @@ def __init__( _api_base = get_api_base( model=model or "", - optional_params=self.logging_obj.model_call_details.get( - "litellm_params", {} - ), + optional_params=self.logging_obj.model_call_details.get("litellm_params", {}), ) self._hidden_params = { @@ -180,14 +174,10 @@ def __init__( self.response_id: Optional[str] = None self.logging_loop = None self.rules = Rules() - self.stream_options = stream_options or getattr( - logging_obj, "stream_options", None - ) + self.stream_options = stream_options or getattr(logging_obj, "stream_options", None) self.messages = getattr(logging_obj, "messages", None) self.sent_stream_usage = False - self.send_stream_usage = ( - True if self.check_send_stream_usage(self.stream_options) else False - ) + self.send_stream_usage = True if self.check_send_stream_usage(self.stream_options) else False self.tool_call = False self.chunks: List = [] # keep track of the returned chunks - used for calculating the input/output tokens for stream options self._repeated_messages_count = 1 @@ -195,18 +185,11 @@ def __init__( self.created: Optional[int] = None self._last_returned_hidden_params: Optional[dict] = None - _cached_logging_provider = self.logging_obj.model_call_details.get( - "custom_llm_provider", None - ) + _cached_logging_provider = self.logging_obj.model_call_details.get("custom_llm_provider", None) self._cached_logging_llm_provider: Optional[str] = _cached_logging_provider _effective_model = model or "" - if ( - custom_llm_provider == "openai" - and custom_llm_provider != _cached_logging_provider - ): - _effective_model = "{}/{}".format( - _cached_logging_provider, _effective_model - ) + if custom_llm_provider == "openai" and custom_llm_provider != _cached_logging_provider: + _effective_model = "{}/{}".format(_cached_logging_provider, _effective_model) self._cached_model_name: str = _effective_model # Snapshot assumes self._hidden_params is populated from litellm_params @@ -261,19 +244,14 @@ async def aclose(self): ) def check_send_stream_usage(self, stream_options: Optional[dict]): - return ( - stream_options is not None - and stream_options.get("include_usage", False) is True - ) + return stream_options is not None and stream_options.get("include_usage", False) is True def check_is_function_call(self, logging_obj) -> bool: from litellm.litellm_core_utils.prompt_templates.common_utils import ( is_function_call, ) - if hasattr(logging_obj, "optional_params") and isinstance( - logging_obj.optional_params, dict - ): + if hasattr(logging_obj, "optional_params") and isinstance(logging_obj.optional_params, dict): if is_function_call(logging_obj.optional_params): return True @@ -316,9 +294,7 @@ def raise_on_model_repetition(self) -> None: last_content = self.chunks[-1].choices[0].delta.content if ( - last_content is None - or not isinstance(last_content, str) - or len(last_content) <= 2 + last_content is None or not isinstance(last_content, str) or len(last_content) <= 2 ): # ignore empty content - https://github.com/BerriAI/litellm/issues/5158#issuecomment-2287156946 self._repeated_messages_count = 1 return @@ -333,9 +309,7 @@ def raise_on_model_repetition(self) -> None: if self._repeated_messages_count >= litellm.REPEATED_STREAMING_CHUNK_LIMIT: # All last n chunks are identical raise litellm.InternalServerError( - message="The model is repeating the same chunk = {}.".format( - last_content - ), + message="The model is repeating the same chunk = {}.".format(last_content), model="", llm_provider="", ) @@ -378,9 +352,7 @@ def check_special_tokens(self, chunk: str, finish_reason: Optional[str]): def handle_predibase_chunk(self, chunk): try: if not isinstance(chunk, str): - chunk = chunk.decode( - "utf-8" - ) # DO NOT REMOVE this: This is required for HF inference API + Streaming + chunk = chunk.decode("utf-8") # DO NOT REMOVE this: This is required for HF inference API + Streaming text = "" is_finished = False finish_reason = "" @@ -390,14 +362,10 @@ def handle_predibase_chunk(self, chunk): print_verbose(f"data json: {data_json}") if "token" in data_json and "text" in data_json["token"]: text = data_json["token"]["text"] - if data_json.get("details", False) and data_json["details"].get( - "finish_reason", False - ): + if data_json.get("details", False) and data_json["details"].get("finish_reason", False): is_finished = True finish_reason = data_json["details"]["finish_reason"] - elif data_json.get( - "generated_text", False - ): # if full generated text exists, then stream is complete + elif data_json.get("generated_text", False): # if full generated text exists, then stream is complete text = "" # don't return the final bos token is_finished = True finish_reason = "stop" @@ -509,18 +477,14 @@ def handle_azure_chunk(self, chunk): if data_json["choices"][0].get("finish_reason", None): is_finished = True finish_reason = data_json["choices"][0]["finish_reason"] - print_verbose( - f"text: {text}; is_finished: {is_finished}; finish_reason: {finish_reason}" - ) + print_verbose(f"text: {text}; is_finished: {is_finished}; finish_reason: {finish_reason}") return { "text": text, "is_finished": is_finished, "finish_reason": finish_reason, } except Exception: - raise ValueError( - f"Unable to parse response. Original response: {chunk}" - ) + raise ValueError(f"Unable to parse response. Original response: {chunk}") elif "error" in chunk: raise ValueError(f"Unable to parse response. Original response: {chunk}") else: @@ -560,29 +524,18 @@ def handle_openai_chat_completion_chunk(self, chunk): logprobs = None usage = None if str_line and str_line.choices and len(str_line.choices) > 0: - if ( - str_line.choices[0].delta is not None - and str_line.choices[0].delta.content is not None - ): + if str_line.choices[0].delta is not None and str_line.choices[0].delta.content is not None: text = str_line.choices[0].delta.content else: # function/tool calling chunk - when content is None. in this case we just return the original chunk from openai pass if str_line.choices[0].finish_reason: - is_finished = ( - True # check if str_line._hidden_params["is_finished"] is True - ) - if ( - hasattr(str_line, "_hidden_params") - and str_line._hidden_params.get("is_finished") is not None - ): + is_finished = True # check if str_line._hidden_params["is_finished"] is True + if hasattr(str_line, "_hidden_params") and str_line._hidden_params.get("is_finished") is not None: is_finished = str_line._hidden_params.get("is_finished") finish_reason = str_line.choices[0].finish_reason # checking for logprobs - if ( - hasattr(str_line.choices[0], "logprobs") - and str_line.choices[0].logprobs is not None - ): + if hasattr(str_line.choices[0], "logprobs") and str_line.choices[0].logprobs is not None: logprobs = str_line.choices[0].logprobs else: logprobs = None @@ -663,23 +616,17 @@ def handle_baseten_chunk(self, chunk): return data_json["model_output"]["data"][0] elif isinstance(data_json["model_output"], str): return data_json["model_output"] - elif "completion" in data_json and isinstance( - data_json["completion"], str - ): + elif "completion" in data_json and isinstance(data_json["completion"], str): return data_json["completion"] else: - raise ValueError( - f"Unable to parse response. Original response: {chunk}" - ) + raise ValueError(f"Unable to parse response. Original response: {chunk}") else: return "" else: return "" except Exception as e: verbose_logger.exception( - "litellm.CustomStreamWrapper.handle_baseten_chunk(): Exception occured - {}".format( - str(e) - ) + "litellm.CustomStreamWrapper.handle_baseten_chunk(): Exception occured - {}".format(str(e)) ) return "" @@ -691,9 +638,7 @@ def handle_triton_stream(self, chunk): if isinstance(chunk, bytes): chunk = chunk.decode("utf-8") if "text_output" in chunk: - response = ( - CustomStreamWrapper._strip_sse_data_from_chunk(chunk) or "" - ) + response = CustomStreamWrapper._strip_sse_data_from_chunk(chunk) or "" response = response.strip() parsed_response = json.loads(response) else: @@ -705,9 +650,7 @@ def handle_triton_stream(self, chunk): } else: print_verbose(f"chunk: {chunk} (Type: {type(chunk)})") - raise ValueError( - f"Unable to parse response. Original response: {chunk}" - ) + raise ValueError(f"Unable to parse response. Original response: {chunk}") text = parsed_response.get("text_output", "") finish_reason = parsed_response.get("stop_reason") is_finished = parsed_response.get("is_finished", False) @@ -722,9 +665,7 @@ def handle_triton_stream(self, chunk): except Exception as e: raise e - def model_response_creator( - self, chunk: Optional[dict] = None, hidden_params: Optional[dict] = None - ): + def model_response_creator(self, chunk: Optional[dict] = None, hidden_params: Optional[dict] = None): _model = self._cached_model_name _logging_obj_llm_provider = self._cached_logging_llm_provider @@ -766,10 +707,7 @@ def model_response_creator( **self._base_hidden_params, } - if ( - len(model_response.choices) > 0 - and getattr(model_response.choices[0], "delta") is not None - ): + if len(model_response.choices) > 0 and getattr(model_response.choices[0], "delta") is not None: # do nothing, if object instantiated pass else: @@ -786,9 +724,7 @@ def is_delta_empty(self, delta: Delta) -> bool: is_empty = False return is_empty - def set_model_id( - self, id: str, model_response: ModelResponseStream - ) -> ModelResponseStream: + def set_model_id(self, id: str, model_response: ModelResponseStream) -> ModelResponseStream: """ Set the model id and response id to the given id. @@ -814,9 +750,7 @@ def copy_model_response_level_provider_specific_fields( """ Copy provider_specific_fields from original_chunk to model_response. """ - provider_specific_fields = getattr( - original_chunk, "provider_specific_fields", None - ) + provider_specific_fields = getattr(original_chunk, "provider_specific_fields", None) if provider_specific_fields is not None: model_response.provider_specific_fields = provider_specific_fields for k, v in provider_specific_fields.items(): @@ -831,19 +765,13 @@ def is_chunk_non_empty( ) -> bool: if ( "content" in completion_obj - and ( - isinstance(completion_obj["content"], str) - and len(completion_obj["content"]) > 0 - ) + and (isinstance(completion_obj["content"], str) and len(completion_obj["content"]) > 0) or ( "tool_calls" in completion_obj and completion_obj["tool_calls"] is not None and len(completion_obj["tool_calls"]) > 0 ) - or ( - "function_call" in completion_obj - and completion_obj["function_call"] is not None - ) + or ("function_call" in completion_obj and completion_obj["function_call"] is not None) or ( "tool_calls" in model_response.choices[0].delta and model_response.choices[0].delta["tool_calls"] is not None @@ -862,10 +790,7 @@ def is_chunk_non_empty( "provider_specific_fields" in model_response and model_response.choices[0].delta.provider_specific_fields is not None ) - or ( - "provider_specific_fields" in response_obj - and response_obj["provider_specific_fields"] is not None - ) + or ("provider_specific_fields" in response_obj and response_obj["provider_specific_fields"] is not None) or ( "annotations" in model_response.choices[0].delta and model_response.choices[0].delta.annotations is not None @@ -875,27 +800,20 @@ def is_chunk_non_empty( and hasattr(model_response.choices[0].delta, "role") and model_response.choices[0].delta.role is not None ) - or ( - getattr(model_response.choices[0].delta, "reasoning_items", None) - is not None - ) + or (getattr(model_response.choices[0].delta, "reasoning_items", None) is not None) ): return True else: return False - def strip_role_from_delta( - self, model_response: ModelResponseStream - ) -> ModelResponseStream: + def strip_role_from_delta(self, model_response: ModelResponseStream) -> ModelResponseStream: """ Strip the role from the delta. """ if self.sent_first_chunk is False: model_response.choices[0].delta["role"] = "assistant" self.sent_first_chunk = True - elif self.sent_first_chunk is True and hasattr( - model_response.choices[0].delta, "role" - ): + elif self.sent_first_chunk is True and hasattr(model_response.choices[0].delta, "role"): _initial_delta = model_response.choices[0].delta.model_dump() _initial_delta.pop("role", None) @@ -919,24 +837,16 @@ def _has_special_delta_content(self, model_response: ModelResponseStream) -> boo return True # Check for audio - if ( - hasattr(delta, AUDIO_ATTRIBUTE) - and getattr(delta, AUDIO_ATTRIBUTE, None) is not None - ): + if hasattr(delta, AUDIO_ATTRIBUTE) and getattr(delta, AUDIO_ATTRIBUTE, None) is not None: return True # Check for image - if ( - hasattr(delta, IMAGE_ATTRIBUTE) - and getattr(delta, IMAGE_ATTRIBUTE, None) is not None - ): + if hasattr(delta, IMAGE_ATTRIBUTE) and getattr(delta, IMAGE_ATTRIBUTE, None) is not None: return True return False - def _handle_special_delta_content( - self, model_response: ModelResponseStream - ) -> ModelResponseStream: + def _handle_special_delta_content(self, model_response: ModelResponseStream) -> ModelResponseStream: """ Handle special delta content types by stripping role and returning the response. """ @@ -948,9 +858,7 @@ def _has_special_delta_attribute(self, delta, attribute_name: str) -> bool: """ return delta is not None and getattr(delta, attribute_name, None) is not None - def _copy_delta_attribute( - self, source_delta, target_delta, attribute_name: str - ) -> None: + def _copy_delta_attribute(self, source_delta, target_delta, attribute_name: str) -> None: """ Copy a specific attribute from source delta to target delta. """ @@ -966,18 +874,14 @@ def _has_any_special_delta_attributes(self, delta) -> bool: return True return False - def _handle_special_delta_attributes( - self, delta, model_response: "ModelResponseStream" - ) -> None: + def _handle_special_delta_attributes(self, delta, model_response: "ModelResponseStream") -> None: """ Handle special delta attributes (audio, image) by copying them to model_response. """ special_attributes = [AUDIO_ATTRIBUTE, IMAGE_ATTRIBUTE] for attribute in special_attributes: if self._has_special_delta_attribute(delta, attribute): - self._copy_delta_attribute( - delta, model_response.choices[0].delta, attribute - ) + self._copy_delta_attribute(delta, model_response.choices[0].delta, attribute) def return_processed_chunk_logic( # noqa: C901 self, @@ -989,13 +893,9 @@ def return_processed_chunk_logic( # noqa: C901 preserve_upstream_non_openai_attributes, ) - is_chunk_non_empty = self.is_chunk_non_empty( - completion_obj, model_response, response_obj - ) + is_chunk_non_empty = self.is_chunk_non_empty(completion_obj, model_response, response_obj) - if ( - is_chunk_non_empty - ): # cannot set content of an OpenAI Object to be an empty string + if is_chunk_non_empty: # cannot set content of an OpenAI Object to be an empty string self.raise_on_model_repetition() hold, model_response_str = self.check_special_tokens( chunk=completion_obj["content"], @@ -1021,9 +921,7 @@ def return_processed_chunk_logic( # noqa: C901 setattr(model_response, "choices", choices) else: return - model_response.system_fingerprint = ( - original_chunk.system_fingerprint - ) + model_response.system_fingerprint = original_chunk.system_fingerprint setattr( model_response, "citations", @@ -1047,17 +945,13 @@ def return_processed_chunk_logic( # noqa: C901 completion_obj["role"] = "assistant" self.sent_first_chunk = True if response_obj.get("provider_specific_fields") is not None: - completion_obj["provider_specific_fields"] = response_obj[ - "provider_specific_fields" - ] + completion_obj["provider_specific_fields"] = response_obj["provider_specific_fields"] model_response.choices[0].delta = Delta(**completion_obj) _index: Optional[int] = completion_obj.get("index") if _index is not None: model_response.choices[0].index = _index - self._optional_combine_thinking_block_in_choices( - model_response=model_response - ) + self._optional_combine_thinking_block_in_choices(model_response=model_response) return model_response else: @@ -1094,9 +988,7 @@ def return_processed_chunk_logic( # noqa: C901 ) if _is_delta_empty: - model_response.choices[0].delta = Delta( - content=None - ) # ensure empty delta chunk returned + model_response.choices[0].delta = Delta(content=None) # ensure empty delta chunk returned # get any function call arguments model_response.choices[0].finish_reason = map_finish_reason( finish_reason=self.received_finish_reason @@ -1112,9 +1004,7 @@ def return_processed_chunk_logic( # noqa: C901 self.chunks.append(model_response) return - def _optional_combine_thinking_block_in_choices( - self, model_response: ModelResponseStream - ) -> None: + def _optional_combine_thinking_block_in_choices(self, model_response: ModelResponseStream) -> None: """ UI's Like OpenWebUI expect to get 1 chunk with ... tags in the chunk content @@ -1125,17 +1015,13 @@ def _optional_combine_thinking_block_in_choices( """ if self.merge_reasoning_content_in_choices is True: - reasoning_content = getattr( - model_response.choices[0].delta, "reasoning_content", None - ) + reasoning_content = getattr(model_response.choices[0].delta, "reasoning_content", None) if reasoning_content: if self.sent_first_thinking_block is False: # Ensure content is not None before concatenation if model_response.choices[0].delta.content is None: model_response.choices[0].delta.content = "" - model_response.choices[0].delta.content += ( - "" + reasoning_content - ) + model_response.choices[0].delta.content += "" + reasoning_content self.sent_first_thinking_block = True elif ( self.sent_first_thinking_block is True @@ -1148,9 +1034,7 @@ def _optional_combine_thinking_block_in_choices( and not self.sent_last_thinking_block and model_response.choices[0].delta.content ): - model_response.choices[0].delta.content = "" + ( - model_response.choices[0].delta.content or "" - ) + model_response.choices[0].delta.content = "" + (model_response.choices[0].delta.content or "") self.sent_last_thinking_block = True if hasattr(model_response.choices[0].delta, "reasoning_content"): @@ -1172,9 +1056,7 @@ def _dispatch_provider_chunk( _has_content = bool( chunk.choices and chunk.choices[0].delta is not None - and ( - chunk.choices[0].delta.content or chunk.choices[0].delta.tool_calls - ) + and (chunk.choices[0].delta.content or chunk.choices[0].delta.tool_calls) ) if self.received_finish_reason is not None: if not _has_content: @@ -1191,13 +1073,8 @@ def _dispatch_provider_chunk( if ( isinstance(chunk, dict) - and generic_chunk_has_all_required_fields( - chunk=chunk - ) # check if chunk is a generic streaming chunk - ) or ( - self.custom_llm_provider - and self.custom_llm_provider in litellm._custom_providers - ): + and generic_chunk_has_all_required_fields(chunk=chunk) # check if chunk is a generic streaming chunk + ) or (self.custom_llm_provider and self.custom_llm_provider in litellm._custom_providers): if self.received_finish_reason is not None: _chunk_has_content = isinstance(chunk, dict) and ( bool(chunk.get("text", "")) @@ -1206,10 +1083,7 @@ def _dispatch_provider_chunk( # finish_reason/usage to downstream translators. or chunk.get("usage") is not None ) - if not _chunk_has_content and ( - not isinstance(chunk, dict) - or "provider_specific_fields" not in chunk - ): + if not _chunk_has_content and (not isinstance(chunk, dict) or "provider_specific_fields" not in chunk): raise StopIteration anthropic_response_obj: GChunk = cast(GChunk, chunk) completion_obj["content"] = anthropic_response_obj["text"] @@ -1217,9 +1091,7 @@ def _dispatch_provider_chunk( self.received_finish_reason = anthropic_response_obj["finish_reason"] if anthropic_response_obj["finish_reason"]: - self.intermittent_finish_reason = anthropic_response_obj[ - "finish_reason" - ] + self.intermittent_finish_reason = anthropic_response_obj["finish_reason"] if anthropic_response_obj["usage"] is not None: setattr( @@ -1228,19 +1100,14 @@ def _dispatch_provider_chunk( litellm.Usage(**anthropic_response_obj["usage"]), ) - if ( - "tool_use" in anthropic_response_obj - and anthropic_response_obj["tool_use"] is not None - ): + if "tool_use" in anthropic_response_obj and anthropic_response_obj["tool_use"] is not None: completion_obj["tool_calls"] = [anthropic_response_obj["tool_use"]] if ( "provider_specific_fields" in anthropic_response_obj and anthropic_response_obj["provider_specific_fields"] is not None ): - for key, value in anthropic_response_obj[ - "provider_specific_fields" - ].items(): + for key, value in anthropic_response_obj["provider_specific_fields"].items(): setattr(model_response, key, value) response_obj = cast(dict[str, Any], anthropic_response_obj) @@ -1254,13 +1121,9 @@ def _dispatch_provider_chunk( completion_obj["content"] = response_obj["text"] if response_obj["is_finished"]: self.received_finish_reason = response_obj["finish_reason"] - elif ( - self.custom_llm_provider and self.custom_llm_provider == "baseten" - ): # baseten doesn't provide streaming + elif self.custom_llm_provider and self.custom_llm_provider == "baseten": # baseten doesn't provide streaming completion_obj["content"] = self.handle_baseten_chunk(chunk) - elif ( - self.custom_llm_provider and self.custom_llm_provider == "ai21" - ): # ai21 doesn't provide streaming + elif self.custom_llm_provider and self.custom_llm_provider == "ai21": # ai21 doesn't provide streaming response_obj = self.handle_ai21_chunk(chunk) completion_obj["content"] = response_obj["text"] if response_obj["is_finished"]: @@ -1292,9 +1155,7 @@ def _dispatch_provider_chunk( if self.sent_first_chunk is False: raise Exception("An unknown error occurred with the stream") self.received_finish_reason = "stop" - elif self.custom_llm_provider == "vertex_ai" and not isinstance( - chunk, ModelResponseStream - ): + elif self.custom_llm_provider == "vertex_ai" and not isinstance(chunk, ModelResponseStream): chunk = cast(Any, chunk) import proto # type: ignore @@ -1356,9 +1217,7 @@ def _dispatch_provider_chunk( ) except Exception: if chunk.candidates[0].finish_reason.name == "SAFETY": # type: ignore - raise Exception( - f"The response was blocked by VertexAI. {str(chunk)}" - ) + raise Exception(f"The response was blocked by VertexAI. {str(chunk)}") else: completion_obj["content"] = str(chunk) elif self.custom_llm_provider == "petals": @@ -1443,9 +1302,7 @@ def _dispatch_provider_chunk( "finish_reason": chunk_finish_reason, "original_chunk": chunk, "tool_calls": ( - chunk.choices[0].delta.tool_calls - if hasattr(chunk.choices[0].delta, "tool_calls") - else None + chunk.choices[0].delta.tool_calls if hasattr(chunk.choices[0].delta, "tool_calls") else None ), } @@ -1483,16 +1340,10 @@ def _dispatch_provider_chunk( self.received_finish_reason = response_obj["finish_reason"] if response_obj.get("original_chunk", None) is not None: if hasattr(response_obj["original_chunk"], "id"): - model_response = self.set_model_id( - response_obj["original_chunk"].id, model_response - ) + model_response = self.set_model_id(response_obj["original_chunk"].id, model_response) if hasattr(response_obj["original_chunk"], "system_fingerprint"): - model_response.system_fingerprint = response_obj[ - "original_chunk" - ].system_fingerprint - self.system_fingerprint = response_obj[ - "original_chunk" - ].system_fingerprint + model_response.system_fingerprint = response_obj["original_chunk"].system_fingerprint + self.system_fingerprint = response_obj["original_chunk"].system_fingerprint if response_obj["logprobs"] is not None: model_response.choices[0].logprobs = response_obj["logprobs"] @@ -1502,16 +1353,9 @@ def _dispatch_provider_chunk( model_response, "usage", litellm.Usage( - prompt_tokens=response_obj["usage"].get( - "prompt_tokens", None - ) - or None, - completion_tokens=response_obj["usage"].get( - "completion_tokens", None - ) - or None, - total_tokens=response_obj["usage"].get("total_tokens", None) - or None, + prompt_tokens=response_obj["usage"].get("prompt_tokens", None) or None, + completion_tokens=response_obj["usage"].get("completion_tokens", None) or None, + total_tokens=response_obj["usage"].get("total_tokens", None) or None, ), ) elif isinstance(response_obj["usage"], Usage): @@ -1547,37 +1391,24 @@ def chunk_creator(self, chunk: Any): # type: ignore model_response.model = self.model ## FUNCTION CALL PARSING - original_chunk = ( - response_obj.get("original_chunk") if response_obj is not None else None - ) + original_chunk = response_obj.get("original_chunk") if response_obj is not None else None if ( original_chunk is not None ): # function / tool calling branch - only set for openai/azure compatible endpoints # enter this branch when no content has been passed in response if hasattr(original_chunk, "id"): - model_response = self.set_model_id( - original_chunk.id, model_response - ) + model_response = self.set_model_id(original_chunk.id, model_response) if hasattr(original_chunk, "provider_specific_fields"): - model_response = ( - self.copy_model_response_level_provider_specific_fields( - original_chunk, model_response - ) + model_response = self.copy_model_response_level_provider_specific_fields( + original_chunk, model_response ) if original_chunk.choices and len(original_chunk.choices) > 0: delta = original_chunk.choices[0].delta - if delta is not None and ( - delta.function_call is not None or delta.tool_calls is not None - ): + if delta is not None and (delta.function_call is not None or delta.tool_calls is not None): try: - model_response.system_fingerprint = ( - original_chunk.system_fingerprint - ) + model_response.system_fingerprint = original_chunk.system_fingerprint ## AZURE - check if arguments is not None - if ( - original_chunk.choices[0].delta.function_call - is not None - ): + if original_chunk.choices[0].delta.function_call is not None: if ( getattr( original_chunk.choices[0].delta.function_call, @@ -1585,17 +1416,11 @@ def chunk_creator(self, chunk: Any): # type: ignore ) is None ): - original_chunk.choices[ - 0 - ].delta.function_call.arguments = "" + original_chunk.choices[0].delta.function_call.arguments = "" elif original_chunk.choices[0].delta.tool_calls is not None: - if isinstance( - original_chunk.choices[0].delta.tool_calls, list - ): + if isinstance(original_chunk.choices[0].delta.tool_calls, list): for t in original_chunk.choices[0].delta.tool_calls: - if hasattr(t, "functions") and hasattr( - t.functions, "arguments" - ): + if hasattr(t, "functions") and hasattr(t.functions, "arguments"): if ( getattr( t.function, @@ -1606,12 +1431,8 @@ def chunk_creator(self, chunk: Any): # type: ignore t.function.arguments = "" _json_delta = delta.model_dump() if "role" not in _json_delta or _json_delta["role"] is None: - _json_delta["role"] = ( - "assistant" # mistral's api returns role as None - ) - if "tool_calls" in _json_delta and isinstance( - _json_delta["tool_calls"], list - ): + _json_delta["role"] = "assistant" # mistral's api returns role as None + if "tool_calls" in _json_delta and isinstance(_json_delta["tool_calls"], list): for tool in _json_delta["tool_calls"]: if ( isinstance(tool, dict) @@ -1624,9 +1445,7 @@ def chunk_creator(self, chunk: Any): # type: ignore model_response.choices[0].delta = Delta(**_json_delta) except Exception as e: verbose_logger.exception( - "litellm.CustomStreamWrapper.chunk_creator(): Exception occured - {}".format( - str(e) - ) + "litellm.CustomStreamWrapper.chunk_creator(): Exception occured - {}".format(str(e)) ) model_response.choices[0].delta = Delta() elif self._has_any_special_delta_attributes(delta): @@ -1642,10 +1461,7 @@ def chunk_creator(self, chunk: Any): # type: ignore except Exception: model_response.choices[0].delta = Delta() else: - if ( - self.stream_options is not None - and self.stream_options["include_usage"] is True - ): + if self.stream_options is not None and self.stream_options["include_usage"] is True: model_response.choices = [] return model_response return @@ -1653,9 +1469,7 @@ def chunk_creator(self, chunk: Any): # type: ignore if "tool_calls" in completion_obj and len(completion_obj["tool_calls"]) > 0: if self.is_function_call is True: # user passed in 'functions' param - completion_obj["function_call"] = completion_obj["tool_calls"][0][ - "function" - ] + completion_obj["function_call"] = completion_obj["tool_calls"][0]["function"] completion_obj["tool_calls"] = None self.tool_call = True @@ -1708,8 +1522,7 @@ async def _call_post_streaming_deployment_hook(self, chunk): self._post_streaming_hooks = [ cb for cb in litellm.callbacks - if isinstance(cb, CustomLogger) - and hasattr(cb, "async_post_call_streaming_deployment_hook") + if isinstance(cb, CustomLogger) and hasattr(cb, "async_post_call_streaming_deployment_hook") ] if not self._post_streaming_hooks: @@ -1736,14 +1549,10 @@ async def _call_post_streaming_deployment_hook(self, chunk): except Exception as e: from litellm._logging import verbose_logger - verbose_logger.exception( - f"Error in post-call streaming deployment hook: {str(e)}" - ) + verbose_logger.exception(f"Error in post-call streaming deployment hook: {str(e)}") return chunk - def _add_mcp_list_tools_to_first_chunk( - self, chunk: ModelResponseStream - ) -> ModelResponseStream: + def _add_mcp_list_tools_to_first_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream: """ Add mcp_list_tools from _hidden_params to the first chunk's delta.provider_specific_fields. @@ -1767,37 +1576,24 @@ def _add_mcp_list_tools_to_first_chunk( # Add mcp_list_tools to delta.provider_specific_fields if hasattr(chunk, "choices") and chunk.choices: for choice in chunk.choices: - if ( - isinstance(choice, StreamingChoices) - and hasattr(choice, "delta") - and choice.delta - ): + if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta: # Get existing provider_specific_fields or create new dict - provider_fields = ( - getattr(choice.delta, "provider_specific_fields", None) - or {} - ) + provider_fields = getattr(choice.delta, "provider_specific_fields", None) or {} # Add only mcp_list_tools to first chunk provider_fields["mcp_list_tools"] = mcp_list_tools # Set the provider_specific_fields - setattr( - choice.delta, "provider_specific_fields", provider_fields - ) + setattr(choice.delta, "provider_specific_fields", provider_fields) except Exception as e: from litellm._logging import verbose_logger - verbose_logger.exception( - f"Error adding MCP list tools to first chunk: {str(e)}" - ) + verbose_logger.exception(f"Error adding MCP list tools to first chunk: {str(e)}") return chunk - def _add_mcp_metadata_to_final_chunk( - self, chunk: ModelResponseStream - ) -> ModelResponseStream: + def _add_mcp_metadata_to_final_chunk(self, chunk: ModelResponseStream) -> ModelResponseStream: """ Add MCP metadata from _hidden_params to the final chunk's delta.provider_specific_fields. @@ -1816,32 +1612,21 @@ def _add_mcp_metadata_to_final_chunk( # Add MCP metadata to delta.provider_specific_fields if hasattr(chunk, "choices") and chunk.choices: for choice in chunk.choices: - if ( - isinstance(choice, StreamingChoices) - and hasattr(choice, "delta") - and choice.delta - ): + if isinstance(choice, StreamingChoices) and hasattr(choice, "delta") and choice.delta: # Get existing provider_specific_fields or create new dict - provider_fields = ( - getattr(choice.delta, "provider_specific_fields", None) - or {} - ) + provider_fields = getattr(choice.delta, "provider_specific_fields", None) or {} # Add MCP metadata if isinstance(mcp_metadata, dict): provider_fields.update(mcp_metadata) # Set the provider_specific_fields - setattr( - choice.delta, "provider_specific_fields", provider_fields - ) + setattr(choice.delta, "provider_specific_fields", provider_fields) except Exception as e: from litellm._logging import verbose_logger - verbose_logger.exception( - f"Error adding MCP metadata to final chunk: {str(e)}" - ) + verbose_logger.exception(f"Error adding MCP metadata to final chunk: {str(e)}") return chunk @@ -1850,20 +1635,14 @@ def cache_streaming_response(self, processed_chunk, cache_hit: bool): Caches the streaming response """ if not cache_hit and self.logging_obj._llm_caching_handler is not None: - self.logging_obj._llm_caching_handler._sync_add_streaming_response_to_cache( - processed_chunk - ) + self.logging_obj._llm_caching_handler._sync_add_streaming_response_to_cache(processed_chunk) async def async_cache_streaming_response(self, processed_chunk, cache_hit: bool): """ Caches the streaming response """ if not cache_hit and self.logging_obj._llm_caching_handler is not None: - await ( - self.logging_obj._llm_caching_handler._add_streaming_response_to_cache( - processed_chunk - ) - ) + await self.logging_obj._llm_caching_handler._add_streaming_response_to_cache(processed_chunk) def run_success_logging_and_cache_storage(self, processed_chunk, cache_hit: bool): """ @@ -1881,18 +1660,12 @@ def run_success_logging_and_cache_storage(self, processed_chunk, cache_hit: bool # Create an event loop for the new thread if self.logging_loop is not None: future = asyncio.run_coroutine_threadsafe( - self.logging_obj.async_success_handler( - processed_chunk, None, None, cache_hit - ), + self.logging_obj.async_success_handler(processed_chunk, None, None, cache_hit), loop=self.logging_loop, ) future.result() else: - asyncio.run( - self.logging_obj.async_success_handler( - processed_chunk, None, None, cache_hit - ) - ) + asyncio.run(self.logging_obj.async_success_handler(processed_chunk, None, None, cache_hit)) ## SYNC LOGGING — only for sync SDK entrypoints; async proxy paths export via async_success_handler litellm_params = self.logging_obj.model_call_details.get("litellm_params", {}) if self.logging_obj._is_sync_litellm_request(litellm_params): @@ -1915,10 +1688,7 @@ def finish_reason_handler(self): def __next__(self) -> "ModelResponseStream": cache_hit = False - if ( - self.custom_llm_provider is not None - and self.custom_llm_provider == "cached_response" - ): + if self.custom_llm_provider is not None and self.custom_llm_provider == "cached_response": cache_hit = True self._check_max_streaming_duration() try: @@ -1938,17 +1708,13 @@ def __next__(self) -> "ModelResponseStream": print_verbose( f"PROCESSED CHUNK PRE CHUNK CREATOR: {chunk.decode('utf-8', errors='replace') if isinstance(chunk, bytes) else chunk}; custom_llm_provider: {self.custom_llm_provider}" ) - response: Optional[ModelResponseStream] = self.chunk_creator( - chunk=chunk - ) + response: Optional[ModelResponseStream] = self.chunk_creator(chunk=chunk) print_verbose(f"PROCESSED CHUNK POST CHUNK CREATOR: {response}") if response is None: continue if self.logging_obj.completion_start_time is None: - self.logging_obj._update_completion_start_time( - completion_start_time=datetime.datetime.now() - ) + self.logging_obj._update_completion_start_time(completion_start_time=datetime.datetime.now()) ## LOGGING if not litellm.disable_streaming_logging: executor.submit( @@ -1959,14 +1725,10 @@ def __next__(self) -> "ModelResponseStream": if response.choices: choice = response.choices[0] if isinstance(choice, StreamingChoices): - self.response_uptil_now += ( - choice.delta.get("content", "") or "" - ) + self.response_uptil_now += choice.delta.get("content", "") or "" else: self.response_uptil_now += "" - self.rules.post_call_rules( - input=self.response_uptil_now, model=self.model - ) + self.rules.post_call_rules(input=self.response_uptil_now, model=self.model) # HANDLE STREAM OPTIONS self.chunks.append(response) @@ -1984,13 +1746,9 @@ def __next__(self) -> "ModelResponseStream": if "usage" in obj_dict: del obj_dict["usage"] - response = self.model_response_creator( - chunk=obj_dict, hidden_params=response._hidden_params - ) + response = self.model_response_creator(chunk=obj_dict, hidden_params=response._hidden_params) ## check if empty - is_empty = is_model_response_stream_empty( - model_response=cast(ModelResponseStream, response) - ) + is_empty = is_model_response_stream_empty(model_response=cast(ModelResponseStream, response)) if is_empty: continue @@ -2019,8 +1777,7 @@ def __next__(self) -> "ModelResponseStream": # escape __next__ and drop the request from SpendLogs. Recover # best-effort usage from the raw chunks so cost is still tracked verbose_logger.warning( - "stream_chunk_builder raised at end-of-stream (%s); logging " - "best-effort usage from chunks.", + "stream_chunk_builder raised at end-of-stream (%s); logging best-effort usage from chunks.", str(e), ) try: @@ -2098,9 +1855,7 @@ def __next__(self) -> "ModelResponseStream": except Exception as e: traceback_exception = traceback.format_exc() # LOG FAILURE - handle streaming failure logging in the _next_ object, remove `handle_failure` once it's deprecated - threading.Thread( - target=self.logging_obj.failure_handler, args=(e, traceback_exception) - ).start() + threading.Thread(target=self.logging_obj.failure_handler, args=(e, traceback_exception)).start() self._handle_stream_fallback_error(e) def fetch_sync_stream(self): @@ -2114,19 +1869,14 @@ def fetch_sync_stream(self): async def fetch_stream(self): if self.completion_stream is None and self.make_call is not None: # Call make_call to get the completion stream - self.completion_stream = await self.make_call( - client=litellm.module_level_aclient - ) + self.completion_stream = await self.make_call(client=litellm.module_level_aclient) self._stream_iter = self.completion_stream.__aiter__() return self.completion_stream async def __anext__(self) -> "ModelResponseStream": cache_hit = False - if ( - self.custom_llm_provider is not None - and self.custom_llm_provider == "cached_response" - ): + if self.custom_llm_provider is not None and self.custom_llm_provider == "cached_response": cache_hit = True self._check_max_streaming_duration() try: @@ -2138,44 +1888,29 @@ async def __anext__(self) -> "ModelResponseStream": if chunk == "None" or chunk is None: continue # skip None chunks - elif ( - self.custom_llm_provider == "gemini" - and hasattr(chunk, "parts") - and len(chunk.parts) == 0 - ): + elif self.custom_llm_provider == "gemini" and hasattr(chunk, "parts") and len(chunk.parts) == 0: continue - processed_chunk: Optional[ModelResponseStream] = self.chunk_creator( - chunk=chunk - ) + processed_chunk: Optional[ModelResponseStream] = self.chunk_creator(chunk=chunk) if processed_chunk is None: continue if self.logging_obj.completion_start_time is None: - self.logging_obj._update_completion_start_time( - completion_start_time=datetime.datetime.now() - ) + self.logging_obj._update_completion_start_time(completion_start_time=datetime.datetime.now()) if processed_chunk.choices: choice = processed_chunk.choices[0] if isinstance(choice, StreamingChoices): - self.response_uptil_now += ( - choice.delta.get("content", "") or "" - ) + self.response_uptil_now += choice.delta.get("content", "") or "" else: self.response_uptil_now += "" - self.rules.post_call_rules( - input=self.response_uptil_now, model=self.model - ) + self.rules.post_call_rules(input=self.response_uptil_now, model=self.model) # Add mcp_list_tools to first chunk if present if not self.sent_first_chunk and processed_chunk.choices: - processed_chunk = self._add_mcp_list_tools_to_first_chunk( - processed_chunk - ) + processed_chunk = self._add_mcp_list_tools_to_first_chunk(processed_chunk) self.sent_first_chunk = True _has_usage = ( - hasattr(processed_chunk, "usage") - and getattr(processed_chunk, "usage", None) is not None + hasattr(processed_chunk, "usage") and getattr(processed_chunk, "usage", None) is not None ) if _has_usage: @@ -2205,35 +1940,23 @@ async def __anext__(self) -> "ModelResponseStream": if self.sent_last_chunk is True and self.stream_options is None: usage = calculate_total_usage(chunks=self.chunks) processed_chunk._hidden_params["usage"] = usage - self._last_returned_hidden_params = ( - processed_chunk._hidden_params - ) + self._last_returned_hidden_params = processed_chunk._hidden_params # Call post-call streaming deployment hook for final chunk if self.sent_last_chunk is True: - processed_chunk = ( - await self._call_post_streaming_deployment_hook( - processed_chunk - ) - ) + processed_chunk = await self._call_post_streaming_deployment_hook(processed_chunk) # Add MCP metadata to final chunk if present (after hooks) - processed_chunk = self._add_mcp_metadata_to_final_chunk( - processed_chunk - ) # type: ignore[reportArgumentType] + processed_chunk = self._add_mcp_metadata_to_final_chunk(processed_chunk) # type: ignore[reportArgumentType] return processed_chunk raise StopAsyncIteration else: # temporary patch for non-aiohttp async calls # example - boto3 bedrock llms while True: - if isinstance(self.completion_stream, str) or isinstance( - self.completion_stream, bytes - ): + if isinstance(self.completion_stream, str) or isinstance(self.completion_stream, bytes): chunk = self.completion_stream else: - chunk = await asyncio.to_thread( - _next_sync_or_exhausted, self.completion_stream - ) # type: ignore[arg-type] + chunk = await asyncio.to_thread(_next_sync_or_exhausted, self.completion_stream) # type: ignore[arg-type] if chunk is _SYNC_ITER_EXHAUSTED: raise StopAsyncIteration if chunk is not None and chunk != b"": @@ -2243,14 +1966,10 @@ async def __anext__(self) -> "ModelResponseStream": choice = processed_chunk.choices[0] if isinstance(choice, StreamingChoices): - self.response_uptil_now += ( - choice.delta.get("content", "") or "" - ) + self.response_uptil_now += choice.delta.get("content", "") or "" else: self.response_uptil_now += "" - self.rules.post_call_rules( - input=self.response_uptil_now, model=self.model - ) + self.rules.post_call_rules(input=self.response_uptil_now, model=self.model) # RETURN RESULT self.chunks.append(processed_chunk) return processed_chunk @@ -2268,8 +1987,7 @@ async def __anext__(self) -> "ModelResponseStream": # except handler escapes __anext__ and drops the request from SpendLogs. # Recover best-effort usage from the raw chunks so cost is still tracked verbose_logger.warning( - "stream_chunk_builder raised at end-of-stream (%s); logging " - "best-effort usage from chunks.", + "stream_chunk_builder raised at end-of-stream (%s); logging best-effort usage from chunks.", str(e), ) try: @@ -2350,9 +2068,7 @@ async def __anext__(self) -> "ModelResponseStream": except httpx.TimeoutException as e: # if httpx read timeout error occues traceback_exception = traceback.format_exc() ## ADD DEBUG INFORMATION - E.G. LITELLM REQUEST TIMEOUT - traceback_exception += "\nLiteLLM Default Request Timeout - {}".format( - litellm.request_timeout - ) + traceback_exception += "\nLiteLLM Default Request Timeout - {}".format(litellm.request_timeout) if self.logging_obj is not None: self._record_partial_usage_for_failure() ## LOGGING @@ -2361,9 +2077,7 @@ async def __anext__(self) -> "ModelResponseStream": args=(e, traceback_exception), ).start() # log response # Handle any exceptions that might occur during streaming - asyncio.create_task( - self.logging_obj.async_failure_handler(e, traceback_exception) - ) + asyncio.create_task(self.logging_obj.async_failure_handler(e, traceback_exception)) self._handle_stream_fallback_error(e) except Exception as e: traceback_exception = traceback.format_exc() @@ -2398,8 +2112,7 @@ def _record_partial_usage_for_failure(self) -> None: return self.logging_obj.model_call_details["combined_usage_object"] = usage self.logging_obj.model_call_details["response_cost"] = ( - self.logging_obj._response_cost_calculator(result=partial_response) - or 0.0 + self.logging_obj._response_cost_calculator(result=partial_response) or 0.0 ) except Exception as recover_error: verbose_logger.debug( @@ -2460,17 +2173,9 @@ def _normalize_status_code(exc: Exception) -> Optional[int]: # Raise non-retriable client errors directly (skip fallback). # Exception: 429 (rate-limit) IS retriable/transient — allow it # through so the Router can switch to a different model group. - if ( - mapped_status_code is not None - and 400 <= mapped_status_code < 500 - and mapped_status_code != 429 - ): + if mapped_status_code is not None and 400 <= mapped_status_code < 500 and mapped_status_code != 429: raise mapped_exception - if ( - original_status_code is not None - and 400 <= original_status_code < 500 - and original_status_code != 429 - ): + if original_status_code is not None and 400 <= original_status_code < 500 and original_status_code != 429: raise mapped_exception raise MidStreamFallbackError( diff --git a/litellm/litellm_core_utils/token_counter.py b/litellm/litellm_core_utils/token_counter.py index c766c6edec16..56b9d42092ce 100644 --- a/litellm/litellm_core_utils/token_counter.py +++ b/litellm/litellm_core_utils/token_counter.py @@ -67,9 +67,7 @@ def get_modified_max_tokens( ## MODEL INFO _model_info = litellm.get_model_info(model=model) - max_output_tokens = litellm.get_max_tokens( - model=base_model - ) # assume min context window is 4k tokens + max_output_tokens = litellm.get_max_tokens(model=base_model) # assume min context window is 4k tokens ## UNKNOWN MAX OUTPUT TOKENS - return user defined amount if max_output_tokens is None: @@ -87,14 +85,10 @@ def get_modified_max_tokens( ) # give at least a 10 token buffer. token counting can be imprecise. input_tokens += int(token_buffer) - verbose_logger.debug( - f"max_output_tokens: {max_output_tokens}, user_max_tokens: {user_max_tokens}" - ) + verbose_logger.debug(f"max_output_tokens: {max_output_tokens}, user_max_tokens: {user_max_tokens}") ## CASE 1: model input + output can't exceed X - happens when max input = max output, e.g. gpt-3.5-turbo if _model_info["max_input_tokens"] == max_output_tokens: - verbose_logger.debug( - f"input_tokens: {input_tokens}, max_output_tokens: {max_output_tokens}" - ) + verbose_logger.debug(f"input_tokens: {input_tokens}, max_output_tokens: {max_output_tokens}") if input_tokens > max_output_tokens: pass # allow call to fail normally - don't set max_tokens to negative. elif ( @@ -131,10 +125,7 @@ def resize_image_high_res( max_long_side = MAX_LONG_SIDE_FOR_IMAGE_HIGH_RES # Return early if no resizing is needed - if ( - width <= MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES - and height <= MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES - ): + if width <= MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES and height <= MAX_SHORT_SIDE_FOR_IMAGE_HIGH_RES: return width, height # Determine the longer and shorter sides @@ -296,9 +287,7 @@ def calculate_img_tokens( int: The number of tokens for the image. """ if use_default_image_token_count: - verbose_logger.debug( - "Using default image token count: {}".format(DEFAULT_IMAGE_TOKEN_COUNT) - ) + verbose_logger.debug("Using default image token count: {}".format(DEFAULT_IMAGE_TOKEN_COUNT)) return DEFAULT_IMAGE_TOKEN_COUNT if mode == "low" or mode == "auto": return base_tokens @@ -307,12 +296,8 @@ def calculate_img_tokens( width, height = get_image_dimensions( data=data, ) - resized_width, resized_height = resize_image_high_res( - width=width, height=height - ) - tiles_needed_high_res = calculate_tiles_needed( - resized_width=resized_width, resized_height=resized_height - ) + resized_width, resized_height = resize_image_high_res(width=width, height=height) + tiles_needed_high_res = calculate_tiles_needed(resized_width=resized_width, resized_height=resized_height) tile_tokens = (base_tokens * 2) * tiles_needed_high_res total_tokens = base_tokens + tile_tokens return total_tokens @@ -338,9 +323,7 @@ def __init__( actual_model = _fix_model_name(model) if actual_model == "gpt-3.5-turbo-0301": - self.tokens_per_message = ( - 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n - ) + self.tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n self.tokens_per_name = -1 # if there's a name, the role is omitted elif actual_model in litellm.open_ai_chat_completion_models: self.tokens_per_message = 3 @@ -349,9 +332,7 @@ def __init__( self.tokens_per_message = 3 self.tokens_per_name = 1 else: - print_verbose( - f"Warning: unknown model {model}. Using default token params." - ) + print_verbose(f"Warning: unknown model {model}. Using default token params.") self.tokens_per_message = 3 self.tokens_per_name = 1 self.count_function = _get_count_function(model, custom_tokenizer) @@ -396,9 +377,7 @@ def token_counter( if litellm.disable_token_counter is True: return 0 - verbose_logger.debug( - f"messages in token_counter: {messages}, text in token_counter: {text}" - ) + verbose_logger.debug(f"messages in token_counter: {messages}, text in token_counter: {text}") if text is not None and messages is not None: raise ValueError("text and messages cannot both be set") if use_default_image_token_count is None: @@ -415,20 +394,12 @@ def token_counter( num_tokens = count_function(text_to_count) elif messages is not None: - new_messages = cast( - List[AllMessageValues], convert_list_message_to_dict(messages) - ) + new_messages = cast(List[AllMessageValues], convert_list_message_to_dict(messages)) params = _MessageCountParams(model, custom_tokenizer) - num_tokens = _count_messages( - params, new_messages, use_default_image_token_count, default_token_count - ) + num_tokens = _count_messages(params, new_messages, use_default_image_token_count, default_token_count) if count_response_tokens is False: - includes_system_message = any( - [message.get("role", None) == "system" for message in new_messages] - ) - num_tokens += _count_extra( - params.count_function, tools, tool_choice, includes_system_message - ) + includes_system_message = any([message.get("role", None) == "system" for message in new_messages]) + num_tokens += _count_extra(params.count_function, tools, tool_choice, includes_system_message) else: raise ValueError("Either text or messages must be provided") @@ -463,18 +434,12 @@ def _count_messages( if isinstance(value, List): for tool_call in value: if "function" in tool_call: - function_arguments = tool_call["function"].get( - "arguments", [] - ) + function_arguments = tool_call["function"].get("arguments", []) num_tokens += params.count_function(str(function_arguments)) else: - raise ValueError( - f"Unsupported tool call {tool_call} must contain a function key" - ) + raise ValueError(f"Unsupported tool call {tool_call} must contain a function key") else: - raise ValueError( - f"Unsupported type {type(value)} for key tool_calls in message {message}" - ) + raise ValueError(f"Unsupported type {type(value)} for key tool_calls in message {message}") elif isinstance(value, str): num_tokens += params.count_function(value) if key == "name": @@ -605,9 +570,7 @@ def _count_image_tokens( if isinstance(image_url, dict): detail = image_url.get("detail", "auto") if detail not in ["low", "high", "auto"]: - raise ValueError( - f"Invalid detail value: {detail}. Expected 'low', 'high', or 'auto'." - ) + raise ValueError(f"Invalid detail value: {detail}. Expected 'low', 'high', or 'auto'.") url = image_url.get("url") if not url: raise ValueError("Missing required key 'url' in image_url dict.") @@ -625,10 +588,7 @@ def _count_image_tokens( use_default_image_token_count=use_default_image_token_count, ) else: - raise ValueError( - f"Invalid image_url type: {type(image_url).__name__}. " - "Expected str or dict with 'url' field." - ) + raise ValueError(f"Invalid image_url type: {type(image_url).__name__}. Expected str or dict with 'url' field.") def _validate_anthropic_content(content: Mapping[str, Any]) -> type: @@ -650,13 +610,9 @@ def _validate_anthropic_content(content: Mapping[str, Any]) -> type: if expected_cls is None: raise ValueError(f"Unknown Anthropic content type: '{content_type}'") - missing = [ - k for k in getattr(expected_cls, "__required_keys__", set()) if k not in content - ] + missing = [k for k in getattr(expected_cls, "__required_keys__", set()) if k not in content] if missing: - raise ValueError( - f"Missing required fields in {content_type} block: {', '.join(missing)}" - ) + raise ValueError(f"Missing required fields in {content_type} block: {', '.join(missing)}") return expected_cls @@ -728,9 +684,7 @@ def _count_content_list( num_tokens += count_function(str(c.get("text", ""))) elif c["type"] == "image_url": image_url = c.get("image_url") - num_tokens += _count_image_tokens( - image_url, use_default_image_token_count - ) + num_tokens += _count_image_tokens(image_url, use_default_image_token_count) elif c["type"] in ("tool_use", "tool_result"): num_tokens += _count_anthropic_content( c, @@ -756,11 +710,7 @@ def _count_content_list( if tool_name: num_tokens += count_function(tool_name) else: - content_type = ( - c.get("type", type(c).__name__) - if isinstance(c, dict) - else type(c).__name__ - ) + content_type = c.get("type", type(c).__name__) if isinstance(c, dict) else type(c).__name__ raise ValueError( f"Invalid content item type: {content_type}. " f"Expected str or dict with 'type' field (text, image_url, tool_use, tool_result, thinking, tool_reference)." @@ -770,8 +720,7 @@ def _count_content_list( if default_token_count is not None: return default_token_count raise ValueError( - f"Error getting number of tokens from content list: {e}, " - f"default_token_count={default_token_count}" + f"Error getting number of tokens from content list: {e}, default_token_count={default_token_count}" ) diff --git a/litellm/litellm_core_utils/url_utils.py b/litellm/litellm_core_utils/url_utils.py index 38a78ee058fd..1cbb1ce973fa 100644 --- a/litellm/litellm_core_utils/url_utils.py +++ b/litellm/litellm_core_utils/url_utils.py @@ -169,9 +169,7 @@ def is_url_destination_allowed_by_host(url: str, allowed_hosts: List[str]) -> bo return False normalized_host = _normalize_host(parsed.hostname) - configured_entries = ( - [allowed_hosts] if isinstance(allowed_hosts, str) else allowed_hosts - ) + configured_entries = [allowed_hosts] if isinstance(allowed_hosts, str) else allowed_hosts for entry in configured_entries or []: if not isinstance(entry, str): continue @@ -272,9 +270,7 @@ def validate_url(url: str) -> Tuple[str, str]: # Resolve hostname and validate ALL addresses try: - addrinfo = socket.getaddrinfo( - hostname, effective_port, proto=socket.IPPROTO_TCP - ) + addrinfo = socket.getaddrinfo(hostname, effective_port, proto=socket.IPPROTO_TCP) except socket.gaierror as e: raise SSRFError(f"DNS resolution failed for '{hostname}': {e}") @@ -311,9 +307,7 @@ def validate_url(url: str) -> Tuple[str, str]: else: new_netloc = ip_host - rewritten = urlunparse( - (parsed.scheme, new_netloc, parsed.path, parsed.params, parsed.query, "") - ) + rewritten = urlunparse((parsed.scheme, new_netloc, parsed.path, parsed.params, parsed.query, "")) return rewritten, host_header diff --git a/litellm/llms/__init__.py b/litellm/llms/__init__.py index fead8a79bc34..6aec359b7b76 100644 --- a/litellm/llms/__init__.py +++ b/litellm/llms/__init__.py @@ -41,9 +41,7 @@ def get_cost_for_web_search_request( if "claude" in model_key.lower(): from .anthropic.cost_calculation import get_cost_for_anthropic_web_search - verbose_logger.debug( - "vertex_ai/claude model detected — routing web search cost to Anthropic calculator" - ) + verbose_logger.debug("vertex_ai/claude model detected — routing web search cost to Anthropic calculator") return get_cost_for_anthropic_web_search(model_info=model_info, usage=usage) from .vertex_ai.gemini.cost_calculator import ( @@ -63,9 +61,7 @@ def get_cost_for_web_search_request( return None -def discover_guardrail_translation_mappings() -> Dict[ - CallTypes, Type["BaseTranslation"] -]: +def discover_guardrail_translation_mappings() -> Dict[CallTypes, Type["BaseTranslation"]]: """ Discover guardrail translation mappings by scanning the llms directory structure. @@ -91,19 +87,14 @@ def discover_guardrail_translation_mappings() -> Dict[ dirs[:] = [d for d in dirs if not d.startswith("__") and d != "base_llm"] # Check if this is a guardrail_translation directory with __init__.py - if ( - os.path.basename(root) == "guardrail_translation" - and "__init__.py" in files - ): + if os.path.basename(root) == "guardrail_translation" and "__init__.py" in files: # Build the module path relative to litellm rel_path = os.path.relpath(root, os.path.dirname(llms_dir)) module_path = "litellm." + rel_path.replace(os.sep, ".") try: # Import the module - verbose_logger.debug( - f"Discovering guardrail translations in: {module_path}" - ) + verbose_logger.debug(f"Discovering guardrail translations in: {module_path}") module = importlib.import_module(module_path) @@ -134,9 +125,7 @@ def discover_guardrail_translation_mappings() -> Dict[ list(mcp_guardrail_translation_mappings.keys()), ) except ImportError: - verbose_logger.debug( - "MCP guardrail translation mappings not available; skipping" - ) + verbose_logger.debug("MCP guardrail translation mappings not available; skipping") verbose_logger.debug( f"Discovered {len(discovered_mappings)} guardrail translation mappings: {list(discovered_mappings.keys())}" @@ -149,17 +138,13 @@ def discover_guardrail_translation_mappings() -> Dict[ # Cache the discovered mappings -endpoint_guardrail_translation_mappings: Optional[ - Dict[CallTypes, Type["BaseTranslation"]] -] = None +endpoint_guardrail_translation_mappings: Optional[Dict[CallTypes, Type["BaseTranslation"]]] = None def load_guardrail_translation_mappings(): global endpoint_guardrail_translation_mappings if endpoint_guardrail_translation_mappings is None: - endpoint_guardrail_translation_mappings = ( - discover_guardrail_translation_mappings() - ) + endpoint_guardrail_translation_mappings = discover_guardrail_translation_mappings() return endpoint_guardrail_translation_mappings @@ -180,9 +165,7 @@ def get_guardrail_translation_mapping(call_type: CallTypes) -> Type["BaseTransla # Lazy load the mappings on first access if endpoint_guardrail_translation_mappings is None: - endpoint_guardrail_translation_mappings = ( - discover_guardrail_translation_mappings() - ) + endpoint_guardrail_translation_mappings = discover_guardrail_translation_mappings() # Get the translation handler class for the call type if call_type not in endpoint_guardrail_translation_mappings: diff --git a/litellm/llms/a2a/chat/guardrail_translation/handler.py b/litellm/llms/a2a/chat/guardrail_translation/handler.py index 3d6037b1f8fe..740b0fff50cc 100644 --- a/litellm/llms/a2a/chat/guardrail_translation/handler.py +++ b/litellm/llms/a2a/chat/guardrail_translation/handler.py @@ -139,9 +139,7 @@ async def process_output_response( response_dict = response is_pydantic = False else: - verbose_proxy_logger.warning( - "A2A: Unknown response type %s, skipping guardrail", type(response) - ) + verbose_proxy_logger.warning("A2A: Unknown response type %s, skipping guardrail", type(response)) return response result = response_dict.get("result", {}) @@ -177,9 +175,7 @@ async def process_output_response( # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata @@ -238,9 +234,7 @@ async def process_output_streaming_response( if not valid_parsed: return responses_so_far - combined_text, chunk_indices_with_text = self._collect_text_from_parsed_chunks( - valid_parsed - ) + combined_text, chunk_indices_with_text = self._collect_text_from_parsed_chunks(valid_parsed) if not combined_text: return responses_so_far @@ -251,9 +245,7 @@ async def process_output_streaming_response( request_data["responses_so_far"] = responses_so_far if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata @@ -270,9 +262,7 @@ async def process_output_streaming_response( guardrailed_text = guardrailed_texts[0] # Find first chunk (by original index) that has text; put full guardrailed text there and clear rest - first_chunk_with_text: Optional[int] = ( - chunk_indices_with_text[0] if chunk_indices_with_text else None - ) + first_chunk_with_text: Optional[int] = chunk_indices_with_text[0] if chunk_indices_with_text else None for orig_i, obj in valid_parsed: result = obj.get("result", {}) @@ -399,11 +389,7 @@ def _extract_texts_from_result( status = result.get("status", {}) if isinstance(status, dict): status_message = status.get("message") - if ( - status_message - and isinstance(status_message, dict) - and "parts" in status_message - ): + if status_message and isinstance(status_message, dict) and "parts" in status_message: self._extract_texts_from_parts( parts=status_message["parts"], path=("status", "message", "parts"), diff --git a/litellm/llms/a2a/chat/streaming_iterator.py b/litellm/llms/a2a/chat/streaming_iterator.py index 29167d89ae74..a7302ac2f0b4 100644 --- a/litellm/llms/a2a/chat/streaming_iterator.py +++ b/litellm/llms/a2a/chat/streaming_iterator.py @@ -31,9 +31,7 @@ def __init__( ) self.model = model - def chunk_parser( - self, chunk: dict - ) -> Union[GenericStreamingChunk, ModelResponseStream]: + def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]: """ Parse A2A streaming chunk to OpenAI format. diff --git a/litellm/llms/a2a/chat/transformation.py b/litellm/llms/a2a/chat/transformation.py index b9c9f944b3e9..c9623a817bf2 100644 --- a/litellm/llms/a2a/chat/transformation.py +++ b/litellm/llms/a2a/chat/transformation.py @@ -55,9 +55,7 @@ def resolve_agent_config_from_registry( agent_name = model.split("/", 1)[1] if "/" in model else None # Only lookup if agent name exists and some config is missing - if not agent_name or ( - api_base is not None and api_key is not None and headers is not None - ): + if not agent_name or (api_base is not None and api_key is not None and headers is not None): return api_base, api_key, headers # Try registry lookup (only available in proxy context) @@ -84,10 +82,7 @@ def resolve_agent_config_from_registry( # Merge other litellm_params (timeout, max_retries, etc.) for key, value in agent.litellm_params.items(): - if ( - key not in ["api_key", "api_base", "headers", "model"] - and key not in optional_params - ): + if key not in ["api_key", "api_base", "headers", "model"] and key not in optional_params: optional_params[key] = value except ImportError: pass # Registry not available (not running in proxy context) diff --git a/litellm/llms/a2a/common_utils.py b/litellm/llms/a2a/common_utils.py index 15ea9f01abd6..4fc0ff2623eb 100644 --- a/litellm/llms/a2a/common_utils.py +++ b/litellm/llms/a2a/common_utils.py @@ -61,9 +61,7 @@ def convert_messages_to_prompt(messages: List[AllMessageValues]) -> str: return "\n".join(conversation_parts) -def extract_text_from_a2a_message( - message: Dict[str, Any], depth: int = 0, max_depth: int = 10 -) -> str: +def extract_text_from_a2a_message(message: Dict[str, Any], depth: int = 0, max_depth: int = 10) -> str: """ Extract text content from A2A message parts. @@ -93,9 +91,7 @@ def extract_text_from_a2a_message( return " ".join(text_parts) -def extract_text_from_a2a_response( - response_dict: Dict[str, Any], max_depth: int = 10 -) -> str: +def extract_text_from_a2a_response(response_dict: Dict[str, Any], max_depth: int = 10) -> str: """ Extract text content from A2A response result. @@ -136,16 +132,12 @@ def extract_text_from_a2a_response( if isinstance(status, dict): status_message = status.get("message") if status_message: - return extract_text_from_a2a_message( - status_message, depth=0, max_depth=max_depth - ) + return extract_text_from_a2a_message(status_message, depth=0, max_depth=max_depth) # Handle task result with artifacts (plural, array) artifacts = result.get("artifacts", []) if artifacts and len(artifacts) > 0: first_artifact = artifacts[0] - return extract_text_from_a2a_message( - first_artifact, depth=0, max_depth=max_depth - ) + return extract_text_from_a2a_message(first_artifact, depth=0, max_depth=max_depth) return "" diff --git a/litellm/llms/aiml/chat/transformation.py b/litellm/llms/aiml/chat/transformation.py index 72e30a081732..e62aa6238d7d 100644 --- a/litellm/llms/aiml/chat/transformation.py +++ b/litellm/llms/aiml/chat/transformation.py @@ -14,9 +14,7 @@ def _get_openai_compatible_provider_info( ) -> Tuple[Optional[str], Optional[str]]: # AIML is openai compatible, we just need to set the api_base api_base = ( - api_base - or get_secret_str("AIML_API_BASE") - or "https://api.aimlapi.com/v1" # Default AIML API base URL + api_base or get_secret_str("AIML_API_BASE") or "https://api.aimlapi.com/v1" # Default AIML API base URL ) # type: ignore dynamic_api_key = api_key or get_secret_str("AIML_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/aiml/image_generation/cost_calculator.py b/litellm/llms/aiml/image_generation/cost_calculator.py index 4442f57c555b..1fecfb6a9a59 100644 --- a/litellm/llms/aiml/image_generation/cost_calculator.py +++ b/litellm/llms/aiml/image_generation/cost_calculator.py @@ -22,6 +22,4 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") diff --git a/litellm/llms/aiml/image_generation/transformation.py b/litellm/llms/aiml/image_generation/transformation.py index 92a1510f3a12..b1ab443eb84d 100644 --- a/litellm/llms/aiml/image_generation/transformation.py +++ b/litellm/llms/aiml/image_generation/transformation.py @@ -37,9 +37,7 @@ def _is_openai_style_model(model: str) -> bool: """ return model.startswith(OPENAI_STYLE_IMAGE_MODEL_PREFIXES) - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ https://api.aimlapi.com/v1/images/generations """ @@ -111,9 +109,7 @@ def get_complete_url( """ Get the complete url for the request """ - complete_url: str = ( - api_base or get_secret_str("AIML_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("AIML_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") # Strip /v1 suffix if present since IMAGE_GENERATION_ENDPOINT already includes v1 @@ -133,9 +129,7 @@ def validate_environment( api_base: Optional[str] = None, ) -> dict: final_api_key: Optional[str] = ( - api_key - or get_secret_str("AIML_API_KEY") - or get_secret_str("AIMLAPI_KEY") # Alternative name + api_key or get_secret_str("AIML_API_KEY") or get_secret_str("AIMLAPI_KEY") # Alternative name ) if not final_api_key: raise ValueError("AIML_API_KEY or AIMLAPI_KEY is not set") @@ -160,12 +154,10 @@ def transform_image_generation_request( if self._is_openai_style_model(model): return {"model": model, "prompt": prompt, **optional_params} - aiml_image_generation_request_body: AimlImageGenerationRequestParams = ( - AimlImageGenerationRequestParams( - prompt=prompt, - model=model, - **optional_params, - ) + aiml_image_generation_request_body: AimlImageGenerationRequestParams = AimlImageGenerationRequestParams( + prompt=prompt, + model=model, + **optional_params, ) return dict(aiml_image_generation_request_body) diff --git a/litellm/llms/aiohttp_openai/chat/transformation.py b/litellm/llms/aiohttp_openai/chat/transformation.py index c2d4e5adcd7a..346b565b6f52 100644 --- a/litellm/llms/aiohttp_openai/chat/transformation.py +++ b/litellm/llms/aiohttp_openai/chat/transformation.py @@ -72,9 +72,7 @@ async def transform_response( # type: ignore ) -> ModelResponse: _json_response = await raw_response.json() model_response.id = _json_response.get("id") - model_response.choices = [ - Choices(**choice) for choice in _json_response.get("choices") - ] + model_response.choices = [Choices(**choice) for choice in _json_response.get("choices")] model_response.created = _json_response.get("created") model_response.model = _json_response.get("model") model_response.object = _json_response.get("object") diff --git a/litellm/llms/amazon_nova/chat/transformation.py b/litellm/llms/amazon_nova/chat/transformation.py index 74c7fd234fe9..8afcbd40ffc2 100644 --- a/litellm/llms/amazon_nova/chat/transformation.py +++ b/litellm/llms/amazon_nova/chat/transformation.py @@ -52,19 +52,10 @@ def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: # Amazon Nova is openai compatible, we just need to set this to custom_openai and have the api_base be Nova's endpoint - api_base = ( - api_base - or get_secret_str("AMAZON_NOVA_API_BASE") - or "https://api.nova.amazon.com/v1" - ) # type: ignore + api_base = api_base or get_secret_str("AMAZON_NOVA_API_BASE") or "https://api.nova.amazon.com/v1" # type: ignore # Get API key from multiple sources - key = ( - api_key - or litellm.amazon_nova_api_key - or get_secret_str("AMAZON_NOVA_API_KEY") - or litellm.api_key - ) + key = api_key or litellm.amazon_nova_api_key or get_secret_str("AMAZON_NOVA_API_KEY") or litellm.api_key return api_base, key def get_supported_openai_params(self, model: str) -> List: diff --git a/litellm/llms/amazon_nova/cost_calculation.py b/litellm/llms/amazon_nova/cost_calculation.py index 857369b76ede..3b1121f1f8cd 100644 --- a/litellm/llms/amazon_nova/cost_calculation.py +++ b/litellm/llms/amazon_nova/cost_calculation.py @@ -16,6 +16,4 @@ def cost_per_token(model: str, usage: "Usage") -> Tuple[float, float]: Calculates the cost per token for a given model, prompt tokens, and completion tokens. Follows the same logic as Anthropic's cost per token calculation. """ - return generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="amazon_nova" - ) + return generic_cost_per_token(model=model, usage=usage, custom_llm_provider="amazon_nova") diff --git a/litellm/llms/anthropic/batches/transformation.py b/litellm/llms/anthropic/batches/transformation.py index 7c4e9386d5f5..bfae42f96cf4 100644 --- a/litellm/llms/anthropic/batches/transformation.py +++ b/litellm/llms/anthropic/batches/transformation.py @@ -233,12 +233,8 @@ def parse_timestamp(ts_str: Optional[str]) -> Optional[int]: completed_at=ended_at if processing_status == "ended" else None, failed_at=None, expired_at=archived_at if archived_at else None, - cancelling_at=( - cancel_initiated_at if processing_status == "canceling" else None - ), - cancelled_at=( - ended_at if processing_status == "canceling" and ended_at else None - ), + cancelling_at=(cancel_initiated_at if processing_status == "canceling" else None), + cancelled_at=(ended_at if processing_status == "canceling" and ended_at else None), request_counts=request_counts, metadata={}, ) @@ -255,9 +251,7 @@ def get_error_class( else: headers_obj = headers if isinstance(headers, Headers) else None - return AnthropicError( - status_code=status_code, message=error_message, headers=headers_obj - ) + return AnthropicError(status_code=status_code, message=error_message, headers=headers_obj) def transform_response( self, @@ -290,17 +284,13 @@ def transform_response( response_json = json.loads(line) # Update model_response with the parsed JSON completion_response = response_json["result"]["message"] - transformed_response = ( - self.anthropic_chat_config.transform_parsed_response( - completion_response=completion_response, - raw_response=raw_response, - model_response=model_response, - ) + transformed_response = self.anthropic_chat_config.transform_parsed_response( + completion_response=completion_response, + raw_response=raw_response, + model_response=model_response, ) - transformed_response_usage = getattr( - transformed_response, "usage", None - ) + transformed_response_usage = getattr(transformed_response, "usage", None) if transformed_response_usage: all_usage.append(cast(Usage, transformed_response_usage)) except json.JSONDecodeError: diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py index 7d5944b4cc24..4506c1142081 100644 --- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py +++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py @@ -125,9 +125,7 @@ async def process_input_messages( texts_to_check: List[str] = [] images_to_check: List[str] = [] - tools_to_check: List[ChatCompletionToolParam] = ( - chat_completion_compatible_request.get("tools", []) - ) + tools_to_check: List[ChatCompletionToolParam] = chat_completion_compatible_request.get("tools", []) task_mappings: List[Tuple[int, Optional[int]]] = [] # Step 1: Extract all text content and images @@ -149,6 +147,7 @@ async def process_input_messages( inputs["images"] = images_to_check if tools_to_check: inputs["tools"] = tools_to_check + original_structured_messages = structured_messages if structured_messages: inputs["structured_messages"] = structured_messages # Include model information if available @@ -175,19 +174,42 @@ async def process_input_messages( # Note: MCP servers are handled separately in the main transformation data["tools"] = anthropic_tools - # Step 3: Map guardrail responses back to original message structure - await self._apply_guardrail_responses_to_input( - messages=messages, - responses=guardrailed_texts, - task_mappings=task_mappings, - ) + guardrailed_structured_messages = guardrailed_inputs.get("structured_messages") + if ( + guardrailed_structured_messages is not None + and guardrailed_structured_messages is not original_structured_messages + ): + self._write_back_structured_messages(data, guardrailed_structured_messages) + else: + # Step 3: Map guardrail responses back to original message structure + await self._apply_guardrail_responses_to_input( + messages=messages, + responses=guardrailed_texts, + task_mappings=task_mappings, + ) - verbose_proxy_logger.debug( - "Anthropic Messages: Processed input messages: %s", messages - ) + verbose_proxy_logger.debug("Anthropic Messages: Processed input messages: %s", messages) return data + @staticmethod + def _write_back_structured_messages(data: dict, structured_messages: list) -> None: + """Convert compressed structured_messages back to Anthropic format and write to data.""" + from litellm.litellm_core_utils.prompt_templates.factory import ( + anthropic_messages_pt, + ) + + model = str(data.get("model") or "") + non_system = [m for m in structured_messages if m.get("role") != "system"] + converted = anthropic_messages_pt(messages=non_system, model=model, llm_provider="anthropic") + for msg in converted: + content = msg.get("content") + if isinstance(content, list): + for block in content: + if isinstance(block, dict) and block.get("type") == "thinking": + block.pop("cache_control", None) + data["messages"] = converted + def extract_request_tool_names(self, data: dict) -> List[str]: """Extract tool names from Anthropic messages request (tools[].name).""" names: List[str] = [] @@ -288,9 +310,7 @@ async def _apply_guardrail_responses_to_input( elif isinstance(content, list) and content_idx_optional is not None: # Replace specific text item in list content - messages[msg_idx]["content"][content_idx_optional]["text"] = ( - guardrail_response - ) + messages[msg_idx]["content"][content_idx_optional]["text"] = guardrail_response async def process_output_response( self, @@ -369,9 +389,7 @@ async def process_output_response( task_mappings=task_mappings, ) - verbose_proxy_logger.debug( - "Anthropic Messages: Processed output response: %s", response - ) + verbose_proxy_logger.debug("Anthropic Messages: Processed output response: %s", response) return response @@ -391,20 +409,14 @@ async def process_output_streaming_response( has_ended = self._check_streaming_has_ended(responses_so_far) if has_ended: # build the model response from the responses_so_far - built_response = ( - AnthropicPassthroughLoggingHandler._build_complete_streaming_response( - all_chunks=responses_so_far, - litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj), - model="", - ) + built_response = AnthropicPassthroughLoggingHandler._build_complete_streaming_response( + all_chunks=responses_so_far, + litellm_logging_obj=cast("LiteLLMLoggingObj", litellm_logging_obj), + model="", ) # Check if model_response is valid and has choices before accessing - if ( - built_response is not None - and hasattr(built_response, "choices") - and built_response.choices - ): + if built_response is not None and hasattr(built_response, "choices") and built_response.choices: model_response = cast(ModelResponse, built_response) first_choice = cast(Choices, model_response.choices[0]) tool_calls_list = cast( @@ -418,16 +430,16 @@ async def process_output_streaming_response( if tool_calls_list: guardrail_inputs["tool_calls"] = tool_calls_list - _guardrailed_inputs = await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid - inputs=guardrail_inputs, - request_data=request_data if request_data is not None else {}, - input_type="response", - logging_obj=litellm_logging_obj, + _guardrailed_inputs = ( + await guardrail_to_apply.apply_guardrail( # allow rejecting the response, if invalid + inputs=guardrail_inputs, + request_data=request_data if request_data is not None else {}, + input_type="response", + logging_obj=litellm_logging_obj, + ) ) else: - verbose_proxy_logger.debug( - "Skipping output guardrail - model response has no choices" - ) + verbose_proxy_logger.debug("Skipping output guardrail - model response has no choices") return responses_so_far string_so_far = self.get_streaming_string_so_far(responses_so_far) @@ -454,9 +466,7 @@ def _prepare_request_data( request_data[key] = response if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata return request_data @@ -604,9 +614,7 @@ def _extract_text_from_sse(self, sse_bytes: bytes) -> str: if delta.get("type") == "text_delta": text += delta.get("text", "") except json.JSONDecodeError: - verbose_proxy_logger.warning( - f"Failed to parse JSON from SSE data: {data_line}" - ) + verbose_proxy_logger.warning(f"Failed to parse JSON from SSE data: {data_line}") except Exception as e: verbose_proxy_logger.error(f"Error extracting text from SSE: {e}") @@ -670,14 +678,10 @@ def _check_streaming_has_ended(self, responses_so_far: List[Any]) -> bool: if stop_reason is not None: return True except json.JSONDecodeError: - verbose_proxy_logger.warning( - f"Failed to parse JSON from SSE data: {data_line}" - ) + verbose_proxy_logger.warning(f"Failed to parse JSON from SSE data: {data_line}") except Exception as e: - verbose_proxy_logger.error( - f"Error checking streaming end in SSE: {e}" - ) + verbose_proxy_logger.error(f"Error checking streaming end in SSE: {e}") # Handle already-parsed dict format elif isinstance(response, dict): @@ -783,10 +787,7 @@ async def _apply_guardrail_responses_to_output( if isinstance(content_block, dict): if content_block.get("type") == "text": cast(Dict[str, Any], content_block)["text"] = guardrail_response - elif ( - hasattr(content_block, "type") - and getattr(content_block, "type", None) == "text" - ): + elif hasattr(content_block, "type") and getattr(content_block, "type", None) == "text": # Update Pydantic object's text attribute if hasattr(content_block, "text"): content_block.text = guardrail_response diff --git a/litellm/llms/anthropic/chat/handler.py b/litellm/llms/anthropic/chat/handler.py index 7154a6f35958..c8872306e82f 100644 --- a/litellm/llms/anthropic/chat/handler.py +++ b/litellm/llms/anthropic/chat/handler.py @@ -241,9 +241,7 @@ async def acompletion_stream_function( json_mode=json_mode, speed=optional_params.get("speed") if optional_params else None, tool_name_reverse_map=( - litellm_params.get(ANTHROPIC_TOOL_NAME_REVERSE_MAP_KEY) - if isinstance(litellm_params, dict) - else None + litellm_params.get(ANTHROPIC_TOOL_NAME_REVERSE_MAP_KEY) if isinstance(litellm_params, dict) else None ), ) streamwrapper = CustomStreamWrapper( @@ -278,9 +276,7 @@ async def acompletion_function( headers={}, client: AsyncHTTPHandler | None = None, ) -> Union[ModelResponse, "CustomStreamWrapper"]: - async_handler = client or get_async_httpx_client( - llm_provider=litellm.LlmProviders.ANTHROPIC - ) + async_handler = client or get_async_httpx_client(llm_provider=litellm.LlmProviders.ANTHROPIC) try: response = await async_handler.post( @@ -371,9 +367,7 @@ def completion( provider=LlmProviders(custom_llm_provider), ) if config is None: - raise ValueError( - f"Provider config not found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"Provider config not found for model: {model} and provider: {custom_llm_provider}") data = config.transform_request( model=model, @@ -425,11 +419,7 @@ def completion( logger_fn=logger_fn, headers=headers, timeout=timeout, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), ) else: return self.acompletion_function( @@ -613,11 +603,7 @@ def check_empty_tool_call_args(self) -> bool: return False def _handle_usage(self, anthropic_usage_chunk: Union[dict, UsageDelta]) -> Usage: - reasoning_content = ( - "".join(self.reasoning_content_chunks) - if self.reasoning_content_chunks - else None - ) + reasoning_content = "".join(self.reasoning_content_chunks) if self.reasoning_content_chunks else None return AnthropicConfig().calculate_usage( usage_object=cast(dict, anthropic_usage_chunk), reasoning_content=reasoning_content, @@ -641,9 +627,7 @@ def _content_block_delta_helper( provider_specific_fields = {} reasoning_content: str | None = None content_block = ContentBlockDelta(**chunk) # type: ignore - thinking_blocks: List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] = [] + thinking_blocks: List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] = [] self.content_blocks.append(content_block) if "text" in content_block["delta"]: @@ -667,10 +651,7 @@ def _content_block_delta_helper( ) elif "citation" in content_block["delta"]: provider_specific_fields["citation"] = content_block["delta"]["citation"] - elif ( - "thinking" in content_block["delta"] - or "signature" in content_block["delta"] - ): + elif "thinking" in content_block["delta"] or "signature" in content_block["delta"]: thinking_content = content_block["delta"].get("thinking") if isinstance(thinking_content, str) and thinking_content: self.reasoning_content_chunks.append(thinking_content) @@ -699,10 +680,7 @@ def _content_block_delta_helper( provider_specific_fields["thinking_blocks"] = thinking_blocks if reasoning_content is None: reasoning_content = "" - elif ( - "content" in content_block["delta"] - and content_block["delta"].get("type") == "compaction_delta" - ): + elif "content" in content_block["delta"] and content_block["delta"].get("type") == "compaction_delta": # Handle compaction delta provider_specific_fields["compaction_delta"] = { "type": "compaction_delta", @@ -791,14 +769,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: usage: Usage | None = None provider_specific_fields: Dict[str, Any] = {} reasoning_content: str | None = None - thinking_blocks: ( - List[ - Union[ - ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock - ] - ] - | None - ) = None + thinking_blocks: List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] | None = None # Always use index=0 for OpenAI choice format (fixes multi-choice errors) index = 0 @@ -823,9 +794,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: content_block_start = self.get_content_block_start(chunk=chunk) self.content_blocks = [] # reset content blocks when new block starts # Track current content block type for filtering deltas - self.current_content_block_type = content_block_start["content_block"][ - "type" - ] + self.current_content_block_type = content_block_start["content_block"]["type"] if content_block_start["content_block"]["type"] == "text": text = content_block_start["content_block"]["text"] elif ( @@ -836,13 +805,8 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # Reverse-map the (sanitized) tool name back to the # caller's original. No-op when the map is empty. _stream_tool_name = content_block_start["content_block"]["name"] - if ( - self.tool_name_reverse_map - and _stream_tool_name in self.tool_name_reverse_map - ): - _stream_tool_name = self.tool_name_reverse_map[ - _stream_tool_name - ] + if self.tool_name_reverse_map and _stream_tool_name in self.tool_name_reverse_map: + _stream_tool_name = self.tool_name_reverse_map[_stream_tool_name] # Use empty string for arguments in content_block_start - actual arguments # come in subsequent content_block_delta chunks and get accumulated. # Using str(input) here would prepend '{}' causing invalid JSON accumulation. @@ -859,27 +823,16 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # The initial input in content_block_start is typically {} # for streaming; the full input arrives via input_json_delta # and is assembled at content_block_stop. - if ( - content_block_start["content_block"]["type"] - == "server_tool_use" - ): - self._current_server_tool_id = content_block_start[ - "content_block" - ]["id"] - tool_input = content_block_start["content_block"].get( - "input", {} - ) - self._server_tool_inputs[self._current_server_tool_id] = ( - tool_input - ) + if content_block_start["content_block"]["type"] == "server_tool_use": + self._current_server_tool_id = content_block_start["content_block"]["id"] + tool_input = content_block_start["content_block"].get("input", {}) + self._server_tool_inputs[self._current_server_tool_id] = tool_input # Include caller information if present (for programmatic tool calling) if "caller" in content_block_start["content_block"]: caller_data = content_block_start["content_block"]["caller"] if caller_data: tool_use["caller"] = cast(Dict[str, Any], caller_data) # type: ignore[typeddict-item] - elif ( - content_block_start["content_block"]["type"] == "redacted_thinking" - ): + elif content_block_start["content_block"]["type"] == "redacted_thinking": ( thinking_blocks, provider_specific_fields, @@ -892,19 +845,13 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # Handle compaction blocks # The full content comes in content_block_start self.compaction_blocks.append(content_block_start["content_block"]) - provider_specific_fields["compaction_blocks"] = ( - self.compaction_blocks - ) + provider_specific_fields["compaction_blocks"] = self.compaction_blocks provider_specific_fields["compaction_start"] = { "type": "compaction", - "content": content_block_start["content_block"].get( - "content", "" - ), + "content": content_block_start["content_block"].get("content", ""), } - elif content_block_start["content_block"]["type"].endswith( - "_tool_result" - ): + elif content_block_start["content_block"]["type"].endswith("_tool_result"): # Handle all tool result types (web_search, bash_code_execution, text_editor, etc.) content_type = content_block_start["content_block"]["type"] @@ -913,31 +860,21 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # Capture web_search_tool_result for multi-turn reconstruction # The full content comes in content_block_start, not in deltas # See: https://github.com/BerriAI/litellm/issues/17737 - self.web_search_results.append( - content_block_start["content_block"] - ) - provider_specific_fields["web_search_results"] = ( - self.web_search_results - ) + self.web_search_results.append(content_block_start["content_block"]) + provider_specific_fields["web_search_results"] = self.web_search_results elif content_type == "web_fetch_tool_result": # Capture web_fetch_tool_result for multi-turn reconstruction # The full content comes in content_block_start, not in deltas # Fixes: https://github.com/BerriAI/litellm/issues/18137 - self.web_search_results.append( - content_block_start["content_block"] - ) - provider_specific_fields["web_search_results"] = ( - self.web_search_results - ) + self.web_search_results.append(content_block_start["content_block"]) + provider_specific_fields["web_search_results"] = self.web_search_results elif content_type != "tool_search_tool_result": # Handle other tool results (code execution, etc.) # Skip tool_search_tool_result as it's internal metadata self.tool_results.append(content_block_start["content_block"]) provider_specific_fields["tool_results"] = self.tool_results # Convert to provider-neutral code_interpreter_results - provider_specific_fields["code_interpreter_results"] = ( - self._build_code_interpreter_results() - ) + provider_specific_fields["code_interpreter_results"] = self._build_code_interpreter_results() elif type_chunk == "content_block_stop": ContentBlockStop(**chunk) # type: ignore @@ -956,10 +893,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: ) # Update server_tool_inputs with fully assembled input # from input_json_delta chunks (content_block_start has {}) - if ( - self.current_content_block_type == "server_tool_use" - and self._current_server_tool_id - ): + if self.current_content_block_type == "server_tool_use" and self._current_server_tool_id: args = "" for block in self.content_blocks: if block["delta"]["type"] == "input_json_delta": @@ -968,9 +902,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: args += partial_json if args: try: - self._server_tool_inputs[ - self._current_server_tool_id - ] = json.loads(args) + self._server_tool_inputs[self._current_server_tool_id] = json.loads(args) except (json.JSONDecodeError, TypeError): pass self._current_server_tool_id = None @@ -989,14 +921,10 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # Store container_id and re-emit code_interpreter_results # so stream_chunk_builder's last-value-wins picks up the # version with container_id populated. - container_id = ( - container.get("id") if isinstance(container, dict) else None - ) + container_id = container.get("id") if isinstance(container, dict) else None if container_id and self.tool_results: self._container_id = container_id - provider_specific_fields["code_interpreter_results"] = ( - self._build_code_interpreter_results() - ) + provider_specific_fields["code_interpreter_results"] = self._build_code_interpreter_results() elif type_chunk == "message_start": """ Anthropic @@ -1019,9 +947,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: """ message_start_block = MessageStartBlock(**chunk) # type: ignore if "usage" in message_start_block["message"]: - usage = self._handle_usage( - anthropic_usage_chunk=message_start_block["message"]["usage"] - ) + usage = self._handle_usage(anthropic_usage_chunk=message_start_block["message"]["usage"]) elif type_chunk == "error": """ {"type":"error","error":{"details":null,"type":"api_error","message":"Internal server error"} } @@ -1042,14 +968,8 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: delta=Delta( content=text, tool_calls=[tool_use] if tool_use is not None else None, - provider_specific_fields=( - provider_specific_fields - if provider_specific_fields - else None - ), - thinking_blocks=( - thinking_blocks if thinking_blocks else None - ), + provider_specific_fields=(provider_specific_fields if provider_specific_fields else None), + thinking_blocks=(thinking_blocks if thinking_blocks else None), reasoning_content=reasoning_content, ), finish_reason=finish_reason, @@ -1101,9 +1021,7 @@ def _handle_json_mode_chunk( # Convert tool to content if we're tracking a response_format tool if self.is_response_format_tool: - message = AnthropicConfig._convert_tool_response_to_message( - tool_calls=[tool_use] - ) + message = AnthropicConfig._convert_tool_response_to_message(tool_calls=[tool_use]) if message is not None: text = message.content or "" tool_use = None @@ -1112,9 +1030,7 @@ def _handle_json_mode_chunk( return text, tool_use - def _handle_message_delta( - self, chunk: dict - ) -> Tuple[str, Usage | None, Dict[str, Any] | None]: + def _handle_message_delta(self, chunk: dict) -> Tuple[str, Usage | None, Dict[str, Any] | None]: """ Handle message_delta event for finish_reason, usage, and container. @@ -1125,9 +1041,7 @@ def _handle_message_delta( Tuple of (finish_reason, usage, container) """ message_delta = MessageBlockDelta(**chunk) # type: ignore - finish_reason = map_finish_reason( - finish_reason=message_delta["delta"].get("stop_reason", "stop") or "stop" - ) + finish_reason = map_finish_reason(finish_reason=message_delta["delta"].get("stop_reason", "stop") or "stop") # Override finish_reason to "stop" if we converted response_format tools # (matches OpenAI behavior and non-streaming Anthropic implementation) if self.converted_response_format_tool: @@ -1136,9 +1050,7 @@ def _handle_message_delta( container = message_delta["delta"].get("container") return finish_reason, usage, container - def _handle_accumulated_json_chunk( - self, data_str: str - ) -> ModelResponseStream | None: + def _handle_accumulated_json_chunk(self, data_str: str) -> ModelResponseStream | None: """ Handle partial JSON chunks by accumulating them until valid JSON is received. @@ -1234,9 +1146,7 @@ def __next__(self): except StopIteration: raise StopIteration except ValueError as e: - raise RuntimeError( - f"Error parsing chunk: {e},\nReceived chunk: {chunk}" - ) + raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") # Async iterator def __aiter__(self): @@ -1285,9 +1195,7 @@ async def __anext__(self): except StopAsyncIteration: raise StopAsyncIteration except ValueError as e: - raise RuntimeError( - f"Error parsing chunk: {e},\nReceived chunk: {chunk}" - ) + raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") def convert_str_chunk_to_generic_chunk(self, chunk: str) -> ModelResponseStream: """ diff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.py index 2b2264e6da97..9721b797584c 100644 --- a/litellm/llms/anthropic/chat/transformation.py +++ b/litellm/llms/anthropic/chat/transformation.py @@ -146,9 +146,7 @@ def _basic_sanitize_anthropic_tool_name(name: str) -> str: """ if not isinstance(name, str) or not name: return name - return _ANTHROPIC_TOOL_NAME_INVALID_CHARS.sub("_", name)[ - :_ANTHROPIC_TOOL_NAME_MAX_LEN - ] + return _ANTHROPIC_TOOL_NAME_INVALID_CHARS.sub("_", name)[:_ANTHROPIC_TOOL_NAME_MAX_LEN] def _build_anthropic_tool_name_maps( @@ -230,8 +228,7 @@ def _build_anthropic_tool_name_maps( ) DROP_UNSUPPORTED_SPEED_WARNING = ( - "Dropping unsupported `speed` for model=%s " - "(drop_params=True). Fast mode is only supported on select Opus models." + "Dropping unsupported `speed` for model=%s (drop_params=True). Fast mode is only supported on select Opus models." ) @@ -329,37 +326,27 @@ def convert_tool_use_to_openai_format( def _is_opus_4_6_model(model: str) -> bool: """Check if the model is specifically Claude Opus 4.6.""" model_lower = model.lower() - return any( - v in model_lower for v in ("opus-4-6", "opus_4_6", "opus-4.6", "opus_4.6") - ) + return any(v in model_lower for v in ("opus-4-6", "opus_4_6", "opus-4.6", "opus_4.6")) @staticmethod def _is_opus_4_7_model(model: str) -> bool: """Check if the model is specifically Claude Opus 4.7.""" model_lower = model.lower() - return any( - v in model_lower for v in ("opus-4-7", "opus_4_7", "opus-4.7", "opus_4.7") - ) + return any(v in model_lower for v in ("opus-4-7", "opus_4_7", "opus-4.7", "opus_4.7")) @staticmethod def _supports_effort_level(model: str, level: str) -> bool: """Check ``supports_{level}_reasoning_effort`` in the model map.""" - return AnthropicConfig._supports_model_capability( - model, f"supports_{level}_reasoning_effort" - ) + return AnthropicConfig._supports_model_capability(model, f"supports_{level}_reasoning_effort") @staticmethod def _validate_effort_for_model(model: str, effort: Optional[str]) -> Optional[str]: """Return ``None`` if ``effort`` is allowed on ``model``, else an error message.""" if effort == "max" and not ( - AnthropicConfig._is_claude_4_6_model(model) - or AnthropicConfig._is_claude_4_7_model(model) - or AnthropicConfig._supports_effort_level(model, "max") + AnthropicConfig._is_adaptive_thinking_model(model) or AnthropicConfig._supports_effort_level(model, "max") ): return f"effort='max' is not supported by this model. Got model: {model}" - if effort == "xhigh" and not AnthropicConfig._supports_effort_level( - model, "xhigh" - ): + if effort == "xhigh" and not AnthropicConfig._supports_effort_level(model, "xhigh"): return f"effort='xhigh' is not supported by this model. Got model: {model}" return None @@ -380,9 +367,7 @@ def _model_supports_effort_param(model: str) -> bool: ) @staticmethod - def _model_supports_speed_param( - model: str, custom_llm_provider: Optional[str] = None - ) -> bool: + def _model_supports_speed_param(model: str, custom_llm_provider: Optional[str] = None) -> bool: """Whether the model accepts Anthropic's ``speed`` parameter (fast mode). Fast mode is direct Anthropic API-only (not Bedrock, Vertex, or Azure). @@ -392,10 +377,7 @@ def _model_supports_speed_param( """ if custom_llm_provider is not None and custom_llm_provider != "anthropic": return False - return ( - AnthropicModelInfo._get_exact_model_capability(model, "supports_speed") - is True - ) + return AnthropicModelInfo._get_exact_model_capability(model, "supports_speed") is True @staticmethod def _maybe_drop_speed_param( @@ -425,9 +407,7 @@ def _maybe_drop_speed_param( optional_params.pop("speed", None) @staticmethod - def _raise_invalid_reasoning_effort( - model: str, value: Any, llm_provider: str - ) -> NoReturn: + def _raise_invalid_reasoning_effort(model: str, value: Any, llm_provider: str) -> NoReturn: """Raise a ``BadRequestError`` for an unrecognised ``reasoning_effort``. Args: @@ -471,8 +451,7 @@ def get_supported_openai_params(self, model: str): if ( "claude-3-7-sonnet" in model - or AnthropicConfig._is_claude_4_6_model(model) - or AnthropicConfig._is_claude_4_7_model(model) + or AnthropicConfig._is_adaptive_thinking_model(model) or supports_reasoning( model=model, custom_llm_provider=self.custom_llm_provider, @@ -538,9 +517,7 @@ def filter_anthropic_output_schema(schema: Dict[str, Any]) -> Dict[str, Any]: } for field in unsupported_fields: if field in schema: - constraint_descriptions.append( - constraint_labels[field].format(schema[field]) - ) + constraint_descriptions.append(constraint_labels[field].format(schema[field])) result: Dict[str, Any] = {} @@ -561,32 +538,17 @@ def filter_anthropic_output_schema(schema: Dict[str, Any]) -> Dict[str, Any]: continue if key == "properties" and isinstance(value, dict): - result[key] = { - k: AnthropicConfig.filter_anthropic_output_schema(v) - for k, v in value.items() - } + result[key] = {k: AnthropicConfig.filter_anthropic_output_schema(v) for k, v in value.items()} elif key == "items" and isinstance(value, dict): result[key] = AnthropicConfig.filter_anthropic_output_schema(value) elif key == "$defs" and isinstance(value, dict): - result[key] = { - k: AnthropicConfig.filter_anthropic_output_schema(v) - for k, v in value.items() - } + result[key] = {k: AnthropicConfig.filter_anthropic_output_schema(v) for k, v in value.items()} elif key == "anyOf" and isinstance(value, list): - result[key] = [ - AnthropicConfig.filter_anthropic_output_schema(item) - for item in value - ] + result[key] = [AnthropicConfig.filter_anthropic_output_schema(item) for item in value] elif key == "allOf" and isinstance(value, list): - result[key] = [ - AnthropicConfig.filter_anthropic_output_schema(item) - for item in value - ] + result[key] = [AnthropicConfig.filter_anthropic_output_schema(item) for item in value] elif key == "oneOf" and isinstance(value, list): - result[key] = [ - AnthropicConfig.filter_anthropic_output_schema(item) - for item in value - ] + result[key] = [AnthropicConfig.filter_anthropic_output_schema(item) for item in value] else: result[key] = value @@ -597,9 +559,7 @@ def filter_anthropic_output_schema(schema: Dict[str, Any]) -> Dict[str, Any]: return result - def get_json_schema_from_pydantic_object( - self, response_format: Union[Any, Dict, None] - ) -> Optional[dict]: + def get_json_schema_from_pydantic_object(self, response_format: Union[Any, Dict, None]) -> Optional[dict]: return type_to_response_format_param( response_format, ref_template="/$defs/{model}" ) # Relevant issue: https://github.com/BerriAI/litellm/issues/7755 @@ -691,12 +651,8 @@ def _map_tool_helper( _input_schema = unpack_legacy_defs(_input_schema, copy=True) _allowed_properties = set(AnthropicInputSchema.__annotations__.keys()) - input_schema_filtered = { - k: v for k, v in _input_schema.items() if k in _allowed_properties - } - input_anthropic_schema: AnthropicInputSchema = AnthropicInputSchema( - **input_schema_filtered - ) + input_schema_filtered = {k: v for k, v in _input_schema.items() if k in _allowed_properties} + input_anthropic_schema: AnthropicInputSchema = AnthropicInputSchema(**input_schema_filtered) _tool = AnthropicMessagesTool( name=tool["function"]["name"], @@ -715,16 +671,10 @@ def _map_tool_helper( if "parameters" not in tool["function"]: raise ValueError("Missing required parameter: parameters") - _display_width_px: Optional[int] = tool["function"]["parameters"].get( - "display_width_px" - ) - _display_height_px: Optional[int] = tool["function"]["parameters"].get( - "display_height_px" - ) + _display_width_px: Optional[int] = tool["function"]["parameters"].get("display_width_px") + _display_height_px: Optional[int] = tool["function"]["parameters"].get("display_height_px") if _display_width_px is None or _display_height_px is None: - raise ValueError( - "Missing required parameter: display_width_px or display_height_px" - ) + raise ValueError("Missing required parameter: display_width_px or display_height_px") _computer_tool = AnthropicComputerTool( type=tool["type"], @@ -757,9 +707,7 @@ def _map_tool_helper( elif tool["type"] == "url": # mcp server tool mcp_server = AnthropicMcpServerTool(**tool) # type: ignore elif tool["type"] == "mcp": - mcp_server = self._map_openai_mcp_server_tool( - cast(OpenAIMcpServerTool, tool) - ) + mcp_server = self._map_openai_mcp_server_tool(cast(OpenAIMcpServerTool, tool)) elif tool["type"] == "tool_search_tool_regex_20251119": # Tool search tool using regex from litellm.types.llms.anthropic import AnthropicToolSearchToolRegex @@ -816,9 +764,7 @@ def _map_tool_helper( ): if _cache_control is not None: returned_tool["cache_control"] = _cache_control # type: ignore[typeddict-item] - elif _cache_control_function is not None and isinstance( - _cache_control_function, dict - ): + elif _cache_control_function is not None and isinstance(_cache_control_function, dict): returned_tool["cache_control"] = ChatCompletionCachedContent( # type: ignore[typeddict-item] **_cache_control_function # type: ignore ) @@ -846,9 +792,7 @@ def _map_tool_helper( ## check if allowed_callers is set in the tool _allowed_callers = tool.get("allowed_callers", None) - _allowed_callers_function = tool.get("function", {}).get( - "allowed_callers", None - ) + _allowed_callers_function = tool.get("function", {}).get("allowed_callers", None) if returned_tool is not None: # Only set allowed_callers on tools that support it (not tool search tools or computer tools) tool_type = returned_tool.get("type", "") @@ -880,16 +824,12 @@ def _map_tool_helper( if tool_type == "custom" or (tool_type == "" and "name" in returned_tool): if _input_examples is not None and isinstance(_input_examples, list): returned_tool["input_examples"] = _input_examples # type: ignore[typeddict-item] - elif _input_examples_function is not None and isinstance( - _input_examples_function, list - ): + elif _input_examples_function is not None and isinstance(_input_examples_function, list): returned_tool["input_examples"] = _input_examples_function # type: ignore[typeddict-item] return returned_tool, mcp_server - def _map_openai_mcp_server_tool( - self, tool: OpenAIMcpServerTool - ) -> AnthropicMcpServerTool: + def _map_openai_mcp_server_tool(self, tool: OpenAIMcpServerTool) -> AnthropicMcpServerTool: from litellm.types.llms.anthropic import AnthropicMcpServerToolConfiguration allowed_tools = tool.get("allowed_tools", None) @@ -939,9 +879,7 @@ def _map_tools( ChatCompletionToolParam, { "type": nested.get("type", "function"), - "function": { - k: v for k, v in nested.items() if k != "type" - }, + "function": {k: v for k, v in nested.items() if k != "type"}, }, ) nested_tool, nested_mcp = self._map_tool_helper(wrapped) @@ -950,9 +888,7 @@ def _map_tools( if nested_mcp is not None: mcp_servers.append(nested_mcp) elif "function" in nested: - nested_tool, nested_mcp = self._map_tool_helper( - cast(ChatCompletionToolParam, nested) - ) + nested_tool, nested_mcp = self._map_tool_helper(cast(ChatCompletionToolParam, nested)) if nested_tool is not None: anthropic_tools.append(nested_tool) if nested_mcp is not None: @@ -1002,11 +938,7 @@ def _rewrite_tool_names_in_messages( continue fn = tc.get("function") fn_name = fn.get("name") if isinstance(fn, dict) else None - if ( - isinstance(fn, dict) - and isinstance(fn_name, str) - and fn_name in name_forward_map - ): + if isinstance(fn, dict) and isinstance(fn_name, str) and fn_name in name_forward_map: new_fn = dict(fn) new_fn["name"] = name_forward_map[fn_name] new_tc = dict(tc) @@ -1015,14 +947,8 @@ def _rewrite_tool_names_in_messages( else: new_calls.append(tc) new_msg["tool_calls"] = new_calls - fc_name = ( - function_call.get("name") if isinstance(function_call, dict) else None - ) - if ( - isinstance(function_call, dict) - and isinstance(fc_name, str) - and fc_name in name_forward_map - ): + fc_name = function_call.get("name") if isinstance(function_call, dict) else None + if isinstance(function_call, dict) and isinstance(fc_name, str) and fc_name in name_forward_map: new_fc = dict(function_call) new_fc["name"] = name_forward_map[fc_name] new_msg["function_call"] = new_fc @@ -1050,11 +976,7 @@ def _build_request_tool_name_maps( for tool in tools or []: if not isinstance(tool, dict): continue - original = ( - tool.get("function", {}).get("name") - if isinstance(tool.get("function"), dict) - else None - ) + original = tool.get("function", {}).get("name") if isinstance(tool.get("function"), dict) else None if original is None: original = tool.get("name") if isinstance(original, str) and original: @@ -1213,9 +1135,7 @@ def _expand_tool_references( return expanded_content - def _map_stop_sequences( - self, stop: Optional[Union[str, List[str]]] - ) -> Optional[List[str]]: + def _map_stop_sequences(self, stop: Optional[Union[str, List[str]]]) -> Optional[List[str]]: new_stop: Optional[List[str]] = None if isinstance(stop, str): if ( @@ -1291,9 +1211,7 @@ def _map_reasoning_effort( llm_provider=llm_provider, ) - def _extract_json_schema_from_response_format( - self, value: Optional[dict] - ) -> Optional[dict]: + def _extract_json_schema_from_response_format(self, value: Optional[dict]) -> Optional[dict]: if value is None: return None json_schema: Optional[dict] = None @@ -1304,12 +1222,8 @@ def _extract_json_schema_from_response_format( return json_schema - def map_response_format_to_anthropic_output_format( - self, value: Optional[dict] - ) -> Optional[AnthropicOutputSchema]: - json_schema: Optional[dict] = self._extract_json_schema_from_response_format( - value - ) + def map_response_format_to_anthropic_output_format(self, value: Optional[dict]) -> Optional[AnthropicOutputSchema]: + json_schema: Optional[dict] = self._extract_json_schema_from_response_format(value) if json_schema is None: return None @@ -1338,14 +1252,10 @@ def map_response_format_to_anthropic_tool( self, value: Optional[dict], optional_params: dict, is_thinking_enabled: bool ) -> Optional[AnthropicMessagesTool]: ignore_response_format_types = ["text"] - if ( - value is None or value["type"] in ignore_response_format_types - ): # value is a no-op + if value is None or value["type"] in ignore_response_format_types: # value is a no-op return None - json_schema: Optional[dict] = self._extract_json_schema_from_response_format( - value - ) + json_schema: Optional[dict] = self._extract_json_schema_from_response_format(value) if json_schema is None: return None """ @@ -1373,9 +1283,7 @@ def map_web_search_tool( user_location = value_typed.get("user_location") if user_location is not None: anthropic_user_location = AnthropicWebSearchUserLocation(type="approximate") - anthropic_user_location_keys = ( - AnthropicWebSearchUserLocation.__annotations__.keys() - ) + anthropic_user_location_keys = AnthropicWebSearchUserLocation.__annotations__.keys() user_location_approximate = user_location.get("approximate") if user_location_approximate is not None: for key, user_location_value in user_location_approximate.items(): @@ -1386,9 +1294,7 @@ def map_web_search_tool( ## MAP SEARCH CONTEXT SIZE search_context_size = value_typed.get("search_context_size") if search_context_size is not None: - hosted_web_search_tool["max_uses"] = ANTHROPIC_WEB_SEARCH_TOOL_MAX_USES[ - search_context_size - ] + hosted_web_search_tool["max_uses"] = ANTHROPIC_WEB_SEARCH_TOOL_MAX_USES[search_context_size] return hosted_web_search_tool @@ -1429,9 +1335,7 @@ def map_openai_context_management_to_anthropic( anthropic_edit: Dict[str, Any] = {"type": "compact_20260112"} compact_threshold = entry.get("compact_threshold") # Rewrite to 'trigger' with correct nesting if threshold exists - if compact_threshold is not None and isinstance( - compact_threshold, (int, float) - ): + if compact_threshold is not None and isinstance(compact_threshold, (int, float)): anthropic_edit["trigger"] = { "type": "input_tokens", "value": int(compact_threshold), @@ -1458,9 +1362,7 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - is_thinking_enabled = self.is_thinking_enabled( - non_default_params=non_default_params - ) + is_thinking_enabled = self.is_thinking_enabled(non_default_params=non_default_params) # NB: ``map_openai_params`` deliberately does NOT sanitize tool names # here. Names are the *original* OpenAI names at this stage, and must @@ -1475,13 +1377,9 @@ def map_openai_params( for param, value in non_default_params.items(): if param == "max_tokens": - optional_params["max_tokens"] = ( - value if isinstance(value, int) else max(1, int(round(value))) - ) + optional_params["max_tokens"] = value if isinstance(value, int) else max(1, int(round(value))) elif param == "max_completion_tokens": - optional_params["max_tokens"] = ( - value if isinstance(value, int) else max(1, int(round(value))) - ) + optional_params["max_tokens"] = value if isinstance(value, int) else max(1, int(round(value))) elif param == "tools": anthropic_tools, mcp_servers = self._map_tools(value) optional_params = self._add_tools_to_optional_params( @@ -1490,20 +1388,16 @@ def map_openai_params( if mcp_servers: optional_params["mcp_servers"] = mcp_servers elif param == "tool_choice" or param == "parallel_tool_calls": - _tool_choice: Optional[AnthropicMessagesToolChoice] = ( - self._map_tool_choice( - tool_choice=non_default_params.get("tool_choice"), - parallel_tool_use=non_default_params.get("parallel_tool_calls"), - ) + _tool_choice: Optional[AnthropicMessagesToolChoice] = self._map_tool_choice( + tool_choice=non_default_params.get("tool_choice"), + parallel_tool_use=non_default_params.get("parallel_tool_calls"), ) if _tool_choice is not None: optional_params["tool_choice"] = _tool_choice elif param == "stream" and value is True: optional_params["stream"] = value - elif param == "stop" and ( - isinstance(value, str) or isinstance(value, list) - ): + elif param == "stop" and (isinstance(value, str) or isinstance(value, list)): _value = self._map_stop_sequences(value) if _value is not None: optional_params["stop_sequences"] = _value @@ -1536,15 +1430,11 @@ def map_openai_params( "sonnet_4_6", } ): - _output_format = ( - self.map_response_format_to_anthropic_output_format(value) - ) + _output_format = self.map_response_format_to_anthropic_output_format(value) if _output_format is not None: optional_params["output_format"] = _output_format else: - _tool = self.map_response_format_to_anthropic_tool( - value, optional_params, is_thinking_enabled - ) + _tool = self.map_response_format_to_anthropic_tool(value, optional_params, is_thinking_enabled) if _tool is None: continue if not is_thinking_enabled: @@ -1554,9 +1444,7 @@ def map_openai_params( } optional_params["tool_choice"] = _tool_choice - optional_params = self._add_tools_to_optional_params( - optional_params=optional_params, tools=[_tool] - ) + optional_params = self._add_tools_to_optional_params(optional_params=optional_params, tools=[_tool]) optional_params["json_mode"] = True elif ( param == "user" @@ -1591,9 +1479,7 @@ def map_openai_params( else: optional_params["thinking"] = mapped_thinking if AnthropicConfig._is_adaptive_thinking_model(model): - mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get( - effort_value - ) + mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get(effort_value) if mapped_effort is None: AnthropicConfig._raise_invalid_reasoning_effort( model=model, @@ -1602,24 +1488,16 @@ def map_openai_params( ) optional_params["output_config"] = {"effort": mapped_effort} elif param == "web_search_options" and isinstance(value, dict): - hosted_web_search_tool = self.map_web_search_tool( - cast(OpenAIWebSearchOptions, value) - ) - self._add_tools_to_optional_params( - optional_params=optional_params, tools=[hosted_web_search_tool] - ) + hosted_web_search_tool = self.map_web_search_tool(cast(OpenAIWebSearchOptions, value)) + self._add_tools_to_optional_params(optional_params=optional_params, tools=[hosted_web_search_tool]) elif param == "extra_headers": optional_params["extra_headers"] = value elif param == "context_management": # Supports both OpenAI list format and Anthropic dict format if isinstance(value, (list, dict)): - anthropic_context_management = ( - self.map_openai_context_management_to_anthropic(value) - ) + anthropic_context_management = self.map_openai_context_management_to_anthropic(value) if anthropic_context_management is not None: - optional_params["context_management"] = ( - anthropic_context_management - ) + optional_params["context_management"] = anthropic_context_management elif param == "speed" and isinstance(value, str): optional_params["speed"] = value AnthropicConfig._maybe_drop_speed_param( @@ -1664,9 +1542,7 @@ def _create_json_tool_call_for_response_format( else: _input_schema.update(cast(AnthropicInputSchema, json_schema)) - _tool = AnthropicMessagesTool( - name=RESPONSE_FORMAT_TOOL_NAME, input_schema=_input_schema - ) + _tool = AnthropicMessagesTool(name=RESPONSE_FORMAT_TOOL_NAME, input_schema=_input_schema) return _tool def should_strip_billing_metadata(self) -> bool: @@ -1678,9 +1554,7 @@ def should_strip_billing_metadata(self) -> bool: """ return False - def translate_system_message( - self, messages: List[AllMessageValues] - ) -> List[AnthropicSystemMessageContent]: + def translate_system_message(self, messages: List[AllMessageValues]) -> List[AnthropicSystemMessageContent]: """ Translate system message to anthropic format. @@ -1697,21 +1571,17 @@ def translate_system_message( # Skip empty text blocks - Anthropic API raises errors for empty text if not system_message_block["content"]: continue - if self.should_strip_billing_metadata() and system_message_block[ - "content" - ].startswith("x-anthropic-billing-header:"): + if self.should_strip_billing_metadata() and system_message_block["content"].startswith( + "x-anthropic-billing-header:" + ): continue anthropic_system_message_content = AnthropicSystemMessageContent( type="text", text=system_message_block["content"], ) if "cache_control" in system_message_block: - anthropic_system_message_content["cache_control"] = ( - system_message_block["cache_control"] - ) - anthropic_system_message_list.append( - anthropic_system_message_content - ) + anthropic_system_message_content["cache_control"] = system_message_block["cache_control"] + anthropic_system_message_list.append(anthropic_system_message_content) elif isinstance(message["content"], list): for _content in message["content"]: # Skip empty text blocks - Anthropic API raises errors for empty text @@ -1725,20 +1595,14 @@ def translate_system_message( and text_value.startswith("x-anthropic-billing-header:") ): continue - anthropic_system_message_content = ( - AnthropicSystemMessageContent( - type=_content.get("type"), - text=text_value, - ) + anthropic_system_message_content = AnthropicSystemMessageContent( + type=_content.get("type"), + text=text_value, ) if "cache_control" in _content: - anthropic_system_message_content["cache_control"] = ( - _content["cache_control"] - ) + anthropic_system_message_content["cache_control"] = _content["cache_control"] - anthropic_system_message_list.append( - anthropic_system_message_content - ) + anthropic_system_message_list.append(anthropic_system_message_content) if len(system_prompt_indices) > 0: for idx in reversed(system_prompt_indices): @@ -1766,11 +1630,7 @@ def add_code_execution_tool( ## check if code_execution tool is already in tools for tool in tools: tool_type = tool.get("type", None) - if ( - tool_type - and isinstance(tool_type, str) - and tool_type.startswith("code_execution") - ): + if tool_type and isinstance(tool_type, str) and tool_type.startswith("code_execution"): return tools tools.append( AnthropicCodeExecutionTool( @@ -1797,9 +1657,7 @@ def _ensure_beta_header(self, headers: dict, beta_value: str) -> None: if beta_value not in existing_values: headers["anthropic-beta"] = f"{existing_beta}, {beta_value}" - def _ensure_context_management_beta_header( - self, headers: dict, context_management: object - ) -> None: + def _ensure_context_management_beta_header(self, headers: dict, context_management: object) -> None: """ Add appropriate beta headers based on context_management edits. """ @@ -1826,9 +1684,7 @@ def _ensure_context_management_beta_header( # Add compact header if any compact edits/entries exist if has_compact: - self._ensure_beta_header( - headers, ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value - ) + self._ensure_beta_header(headers, ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value) # Add context management header if any other edits/entries exist if has_other: @@ -1837,9 +1693,7 @@ def _ensure_context_management_beta_header( ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value, ) - def update_headers_with_optional_anthropic_beta( - self, headers: dict, optional_params: dict - ) -> dict: + def update_headers_with_optional_anthropic_beta(self, headers: dict, optional_params: dict) -> dict: """Update headers with optional anthropic beta.""" # Skip adding beta headers for Vertex requests @@ -1850,39 +1704,25 @@ def update_headers_with_optional_anthropic_beta( _tools = optional_params.get("tools", []) for tool in _tools: - if tool.get("type", None) and tool.get("type").startswith( - ANTHROPIC_HOSTED_TOOLS.WEB_FETCH.value - ): - self._ensure_beta_header( - headers, ANTHROPIC_BETA_HEADER_VALUES.WEB_FETCH_2025_09_10.value - ) - elif tool.get("type", None) and tool.get("type").startswith( - ANTHROPIC_HOSTED_TOOLS.MEMORY.value - ): + if tool.get("type", None) and tool.get("type").startswith(ANTHROPIC_HOSTED_TOOLS.WEB_FETCH.value): + self._ensure_beta_header(headers, ANTHROPIC_BETA_HEADER_VALUES.WEB_FETCH_2025_09_10.value) + elif tool.get("type", None) and tool.get("type").startswith(ANTHROPIC_HOSTED_TOOLS.MEMORY.value): self._ensure_beta_header( headers, ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value, ) if optional_params.get("context_management") is not None: - self._ensure_context_management_beta_header( - headers, optional_params["context_management"] - ) + self._ensure_context_management_beta_header(headers, optional_params["context_management"]) output_config = optional_params.get("output_config") if optional_params.get("output_format") is not None or ( isinstance(output_config, dict) and output_config.get("format") is not None ): - self._ensure_beta_header( - headers, ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value - ) + self._ensure_beta_header(headers, ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value) if optional_params.get("speed") == "fast": - self._ensure_beta_header( - headers, ANTHROPIC_BETA_HEADER_VALUES.FAST_MODE_2026_02_01.value - ) + self._ensure_beta_header(headers, ANTHROPIC_BETA_HEADER_VALUES.FAST_MODE_2026_02_01.value) for tool in _tools: if tool.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE: - self._ensure_beta_header( - headers, ANTHROPIC_BETA_HEADER_VALUES.ADVISOR_TOOL_2026_03_01.value - ) + self._ensure_beta_header(headers, ANTHROPIC_BETA_HEADER_VALUES.ADVISOR_TOOL_2026_03_01.value) break return headers @@ -1903,14 +1743,8 @@ def transform_request( anthropic_messages_pt, ) - if ( - "tools" not in optional_params - and messages is not None - and has_tool_call_blocks(messages) - ): - optional_params["tools"], _ = self._map_tools( - add_dummy_tool(custom_llm_provider="anthropic") - ) + if "tools" not in optional_params and messages is not None and has_tool_call_blocks(messages): + optional_params["tools"], _ = self._map_tools(add_dummy_tool(custom_llm_provider="anthropic")) # Drop thinking param if thinking is enabled but thinking_blocks are missing # This prevents the error: "Expected thinking or redacted_thinking, but found tool_use" @@ -1935,14 +1769,11 @@ def transform_request( AnthropicConfig._maybe_drop_speed_param( model=model, optional_params=optional_params, - drop_params=litellm.drop_params - or litellm_params.get("drop_params") is True, + drop_params=litellm.drop_params or litellm_params.get("drop_params") is True, custom_llm_provider=self.custom_llm_provider, ) - headers = self.update_headers_with_optional_anthropic_beta( - headers=headers, optional_params=optional_params - ) + headers = self.update_headers_with_optional_anthropic_beta(headers=headers, optional_params=optional_params) # === Tool-name sanitization (single chokepoint) === # Anthropic enforces ^[a-zA-Z0-9_-]{1,128}$ on every tool name. We @@ -1993,10 +1824,7 @@ def transform_request( ## Auto-strip advisor blocks from history if advisor tool is absent. ## Prevents Anthropic 400: advisor_tool_result in history requires advisor tool. _all_tools = optional_params.get("tools") or [] - _has_advisor = any( - isinstance(t, dict) and t.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE - for t in _all_tools - ) + _has_advisor = any(isinstance(t, dict) and t.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE for t in _all_tools) if not _has_advisor: anthropic_messages = strip_advisor_blocks_from_messages(anthropic_messages) @@ -2032,9 +1860,7 @@ def transform_request( optional_params["metadata"] = {"user_id": _litellm_metadata["user_id"]} ## Ensure metadata only contains user_id (only documented field in Anthropic Messages API) - if "metadata" in optional_params and isinstance( - optional_params["metadata"], dict - ): + if "metadata" in optional_params and isinstance(optional_params["metadata"], dict): _user_id = optional_params["metadata"].get("user_id") if _user_id is not None: optional_params["metadata"] = {"user_id": _user_id} @@ -2065,15 +1891,11 @@ def transform_request( **optional_params, } - self._apply_output_config( - data=data, model=model, optional_params=optional_params - ) + self._apply_output_config(data=data, model=model, optional_params=optional_params) return data - def _apply_output_config( - self, data: dict, model: str, optional_params: dict - ) -> None: + def _apply_output_config(self, data: dict, model: str, optional_params: dict) -> None: """Validate and apply output_config to the request data.""" if "output_config" not in optional_params: return @@ -2092,10 +1914,7 @@ def _apply_output_config( valid_efforts = ["high", "medium", "low", "xhigh", "max"] if effort is not None and effort not in valid_efforts: raise litellm.exceptions.BadRequestError( - message=( - f"Invalid effort value: {effort!r}. Must be one of: " - f"'high', 'medium', 'low', 'xhigh', 'max'" - ), + message=(f"Invalid effort value: {effort!r}. Must be one of: 'high', 'medium', 'low', 'xhigh', 'max'"), model=model, llm_provider=self.custom_llm_provider or "anthropic", ) @@ -2122,9 +1941,7 @@ def _resolve_json_mode_non_streaming( return None, tool_calls, None json_indices = [ - i - for i, t in enumerate(tool_calls) - if t.get("function", {}).get("name") == RESPONSE_FORMAT_TOOL_NAME + i for i, t in enumerate(tool_calls) if t.get("function", {}).get("name") == RESPONSE_FORMAT_TOOL_NAME ] if not json_indices: return None, tool_calls, None @@ -2133,16 +1950,12 @@ def _resolve_json_mode_non_streaming( json_tool = tool_calls[json_indices[0]] if json_tool.get("function", {}).get("arguments") is None: return None, tool_calls, None - _message = AnthropicConfig._convert_tool_response_to_message( - tool_calls=[json_tool] - ) + _message = AnthropicConfig._convert_tool_response_to_message(tool_calls=[json_tool]) return _message, [], None first_json = tool_calls[json_indices[0]] json_msg = AnthropicConfig._convert_tool_response_to_message([first_json]) - extra_content: Optional[str] = ( - json_msg.content if json_msg is not None else None - ) + extra_content: Optional[str] = json_msg.content if json_msg is not None else None filtered_tools = [t for i, t in enumerate(tool_calls) if i not in json_indices] return None, filtered_tools, extra_content @@ -2151,11 +1964,7 @@ def extract_response_content( ) -> Tuple[ str, Optional[List[Any]], - Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ], + Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]], Optional[str], List[ChatCompletionToolCallChunk], Optional[List[Any]], @@ -2164,11 +1973,7 @@ def extract_response_content( ]: text_content = "" citations: Optional[List[Any]] = None - thinking_blocks: Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ] = None + thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]] = None reasoning_content: Optional[str] = None tool_calls: List[ChatCompletionToolCallChunk] = [] web_search_results: Optional[List[Any]] = None @@ -2212,9 +2017,7 @@ def extract_response_content( elif content["type"] == "redacted_thinking": if thinking_blocks is None: thinking_blocks = [] - thinking_blocks.append( - cast(ChatCompletionRedactedThinkingBlock, content) - ) + thinking_blocks.append(cast(ChatCompletionRedactedThinkingBlock, content)) ## COMPACTION elif content["type"] == "compaction": @@ -2262,15 +2065,9 @@ def calculate_usage( ) -> Usage: # NOTE: Sometimes the usage object has None set explicitly for token counts, meaning .get() & key access returns None, and we need to account for this raw_prompt_tokens = usage_object.get("input_tokens", 0) or 0 - prompt_tokens: int = ( - int(raw_prompt_tokens) if isinstance(raw_prompt_tokens, (int, float)) else 0 - ) + prompt_tokens: int = int(raw_prompt_tokens) if isinstance(raw_prompt_tokens, (int, float)) else 0 raw_completion_tokens = usage_object.get("output_tokens", 0) or 0 - completion_tokens: int = ( - int(raw_completion_tokens) - if isinstance(raw_completion_tokens, (int, float)) - else 0 - ) + completion_tokens: int = int(raw_completion_tokens) if isinstance(raw_completion_tokens, (int, float)) else 0 _usage = usage_object cache_creation_input_tokens: int = 0 cache_read_input_tokens: int = 0 @@ -2288,28 +2085,16 @@ def calculate_usage( iterations: Optional[List[Any]] = _usage.get("iterations") if iterations: prompt_tokens = sum(it.get("input_tokens", 0) or 0 for it in iterations) - completion_tokens = sum( - it.get("output_tokens", 0) or 0 for it in iterations - ) - cache_creation_input_tokens = sum( - it.get("cache_creation_input_tokens", 0) or 0 for it in iterations - ) - cache_read_input_tokens = sum( - it.get("cache_read_input_tokens", 0) or 0 for it in iterations - ) + completion_tokens = sum(it.get("output_tokens", 0) or 0 for it in iterations) + cache_creation_input_tokens = sum(it.get("cache_creation_input_tokens", 0) or 0 for it in iterations) + cache_read_input_tokens = sum(it.get("cache_read_input_tokens", 0) or 0 for it in iterations) prompt_tokens += cache_creation_input_tokens + cache_read_input_tokens if not iterations: - if ( - "cache_creation_input_tokens" in _usage - and _usage["cache_creation_input_tokens"] is not None - ): + if "cache_creation_input_tokens" in _usage and _usage["cache_creation_input_tokens"] is not None: cache_creation_input_tokens = _usage["cache_creation_input_tokens"] prompt_tokens += cache_creation_input_tokens - if ( - "cache_read_input_tokens" in _usage - and _usage["cache_read_input_tokens"] is not None - ): + if "cache_read_input_tokens" in _usage and _usage["cache_read_input_tokens"] is not None: cache_read_input_tokens = _usage["cache_read_input_tokens"] prompt_tokens += cache_read_input_tokens if "server_tool_use" in _usage and _usage["server_tool_use"] is not None: @@ -2317,16 +2102,12 @@ def calculate_usage( "web_search_requests" in _usage["server_tool_use"] and _usage["server_tool_use"]["web_search_requests"] is not None ): - web_search_requests = cast( - int, _usage["server_tool_use"]["web_search_requests"] - ) + web_search_requests = cast(int, _usage["server_tool_use"]["web_search_requests"]) if ( "tool_search_requests" in _usage["server_tool_use"] and _usage["server_tool_use"]["tool_search_requests"] is not None ): - tool_search_requests = cast( - int, _usage["server_tool_use"]["tool_search_requests"] - ) + tool_search_requests = cast(int, _usage["server_tool_use"]["tool_search_requests"]) # Count tool_search_requests from content blocks if not in usage # Anthropic doesn't always include tool_search_requests in the usage object @@ -2342,17 +2123,11 @@ def calculate_usage( if "cache_creation" in _usage and _usage["cache_creation"] is not None: cache_creation_token_details = CacheCreationTokenDetails( - ephemeral_5m_input_tokens=_usage["cache_creation"].get( - "ephemeral_5m_input_tokens" - ), - ephemeral_1h_input_tokens=_usage["cache_creation"].get( - "ephemeral_1h_input_tokens" - ), + ephemeral_5m_input_tokens=_usage["cache_creation"].get("ephemeral_5m_input_tokens"), + ephemeral_1h_input_tokens=_usage["cache_creation"].get("ephemeral_1h_input_tokens"), ) - raw_input_tokens = ( - prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens - ) + raw_input_tokens = prompt_tokens - cache_read_input_tokens - cache_creation_input_tokens prompt_tokens_details = PromptTokensDetailsWrapper( cached_tokens=cache_read_input_tokens, cache_creation_tokens=cache_creation_input_tokens, @@ -2361,18 +2136,12 @@ def calculate_usage( ) # Always populate completion_token_details, not just when there's reasoning_content estimated_reasoning_tokens = ( - token_counter(text=reasoning_content, count_response_tokens=True) - if reasoning_content - else 0 + token_counter(text=reasoning_content, count_response_tokens=True) if reasoning_content else 0 ) reasoning_tokens = min(estimated_reasoning_tokens, completion_tokens) completion_token_details = CompletionTokensDetailsWrapper( reasoning_tokens=reasoning_tokens if reasoning_tokens > 0 else 0, - text_tokens=( - completion_tokens - reasoning_tokens - if reasoning_tokens > 0 - else completion_tokens - ), + text_tokens=(completion_tokens - reasoning_tokens if reasoning_tokens > 0 else completion_tokens), ) total_tokens = prompt_tokens + completion_tokens @@ -2399,9 +2168,7 @@ def calculate_usage( ) return usage - def _build_code_by_id_map( - self, tool_calls: List[ChatCompletionToolCallChunk] - ) -> Dict[str, str]: + def _build_code_by_id_map(self, tool_calls: List[ChatCompletionToolCallChunk]) -> Dict[str, str]: code_by_id: Dict[str, str] = {} for tc in tool_calls: try: @@ -2443,11 +2210,7 @@ def _build_provider_specific_fields( self, completion_response: dict, citations: Optional[List[Any]], - thinking_blocks: Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ], + thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]], web_search_results: Optional[List[Any]], tool_results: Optional[List[Any]], compaction_blocks: Optional[List[Any]], @@ -2473,12 +2236,8 @@ def _build_provider_specific_fields( else None ) code_by_id = self._build_code_by_id_map(tool_calls) - code_interpreter_results = self._build_code_interpreter_results( - tool_results, code_by_id, container_id - ) - provider_specific_fields["code_interpreter_results"] = ( - code_interpreter_results - ) + code_interpreter_results = self._build_code_interpreter_results(tool_results, code_by_id, container_id) + provider_specific_fields["code_interpreter_results"] = code_interpreter_results container = completion_response.get("container") if container is not None: @@ -2500,9 +2259,7 @@ def transform_parsed_response( tool_name_reverse_map: Optional[Dict[str, str]] = None, ): _hidden_params: Dict = {} - _hidden_params["additional_headers"] = process_anthropic_headers( - dict(raw_response.headers) - ) + _hidden_params["additional_headers"] = process_anthropic_headers(dict(raw_response.headers)) if "error" in completion_response: response_headers = getattr(raw_response, "headers", None) raise AnthropicError( @@ -2554,17 +2311,13 @@ def transform_parsed_response( tool_calls, ) - json_mode_message, tool_calls_for_message, json_extra_content = ( - self._resolve_json_mode_non_streaming( - json_mode=json_mode, - tool_calls=tool_calls, - ) + json_mode_message, tool_calls_for_message, json_extra_content = self._resolve_json_mode_non_streaming( + json_mode=json_mode, + tool_calls=tool_calls, ) merged_text = text_content or "" if json_extra_content: - merged_text = ( - merged_text + json_extra_content if merged_text else json_extra_content - ) + merged_text = merged_text + json_extra_content if merged_text else json_extra_content _message = litellm.Message( tool_calls=tool_calls_for_message, @@ -2580,9 +2333,7 @@ def transform_parsed_response( _message = json_mode_message model_response.choices[0].message = _message - model_response._hidden_params["original_response"] = completion_response[ - "content" - ] + model_response._hidden_params["original_response"] = completion_response["content"] model_response.choices[0].finish_reason = cast( OpenAIChatCompletionFinishReason, map_finish_reason(completion_response["stop_reason"]), @@ -2617,11 +2368,7 @@ def get_prefix_prompt(self, messages: List[AllMessageValues]) -> Optional[str]: message = messages[-1] message_content = message.get("content") - if ( - message["role"] == "assistant" - and message.get("prefix", False) - and isinstance(message_content, str) - ): + if message["role"] == "assistant" and message.get("prefix", False) and isinstance(message_content, str): return message_content return None @@ -2654,9 +2401,7 @@ def transform_response( except Exception as e: response_headers = getattr(raw_response, "headers", None) raise AnthropicError( - message="Unable to get json response - {}, Original Response: {}".format( - str(e), raw_response.text - ), + message="Unable to get json response - {}, Original Response: {}".format(str(e), raw_response.text), status_code=raw_response.status_code, headers=response_headers, ) @@ -2689,16 +2434,11 @@ def _convert_tool_response_to_message( """ ## HANDLE JSON MODE - anthropic returns single function call - json_mode_content_str: Optional[str] = tool_calls[0]["function"].get( - "arguments" - ) + json_mode_content_str: Optional[str] = tool_calls[0]["function"].get("arguments") try: if json_mode_content_str is not None: args = json.loads(json_mode_content_str) - if ( - isinstance(args, dict) - and (values := args.get("values")) is not None - ): + if isinstance(args, dict) and (values := args.get("values")) is not None: _message = litellm.Message(content=json.dumps(values)) return _message else: diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py index d27187cf2e73..721fcae4c081 100644 --- a/litellm/llms/anthropic/common_utils.py +++ b/litellm/llms/anthropic/common_utils.py @@ -26,6 +26,23 @@ ) from litellm.types.llms.openai import AllMessageValues +_BEDROCK_VERSION_SUFFIX_RE = re.compile(r"-v\d+(?::\d+)?$") +_INFERENCE_PROFILE_MINOR_RE = re.compile(r":\d+$") +_DATED_RELEASE_SUFFIX_RE = re.compile(r"-\d{8}$") +_DOTTED_VERSION_RE = re.compile(r"(\d)\.(\d)") + + +def _strip_bedrock_id_suffixes(model: str) -> str: + """Reduce a full Bedrock model id to its base cost-map key by rewriting a + dotted family version then peeling a trailing ``-vN:rev`` and ``-YYYYMMDD`` + in that order, so the real ``--v1:0`` shape (e.g. + ``us.anthropic.claude-sonnet-4-6-20251101-v1:0``) resolves rather than only + the date or version in isolation.""" + return _DATED_RELEASE_SUFFIX_RE.sub( + "", + _BEDROCK_VERSION_SUFFIX_RE.sub("", _DOTTED_VERSION_RE.sub(r"\1-\2", model)), + ) + def is_anthropic_oauth_key(value: Optional[str]) -> bool: """Check if a value contains an Anthropic OAuth token (sk-ant-oat*).""" @@ -46,9 +63,7 @@ def _merge_beta_headers(existing: Optional[str], new_beta: str) -> str: return ",".join(sorted(betas)) -def optionally_handle_anthropic_oauth( - headers: dict, api_key: Optional[str] -) -> tuple[dict, Optional[str]]: +def optionally_handle_anthropic_oauth(headers: dict, api_key: Optional[str]) -> tuple[dict, Optional[str]]: """ Handle Anthropic OAuth token detection and header setup. @@ -67,18 +82,14 @@ def optionally_handle_anthropic_oauth( if auth_header and auth_header.startswith(f"Bearer {ANTHROPIC_OAUTH_TOKEN_PREFIX}"): api_key = auth_header.replace("Bearer ", "") headers.pop("x-api-key", None) - headers["anthropic-beta"] = _merge_beta_headers( - headers.get("anthropic-beta"), ANTHROPIC_OAUTH_BETA_HEADER - ) + headers["anthropic-beta"] = _merge_beta_headers(headers.get("anthropic-beta"), ANTHROPIC_OAUTH_BETA_HEADER) headers["anthropic-dangerous-direct-browser-access"] = "true" return headers, api_key # Check api_key directly (standard chat/completion flow) if api_key and api_key.startswith(ANTHROPIC_OAUTH_TOKEN_PREFIX): headers.pop("x-api-key", None) headers["authorization"] = f"Bearer {api_key}" - headers["anthropic-beta"] = _merge_beta_headers( - headers.get("anthropic-beta"), ANTHROPIC_OAUTH_BETA_HEADER - ) + headers["anthropic-beta"] = _merge_beta_headers(headers.get("anthropic-beta"), ANTHROPIC_OAUTH_BETA_HEADER) headers["anthropic-dangerous-direct-browser-access"] = "true" return headers, api_key @@ -118,18 +129,14 @@ def is_file_id_used(self, messages: List[AllMessageValues]) -> bool: file_ids = get_file_ids_from_messages(messages) return len(file_ids) > 0 - def is_mcp_server_used( - self, mcp_servers: Optional[List[AnthropicMcpServerTool]] - ) -> bool: + def is_mcp_server_used(self, mcp_servers: Optional[List[AnthropicMcpServerTool]]) -> bool: if mcp_servers is None: return False if mcp_servers: return True return False - def is_computer_tool_used( - self, tools: Optional[List[AllAnthropicToolsValues]] - ) -> Optional[str]: + def is_computer_tool_used(self, tools: Optional[List[AllAnthropicToolsValues]]) -> Optional[str]: """Returns the computer tool version if used, e.g. 'computer_20250124' or None""" if tools is None: return None @@ -138,16 +145,12 @@ def is_computer_tool_used( return tool["type"] return None - def is_web_search_tool_used( - self, tools: Optional[List[AllAnthropicToolsValues]] - ) -> bool: + def is_web_search_tool_used(self, tools: Optional[List[AllAnthropicToolsValues]]) -> bool: """Returns True if web_search tool is used""" if tools is None: return False for tool in tools: - if "type" in tool and tool["type"].startswith( - ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value - ): + if "type" in tool and tool["type"].startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value): return True return False @@ -157,11 +160,7 @@ def is_pdf_used(self, messages: List[AllMessageValues]) -> bool: """ for message in messages: - if ( - "content" in message - and message["content"] is not None - and isinstance(message["content"], list) - ): + if "content" in message and message["content"] is not None and isinstance(message["content"], list): for content in message["content"]: if "type" in content and content["type"] != "text": return True @@ -203,9 +202,7 @@ def is_programmatic_tool_calling_used(self, tools: Optional[List]) -> bool: function = tool.get("function", {}) if isinstance(function, dict): function_allowed_callers = function.get("allowed_callers", None) - if function_allowed_callers and isinstance( - function_allowed_callers, list - ): + if function_allowed_callers and isinstance(function_allowed_callers, list): if "code_execution_20250825" in function_allowed_callers: return True @@ -223,11 +220,7 @@ def is_input_examples_used(self, tools: Optional[List]) -> bool: for tool in tools: # Check top-level input_examples input_examples = tool.get("input_examples", None) - if ( - input_examples - and isinstance(input_examples, list) - and len(input_examples) > 0 - ): + if input_examples and isinstance(input_examples, list) and len(input_examples) > 0: return True # Check function.input_examples for OpenAI format tools @@ -243,38 +236,6 @@ def is_input_examples_used(self, tools: Optional[List]) -> bool: return False - @staticmethod - def _is_claude_4_6_model(model: str) -> bool: - """Check if the model is a Claude 4.6 model (Opus 4.6 or Sonnet 4.6).""" - model_lower = model.lower() - return any( - v in model_lower - for v in ( - "opus-4-6", - "opus_4_6", - "opus-4.6", - "opus_4.6", - "sonnet-4-6", - "sonnet_4_6", - "sonnet-4.6", - "sonnet_4.6", - ) - ) - - @staticmethod - def _is_claude_4_7_model(model: str) -> bool: - """Check if the model is a Claude 4.7 model (Opus 4.7).""" - model_lower = model.lower() - return any( - v in model_lower - for v in ( - "opus-4-7", - "opus_4_7", - "opus-4.7", - "opus_4.7", - ) - ) - @staticmethod def _supports_sampling_params(model: str) -> bool: """Claude 4.7+ (Opus 4.7/4.8, Fable 5) removed sampling params: the API @@ -284,9 +245,7 @@ def _supports_sampling_params(model: str) -> bool: Driven by the ``supports_sampling_params`` flag in the model map; the name check remains only as a fallback for provider-routed ids whose map entries predate the flag.""" - flag = AnthropicModelInfo._get_model_capability( - model, "supports_sampling_params" - ) + flag = AnthropicModelInfo._get_model_capability(model, "supports_sampling_params") if flag is not None: return flag model_lower = model.lower() @@ -318,14 +277,10 @@ def _apply_sampling_param( ``optional_params[output_key]`` unless the model removed sampling params, in which case drop the param (with drop_params) or raise a clean client-side 400.""" - if AnthropicModelInfo._supports_sampling_params(model) or ( - param == "temperature" and value == 1 - ): + if AnthropicModelInfo._supports_sampling_params(model) or (param == "temperature" and value == 1): optional_params[output_key] = value elif not (litellm.drop_params or drop_params): - supported_hint = ( - "Only temperature=1 is supported. " if param == "temperature" else "" - ) + supported_hint = "Only temperature=1 is supported. " if param == "temperature" else "" raise litellm.utils.UnsupportedParamsError( message=( f"{model} does not support {param}={value}. {supported_hint}" @@ -336,27 +291,42 @@ def _apply_sampling_param( @staticmethod def _model_map_lookup_candidates(model: str) -> List[str]: - """Model-map keys to try for ``model``, stripping bedrock/vertex - prefixes so a provider-routed Claude still resolves to its entry.""" - candidates = [model] - for prefix in ( + """Model-map keys to try for ``model``: the id itself, the same id with a + bedrock/vertex routing prefix removed, the Bedrock base model, and each of + those normalized by stripping a Bedrock version suffix (``-v1:0`` fully or + just the ``:0`` inference-profile minor), stripping a dated-release suffix + (``-20260205``), or rewriting a dotted family version to hyphens + (``4.6`` -> ``4-6``). Lets any reasonable alias (e.g. + ``bedrock/invoke/global.anthropic.claude-opus-4-7-v1:0``, + ``claude-sonnet-4-6-20260219`` or ``claude-sonnet-4.6``) resolve to its base + cost-map entry so the capability flag on that entry stays authoritative.""" + prefixes = ( "bedrock/converse/", "bedrock/invoke/", "bedrock/", "vertex_ai/", - ): - if model.startswith(prefix): - candidates.append(model[len(prefix) :]) + ) + deprefixed = tuple(model[len(p) :] for p in prefixes if model.startswith(p)) try: from litellm.llms.bedrock.common_utils import BedrockModelInfo base = BedrockModelInfo.get_base_model(model) - if base: - candidates.append(base) - candidates.append(f"bedrock/{base}") except Exception: - pass - return candidates + base = None + bedrock_base = (base, f"bedrock/{base}") if base else () + primary = (model, *deprefixed, *bedrock_base) + normalized = tuple( + stripped + for cand in primary + for stripped in ( + _BEDROCK_VERSION_SUFFIX_RE.sub("", cand), + _INFERENCE_PROFILE_MINOR_RE.sub("", cand), + _DATED_RELEASE_SUFFIX_RE.sub("", cand), + _DOTTED_VERSION_RE.sub(r"\1-\2", cand), + _strip_bedrock_id_suffixes(cand), + ) + ) + return list(dict.fromkeys((*primary, *normalized))) @staticmethod def _get_model_capability(model: str, key: str) -> Optional[bool]: @@ -403,23 +373,16 @@ def _supports_model_capability(model: str, key: str) -> bool: @staticmethod def _is_adaptive_thinking_model(model: str) -> bool: - """Claude 4.6+ models use adaptive thinking with ``output_config.effort``. + """Whether ``model`` uses adaptive thinking (``output_config.effort``). - Driven by the ``supports_adaptive_thinking`` flag in the model map; the - 4.6/4.7 name checks remain only as a fallback for provider-routed ids - whose map entries predate the flag. + Sourced solely from the model cost map's ``supports_adaptive_thinking`` flag, + resolved through provider prefixes. A model that resolves to no mapped entry + (an unmapped alias or a future release not yet in the map) is treated as + non-adaptive until a ``fallback_generalizations`` rule covers it. """ - if AnthropicModelInfo._supports_model_capability( - model, "supports_adaptive_thinking" - ): - return True - return AnthropicModelInfo._is_claude_4_6_model( - model - ) or AnthropicModelInfo._is_claude_4_7_model(model) + return AnthropicModelInfo._supports_model_capability(model, "supports_adaptive_thinking") - def is_effort_used( - self, optional_params: Optional[dict], model: Optional[str] = None - ) -> bool: + def is_effort_used(self, optional_params: Optional[dict], model: Optional[str] = None) -> bool: """ Check if effort parameter is being used and requires a beta header. @@ -480,9 +443,7 @@ def is_container_with_skills_used(self, optional_params: Optional[dict]) -> bool return True return False - def _get_user_anthropic_beta_headers( - self, anthropic_beta_header: Optional[str] - ) -> Optional[List[str]]: + def _get_user_anthropic_beta_headers(self, anthropic_beta_header: Optional[str]) -> Optional[List[str]]: if anthropic_beta_header is None: return None return anthropic_beta_header.split(",") @@ -549,13 +510,9 @@ def get_anthropic_beta_list( return list(set(betas)) @staticmethod - def _make_api_key_auth_header( - api_key: str, api_base: str | None, use_bearer_for_custom_base: bool = False - ) -> dict: + def _make_api_key_auth_header(api_key: str, api_base: str | None, use_bearer_for_custom_base: bool = False) -> dict: if use_bearer_for_custom_base and ( - api_base - and "api.anthropic.com" not in api_base - and not api_key.startswith("sk-ant-") + api_base and "api.anthropic.com" not in api_base and not api_key.startswith("sk-ant-") ): value = api_key if api_key.startswith("Bearer ") else f"Bearer {api_key}" return {"authorization": value} @@ -630,11 +587,7 @@ def get_anthropic_headers( elif auth_token and not api_key: headers["authorization"] = f"Bearer {auth_token}" elif api_key: - headers.update( - self._make_api_key_auth_header( - api_key, api_base, use_bearer_for_custom_base - ) - ) + headers.update(self._make_api_key_auth_header(api_key, api_base, use_bearer_for_custom_base)) if user_anthropic_beta_headers is not None: betas.update(user_anthropic_beta_headers) @@ -645,9 +598,7 @@ def get_anthropic_headers( if web_search_tool_used: from litellm.types.llms.anthropic import ANTHROPIC_BETA_HEADER_VALUES - headers["anthropic-beta"] = ( - ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value - ) + headers["anthropic-beta"] = ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value elif len(betas) > 0: headers["anthropic-beta"] = ",".join(betas) @@ -666,13 +617,10 @@ def validate_environment( if api_base is None and isinstance(litellm_params, dict): api_base = litellm_params.get("api_base") use_bearer_for_custom_base: bool = bool( - isinstance(litellm_params, dict) - and litellm_params.get("use_bearer_for_custom_base", False) + isinstance(litellm_params, dict) and litellm_params.get("use_bearer_for_custom_base", False) ) # Check for Anthropic OAuth token in headers - headers, api_key = optionally_handle_anthropic_oauth( - headers=headers, api_key=api_key - ) + headers, api_key = optionally_handle_anthropic_oauth(headers=headers, api_key=api_key) api_key = AnthropicModelInfo.get_api_key(api_key) # Resolve auth_token from ANTHROPIC_AUTH_TOKEN if api_key is not set auth_token: Optional[str] = None @@ -688,22 +636,16 @@ def validate_environment( tools = optional_params.get("tools") prompt_caching_set = self.is_cache_control_set(messages=messages) computer_tool_used = self.is_computer_tool_used(tools=tools) - mcp_server_used = self.is_mcp_server_used( - mcp_servers=optional_params.get("mcp_servers") - ) + mcp_server_used = self.is_mcp_server_used(mcp_servers=optional_params.get("mcp_servers")) pdf_used = self.is_pdf_used(messages=messages) file_id_used = self.is_file_id_used(messages=messages) web_search_tool_used = self.is_web_search_tool_used(tools=tools) tool_search_used = self.is_tool_search_used(tools=tools) - programmatic_tool_calling_used = self.is_programmatic_tool_calling_used( - tools=tools - ) + programmatic_tool_calling_used = self.is_programmatic_tool_calling_used(tools=tools) input_examples_used = self.is_input_examples_used(tools=tools) effort_used = self.is_effort_used(optional_params=optional_params, model=model) code_execution_tool_used = self.is_code_execution_tool_used(tools=tools) - container_with_skills_used = self.is_container_with_skills_used( - optional_params=optional_params - ) + container_with_skills_used = self.is_container_with_skills_used(optional_params=optional_params) user_anthropic_beta_headers = self._get_user_anthropic_beta_headers( anthropic_beta_header=headers.get("anthropic-beta") ) @@ -776,9 +718,7 @@ def get_auth_header( if resolved_key is not None: if is_anthropic_oauth_key(resolved_key): return {"authorization": f"Bearer {resolved_key}"} - return AnthropicModelInfo._make_api_key_auth_header( - resolved_key, api_base, use_bearer_for_custom_base - ) + return AnthropicModelInfo._make_api_key_auth_header(resolved_key, api_base, use_bearer_for_custom_base) auth_token = AnthropicModelInfo.get_auth_token() if auth_token is not None: return {"authorization": f"Bearer {auth_token}"} @@ -788,9 +728,7 @@ def get_auth_header( def get_base_model(model: Optional[str] = None) -> Optional[str]: return model.replace("anthropic/", "") if model else None - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: api_base = AnthropicModelInfo.get_api_base(api_base) auth_header = AnthropicModelInfo.get_auth_header(api_key, api_base) if api_base is None or auth_header is None: @@ -834,9 +772,7 @@ def get_token_counter(self) -> Optional[BaseTokenCounter]: return AnthropicTokenCounter() -def strip_advisor_blocks_from_messages( - messages: List[Any], replace_with_text: bool = False -) -> List[Any]: +def strip_advisor_blocks_from_messages(messages: List[Any], replace_with_text: bool = False) -> List[Any]: """ Remove (or replace) server_tool_use (name='advisor') and advisor_tool_result blocks from assistant message content. @@ -862,11 +798,7 @@ def strip_advisor_blocks_from_messages( # Collect advisor server_tool_use ids and their advice text (for replace mode). advisor_id_to_text: dict = {} for block in content: - if ( - isinstance(block, dict) - and block.get("type") == "server_tool_use" - and block.get("name") == "advisor" - ): + if isinstance(block, dict) and block.get("type") == "server_tool_use" and block.get("name") == "advisor": bid = block.get("id") if bid: advisor_id_to_text[bid] = None # text filled in below @@ -887,11 +819,7 @@ def strip_advisor_blocks_from_messages( raw if isinstance(raw, str) else next( - ( - b.get("text", "") - for b in raw - if isinstance(b, dict) and b.get("type") == "text" - ), + (b.get("text", "") for b in raw if isinstance(b, dict) and b.get("type") == "text"), "", ) ) @@ -908,8 +836,7 @@ def strip_advisor_blocks_from_messages( and block.get("id") in advisor_id_to_text ) is_advisor_result = ( - block.get("type") == "advisor_tool_result" - and block.get("tool_use_id") in advisor_id_to_text + block.get("type") == "advisor_tool_result" and block.get("tool_use_id") in advisor_id_to_text ) if is_advisor_use: if replace_with_text: @@ -942,12 +869,7 @@ def is_anthropic_invalid_thinking_signature_error(error_text: str) -> bool: if not error_text: return False lower = error_text.lower() - return ( - "invalid" in lower - and "signature" in lower - and "thinking" in lower - and "block" in lower - ) + return "invalid" in lower and "signature" in lower and "thinking" in lower and "block" in lower def strip_thinking_blocks_from_anthropic_messages(messages: List[Any]) -> List[Any]: @@ -967,12 +889,7 @@ def strip_thinking_blocks_from_anthropic_messages(messages: List[Any]) -> List[A content = mm.get("content") if isinstance(content, list): filtered = [ - b - for b in content - if not ( - isinstance(b, dict) - and b.get("type") in ("thinking", "redacted_thinking") - ) + b for b in content if not (isinstance(b, dict) and b.get("type") in ("thinking", "redacted_thinking")) ] if not filtered: continue @@ -1045,11 +962,7 @@ def normalize_anthropic_tool_use_id(raw_id: str) -> str: Strips Gemini thought-signature suffixes (``__thought__``) first, then replaces any remaining invalid characters with underscores. """ - base_id = ( - raw_id.split(THOUGHT_SIGNATURE_SEPARATOR, 1)[0] - if THOUGHT_SIGNATURE_SEPARATOR in raw_id - else raw_id - ) + base_id = raw_id.split(THOUGHT_SIGNATURE_SEPARATOR, 1)[0] if THOUGHT_SIGNATURE_SEPARATOR in raw_id else raw_id sanitized = re.sub(r"[^a-zA-Z0-9_-]", "_", base_id) return sanitized or "tool_use_id" @@ -1101,25 +1014,15 @@ def sanitize_tool_use_ids_in_anthropic_messages(messages: list[Any]) -> list[Any def process_anthropic_headers(headers: Union[httpx.Headers, dict]) -> dict: openai_headers = {} if "anthropic-ratelimit-requests-limit" in headers: - openai_headers["x-ratelimit-limit-requests"] = headers[ - "anthropic-ratelimit-requests-limit" - ] + openai_headers["x-ratelimit-limit-requests"] = headers["anthropic-ratelimit-requests-limit"] if "anthropic-ratelimit-requests-remaining" in headers: - openai_headers["x-ratelimit-remaining-requests"] = headers[ - "anthropic-ratelimit-requests-remaining" - ] + openai_headers["x-ratelimit-remaining-requests"] = headers["anthropic-ratelimit-requests-remaining"] if "anthropic-ratelimit-tokens-limit" in headers: - openai_headers["x-ratelimit-limit-tokens"] = headers[ - "anthropic-ratelimit-tokens-limit" - ] + openai_headers["x-ratelimit-limit-tokens"] = headers["anthropic-ratelimit-tokens-limit"] if "anthropic-ratelimit-tokens-remaining" in headers: - openai_headers["x-ratelimit-remaining-tokens"] = headers[ - "anthropic-ratelimit-tokens-remaining" - ] + openai_headers["x-ratelimit-remaining-tokens"] = headers["anthropic-ratelimit-tokens-remaining"] - llm_response_headers = { - "{}-{}".format("llm_provider", k): v for k, v in headers.items() - } + llm_response_headers = {"{}-{}".format("llm_provider", k): v for k, v in headers.items()} additional_headers = {**llm_response_headers, **openai_headers} return additional_headers diff --git a/litellm/llms/anthropic/completion/transformation.py b/litellm/llms/anthropic/completion/transformation.py index a8798cd5d0ef..d06eac51101d 100644 --- a/litellm/llms/anthropic/completion/transformation.py +++ b/litellm/llms/anthropic/completion/transformation.py @@ -36,9 +36,7 @@ class AnthropicTextError(BaseLLMException): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.anthropic.com/v1/complete" - ) + self.request = httpx.Request(method="POST", url="https://api.anthropic.com/v1/complete") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( message=self.message, @@ -55,9 +53,7 @@ class AnthropicTextConfig(BaseConfig): to pass metadata to anthropic, it's {"user_id": "any-relevant-information"} """ - max_tokens_to_sample: Optional[int] = ( - litellm.max_tokens - ) # anthropic requires a default + max_tokens_to_sample: Optional[int] = litellm.max_tokens # anthropic requires a default stop_sequences: Optional[list] = None temperature: Optional[int] = None top_p: Optional[int] = None @@ -66,9 +62,7 @@ class AnthropicTextConfig(BaseConfig): def __init__( self, - max_tokens_to_sample: Optional[ - int - ] = DEFAULT_MAX_TOKENS, # anthropic requires a default + max_tokens_to_sample: Optional[int] = DEFAULT_MAX_TOKENS, # anthropic requires a default stop_sequences: Optional[list] = None, temperature: Optional[int] = None, top_p: Optional[int] = None, @@ -112,9 +106,7 @@ def transform_request( litellm_params: dict, headers: dict, ) -> dict: - prompt = self._get_anthropic_text_prompt_from_messages( - messages=messages, model=model - ) + prompt = self._get_anthropic_text_prompt_from_messages(messages=messages, model=model) ## Load Config config = litellm.AnthropicTextConfig.get_config() for k, v in config.items(): @@ -196,12 +188,8 @@ def transform_response( try: completion_response = raw_response.json() except Exception: - raise AnthropicTextError( - message=raw_response.text, status_code=raw_response.status_code - ) - prompt = self._get_anthropic_text_prompt_from_messages( - messages=messages, model=model - ) + raise AnthropicTextError(message=raw_response.text, status_code=raw_response.status_code) + prompt = self._get_anthropic_text_prompt_from_messages(messages=messages, model=model) if "error" in completion_response: raise AnthropicTextError( message=str(completion_response["error"]), @@ -215,9 +203,7 @@ def transform_response( model_response.choices[0].finish_reason = completion_response["stop_reason"] ## CALCULATING USAGE - prompt_tokens = len( - encoding.encode(prompt) - ) ##[TODO] use the anthropic tokenizer here + prompt_tokens = len(encoding.encode(prompt)) ##[TODO] use the anthropic tokenizer here completion_tokens = len( encoding.encode(model_response["choices"][0]["message"].get("content", "")) ) ##[TODO] use the anthropic tokenizer here @@ -245,9 +231,7 @@ def get_error_class( def _is_anthropic_text_model(model: str) -> bool: return model == "claude-2" or model == "claude-instant-1" - def _get_anthropic_text_prompt_from_messages( - self, messages: List[AllMessageValues], model: str - ) -> str: + def _get_anthropic_text_prompt_from_messages(self, messages: List[AllMessageValues], model: str) -> str: custom_prompt_dict = litellm.custom_prompt_dict if model in custom_prompt_dict: # check if the model has a registered custom prompt @@ -259,9 +243,7 @@ def _get_anthropic_text_prompt_from_messages( messages=messages, ) else: - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="anthropic" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="anthropic") return str(prompt) diff --git a/litellm/llms/anthropic/cost_calculation.py b/litellm/llms/anthropic/cost_calculation.py index 44081ea9e793..82a97b53d28c 100644 --- a/litellm/llms/anthropic/cost_calculation.py +++ b/litellm/llms/anthropic/cost_calculation.py @@ -5,6 +5,8 @@ from typing import TYPE_CHECKING, Optional, Tuple +from pydantic import BaseModel, ValidationError + from litellm.litellm_core_utils.llm_cost_calc.utils import ( _get_token_base_cost, _get_web_search_requests, @@ -18,9 +20,7 @@ import litellm -def _compute_cache_only_cost( - model_info: "ModelInfo", usage: "Usage", service_tier: str | None = None -) -> float: +def _compute_cache_only_cost(model_info: "ModelInfo", usage: "Usage", service_tier: str | None = None) -> float: """ Return only the cache-related portion of the prompt cost (cache read + cache write). @@ -38,9 +38,7 @@ def _compute_cache_only_cost( cache_creation_cost, cache_creation_cost_above_1hr, cache_read_cost, - ) = _get_token_base_cost( - model_info=model_info, usage=usage, service_tier=service_tier - ) + ) = _get_token_base_cost(model_info=model_info, usage=usage, service_tier=service_tier) cache_cost = float(prompt_tokens_details["cache_hit_tokens"]) * cache_read_cost @@ -50,9 +48,7 @@ def _compute_cache_only_cost( ): cache_cost += calculate_cache_writing_cost( cache_creation_tokens=prompt_tokens_details["cache_creation_tokens"], - cache_creation_token_details=prompt_tokens_details[ - "cache_creation_token_details" - ], + cache_creation_token_details=prompt_tokens_details["cache_creation_token_details"], cache_creation_cost_above_1hr=cache_creation_cost_above_1hr, cache_creation_cost=cache_creation_cost, ) @@ -60,9 +56,7 @@ def _compute_cache_only_cost( return cache_cost -def cost_per_token( - model: str, usage: "Usage", service_tier: str | None = None -) -> Tuple[float, float]: +def cost_per_token(model: str, usage: "Usage", service_tier: str | None = None) -> Tuple[float, float]: """ Calculates the cost per token for a given model, prompt tokens, and completion tokens. @@ -84,9 +78,7 @@ def cost_per_token( # Apply provider_specific_entry multipliers for geo/speed routing try: - model_info = litellm.get_model_info( - model=model, custom_llm_provider="anthropic" - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider="anthropic") provider_specific_entry: dict = model_info.get("provider_specific_entry") or {} multiplier = 1.0 @@ -100,9 +92,7 @@ def cost_per_token( multiplier *= provider_specific_entry.get("fast", 1.0) if multiplier != 1.0: - cache_cost = _compute_cache_only_cost( - model_info=model_info, usage=usage, service_tier=service_tier - ) + cache_cost = _compute_cache_only_cost(model_info=model_info, usage=usage, service_tier=service_tier) prompt_cost = (prompt_cost - cache_cost) * multiplier + cache_cost completion_cost *= multiplier except Exception: @@ -111,6 +101,34 @@ def cost_per_token( return prompt_cost, completion_cost +class _AnthropicServerToolUseProbe(BaseModel): + web_search_requests: int | None = None + + +class _AnthropicUsageProbe(BaseModel): + server_tool_use: _AnthropicServerToolUseProbe | None = None + + +class _AnthropicResponseProbe(BaseModel): + usage: _AnthropicUsageProbe | None = None + + +def get_anthropic_web_search_requests_from_response( + response_object: object, +) -> int | None: + """Read usage.server_tool_use.web_search_requests from a raw Anthropic + /v1/messages response dict, returning None when absent.""" + if not isinstance(response_object, dict): + return None + try: + probe = _AnthropicResponseProbe.model_validate(response_object) + except ValidationError: + return None + if probe.usage is None or probe.usage.server_tool_use is None: + return None + return probe.usage.server_tool_use.web_search_requests + + def get_cost_for_anthropic_web_search( model_info: Optional["ModelInfo"] = None, usage: Optional["Usage"] = None, @@ -126,9 +144,7 @@ def get_cost_for_anthropic_web_search( if usage is None: return 0.0 - web_search_requests = _get_web_search_requests( - getattr(usage, "server_tool_use", None) - ) + web_search_requests = _get_web_search_requests(getattr(usage, "server_tool_use", None)) if web_search_requests is None: return 0.0 @@ -136,9 +152,7 @@ def get_cost_for_anthropic_web_search( search_context_pricing: SearchContextCostPerQuery = ( model_info.get("search_context_cost_per_query") or SearchContextCostPerQuery() ) - cost_per_web_search_request = search_context_pricing.get( - "search_context_size_medium", 0.0 - ) + cost_per_web_search_request = search_context_pricing.get("search_context_size_medium", 0.0) if cost_per_web_search_request is None or cost_per_web_search_request == 0.0: return 0.0 diff --git a/litellm/llms/anthropic/count_tokens/handler.py b/litellm/llms/anthropic/count_tokens/handler.py index 4d0af0b36c85..e70e0f19b333 100644 --- a/litellm/llms/anthropic/count_tokens/handler.py +++ b/litellm/llms/anthropic/count_tokens/handler.py @@ -54,9 +54,7 @@ async def handle_count_tokens_request( # Validate the request self.validate_request(model, messages) - verbose_logger.debug( - f"Processing Anthropic CountTokens request for model: {model}" - ) + verbose_logger.debug(f"Processing Anthropic CountTokens request for model: {model}") # Transform request to Anthropic format request_body = self.transform_request_to_count_tokens( @@ -77,14 +75,10 @@ async def handle_count_tokens_request( headers = self.get_required_headers(api_key) # Use LiteLLM's async httpx client - async_client = get_async_httpx_client( - llm_provider=litellm.LlmProviders.ANTHROPIC - ) + async_client = get_async_httpx_client(llm_provider=litellm.LlmProviders.ANTHROPIC) # Use provided timeout or fall back to litellm.request_timeout - request_timeout = ( - timeout if timeout is not None else litellm.request_timeout - ) + request_timeout = timeout if timeout is not None else litellm.request_timeout response = await async_client.post( endpoint_url, diff --git a/litellm/llms/anthropic/count_tokens/token_counter.py b/litellm/llms/anthropic/count_tokens/token_counter.py index 93989c585470..89249ec42f07 100644 --- a/litellm/llms/anthropic/count_tokens/token_counter.py +++ b/litellm/llms/anthropic/count_tokens/token_counter.py @@ -81,9 +81,7 @@ async def count_tokens( original_response=result, ) except AnthropicError as e: - verbose_logger.warning( - f"Anthropic CountTokens API error: status={e.status_code}, message={e.message}" - ) + verbose_logger.warning(f"Anthropic CountTokens API error: status={e.status_code}, message={e.message}") return TokenCountResponse( total_tokens=0, request_model=request_model, diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py index efb913f709a0..812e0f62c96d 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py @@ -107,9 +107,7 @@ async def _prepare_context_managed_request( messages=cast(List[Dict[str, Any]], messages), system=system, ) - working_messages = ( - history_result.messages if history_result is not None else messages - ) + working_messages = history_result.messages if history_result is not None else messages working_system = history_result.system if history_result is not None else system polyfill_result = await _run_polyfill_if_enabled( @@ -165,10 +163,7 @@ def _polyfill_will_run( COMPACT_EDIT_TYPE, ) - return any( - isinstance(edit, dict) and edit.get("type") == COMPACT_EDIT_TYPE - for edit in edits - ) + return any(isinstance(edit, dict) and edit.get("type") == COMPACT_EDIT_TYPE for edit in edits) def _spec_has_non_compact_edits( @@ -195,9 +190,7 @@ def _spec_has_non_compact_edits( ) return any( - isinstance(edit, dict) - and isinstance(edit.get("type"), str) - and edit.get("type") != COMPACT_EDIT_TYPE + isinstance(edit, dict) and isinstance(edit.get("type"), str) and edit.get("type") != COMPACT_EDIT_TYPE for edit in edits ) @@ -215,9 +208,7 @@ def _normalize_spec_edits( if not context_management_spec: return None - effective_drop_params = ( - drop_params if drop_params is not None else litellm.drop_params - ) + effective_drop_params = drop_params if drop_params is not None else litellm.drop_params if effective_drop_params: return None @@ -253,9 +244,7 @@ async def _run_polyfill_if_enabled( if not context_management_spec: return None - effective_drop_params = ( - drop_params if drop_params is not None else litellm.drop_params - ) + effective_drop_params = drop_params if drop_params is not None else litellm.drop_params if effective_drop_params: return None @@ -275,9 +264,7 @@ async def _run_polyfill_if_enabled( # 400. Other exception types fall into the best-effort branch below. raise except Exception as e: - verbose_logger.exception( - "context_management polyfill: skipping edits due to error: %s", e - ) + verbose_logger.exception("context_management polyfill: skipping edits due to error: %s", e) # Best-effort swallow is only safe for compact-only specs, where the # caller's compaction-block-slicing safety net produces a correct # (if degraded) result. When the spec also requested non-compact @@ -338,9 +325,7 @@ def _route_openai_thinking_to_responses_api_if_needed( model = completion_kwargs.get("model") try: - model_info = get_model_info( - model=cast(str, model), custom_llm_provider=custom_llm_provider - ) + model_info = get_model_info(model=cast(str, model), custom_llm_provider=custom_llm_provider) if model_info and model_info.get("supports_reasoning") is False: # Model doesn't support reasoning/responses API, don't route return @@ -363,13 +348,8 @@ def _route_openai_thinking_to_responses_api_if_needed( reasoning_dict["summary"] = "detailed" completion_kwargs["reasoning_effort"] = reasoning_dict elif isinstance(reasoning_effort, dict): - if ( - "summary" not in reasoning_effort - and "generate_summary" not in reasoning_effort - ): - effective_summary = ( - summary if summary else ("detailed" if auto_summary else None) - ) + if "summary" not in reasoning_effort and "generate_summary" not in reasoning_effort: + effective_summary = summary if summary else ("detailed" if auto_summary else None) if effective_summary: updated_reasoning_effort = dict(reasoning_effort) updated_reasoning_effort["summary"] = effective_summary @@ -404,9 +384,7 @@ def _normalize_reasoning_effort( completion_kwargs["reasoning_effort"] = normalized elif isinstance(reasoning_effort, dict) and "effort" in reasoning_effort: effort = reasoning_effort["effort"] - normalized = normalize_reasoning_effort_value( - effort, model=model, custom_llm_provider=custom_llm_provider - ) + normalized = normalize_reasoning_effort_value(effort, model=model, custom_llm_provider=custom_llm_provider) if normalized != effort: completion_kwargs["reasoning_effort"] = { **reasoning_effort, @@ -483,9 +461,7 @@ def _prepare_completion_kwargs( ( openai_request, tool_name_mapping, - ) = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping( - request_data - ) + ) = ANTHROPIC_ADAPTER.translate_completion_input_params_with_tool_mapping(request_data) if openai_request is None: raise ValueError("Failed to translate request to OpenAI format") @@ -516,31 +492,19 @@ def _prepare_completion_kwargs( # NOTE: extra_kwargs was already coerced from None to {} at the top of # this method (line ~220). It is guaranteed to be a dict here. for key, value in extra_kwargs.items(): - if ( - key == "litellm_logging_obj" - and value is not None - and isinstance(value, LiteLLMLoggingObject) - ): + if key == "litellm_logging_obj" and value is not None and isinstance(value, LiteLLMLoggingObject): from litellm.types.utils import CallTypes setattr(value, "call_type", CallTypes.anthropic_messages.value) - setattr( - value, "stream_options", completion_kwargs.get("stream_options") - ) - if ( - key not in excluded_keys - and key not in completion_kwargs - and value is not None - ): + setattr(value, "stream_options", completion_kwargs.get("stream_options")) + if key not in excluded_keys and key not in completion_kwargs and value is not None: completion_kwargs[key] = value # Normalize reasoning_effort based on model capabilities # (e.g. "max" → "xhigh"/"high", "minimal" → "low" if unsupported) # Must run BEFORE _route_openai_thinking, which prepends "responses/" # to the model name and would break get_model_info() lookups. - LiteLLMMessagesToCompletionTransformationHandler._normalize_reasoning_effort( - completion_kwargs - ) + LiteLLMMessagesToCompletionTransformationHandler._normalize_reasoning_effort(completion_kwargs) LiteLLMMessagesToCompletionTransformationHandler._route_openai_thinking_to_responses_api_if_needed( completion_kwargs, @@ -581,9 +545,7 @@ async def async_anthropic_messages_handler( proxy_litellm_metadata = _extract_proxy_litellm_metadata(kwargs) user_api_key_auth = ( - proxy_litellm_metadata.get("user_api_key_auth") - if proxy_litellm_metadata is not None - else None + proxy_litellm_metadata.get("user_api_key_auth") if proxy_litellm_metadata is not None else None ) polyfill_result = await _prepare_context_managed_request( @@ -598,12 +560,8 @@ async def async_anthropic_messages_handler( user_api_key_auth=user_api_key_auth, ) - effective_messages = ( - polyfill_result.messages if polyfill_result is not None else messages - ) - effective_system = ( - polyfill_result.system if polyfill_result is not None else system - ) + effective_messages = polyfill_result.messages if polyfill_result is not None else messages + effective_system = polyfill_result.system if polyfill_result is not None else system ( completion_kwargs, @@ -629,14 +587,12 @@ async def async_anthropic_messages_handler( completion_response = await litellm.acompletion(**completion_kwargs) if stream: - transformed_stream = ( - ANTHROPIC_ADAPTER.translate_completion_output_params_streaming( - completion_response, - model=model, - tool_name_mapping=tool_name_mapping, - polyfill_result=polyfill_result, - is_async=True, - ) + transformed_stream = ANTHROPIC_ADAPTER.translate_completion_output_params_streaming( + completion_response, + model=model, + tool_name_mapping=tool_name_mapping, + polyfill_result=polyfill_result, + is_async=True, ) if transformed_stream is not None: return transformed_stream @@ -730,9 +686,7 @@ def anthropic_messages_handler( else: proxy_litellm_metadata = _extract_proxy_litellm_metadata(kwargs) user_api_key_auth = ( - proxy_litellm_metadata.get("user_api_key_auth") - if proxy_litellm_metadata is not None - else None + proxy_litellm_metadata.get("user_api_key_auth") if proxy_litellm_metadata is not None else None ) polyfill_result = run_async_function( _prepare_context_managed_request, @@ -747,12 +701,8 @@ def anthropic_messages_handler( user_api_key_auth=user_api_key_auth, ) - effective_messages = ( - polyfill_result.messages if polyfill_result is not None else messages - ) - effective_system = ( - polyfill_result.system if polyfill_result is not None else system - ) + effective_messages = polyfill_result.messages if polyfill_result is not None else messages + effective_system = polyfill_result.system if polyfill_result is not None else system ( completion_kwargs, @@ -778,14 +728,12 @@ def anthropic_messages_handler( completion_response = litellm.completion(**completion_kwargs) if stream: - transformed_stream = ( - ANTHROPIC_ADAPTER.translate_completion_output_params_streaming( - completion_response, - model=model, - tool_name_mapping=tool_name_mapping, - polyfill_result=polyfill_result, - is_async=False, - ) + transformed_stream = ANTHROPIC_ADAPTER.translate_completion_output_params_streaming( + completion_response, + model=model, + tool_name_mapping=tool_name_mapping, + polyfill_result=polyfill_result, + is_async=False, ) if transformed_stream is not None: return transformed_stream diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py index a92834b5d717..44c367ee8059 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py @@ -212,14 +212,10 @@ def _merge_usage_into_held_stop_reason_chunk(self, chunk: Any) -> Dict[str, Any] ) merged_chunk["usage"] = usage_dict if self.applied_edits and "context_management" not in merged_chunk: - merged_chunk["context_management"] = ContextManagementResponse( - applied_edits=list(self.applied_edits) - ) + merged_chunk["context_management"] = ContextManagementResponse(applied_edits=list(self.applied_edits)) return self._augment_message_delta_usage(merged_chunk) - def _ensure_context_management_attached( - self, message_delta_chunk: Dict[str, Any] - ) -> Dict[str, Any]: + def _ensure_context_management_attached(self, message_delta_chunk: Dict[str, Any]) -> Dict[str, Any]: """Attach ``context_management`` to a ``message_delta`` chunk if ``self.applied_edits`` is non-empty and the chunk does not already carry it. Returns the (possibly new) chunk dict. @@ -231,23 +227,17 @@ def _ensure_context_management_attached( if not self.applied_edits or "context_management" in message_delta_chunk: return message_delta_chunk augmented = message_delta_chunk.copy() - augmented["context_management"] = ContextManagementResponse( - applied_edits=list(self.applied_edits) - ) + augmented["context_management"] = ContextManagementResponse(applied_edits=list(self.applied_edits)) return augmented - def _augment_message_delta_usage( - self, message_delta_chunk: Dict[str, Any] - ) -> Dict[str, Any]: + def _augment_message_delta_usage(self, message_delta_chunk: Dict[str, Any]) -> Dict[str, Any]: """Attach polyfill compaction iteration usage to the final message_delta. Also defensively re-attaches ``context_management`` so the direct held-chunk flush path stays in sync with the merge path's guarantee when ``self.applied_edits`` is non-empty. """ - message_delta_chunk = self._ensure_context_management_attached( - message_delta_chunk - ) + message_delta_chunk = self._ensure_context_management_attached(message_delta_chunk) if self.iterations_usage is None: return message_delta_chunk usage = message_delta_chunk.get("usage") @@ -377,10 +367,7 @@ def __next__(self): ) return self.chunk_queue.popleft() - if ( - self.sent_compaction_block is False - and self.compaction_block is not None - ): + if self.sent_compaction_block is False and self.compaction_block is not None: compaction_event = self._next_compaction_event() if compaction_event is not None: return compaction_event @@ -413,18 +400,13 @@ def __next__(self): # skip the applied_edits attachment in that case to avoid # allocating a throwaway ``MessageBlockDelta``. will_merge_into_held = ( - self.holding_stop_reason_chunk is not None - and getattr(chunk, "usage", None) is not None + self.holding_stop_reason_chunk is not None and getattr(chunk, "usage", None) is not None ) is_final_chunk = chunk.choices[0].finish_reason is not None processed_chunk = LiteLLMAnthropicMessagesAdapter().translate_streaming_openai_response_to_anthropic( response=chunk, current_content_block_index=self.current_content_block_index, - applied_edits=( - self.applied_edits - if is_final_chunk and not will_merge_into_held - else None - ), + applied_edits=(self.applied_edits if is_final_chunk and not will_merge_into_held else None), ) # Check if this is a usage chunk and we have a held stop_reason chunk @@ -482,10 +464,7 @@ def __next__(self): self.sent_content_block_finish = False return self.chunk_queue.popleft() - if ( - processed_chunk["type"] == "message_delta" - and self.sent_content_block_finish is False - ): + if processed_chunk["type"] == "message_delta" and self.sent_content_block_finish is False: # Queue both the content_block_stop and the message_delta self.chunk_queue.append( { @@ -497,25 +476,19 @@ def __next__(self): if processed_chunk.get("delta", {}).get("stop_reason") is not None: self.holding_stop_reason_chunk = processed_chunk else: - processed_chunk = self._augment_message_delta_usage( - processed_chunk - ) + processed_chunk = self._augment_message_delta_usage(processed_chunk) self.chunk_queue.append(processed_chunk) return self.chunk_queue.popleft() elif self.holding_chunk is not None: self.chunk_queue.append(self.holding_chunk) if processed_chunk.get("type") == "message_delta": - processed_chunk = self._augment_message_delta_usage( - processed_chunk - ) + processed_chunk = self._augment_message_delta_usage(processed_chunk) self.chunk_queue.append(processed_chunk) self.holding_chunk = None return self.chunk_queue.popleft() else: if processed_chunk.get("type") == "message_delta": - processed_chunk = self._augment_message_delta_usage( - processed_chunk - ) + processed_chunk = self._augment_message_delta_usage(processed_chunk) self.chunk_queue.append(processed_chunk) return self.chunk_queue.popleft() @@ -545,11 +518,7 @@ def __next__(self): } ) self.sent_content_block_finish = True - self.chunk_queue.append( - self._augment_message_delta_usage( - self.holding_stop_reason_chunk - ) - ) + self.chunk_queue.append(self._augment_message_delta_usage(self.holding_stop_reason_chunk)) self.holding_stop_reason_chunk = None else: self.holding_chunk = None @@ -572,11 +541,7 @@ def __next__(self): if self.holding_stop_reason_chunk is not None: if not self.sent_content_block_finish: self.sent_content_block_finish = True - self.chunk_queue.append( - self._augment_message_delta_usage( - self.holding_stop_reason_chunk - ) - ) + self.chunk_queue.append(self._augment_message_delta_usage(self.holding_stop_reason_chunk)) self.holding_stop_reason_chunk = None return { "type": "content_block_stop", @@ -590,9 +555,7 @@ def __next__(self): return {"type": "message_stop"} raise StopIteration except Exception as e: - verbose_logger.error( - "Anthropic Adapter - {}\n{}".format(e, traceback.format_exc()) - ) + verbose_logger.error("Anthropic Adapter - {}\n{}".format(e, traceback.format_exc())) raise StopIteration async def __anext__(self): @@ -623,10 +586,7 @@ async def __anext__(self): ) return self.chunk_queue.popleft() - if ( - self.sent_compaction_block is False - and self.compaction_block is not None - ): + if self.sent_compaction_block is False and self.compaction_block is not None: compaction_event = self._next_compaction_event() if compaction_event is not None: return compaction_event @@ -660,18 +620,13 @@ async def __anext__(self): # skip the applied_edits attachment in that case to avoid # allocating a throwaway ``MessageBlockDelta``. will_merge_into_held = ( - self.holding_stop_reason_chunk is not None - and getattr(chunk, "usage", None) is not None + self.holding_stop_reason_chunk is not None and getattr(chunk, "usage", None) is not None ) is_final_chunk = chunk.choices[0].finish_reason is not None processed_chunk = LiteLLMAnthropicMessagesAdapter().translate_streaming_openai_response_to_anthropic( response=chunk, current_content_block_index=self.current_content_block_index, - applied_edits=( - self.applied_edits - if is_final_chunk and not will_merge_into_held - else None - ), + applied_edits=(self.applied_edits if is_final_chunk and not will_merge_into_held else None), ) # Check if this is a usage chunk and we have a held stop_reason chunk @@ -722,10 +677,7 @@ async def __anext__(self): self.sent_content_block_finish = False return self.chunk_queue.popleft() - if ( - processed_chunk["type"] == "message_delta" - and self.sent_content_block_finish is False - ): + if processed_chunk["type"] == "message_delta" and self.sent_content_block_finish is False: # Queue both the content_block_stop and the holding chunk self.chunk_queue.append( { @@ -734,32 +686,23 @@ async def __anext__(self): } ) self.sent_content_block_finish = True - if ( - processed_chunk.get("delta", {}).get("stop_reason") - is not None - ): + if processed_chunk.get("delta", {}).get("stop_reason") is not None: self.holding_stop_reason_chunk = processed_chunk else: - processed_chunk = self._augment_message_delta_usage( - processed_chunk - ) + processed_chunk = self._augment_message_delta_usage(processed_chunk) self.chunk_queue.append(processed_chunk) return self.chunk_queue.popleft() elif self.holding_chunk is not None: # Queue both chunks self.chunk_queue.append(self.holding_chunk) if processed_chunk.get("type") == "message_delta": - processed_chunk = self._augment_message_delta_usage( - processed_chunk - ) + processed_chunk = self._augment_message_delta_usage(processed_chunk) self.chunk_queue.append(processed_chunk) self.holding_chunk = None return self.chunk_queue.popleft() else: if processed_chunk.get("type") == "message_delta": - processed_chunk = self._augment_message_delta_usage( - processed_chunk - ) + processed_chunk = self._augment_message_delta_usage(processed_chunk) self.chunk_queue.append(processed_chunk) return self.chunk_queue.popleft() @@ -789,11 +732,7 @@ async def __anext__(self): } ) self.sent_content_block_finish = True - self.chunk_queue.append( - self._augment_message_delta_usage( - self.holding_stop_reason_chunk - ) - ) + self.chunk_queue.append(self._augment_message_delta_usage(self.holding_stop_reason_chunk)) self.holding_stop_reason_chunk = None else: self.holding_chunk = None @@ -821,11 +760,7 @@ async def __anext__(self): if self.holding_stop_reason_chunk is not None: if not self.sent_content_block_finish: self.sent_content_block_finish = True - self.chunk_queue.append( - self._augment_message_delta_usage( - self.holding_stop_reason_chunk - ) - ) + self.chunk_queue.append(self._augment_message_delta_usage(self.holding_stop_reason_chunk)) self.holding_stop_reason_chunk = None return { "type": "content_block_stop", @@ -939,9 +874,7 @@ def _should_start_new_content_block(self, chunk: "ModelResponseStream") -> bool: if tool_block.get("name"): truncated_name = tool_block["name"] - original_name = self.tool_name_mapping.get( - truncated_name, truncated_name - ) + original_name = self.tool_name_mapping.get(truncated_name, truncated_name) tool_block["name"] = original_name if block_type != self.current_content_block_type: diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py index 1fd593f63c80..02625605f372 100644 --- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py @@ -76,6 +76,9 @@ def create_tool_name_mapping( from litellm.litellm_core_utils.prompt_templates.factory import ( THOUGHT_SIGNATURE_SEPARATOR, ) +from litellm.litellm_core_utils.reasoning_effort_utils import ( + reasoning_effort_from_thinking_budget, +) from litellm.llms.anthropic.common_utils import normalize_anthropic_tool_use_id from litellm.llms.anthropic.experimental_pass_through.context_management import ( PolyfillResult, @@ -140,9 +143,7 @@ class AnthropicAdapter: def __init__(self) -> None: pass - def translate_completion_input_params( - self, kwargs - ) -> Optional[ChatCompletionRequest]: + def translate_completion_input_params(self, kwargs) -> Optional[ChatCompletionRequest]: """ Translate Anthropic request params to OpenAI format. @@ -175,27 +176,19 @@ def translate_completion_input_params_with_tool_mapping( model = kwargs.pop("model") messages = kwargs.pop("messages") if not model: - raise ValueError( - "Bad Request: model is required for Anthropic Messages Request" - ) + raise ValueError("Bad Request: model is required for Anthropic Messages Request") if not messages: - raise ValueError( - "Bad Request: messages is required for Anthropic Messages Request" - ) + raise ValueError("Bad Request: messages is required for Anthropic Messages Request") ######################################################### # Created Typed Request Body ######################################################### - request_body = AnthropicMessagesRequest( - model=model, messages=messages, **kwargs - ) + request_body = AnthropicMessagesRequest(model=model, messages=messages, **kwargs) ( translated_body, tool_name_mapping, - ) = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai( - anthropic_message_request=request_body - ) + ) = LiteLLMAnthropicMessagesAdapter().translate_anthropic_to_openai(anthropic_message_request=request_body) return translated_body, tool_name_mapping @@ -244,15 +237,9 @@ def translate_completion_output_params_streaming( the sync handler) don't get back an async iterator they can't iterate without an event loop. """ - applied_edits = ( - polyfill_result.applied_edits_for_response() if polyfill_result else None - ) - compaction_block = ( - polyfill_result.compaction_block if polyfill_result is not None else None - ) - iterations_usage = ( - polyfill_result.iterations_usage if polyfill_result is not None else None - ) + applied_edits = polyfill_result.applied_edits_for_response() if polyfill_result else None + compaction_block = polyfill_result.compaction_block if polyfill_result is not None else None + iterations_usage = polyfill_result.iterations_usage if polyfill_result is not None else None anthropic_wrapper = AnthropicStreamWrapper( completion_stream=completion_stream, model=model, @@ -280,26 +267,16 @@ def _extract_signature_from_tool_call(self, tool_call: Any) -> Optional[str]: """ signature = None - if ( - hasattr(tool_call, "provider_specific_fields") - and tool_call.provider_specific_fields - ): + if hasattr(tool_call, "provider_specific_fields") and tool_call.provider_specific_fields: if "thought_signature" in tool_call.provider_specific_fields: signature = tool_call.provider_specific_fields["thought_signature"] - elif ( - hasattr(tool_call.function, "provider_specific_fields") - and tool_call.function.provider_specific_fields - ): + elif hasattr(tool_call.function, "provider_specific_fields") and tool_call.function.provider_specific_fields: if "thought_signature" in tool_call.function.provider_specific_fields: - signature = tool_call.function.provider_specific_fields[ - "thought_signature" - ] + signature = tool_call.function.provider_specific_fields["thought_signature"] return signature - def _extract_signature_from_tool_use_content( - self, content: Dict[str, Any] - ) -> Optional[str]: + def _extract_signature_from_tool_use_content(self, content: Dict[str, Any]) -> Optional[str]: """ Extract signature from a tool_use content block's provider_specific_fields. """ @@ -329,18 +306,9 @@ def _add_cache_control_if_applicable( """ # TypedDict objects are dicts at runtime, so .get() works cache_control = ( - source.get("cache_control") - if isinstance(source, dict) - else getattr(source, "cache_control", None) + source.get("cache_control") if isinstance(source, dict) else getattr(source, "cache_control", None) ) - if ( - cache_control - and model - and ( - self.is_anthropic_claude_model(model) - or self.is_bedrock_arn_model(model) - ) - ): + if cache_control and model and (self.is_anthropic_claude_model(model) or self.is_bedrock_arn_model(model)): # TypedDict objects support dict operations at runtime # Use type ignore consistent with codebase pattern (see anthropic/chat/transformation.py:432) if isinstance(target, dict): @@ -380,9 +348,7 @@ def _is_web_search_tool(self, tool: Dict[str, Any]) -> bool: """ tool_type = tool.get("type", "") tool_name = tool.get("name", "") - return ( - isinstance(tool_type, str) and tool_type.startswith("web_search") - ) or tool_name == "web_search" + return (isinstance(tool_type, str) and tool_type.startswith("web_search")) or tool_name == "web_search" def translate_anthropic_messages_to_openai( self, @@ -398,66 +364,38 @@ def translate_anthropic_messages_to_openai( for m in messages: user_message: Optional[ChatCompletionUserMessage] = None tool_message_list: List[ChatCompletionToolMessage] = [] - new_user_content_list: List[ - Union[ChatCompletionTextObject, ChatCompletionImageObject] - ] = [] + new_user_content_list: List[Union[ChatCompletionTextObject, ChatCompletionImageObject]] = [] ## USER MESSAGE ## if m["role"] == "user": ## translate user message message_content = m.get("content") if message_content and isinstance(message_content, str): - user_message = ChatCompletionUserMessage( - role="user", content=message_content - ) + user_message = ChatCompletionUserMessage(role="user", content=message_content) elif message_content and isinstance(message_content, list): for content in message_content: if content.get("type") == "text": - text_obj = ChatCompletionTextObject( - type="text", text=content.get("text", "") - ) - self._add_cache_control_if_applicable( - content, text_obj, model - ) + text_obj = ChatCompletionTextObject(type="text", text=content.get("text", "")) + self._add_cache_control_if_applicable(content, text_obj, model) new_user_content_list.append(text_obj) # type: ignore elif content.get("type") == "image": # Convert Anthropic image format to OpenAI format source = content.get("source", {}) - openai_image_url = ( - self._translate_anthropic_image_to_openai( - cast(dict, source) - ) - ) + openai_image_url = self._translate_anthropic_image_to_openai(cast(dict, source)) if openai_image_url: - image_url_obj = ChatCompletionImageUrlObject( - url=openai_image_url - ) - image_obj = ChatCompletionImageObject( - type="image_url", image_url=image_url_obj - ) - self._add_cache_control_if_applicable( - content, image_obj, model - ) + image_url_obj = ChatCompletionImageUrlObject(url=openai_image_url) + image_obj = ChatCompletionImageObject(type="image_url", image_url=image_url_obj) + self._add_cache_control_if_applicable(content, image_obj, model) new_user_content_list.append(image_obj) # type: ignore elif content.get("type") == "document": # Convert Anthropic document format (PDF, etc.) to OpenAI format source = content.get("source", {}) - openai_image_url = ( - self._translate_anthropic_image_to_openai( - cast(dict, source) - ) - ) + openai_image_url = self._translate_anthropic_image_to_openai(cast(dict, source)) if openai_image_url: - image_url_obj = ChatCompletionImageUrlObject( - url=openai_image_url - ) - doc_obj = ChatCompletionImageObject( - type="image_url", image_url=image_url_obj - ) - self._add_cache_control_if_applicable( - content, doc_obj, model - ) + image_url_obj = ChatCompletionImageUrlObject(url=openai_image_url) + doc_obj = ChatCompletionImageObject(type="image_url", image_url=image_url_obj) + self._add_cache_control_if_applicable(content, doc_obj, model) new_user_content_list.append(doc_obj) # type: ignore elif content.get("type") == "tool_result": if "content" not in content: @@ -466,9 +404,7 @@ def translate_anthropic_messages_to_openai( tool_call_id=content.get("tool_use_id", ""), content="", ) - self._add_cache_control_if_applicable( - content, tool_result, model - ) + self._add_cache_control_if_applicable(content, tool_result, model) tool_message_list.append(tool_result) # type: ignore[arg-type] elif isinstance(content.get("content"), str): tool_result = ChatCompletionToolMessage( @@ -476,9 +412,7 @@ def translate_anthropic_messages_to_openai( tool_call_id=content.get("tool_use_id", ""), content=str(content.get("content", "")), ) - self._add_cache_control_if_applicable( - content, tool_result, model - ) + self._add_cache_control_if_applicable(content, tool_result, model) tool_message_list.append(tool_result) # type: ignore[arg-type] elif isinstance(content.get("content"), list): # Combine all content items into a single tool message @@ -495,41 +429,28 @@ def translate_anthropic_messages_to_openai( tool_call_id=content.get("tool_use_id", ""), content=c, ) - self._add_cache_control_if_applicable( - content, tool_result, model - ) + self._add_cache_control_if_applicable(content, tool_result, model) tool_message_list.append(tool_result) # type: ignore[arg-type] elif isinstance(c, dict): if c.get("type") == "text": tool_result = ChatCompletionToolMessage( role="tool", - tool_call_id=content.get( - "tool_use_id", "" - ), + tool_call_id=content.get("tool_use_id", ""), content=c.get("text", ""), ) - self._add_cache_control_if_applicable( - content, tool_result, model - ) + self._add_cache_control_if_applicable(content, tool_result, model) tool_message_list.append(tool_result) # type: ignore[arg-type] elif c.get("type") == "image": source = c.get("source", {}) openai_image_url = ( - self._translate_anthropic_image_to_openai( - cast(dict, source) - ) - or "" + self._translate_anthropic_image_to_openai(cast(dict, source)) or "" ) tool_result = ChatCompletionToolMessage( role="tool", - tool_call_id=content.get( - "tool_use_id", "" - ), + tool_call_id=content.get("tool_use_id", ""), content=openai_image_url, ) - self._add_cache_control_if_applicable( - content, tool_result, model - ) + self._add_cache_control_if_applicable(content, tool_result, model) tool_message_list.append(tool_result) # type: ignore[arg-type] else: # For multiple content items, combine into a single tool message @@ -542,11 +463,7 @@ def translate_anthropic_messages_to_openai( ] = [] for c in content_items: if isinstance(c, str): - combined_content_parts.append( - ChatCompletionTextObject( - type="text", text=c - ) - ) + combined_content_parts.append(ChatCompletionTextObject(type="text", text=c)) elif isinstance(c, dict): if c.get("type") == "text": combined_content_parts.append( @@ -558,10 +475,7 @@ def translate_anthropic_messages_to_openai( elif c.get("type") == "image": source = c.get("source", {}) openai_image_url = ( - self._translate_anthropic_image_to_openai( - cast(dict, source) - ) - or "" + self._translate_anthropic_image_to_openai(cast(dict, source)) or "" ) if openai_image_url: combined_content_parts.append( @@ -579,9 +493,7 @@ def translate_anthropic_messages_to_openai( tool_call_id=content.get("tool_use_id", ""), content=combined_content_parts, # type: ignore ) - self._add_cache_control_if_applicable( - content, tool_result, model - ) + self._add_cache_control_if_applicable(content, tool_result, model) tool_message_list.append(tool_result) # type: ignore[arg-type] if len(tool_message_list) > 0: @@ -595,14 +507,10 @@ def translate_anthropic_messages_to_openai( ## ASSISTANT MESSAGE ## assistant_message_str: Optional[str] = None - assistant_content_list: List[ - Dict[str, Any] - ] = [] # For content blocks with cache_control + assistant_content_list: List[Dict[str, Any]] = [] # For content blocks with cache_control has_cache_control_in_text = False tool_calls: List[ChatCompletionAssistantToolCall] = [] - thinking_blocks: List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] = [] + thinking_blocks: List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] = [] if m["role"] == "assistant": if isinstance(m.get("content"), str): assistant_message_str = str(m.get("content", "")) @@ -616,9 +524,7 @@ def translate_anthropic_messages_to_openai( "type": "text", "text": content.get("text", ""), } - self._add_cache_control_if_applicable( - content, text_block, model - ) + self._add_cache_control_if_applicable(content, text_block, model) if "cache_control" in text_block: has_cache_control_in_text = True assistant_content_list.append(text_block) @@ -629,32 +535,21 @@ def translate_anthropic_messages_to_openai( "name": tool_name, "arguments": json.dumps(content.get("input", {})), } - signature = ( - self._extract_signature_from_tool_use_content( - cast(Dict[str, Any], content) - ) - ) + signature = self._extract_signature_from_tool_use_content(cast(Dict[str, Any], content)) if signature: provider_specific_fields: Dict[str, Any] = ( - function_chunk.get("provider_specific_fields") - or {} - ) - provider_specific_fields["thought_signature"] = ( - signature - ) - function_chunk["provider_specific_fields"] = ( - provider_specific_fields + function_chunk.get("provider_specific_fields") or {} ) + provider_specific_fields["thought_signature"] = signature + function_chunk["provider_specific_fields"] = provider_specific_fields tool_call = ChatCompletionAssistantToolCall( id=content.get("id", ""), type="function", function=function_chunk, ) - self._add_cache_control_if_applicable( - content, tool_call, model - ) + self._add_cache_control_if_applicable(content, tool_call, model) tool_calls.append(tool_call) elif content.get("type") == "thinking": thinking_block = ChatCompletionThinkingBlock( @@ -665,12 +560,10 @@ def translate_anthropic_messages_to_openai( ) thinking_blocks.append(thinking_block) elif content.get("type") == "redacted_thinking": - redacted_thinking_block = ( - ChatCompletionRedactedThinkingBlock( - type="redacted_thinking", - data=content.get("data") or "", - cache_control=content.get("cache_control", {}), - ) + redacted_thinking_block = ChatCompletionRedactedThinkingBlock( + type="redacted_thinking", + data=content.get("data") or "", + cache_control=content.get("cache_control", {}), ) thinking_blocks.append(redacted_thinking_block) @@ -685,18 +578,14 @@ def translate_anthropic_messages_to_openai( assistant_content: Any = assistant_content_list elif len(assistant_content_list) > 0 and not has_cache_control_in_text: # Concatenate text blocks into string when no cache_control - assistant_content = "".join( - block.get("text", "") for block in assistant_content_list - ) + assistant_content = "".join(block.get("text", "") for block in assistant_content_list) else: assistant_content = assistant_message_str assistant_message = ChatCompletionAssistantMessage( role="assistant", content=assistant_content, - thinking_blocks=( - thinking_blocks if len(thinking_blocks) > 0 else None - ), + thinking_blocks=(thinking_blocks if len(thinking_blocks) > 0 else None), ) if len(tool_calls) > 0: assistant_message["tool_calls"] = tool_calls # type: ignore @@ -716,11 +605,8 @@ def translate_anthropic_thinking_to_reasoning_effort( Anthropic thinking format: {'type': 'enabled'|'disabled', 'budget_tokens': int} OpenAI reasoning_effort: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'default' - Mapping: - - budget_tokens >= 10000 -> 'high' - - budget_tokens >= 5000 -> 'medium' - - budget_tokens >= 2000 -> 'low' - - budget_tokens < 2000 -> 'minimal' + ``budget_tokens`` is bucketed via the shared + ``reasoning_effort_from_thinking_budget`` thresholds. """ if not isinstance(thinking, dict): return None @@ -730,15 +616,7 @@ def translate_anthropic_thinking_to_reasoning_effort( if thinking_type == "disabled": return None elif thinking_type == "enabled": - budget_tokens = thinking.get("budget_tokens", 0) - if budget_tokens >= 10000: - return "high" - elif budget_tokens >= 5000: - return "medium" - elif budget_tokens >= 2000: - return "low" - else: - return "minimal" + return reasoning_effort_from_thinking_budget(thinking.get("budget_tokens", 0)) elif thinking_type == "adaptive": # Adaptive thinking: effort is controlled by output_config.effort, # not budget_tokens. Return a default; caller should override with @@ -802,9 +680,7 @@ def translate_thinking_for_model( thinking ) if reasoning_effort: - summary = ( - thinking.get("summary") if isinstance(thinking, dict) else None - ) + summary = thinking.get("summary") if isinstance(thinking, dict) else None auto_summary = is_reasoning_auto_summary_enabled() if summary: return { @@ -834,18 +710,12 @@ def translate_anthropic_tool_choice_to_openai( # Truncate tool name if it exceeds OpenAI's 64-char limit original_name = tool_choice.get("name", "") truncated_name = truncate_tool_name(original_name) - tc_function_param = ChatCompletionToolChoiceFunctionParam( - name=truncated_name - ) - return ChatCompletionToolChoiceObjectParam( - type="function", function=tc_function_param - ) + tc_function_param = ChatCompletionToolChoiceFunctionParam(name=truncated_name) + return ChatCompletionToolChoiceObjectParam(type="function", function=tc_function_param) elif tool_choice["type"] == "none": return "none" else: - raise ValueError( - "Incompatible tool choice param submitted - {}".format(tool_choice) - ) + raise ValueError("Incompatible tool choice param submitted - {}".format(tool_choice)) def translate_anthropic_tools_to_openai( self, tools: List[AllAnthropicToolsValues], model: Optional[str] = None @@ -881,9 +751,7 @@ def translate_anthropic_tools_to_openai( continue raw_name = tool.get("name") - if raw_name is None or ( - isinstance(raw_name, str) and not str(raw_name).strip() - ): + if raw_name is None or (isinstance(raw_name, str) and not str(raw_name).strip()): original_name = f"litellm_unnamed_tool_{idx}" else: original_name = str(raw_name) @@ -904,17 +772,13 @@ def translate_anthropic_tools_to_openai( for k, v in tool.items(): if k not in mapped_tool_params: # pass additional computer kwargs function_chunk.setdefault("parameters", {}).update({k: v}) - tool_param = ChatCompletionToolParam( - type="function", function=function_chunk - ) + tool_param = ChatCompletionToolParam(type="function", function=function_chunk) self._add_cache_control_if_applicable(tool, tool_param, model) new_tools.append(tool_param) # type: ignore[arg-type] return new_tools, tool_name_mapping # type: ignore[return-value] - def translate_anthropic_output_format_to_openai( - self, output_format: Any - ) -> Optional[Dict[str, Any]]: + def translate_anthropic_output_format_to_openai(self, output_format: Any) -> Optional[Dict[str, Any]]: """ Translate Anthropic's output_format to OpenAI's response_format. @@ -973,25 +837,19 @@ def _add_additional_properties_false(schema: dict) -> None: # Handle array items if "items" in schema: - LiteLLMAnthropicMessagesAdapter._add_additional_properties_false( - schema["items"] - ) + LiteLLMAnthropicMessagesAdapter._add_additional_properties_false(schema["items"]) # Handle anyOf/oneOf/allOf for key in ("anyOf", "oneOf", "allOf"): if key in schema: for sub_schema in schema[key]: - LiteLLMAnthropicMessagesAdapter._add_additional_properties_false( - sub_schema - ) + LiteLLMAnthropicMessagesAdapter._add_additional_properties_false(sub_schema) # Handle $defs / definitions for key in ("$defs", "definitions"): if key in schema: for def_schema in schema[key].values(): - LiteLLMAnthropicMessagesAdapter._add_additional_properties_false( - def_schema - ) + LiteLLMAnthropicMessagesAdapter._add_additional_properties_false(def_schema) def _add_system_message_to_messages( self, @@ -1025,9 +883,7 @@ def _add_system_message_to_messages( if openai_system_content: new_messages.insert( 0, - ChatCompletionSystemMessage( - role="system", content=openai_system_content - ), # type: ignore + ChatCompletionSystemMessage(role="system", content=openai_system_content), # type: ignore ) def _translate_metadata_to_openai( @@ -1113,9 +969,7 @@ def _translate_thinking_to_openai( new_kwargs["thinking"] = thinking # type: ignore return - reasoning_effort = self.translate_anthropic_thinking_to_reasoning_effort( - cast(Dict[str, Any], thinking) - ) + reasoning_effort = self.translate_anthropic_thinking_to_reasoning_effort(cast(Dict[str, Any], thinking)) if not reasoning_effort: return @@ -1170,9 +1024,7 @@ def _translate_output_format_to_openai( output_format = output_config.get("format") if not output_format: return - response_format = self.translate_anthropic_output_format_to_openai( - output_format=output_format - ) + response_format = self.translate_anthropic_output_format_to_openai(output_format=output_format) if response_format: new_kwargs["response_format"] = response_format @@ -1203,11 +1055,7 @@ def translate_anthropic_to_openai( tool_name_mapping: Dict[str, str] = {} ## CONVERT ANTHROPIC MESSAGES TO OPENAI - messages_list: List[ - Union[ - AnthropicMessagesUserMessageParam, AnthopicMessagesAssistantMessageParam - ] - ] = cast( + messages_list: List[Union[AnthropicMessagesUserMessageParam, AnthopicMessagesAssistantMessageParam]] = cast( List[ Union[ AnthropicMessagesUserMessageParam, @@ -1294,10 +1142,7 @@ def _translate_openai_content_to_anthropic( new_content: List[Dict[str, Any]] = [] for choice in choices: # Handle thinking blocks first - if ( - hasattr(choice.message, "thinking_blocks") - and choice.message.thinking_blocks - ): + if hasattr(choice.message, "thinking_blocks") and choice.message.thinking_blocks: for thinking_block in choice.message.thinking_blocks: if thinking_block.get("type") == "thinking": thinking_value = thinking_block.get("thinking", "") @@ -1305,16 +1150,8 @@ def _translate_openai_content_to_anthropic( new_content.append( AnthropicResponseContentBlockThinking( type="thinking", - thinking=( - str(thinking_value) - if thinking_value is not None - else "" - ), - signature=( - str(signature_value) - if signature_value is not None - else None - ), + thinking=(str(thinking_value) if thinking_value is not None else ""), + signature=(str(signature_value) if signature_value is not None else None), ).model_dump() ) elif thinking_block.get("type") == "redacted_thinking": @@ -1326,10 +1163,7 @@ def _translate_openai_content_to_anthropic( ).model_dump() ) # Handle reasoning_content when thinking_blocks is not present - elif ( - hasattr(choice.message, "reasoning_content") - and choice.message.reasoning_content - ): + elif hasattr(choice.message, "reasoning_content") and choice.message.reasoning_content: new_content.append( AnthropicResponseContentBlockThinking( type="thinking", @@ -1341,15 +1175,10 @@ def _translate_openai_content_to_anthropic( # Handle text content if choice.message.content is not None: new_content.append( - AnthropicResponseContentBlockText( - type="text", text=choice.message.content - ).model_dump() + AnthropicResponseContentBlockText(type="text", text=choice.message.content).model_dump() ) # Handle tool calls (in parallel to text content) - if ( - choice.message.tool_calls is not None - and len(choice.message.tool_calls) > 0 - ): + if choice.message.tool_calls is not None and len(choice.message.tool_calls) > 0: for tool_call in choice.message.tool_calls: # Extract signature from provider_specific_fields only signature = self._extract_signature_from_tool_call(tool_call) @@ -1361,9 +1190,7 @@ def _translate_openai_content_to_anthropic( # Restore original tool name if it was truncated truncated_name = tool_call.function.name or "" original_name = ( - tool_name_mapping.get(truncated_name, truncated_name) - if tool_name_mapping - else truncated_name + tool_name_mapping.get(truncated_name, truncated_name) if tool_name_mapping else truncated_name ) # Strip Gemini thought-signature suffix and normalize id chars @@ -1381,16 +1208,12 @@ def _translate_openai_content_to_anthropic( ) # Add provider_specific_fields if signature is present if provider_specific_fields: - tool_use_block.provider_specific_fields = ( - provider_specific_fields - ) + tool_use_block.provider_specific_fields = provider_specific_fields new_content.append(tool_use_block.model_dump()) return new_content - def _translate_openai_finish_reason_to_anthropic( - self, openai_finish_reason: str - ) -> AnthropicFinishReason: + def _translate_openai_finish_reason_to_anthropic(self, openai_finish_reason: str) -> AnthropicFinishReason: if openai_finish_reason == "stop": return "end_turn" elif openai_finish_reason == "length": @@ -1410,9 +1233,7 @@ def _positive_int(value: object) -> int: return 0 @classmethod - def _first_positive_usage_value( - cls, usage: Usage, field_names: tuple[str, ...] - ) -> int: + def _first_positive_usage_value(cls, usage: Usage, field_names: tuple[str, ...]) -> int: for field_name in field_names: value = cls._positive_int(getattr(usage, field_name, None)) if value > 0: @@ -1420,9 +1241,7 @@ def _first_positive_usage_value( return 0 @classmethod - def _first_positive_prompt_tokens_detail_value( - cls, usage: Usage, field_names: tuple[str, ...] - ) -> int: + def _first_positive_prompt_tokens_detail_value(cls, usage: Usage, field_names: tuple[str, ...]) -> int: prompt_tokens_details = getattr(usage, "prompt_tokens_details", None) if prompt_tokens_details is None: return 0 @@ -1431,18 +1250,14 @@ def _first_positive_prompt_tokens_detail_value( if isinstance(prompt_tokens_details, dict): value = cls._positive_int(prompt_tokens_details.get(field_name)) else: - value = cls._positive_int( - getattr(prompt_tokens_details, field_name, None) - ) + value = cls._positive_int(getattr(prompt_tokens_details, field_name, None)) if value > 0: return value return 0 @classmethod def _get_cache_read_input_tokens(cls, usage: Usage) -> int: - explicit_value = cls._first_positive_usage_value( - usage, ("cache_read_input_tokens", "_cache_read_input_tokens") - ) + explicit_value = cls._first_positive_usage_value(usage, ("cache_read_input_tokens", "_cache_read_input_tokens")) if explicit_value > 0: return explicit_value return cls._first_positive_prompt_tokens_detail_value(usage, ("cached_tokens",)) @@ -1454,20 +1269,14 @@ def _get_cache_creation_input_tokens(cls, usage: Usage) -> int: ) if explicit_value > 0: return explicit_value - return cls._first_positive_prompt_tokens_detail_value( - usage, ("cache_creation_tokens", "cache_write_tokens") - ) + return cls._first_positive_prompt_tokens_detail_value(usage, ("cache_creation_tokens", "cache_write_tokens")) @classmethod - def _translate_openai_usage_to_anthropic_usage_delta( - cls, usage: Usage - ) -> UsageDelta: + def _translate_openai_usage_to_anthropic_usage_delta(cls, usage: Usage) -> UsageDelta: cache_read_input_tokens = cls._get_cache_read_input_tokens(usage) cache_creation_input_tokens = cls._get_cache_creation_input_tokens(usage) input_tokens = max( - (usage.prompt_tokens or 0) - - cache_read_input_tokens - - cache_creation_input_tokens, + (usage.prompt_tokens or 0) - cache_read_input_tokens - cache_creation_input_tokens, 0, ) @@ -1527,9 +1336,7 @@ def translate_openai_response_to_anthropic( "input_tokens": anthropic_usage["input_tokens"], "output_tokens": usage.completion_tokens or 0, } - anthropic_usage["iterations"] = list(polyfill_result.iterations_usage) + [ - message_iteration - ] # type: ignore[typeddict-unknown-key] + anthropic_usage["iterations"] = list(polyfill_result.iterations_usage) + [message_iteration] # type: ignore[typeddict-unknown-key] translated_obj = AnthropicMessagesResponse( id=response.id, @@ -1542,13 +1349,9 @@ def translate_openai_response_to_anthropic( stop_reason=anthropic_finish_reason, ) - applied_edits = ( - polyfill_result.applied_edits_for_response() if polyfill_result else None - ) + applied_edits = polyfill_result.applied_edits_for_response() if polyfill_result else None if applied_edits: - translated_obj["context_management"] = ContextManagementResponse( - applied_edits=list(applied_edits) - ) + translated_obj["context_management"] = ContextManagementResponse(applied_edits=list(applied_edits)) return translated_obj @@ -1586,9 +1389,7 @@ def _translate_streaming_openai_chunk_to_anthropic_content_block( return "tool_use", cast("ContentBlockContentBlockDict", tool_block) elif choice.delta.content is not None and len(choice.delta.content) > 0: return "text", TextBlock(type="text", text="") - elif isinstance(choice, StreamingChoices) and hasattr( - choice.delta, "thinking_blocks" - ): + elif isinstance(choice, StreamingChoices) and hasattr(choice.delta, "thinking_blocks"): thinking_blocks = choice.delta.thinking_blocks or [] if len(thinking_blocks) > 0: thinking_block = thinking_blocks[0] @@ -1612,12 +1413,8 @@ def _translate_streaming_openai_chunk_to_anthropic_content_block( # ``Delta`` deletes the ``thinking_blocks`` attribute when unset, so the # branch above is skipped entirely; open a ``thinking`` block here so the # matching ``thinking_delta`` stream is not emitted into a text block. - elif isinstance(choice, StreamingChoices) and getattr( - choice.delta, "reasoning_content", None - ): - return "thinking", ChatCompletionThinkingBlock( - type="thinking", thinking="", signature="" - ) + elif isinstance(choice, StreamingChoices) and getattr(choice.delta, "reasoning_content", None): + return "thinking", ChatCompletionThinkingBlock(type="thinking", thinking="", signature="") return "text", TextBlock(type="text", text="") @@ -1642,14 +1439,9 @@ def _translate_streaming_openai_chunk_to_anthropic( if choice.delta.tool_calls: partial_json = "" for tool in choice.delta.tool_calls: - if ( - tool.function is not None - and tool.function.arguments is not None - ): + if tool.function is not None and tool.function.arguments is not None: partial_json = (partial_json or "") + tool.function.arguments - elif isinstance(choice, StreamingChoices) and hasattr( - choice.delta, "thinking_blocks" - ): + elif isinstance(choice, StreamingChoices) and hasattr(choice.delta, "thinking_blocks"): thinking_blocks = choice.delta.thinking_blocks or [] if len(thinking_blocks) > 0: for thinking_block in thinking_blocks: @@ -1664,25 +1456,17 @@ def _translate_streaming_openai_chunk_to_anthropic( reasoning_signature += signature # Handle reasoning_content when thinking_blocks is not present # This handles providers like OpenRouter that return reasoning_content - elif isinstance(choice, StreamingChoices) and hasattr( - choice.delta, "reasoning_content" - ): + elif isinstance(choice, StreamingChoices) and hasattr(choice.delta, "reasoning_content"): if choice.delta.reasoning_content is not None: reasoning_content += choice.delta.reasoning_content if reasoning_content and reasoning_signature: - raise ValueError( - "Both `reasoning` and `signature` in a single streaming chunk isn't supported." - ) + raise ValueError("Both `reasoning` and `signature` in a single streaming chunk isn't supported.") if partial_json is not None: - return "input_json_delta", ContentJsonBlockDelta( - type="input_json_delta", partial_json=partial_json - ) + return "input_json_delta", ContentJsonBlockDelta(type="input_json_delta", partial_json=partial_json) elif reasoning_content: - return "thinking_delta", ContentThinkingBlockDelta( - type="thinking_delta", thinking=reasoning_content - ) + return "thinking_delta", ContentThinkingBlockDelta(type="thinking_delta", thinking=reasoning_content) elif reasoning_signature: return "signature_delta", ContentThinkingSignatureBlockDelta( type="signature_delta", signature=reasoning_signature @@ -1699,23 +1483,16 @@ def translate_streaming_openai_response_to_anthropic( ## base case - final chunk w/ finish reason if response.choices[0].finish_reason is not None: delta = MessageDelta( - stop_reason=self._translate_openai_finish_reason_to_anthropic( - response.choices[0].finish_reason - ), + stop_reason=self._translate_openai_finish_reason_to_anthropic(response.choices[0].finish_reason), ) if getattr(response, "usage", None) is not None: litellm_usage_chunk: Optional[Usage] = response.usage # type: ignore - elif ( - hasattr(response, "_hidden_params") - and "usage" in response._hidden_params - ): + elif hasattr(response, "_hidden_params") and "usage" in response._hidden_params: litellm_usage_chunk = response._hidden_params["usage"] else: litellm_usage_chunk = None if litellm_usage_chunk is not None: - usage_delta = self._translate_openai_usage_to_anthropic_usage_delta( - litellm_usage_chunk - ) + usage_delta = self._translate_openai_usage_to_anthropic_usage_delta(litellm_usage_chunk) else: usage_delta = UsageDelta(input_tokens=0, output_tokens=0) message_block = MessageBlockDelta( @@ -1724,9 +1501,7 @@ def translate_streaming_openai_response_to_anthropic( usage=usage_delta, # type: ignore ) if applied_edits: - message_block["context_management"] = ContextManagementResponse( - applied_edits=list(applied_edits) - ) + message_block["context_management"] = ContextManagementResponse(applied_edits=list(applied_edits)) return message_block ( type_of_content, diff --git a/litellm/llms/anthropic/experimental_pass_through/context_management/constants.py b/litellm/llms/anthropic/experimental_pass_through/context_management/constants.py index ebbc182c427f..50217d4bc82c 100644 --- a/litellm/llms/anthropic/experimental_pass_through/context_management/constants.py +++ b/litellm/llms/anthropic/experimental_pass_through/context_management/constants.py @@ -40,6 +40,4 @@ # Appended to the default prompt when ``tools`` are present and the caller # did not supply custom ``instructions``. Matches the guidance in the # Anthropic docs under "Compaction might fail when tools are defined". -COMPACT_NO_TOOL_CALLS_SUFFIX = ( - " Do not call any tools while writing this summary; respond with text only." -) +COMPACT_NO_TOOL_CALLS_SUFFIX = " Do not call any tools while writing this summary; respond with text only." diff --git a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/clear_tool_uses.py b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/clear_tool_uses.py index 7b1c20ff5227..8bcf8acfff6a 100644 --- a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/clear_tool_uses.py +++ b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/clear_tool_uses.py @@ -68,9 +68,7 @@ def _trigger_met( messages=messages, tools=cast(Any, tools), ) - verbose_logger.debug( - f"context_management polyfill: current_tokens: {current_tokens}" - ) + verbose_logger.debug(f"context_management polyfill: current_tokens: {current_tokens}") verbose_logger.debug(f"context_management polyfill: threshold: {threshold}") return current_tokens > threshold, current_tokens @@ -101,9 +99,7 @@ def _last_completed_tool_use_id( return last_id -def _clear_tool_results( - messages: List[Dict[str, Any]], ids_to_clear: set -) -> Tuple[List[Dict[str, Any]], int]: +def _clear_tool_results(messages: List[Dict[str, Any]], ids_to_clear: set) -> Tuple[List[Dict[str, Any]], int]: """Clear matching tool_result content; return (messages, cleared_count).""" cleared = 0 new_messages: List[Dict[str, Any]] = [] @@ -148,11 +144,7 @@ def apply_clear_tool_uses_20250919( edit_spec: Dict[str, Any], ) -> Tuple[List[Dict[str, Any]], Optional[AppliedEdit]]: """Apply clear_tool_uses; return (messages, AppliedEdit or None).""" - ignored_knobs = [ - knob - for knob in ("clear_at_least", "exclude_tools", "clear_tool_inputs") - if knob in edit_spec - ] + ignored_knobs = [knob for knob in ("clear_at_least", "exclude_tools", "clear_tool_inputs") if knob in edit_spec] for ignored_knob in ignored_knobs: verbose_logger.warning( "context_management polyfill: ignoring '%s' on %s " @@ -192,12 +184,8 @@ def apply_clear_tool_uses_20250919( return messages, None if tokens_before is None: - tokens_before = litellm.token_counter( - model=model, messages=messages, tools=cast(Any, tools) - ) - tokens_after = litellm.token_counter( - model=model, messages=edited, tools=cast(Any, tools) - ) + tokens_before = litellm.token_counter(model=model, messages=messages, tools=cast(Any, tools)) + tokens_after = litellm.token_counter(model=model, messages=edited, tools=cast(Any, tools)) cleared_input_tokens = max(tokens_before - tokens_after, 0) applied: AppliedEdit = { diff --git a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py index 6479ee999b0e..f18a9f419390 100644 --- a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py +++ b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py @@ -266,8 +266,7 @@ async def _check_summary_model_access( team_membership = None member_allowed_models = ( team_membership.litellm_budget_table.allowed_models - if team_membership is not None - and team_membership.litellm_budget_table is not None + if team_membership is not None and team_membership.litellm_budget_table is not None else None ) if member_allowed_models: @@ -328,22 +327,15 @@ async def _check_summary_model_budget( return False except Exception as e: verbose_logger.warning( - "compact_20260112: unexpected error during key model-budget " - "check for summary_model=%s; denying: %s", + "compact_20260112: unexpected error during key model-budget check for summary_model=%s; denying: %s", summary_model, e, ) return False - end_user_model_max_budget = getattr( - user_api_key_auth, "end_user_model_max_budget", None - ) + end_user_model_max_budget = getattr(user_api_key_auth, "end_user_model_max_budget", None) end_user_id = getattr(user_api_key_auth, "end_user_id", None) - if ( - isinstance(end_user_model_max_budget, dict) - and end_user_model_max_budget - and end_user_id is not None - ): + if isinstance(end_user_model_max_budget, dict) and end_user_model_max_budget and end_user_id is not None: try: await model_max_budget_limiter.is_end_user_within_model_budget( end_user_id=end_user_id, @@ -422,11 +414,7 @@ async def _check_summary_model_rate_limit( requested_model=summary_model, descriptors=descriptors, ) - descriptors.extend( - limiter.create_organization_rate_limit_descriptor( - user_api_key_auth, summary_model - ) - ) + descriptors.extend(limiter.create_organization_rate_limit_descriptor(user_api_key_auth, summary_model)) if not descriptors: return True response = await limiter.should_rate_limit( @@ -436,8 +424,7 @@ async def _check_summary_model_rate_limit( ) except Exception as e: verbose_logger.warning( - "compact_20260112: unexpected error during rate-limit check for " - "summary_model=%s; allowing: %s", + "compact_20260112: unexpected error during rate-limit check for summary_model=%s; allowing: %s", summary_model, e, ) @@ -507,11 +494,7 @@ def _strip_compaction_blocks( if not isinstance(content, list): cleaned.append(msg) continue - filtered = [ - block - for block in content - if not (isinstance(block, dict) and block.get("type") == "compaction") - ] + filtered = [block for block in content if not (isinstance(block, dict) and block.get("type") == "compaction")] if not filtered: # The compaction block was the only content; drop the whole turn. continue @@ -573,9 +556,7 @@ def _resolve_trigger_tokens(edit_spec: Dict[str, Any]) -> Tuple[int, List[str]]: return value, warnings -def _build_summary_prompt( - edit_spec: Dict[str, Any], tools: Optional[List[Dict[str, Any]]] -) -> str: +def _build_summary_prompt(edit_spec: Dict[str, Any], tools: Optional[List[Dict[str, Any]]]) -> str: custom = edit_spec.get("instructions") if isinstance(custom, str) and custom.strip(): return custom @@ -628,9 +609,7 @@ def _count_effective_tokens( messages_without_compaction = _strip_compaction_blocks(effective_messages) adapter = LiteLLMAnthropicMessagesAdapter() try: - openai_shape = adapter.translate_anthropic_messages_to_openai( - messages=cast(Any, messages_without_compaction) - ) + openai_shape = adapter.translate_anthropic_messages_to_openai(messages=cast(Any, messages_without_compaction)) except Exception as e: verbose_logger.debug( "compact_20260112: anthropic→openai translation failed during token " @@ -647,9 +626,7 @@ def _count_effective_tokens( openai_tools: Optional[List[Dict[str, Any]]] = None if tools: try: - translated_tools, _ = adapter.translate_anthropic_tools_to_openai( - tools=cast(Any, tools) - ) + translated_tools, _ = adapter.translate_anthropic_tools_to_openai(tools=cast(Any, tools)) openai_tools = cast(List[Dict[str, Any]], translated_tools) except Exception as e: verbose_logger.debug( @@ -713,11 +690,7 @@ def _select_last_user_question( continue content = msg.get("content") if isinstance(content, list): - filtered = [ - blk - for blk in content - if not (isinstance(blk, dict) and blk.get("type") == "tool_result") - ] + filtered = [blk for blk in content if not (isinstance(blk, dict) and blk.get("type") == "tool_result")] if not filtered: # Purely tool_result — skip and look for an earlier turn. continue @@ -755,11 +728,7 @@ def _system_to_openai_message( if isinstance(system, str): return {"role": "system", "content": system} if system else None if isinstance(system, list): - parts = [ - block.get("text", "") - for block in system - if isinstance(block, dict) and block.get("type") == "text" - ] + parts = [block.get("text", "") for block in system if isinstance(block, dict) and block.get("type") == "text"] joined = "\n\n".join(part for part in parts if part) return {"role": "system", "content": joined} if joined else None return None @@ -783,10 +752,8 @@ def _build_summary_messages( stripped = _strip_compaction_blocks(effective_messages) try: - openai_messages = ( - LiteLLMAnthropicMessagesAdapter().translate_anthropic_messages_to_openai( - messages=cast(Any, stripped) - ) + openai_messages = LiteLLMAnthropicMessagesAdapter().translate_anthropic_messages_to_openai( + messages=cast(Any, stripped) ) except Exception as e: verbose_logger.warning( @@ -902,9 +869,7 @@ def _extract_response_text(response: Any) -> Optional[str]: # Some providers return a list of content parts. if isinstance(content, list): text_parts = [ - part.get("text", "") - for part in content - if isinstance(part, dict) and part.get("type") == "text" + part.get("text", "") for part in content if isinstance(part, dict) and part.get("type") == "text" ] return "".join(text_parts) or None except (AttributeError, IndexError, KeyError): @@ -936,9 +901,7 @@ def apply_client_compaction_block_history( tail is forwarded unchanged (with compaction blocks stripped) so recent turns the summary does not cover are preserved. """ - effective_messages, prior_compaction_block = _slice_around_compaction_block( - messages - ) + effective_messages, prior_compaction_block = _slice_around_compaction_block(messages) if prior_compaction_block is None: return None @@ -1006,12 +969,8 @@ async def apply_compact_20260112( # opt-in gate below so that even when summarization is disabled we still # strip Anthropic-only ``compaction`` blocks from messages going to # non-Anthropic backends (which would reject them). - effective_messages, prior_compaction_block = _slice_around_compaction_block( - messages - ) - prior_summary_text = ( - prior_compaction_block.get("content") if prior_compaction_block else None - ) + effective_messages, prior_compaction_block = _slice_around_compaction_block(messages) + prior_summary_text = prior_compaction_block.get("content") if prior_compaction_block else None augmented_system: Union[str, List[Dict[str, Any]], None] = system if isinstance(prior_summary_text, str) and prior_summary_text: augmented_system = _augment_system_with_summary(system, prior_summary_text) @@ -1053,14 +1012,10 @@ async def apply_compact_20260112( system=augmented_system, ) except Exception as e: - verbose_logger.warning( - "compact_20260112: token_counter failed; assuming under threshold: %s", e - ) + verbose_logger.warning("compact_20260112: token_counter failed; assuming under threshold: %s", e) current_tokens = 0 - verbose_logger.debug( - "compact_20260112: current_tokens=%s trigger=%s", current_tokens, trigger_tokens - ) + verbose_logger.debug("compact_20260112: current_tokens=%s trigger=%s", current_tokens, trigger_tokens) if current_tokens <= trigger_tokens: # Slice-only path: the prior compaction summary already lives in @@ -1086,8 +1041,7 @@ async def apply_compact_20260112( llm_router=llm_router, ): verbose_logger.warning( - "compact_20260112: caller not authorized for summary_model=%s; " - "skipping summary call", + "compact_20260112: caller not authorized for summary_model=%s; skipping summary call", summary_model, ) applied["error"] = "summary_model_access_denied" @@ -1102,8 +1056,7 @@ async def apply_compact_20260112( summary_model=summary_model, ): verbose_logger.warning( - "compact_20260112: caller over model budget for summary_model=%s; " - "skipping summary call", + "compact_20260112: caller over model budget for summary_model=%s; skipping summary call", summary_model, ) applied["error"] = "summary_model_budget_exceeded" @@ -1118,8 +1071,7 @@ async def apply_compact_20260112( summary_model=summary_model, ): verbose_logger.warning( - "compact_20260112: caller over rate limit for summary_model=%s; " - "skipping summary call", + "compact_20260112: caller over rate limit for summary_model=%s; skipping summary call", summary_model, ) applied["error"] = "summary_model_rate_limit_exceeded" @@ -1130,9 +1082,7 @@ async def apply_compact_20260112( ) prompt = _build_summary_prompt(edit_spec, tools) - summary_messages = _build_summary_messages( - effective_messages, prompt, system=augmented_system - ) + summary_messages = _build_summary_messages(effective_messages, prompt, system=augmented_system) propagated_metadata = _propagate_metadata(litellm_metadata) allowed_model_region = getattr(user_api_key_auth, "allowed_model_region", None) diff --git a/litellm/llms/anthropic/experimental_pass_through/context_management/result.py b/litellm/llms/anthropic/experimental_pass_through/context_management/result.py index 36bcde98d0c4..14adeb9452ae 100644 --- a/litellm/llms/anthropic/experimental_pass_through/context_management/result.py +++ b/litellm/llms/anthropic/experimental_pass_through/context_management/result.py @@ -42,11 +42,7 @@ def applied_edits_for_response(self) -> Optional[List[AppliedEdit]]: visible: List[AppliedEdit] = [] for edit in self.applied_edits: if edit.get("type") == COMPACT_EDIT_TYPE: - if ( - self.compaction_block is not None - or edit.get("error") - or edit.get("warnings") - ): + if self.compaction_block is not None or edit.get("error") or edit.get("warnings"): visible.append(edit) else: visible.append(edit) diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py index d693d50b8e57..cb37725d79cf 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/agentic_streaming_iterator.py @@ -94,9 +94,7 @@ def _handle_content_block_delta(data: Dict, content_blocks: Dict[int, Dict]) -> if delta_type == "text_delta": block["text"] = block.get("text", "") + delta.get("text", "") elif delta_type == "input_json_delta": - block["_partial_json"] = block.get("_partial_json", "") + delta.get( - "partial_json", "" - ) + block["_partial_json"] = block.get("_partial_json", "") + delta.get("partial_json", "") elif delta_type == "thinking_delta": block["thinking"] = block.get("thinking", "") + delta.get("thinking", "") elif delta_type == "signature_delta": @@ -163,9 +161,7 @@ def __init__( self._model = model self._messages = messages self._anthropic_messages_provider_config = anthropic_messages_provider_config - self._anthropic_messages_optional_request_params = ( - anthropic_messages_optional_request_params - ) + self._anthropic_messages_optional_request_params = anthropic_messages_optional_request_params self._logging_obj = logging_obj self._custom_llm_provider = custom_llm_provider self._kwargs = kwargs @@ -209,17 +205,11 @@ async def _process_agentic_hooks(self) -> None: try: rebuilt = self._rebuild_anthropic_response_from_sse(self._collected_bytes) if rebuilt is None: - verbose_logger.debug( - "AgenticStreamingIterator: Could not rebuild response from SSE bytes" - ) + verbose_logger.debug("AgenticStreamingIterator: Could not rebuild response from SSE bytes") return [ - ( - f"{b.get('type')}({b.get('name', '')})" - if b.get("type") == "tool_use" - else b.get("type") - ) + (f"{b.get('type')}({b.get('name', '')})" if b.get("type") == "tool_use" else b.get("type")) for b in rebuilt.get("content", []) ] @@ -248,9 +238,7 @@ async def _process_agentic_hooks(self) -> None: AnthropicMessagesResponse, ) - fake = FakeAnthropicMessagesStreamIterator( - response=cast(AnthropicMessagesResponse, result) - ) + fake = FakeAnthropicMessagesStreamIterator(response=cast(AnthropicMessagesResponse, result)) self._follow_up_iterator = fake.__aiter__() else: verbose_logger.warning( @@ -260,8 +248,7 @@ async def _process_agentic_hooks(self) -> None: except Exception as e: _call_id = getattr(self._logging_obj, "litellm_call_id", "unknown") verbose_logger.exception( - "AgenticStreamingIterator: Error in agentic hook processing " - "[call_id=%s model=%s]: %s", + "AgenticStreamingIterator: Error in agentic hook processing [call_id=%s model=%s]: %s", _call_id, self._model, str(e), diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py index f704ed2c9d14..184fede25e94 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/fake_stream_iterator.py @@ -38,9 +38,7 @@ def __init__(self, response: AnthropicMessagesResponse): self.chunks = self._create_streaming_chunks() self.current_index = 0 - def _create_content_block_chunks( - self, block_dict: Dict[str, Any], index: int - ) -> List[bytes]: + def _create_content_block_chunks(self, block_dict: Dict[str, Any], index: int) -> List[bytes]: """Build SSE chunks for a single content block.""" chunks = [] block_type = block_dict.get("type") @@ -51,18 +49,14 @@ def _create_content_block_chunks( "index": index, "content_block": {"type": "text", "text": ""}, } - chunks.append( - f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() - ) + chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) text = block_dict.get("text", "") content_block_delta = { "type": "content_block_delta", "index": index, "delta": {"type": "text_delta", "text": text}, } - chunks.append( - f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode() - ) + chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()) elif block_type == "thinking": content_block_start = { @@ -70,9 +64,7 @@ def _create_content_block_chunks( "index": index, "content_block": {"type": "thinking", "thinking": "", "signature": ""}, } - chunks.append( - f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() - ) + chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) thinking_text = block_dict.get("thinking", "") if thinking_text: content_block_delta = { @@ -80,9 +72,7 @@ def _create_content_block_chunks( "index": index, "delta": {"type": "thinking_delta", "thinking": thinking_text}, } - chunks.append( - f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode() - ) + chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()) signature = block_dict.get("signature", "") if signature: signature_delta = { @@ -90,9 +80,7 @@ def _create_content_block_chunks( "index": index, "delta": {"type": "signature_delta", "signature": signature}, } - chunks.append( - f"event: content_block_delta\ndata: {json.dumps(signature_delta)}\n\n".encode() - ) + chunks.append(f"event: content_block_delta\ndata: {json.dumps(signature_delta)}\n\n".encode()) elif block_type == "redacted_thinking": content_block_start = { @@ -100,9 +88,7 @@ def _create_content_block_chunks( "index": index, "content_block": {"type": "redacted_thinking"}, } - chunks.append( - f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() - ) + chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) elif block_type == "tool_use": content_block_start = { @@ -115,9 +101,7 @@ def _create_content_block_chunks( "input": {}, }, } - chunks.append( - f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode() - ) + chunks.append(f"event: content_block_start\ndata: {json.dumps(content_block_start)}\n\n".encode()) input_data = block_dict.get("input", {}) content_block_delta = { "type": "content_block_delta", @@ -127,14 +111,10 @@ def _create_content_block_chunks( "partial_json": json.dumps(input_data), }, } - chunks.append( - f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode() - ) + chunks.append(f"event: content_block_delta\ndata: {json.dumps(content_block_delta)}\n\n".encode()) content_block_stop = {"type": "content_block_stop", "index": index} - chunks.append( - f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode() - ) + chunks.append(f"event: content_block_stop\ndata: {json.dumps(content_block_stop)}\n\n".encode()) return chunks def _create_streaming_chunks(self) -> List[bytes]: @@ -162,9 +142,7 @@ def _create_streaming_chunks(self) -> List[bytes]: }, }, } - chunks.append( - f"event: message_start\ndata: {json.dumps(message_start)}\n\n".encode() - ) + chunks.append(f"event: message_start\ndata: {json.dumps(message_start)}\n\n".encode()) # 2-4. For each content block, send start/delta/stop events content_blocks = response_dict.get("content", []) @@ -182,13 +160,9 @@ def _create_streaming_chunks(self) -> List[bytes]: if usage.get("input_tokens") is not None: delta_usage["input_tokens"] = usage["input_tokens"] if usage.get("cache_creation_input_tokens") is not None: - delta_usage["cache_creation_input_tokens"] = usage[ - "cache_creation_input_tokens" - ] + delta_usage["cache_creation_input_tokens"] = usage["cache_creation_input_tokens"] if usage.get("cache_read_input_tokens") is not None: - delta_usage["cache_read_input_tokens"] = usage[ - "cache_read_input_tokens" - ] + delta_usage["cache_read_input_tokens"] = usage["cache_read_input_tokens"] message_delta = { "type": "message_delta", "delta": { @@ -197,15 +171,11 @@ def _create_streaming_chunks(self) -> List[bytes]: }, "usage": delta_usage, } - chunks.append( - f"event: message_delta\ndata: {json.dumps(message_delta)}\n\n".encode() - ) + chunks.append(f"event: message_delta\ndata: {json.dumps(message_delta)}\n\n".encode()) # 6. message_stop event message_stop = {"type": "message_stop", "usage": usage if usage else {}} - chunks.append( - f"event: message_stop\ndata: {json.dumps(message_stop)}\n\n".encode() - ) + chunks.append(f"event: message_stop\ndata: {json.dumps(message_stop)}\n\n".encode()) return chunks diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py index cb61c196fd82..9c9427c73027 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py @@ -120,9 +120,7 @@ async def _execute_pre_request_hooks( continue # Call the pre-request hook - modified_kwargs = await callback.async_pre_request_hook( - model, messages, request_kwargs - ) + modified_kwargs = await callback.async_pre_request_hook(model, messages, request_kwargs) # If hook returned modified kwargs, use them if modified_kwargs is not None: @@ -219,17 +217,19 @@ async def anthropic_messages( # ids like ``functions.Bash:0`` that violate Anthropic's id pattern. messages = sanitize_tool_use_ids_in_anthropic_messages(messages) - original_stream = stream or kwargs.get( - "_websearch_interception_converted_stream", False - ) + original_stream = stream or kwargs.get("_websearch_interception_converted_stream", False) - # Execute pre-request hooks to allow CustomLoggers to modify request + # Execute pre-request hooks to allow CustomLoggers to modify request. + # tool_choice is forwarded explicitly (it is a named param, not in kwargs) + # so hooks that rename tools — e.g. websearch_interception converting + # web_search -> litellm_web_search — can keep a forced tool_choice in sync. request_kwargs = await _execute_pre_request_hooks( model=model, messages=messages, tools=tools, stream=stream, custom_llm_provider=custom_llm_provider, + tool_choice=tool_choice, **kwargs, ) @@ -251,9 +251,7 @@ async def anthropic_messages( # The litellm_params dict may have been overwritten by **kwargs in # _execute_pre_request_hooks, so fall back to get_llm_provider() if needed. if not custom_llm_provider: - custom_llm_provider = request_kwargs.get("litellm_params", {}).get( - "custom_llm_provider" - ) + custom_llm_provider = request_kwargs.get("litellm_params", {}).get("custom_llm_provider") if not custom_llm_provider: try: _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model) @@ -381,9 +379,7 @@ def anthropic_messages_handler( AnthropicMessagesResponse, Iterator[bytes], AsyncIterator[Any], - Coroutine[ - Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any], Iterator[bytes]] - ], + Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any], Iterator[bytes]]], ]: """ Makes Anthropic `/v1/messages` API calls In the Anthropic API Spec @@ -443,9 +439,7 @@ def anthropic_messages_handler( # Check if stream was converted for WebSearch interception # This is set in the async wrapper above when stream=True is converted to stream=False if kwargs.get("_websearch_interception_converted_stream", False): - litellm_logging_obj.model_call_details[ - "websearch_interception_converted_stream" - ] = True + litellm_logging_obj.model_call_details["websearch_interception_converted_stream"] = True if litellm_params.mock_response and isinstance(litellm_params.mock_response, str): return mock_response( @@ -457,14 +451,10 @@ def anthropic_messages_handler( anthropic_messages_provider_config: Optional[BaseAnthropicMessagesConfig] = None - if custom_llm_provider is not None and custom_llm_provider in [ - provider.value for provider in LlmProviders - ]: - anthropic_messages_provider_config = ( - ProviderConfigManager.get_provider_anthropic_messages_config( - model=model, - provider=litellm.LlmProviders(custom_llm_provider), - ) + if custom_llm_provider is not None and custom_llm_provider in [provider.value for provider in LlmProviders]: + anthropic_messages_provider_config = ProviderConfigManager.get_provider_anthropic_messages_config( + model=model, + provider=litellm.LlmProviders(custom_llm_provider), ) if anthropic_messages_provider_config is None: # Route to Responses API for OpenAI / Azure, chat/completions for everything else. @@ -490,18 +480,14 @@ def anthropic_messages_handler( **kwargs, ) if _should_route_to_responses_api(custom_llm_provider): - return LiteLLMMessagesToResponsesAPIHandler.anthropic_messages_handler( - **_shared_kwargs - ) + return LiteLLMMessagesToResponsesAPIHandler.anthropic_messages_handler(**_shared_kwargs) # The in-gateway context_management polyfill runs inside # ``async_anthropic_messages_handler`` so it can ``await`` the # summarization model for ``compact_20260112``. ``context_management`` # is passed through as a regular kwarg. - return ( - LiteLLMMessagesToCompletionTransformationHandler.anthropic_messages_handler( - **_shared_kwargs, - ) + return LiteLLMMessagesToCompletionTransformationHandler.anthropic_messages_handler( + **_shared_kwargs, ) if custom_llm_provider is None: @@ -520,10 +506,7 @@ def anthropic_messages_handler( ) if is_reasoning_auto_summary_enabled(): thinking_param = anthropic_messages_optional_request_params.get("thinking") - if ( - isinstance(thinking_param, dict) - and thinking_param.get("type") != "disabled" - ): + if isinstance(thinking_param, dict) and thinking_param.get("type") != "disabled": anthropic_messages_optional_request_params["thinking"] = { **thinking_param, "display": "summarized", @@ -533,9 +516,7 @@ def anthropic_messages_handler( model=model, messages=messages, anthropic_messages_provider_config=anthropic_messages_provider_config, - anthropic_messages_optional_request_params=dict( - anthropic_messages_optional_request_params - ), + anthropic_messages_optional_request_params=dict(anthropic_messages_optional_request_params), _is_async=is_async, client=client, custom_llm_provider=custom_llm_provider, diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/interceptors/advisor.py b/litellm/llms/anthropic/experimental_pass_through/messages/interceptors/advisor.py index 8714939f0253..6c72b7a3e007 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/interceptors/advisor.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/interceptors/advisor.py @@ -70,18 +70,12 @@ async def handle( None, ) if advisor_tool is None: - raise ValueError( - f"handle() called but no {ANTHROPIC_ADVISOR_TOOL_TYPE} tool found in tools list" - ) + raise ValueError(f"handle() called but no {ANTHROPIC_ADVISOR_TOOL_TYPE} tool found in tools list") advisor_model: str = advisor_tool.get("model") or "" if not advisor_model: - raise ValueError( - "advisor tool definition must include a 'model' field specifying the advisor model" - ) + raise ValueError("advisor tool definition must include a 'model' field specifying the advisor model") _raw_max_uses = advisor_tool.get("max_uses") - max_uses: int = ( - ADVISOR_MAX_USES if _raw_max_uses is None else int(_raw_max_uses) - ) + max_uses: int = ADVISOR_MAX_USES if _raw_max_uses is None else int(_raw_max_uses) # Optional routing overrides for the advisor sub-call (e.g. proxy routing). # If not set in the tool definition, litellm resolves from env vars. # The advisor tool is caller-controlled; only honor a client-supplied @@ -98,12 +92,7 @@ async def handle( # Executor tools = all original tools with advisor replaced by the synthetic one. executor_tools: List[Dict] = [ - ( - synthetic_advisor_tool - if t.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE - else t - ) - for t in (tools or []) + (synthetic_advisor_tool if t.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE else t) for t in (tools or []) ] # Strip prior advisor blocks from history, preserving advice text as context. @@ -111,9 +100,7 @@ async def handle( [dict(m) for m in messages], replace_with_text=True ) - parent_request_id: str = str( - kwargs.pop("litellm_call_id", None) or uuid.uuid4() - ) + parent_request_id: str = str(kwargs.pop("litellm_call_id", None) or uuid.uuid4()) metadata_base: Dict = dict(kwargs.pop("metadata", None) or {}) iteration = 0 @@ -150,9 +137,7 @@ async def handle( ) # --- Build advisor context --- - advisor_messages = _build_advisor_context( - current_messages, executor_response, advisor_use_block - ) + advisor_messages = _build_advisor_context(current_messages, executor_response, advisor_use_block) # --- Advisor sub-call (always non-streaming, no tools) --- advisor_response: AnthropicMessagesResponse = await _call_messages_handler( @@ -225,11 +210,7 @@ def _find_advisor_tool_use(response: Any) -> Optional[Dict]: if not isinstance(content, list): return None for block in content: - if ( - isinstance(block, dict) - and block.get("type") == "tool_use" - and block.get("name") == "advisor" - ): + if isinstance(block, dict) and block.get("type") == "tool_use" and block.get("name") == "advisor": return block return None @@ -239,11 +220,7 @@ def _extract_response_text(response: Any) -> str: content = response.get("content") if isinstance(response, dict) else [] if not isinstance(content, list): return "" - parts = [ - b.get("text", "") - for b in content - if isinstance(b, dict) and b.get("type") == "text" - ] + parts = [b.get("text", "") for b in content if isinstance(b, dict) and b.get("type") == "text"] return "\n".join(parts).strip() @@ -267,9 +244,7 @@ def _build_advisor_context( question = (advisor_use_block.get("input") or {}).get("question") or ( "Please provide guidance on the current task." ) - raw_content = ( - executor_response.get("content") if isinstance(executor_response, dict) else [] - ) or [] + raw_content = (executor_response.get("content") if isinstance(executor_response, dict) else []) or [] # Keep only text blocks — strip tool_use and provider-specific fields. executor_text_blocks = [ {k: v for k, v in block.items() if k not in _PROVIDER_SPECIFIC_KEYS} @@ -293,9 +268,7 @@ def _inject_advisor_turn( Append the executor's response (as an assistant turn) and the advisor result (as a user tool_result turn) so the executor can continue. """ - executor_content = ( - executor_response.get("content") if isinstance(executor_response, dict) else [] - ) or [] + executor_content = (executor_response.get("content") if isinstance(executor_response, dict) else []) or [] tool_use_id = advisor_use_block.get("id", "") return [ *messages, @@ -322,9 +295,7 @@ def _inject_max_uses_error( Inject a max_uses_exceeded error tool_result so the executor continues without further advisor calls (mirrors Anthropic's server-side behaviour). """ - executor_content = ( - executor_response.get("content") if isinstance(executor_response, dict) else [] - ) or [] + executor_content = (executor_response.get("content") if isinstance(executor_response, dict) else []) or [] tool_use_id = advisor_use_block.get("id", "") return [ *messages, diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py index 251097657729..2357960f716b 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py @@ -40,9 +40,7 @@ async def _handle_streaming_logging(self, collected_chunks: List[bytes]): # chunk rather than falling back to end_time in async_success_handler. if self.completion_start_time is not None: self.litellm_logging_obj.completion_start_time = self.completion_start_time - self.litellm_logging_obj.model_call_details["completion_start_time"] = ( - self.completion_start_time - ) + self.litellm_logging_obj.model_call_details["completion_start_time"] = self.completion_start_time asyncio.create_task( PassThroughStreamingHandler._route_streaming_logging_to_handler( litellm_logging_obj=self.litellm_logging_obj, @@ -95,9 +93,7 @@ def _convert_chunk_to_sse_format(self, chunk: Union[dict, Any]) -> bytes: async def async_sse_wrapper( self, - completion_stream: AsyncIterator[ - Union[bytes, GenericStreamingChunk, ModelResponseStream, dict] - ], + completion_stream: AsyncIterator[Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]], ) -> AsyncIterator[bytes]: """ Generic async SSE wrapper that converts streaming chunks to SSE format diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py index 07e8270b496c..e78802a15878 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/transformation.py @@ -2,6 +2,11 @@ import httpx +from litellm.constants import ( + DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET, + DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET, + DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET, +) from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj from litellm.litellm_core_utils.litellm_logging import verbose_logger from litellm.llms.base_llm.anthropic_messages.transformation import ( @@ -52,9 +57,7 @@ def get_supported_anthropic_messages_params(self, model: str) -> list: # "metadata", ] - def _remove_scope_from_cache_control( - self, anthropic_messages_request: Dict - ) -> None: + def _remove_scope_from_cache_control(self, anthropic_messages_request: Dict) -> None: """ Remove `scope` field from cache_control blocks. @@ -117,9 +120,7 @@ def _filter_billing_headers_from_system(system_param): text = content_block.get("text", "") content_type = content_block.get("type", "") # Skip text blocks that start with billing header - if content_type == "text" and text.startswith( - "x-anthropic-billing-header:" - ): + if content_type == "text" and text.startswith("x-anthropic-billing-header:"): continue filtered_list.append(content_block) else: @@ -138,9 +139,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = ( - AnthropicModelInfo.get_api_base(api_base) or "https://api.anthropic.com" - ) + api_base = AnthropicModelInfo.get_api_base(api_base) or "https://api.anthropic.com" if not api_base.endswith("/v1/messages"): api_base = f"{api_base}/v1/messages" return api_base @@ -156,9 +155,7 @@ def validate_anthropic_messages_environment( api_base: Optional[str] = None, ) -> Tuple[dict, Optional[str]]: # Check for Anthropic OAuth token in Authorization header - headers, api_key = optionally_handle_anthropic_oauth( - headers=headers, api_key=api_key - ) + headers, api_key = optionally_handle_anthropic_oauth(headers=headers, api_key=api_key) if "x-api-key" not in headers and "authorization" not in headers: auth_header = AnthropicModelInfo.get_auth_header(api_key) @@ -177,9 +174,7 @@ def validate_anthropic_messages_environment( return headers, api_base @staticmethod - def _translate_reasoning_effort_to_anthropic( - model: str, optional_params: Dict - ) -> None: + def _translate_reasoning_effort_to_anthropic(model: str, optional_params: Dict) -> None: """Map OpenAI-style ``reasoning_effort`` to native Anthropic params. Caller-supplied ``thinking`` / ``output_config`` win over the alias. @@ -196,9 +191,7 @@ def _translate_reasoning_effort_to_anthropic( return try: - mapped_thinking = AnthropicConfig._map_reasoning_effort( - reasoning_effort=reasoning_effort, model=model - ) + mapped_thinking = AnthropicConfig._map_reasoning_effort(reasoning_effort=reasoning_effort, model=model) except _BadRequestError as e: raise AnthropicError(message=str(e.message), status_code=400) @@ -209,9 +202,7 @@ def _translate_reasoning_effort_to_anthropic( optional_params.setdefault("thinking", mapped_thinking) if AnthropicModelInfo._is_adaptive_thinking_model(model): - mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get( - reasoning_effort - ) + mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get(reasoning_effort) if mapped_effort is None: raise AnthropicError( message=( @@ -221,9 +212,7 @@ def _translate_reasoning_effort_to_anthropic( ), status_code=400, ) - gate_error = AnthropicConfig._validate_effort_for_model( - model, mapped_effort - ) + gate_error = AnthropicConfig._validate_effort_for_model(model, mapped_effort) if gate_error is not None: raise AnthropicError(message=gate_error, status_code=400) existing_output_config = optional_params.get("output_config") @@ -233,9 +222,7 @@ def _translate_reasoning_effort_to_anthropic( optional_params["output_config"] = existing_output_config @staticmethod - def _translate_legacy_thinking_for_adaptive_model( - model: str, optional_params: Dict - ) -> None: + def _translate_legacy_thinking_for_adaptive_model(model: str, optional_params: Dict) -> None: """Translate legacy ``thinking.type=enabled`` to adaptive for 4.6/4.7. Caller-provided ``output_config.effort`` is never overridden. """ @@ -248,11 +235,13 @@ def _translate_legacy_thinking_for_adaptive_model( return budget = int(thinking.get("budget_tokens") or 0) - if budget >= 24000 and AnthropicConfig._supports_effort_level(model, "xhigh"): + if budget >= DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET and ( + AnthropicConfig._supports_effort_level(model, "xhigh") + ): effort = "xhigh" - elif budget >= 10000: + elif budget >= DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET: effort = "high" - elif budget >= 5000: + elif budget >= DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET: effort = "medium" else: effort = "low" @@ -304,21 +293,15 @@ def transform_anthropic_messages_request( anthropic_messages_optional_request_params.pop("system", None) # Transform context_management from OpenAI format to Anthropic format if needed - context_management_param = anthropic_messages_optional_request_params.get( - "context_management" - ) + context_management_param = anthropic_messages_optional_request_params.get("context_management") if context_management_param is not None: from litellm.llms.anthropic.chat.transformation import AnthropicConfig - transformed_context_management = ( - AnthropicConfig.map_openai_context_management_to_anthropic( - context_management_param - ) + transformed_context_management = AnthropicConfig.map_openai_context_management_to_anthropic( + context_management_param ) if transformed_context_management is not None: - anthropic_messages_optional_request_params["context_management"] = ( - transformed_context_management - ) + anthropic_messages_optional_request_params["context_management"] = transformed_context_management ####### get required params for all anthropic messages requests ###### # Lazy %s: the f-string previously stringified the entire messages @@ -329,10 +312,7 @@ def transform_anthropic_messages_request( # Auto-strip advisor blocks from history if advisor tool is absent. # Prevents Anthropic 400: advisor_tool_result in history requires advisor tool. _tools = anthropic_messages_optional_request_params.get("tools") or [] - _has_advisor = any( - isinstance(t, dict) and t.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE - for t in _tools - ) + _has_advisor = any(isinstance(t, dict) and t.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE for t in _tools) if not _has_advisor: messages = strip_advisor_blocks_from_messages(messages) # type: ignore[assignment] @@ -356,9 +336,7 @@ def transform_anthropic_messages_response( try: raw_response_json = raw_response.json() except Exception: - raise AnthropicError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise AnthropicError(message=raw_response.text, status_code=raw_response.status_code) return AnthropicMessagesResponse(**raw_response_json) def get_async_streaming_response_iterator( @@ -432,9 +410,7 @@ def _update_headers_with_anthropic_beta( # Add context management header if any other edits exist if has_other: - beta_values.add( - ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value - ) + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value) # Check for structured outputs. Anthropic's newer request shape nests # the schema under output_config.format; the older top-level @@ -443,9 +419,7 @@ def _update_headers_with_anthropic_beta( if optional_params.get("output_format") is not None or ( isinstance(output_config, dict) and output_config.get("format") is not None ): - beta_values.add( - ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value - ) + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.STRUCTURED_OUTPUT_2025_09_25.value) # Check for fast mode if optional_params.get("speed") == "fast": @@ -455,13 +429,8 @@ def _update_headers_with_anthropic_beta( tools = optional_params.get("tools") if tools: for tool in tools: - if ( - isinstance(tool, dict) - and tool.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE - ): - beta_values.add( - ANTHROPIC_BETA_HEADER_VALUES.ADVISOR_TOOL_2026_03_01.value - ) + if isinstance(tool, dict) and tool.get("type") == ANTHROPIC_ADVISOR_TOOL_TYPE: + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.ADVISOR_TOOL_2026_03_01.value) break # Check for tool search tools diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/utils.py b/litellm/llms/anthropic/experimental_pass_through/messages/utils.py index 42167e0fdaa2..c8060d41fad9 100644 --- a/litellm/llms/anthropic/experimental_pass_through/messages/utils.py +++ b/litellm/llms/anthropic/experimental_pass_through/messages/utils.py @@ -41,9 +41,7 @@ def get_requested_anthropic_messages_optional_param( AnthropicMessagesRequestOptionalParams instance with only the valid parameters """ valid_keys = _anthropic_messages_optional_param_keys() - filtered_params = { - k: v for k, v in params.items() if k in valid_keys and v is not None - } + filtered_params = {k: v for k, v in params.items() if k in valid_keys and v is not None} if model is not None: from litellm.llms.anthropic.chat.transformation import AnthropicConfig diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py index 70855afa81cb..7911845a598a 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/handler.py @@ -163,9 +163,7 @@ async def async_anthropic_messages_handler( result = await litellm.aresponses(**responses_kwargs) if stream: - wrapper = AnthropicResponsesStreamWrapper( - responses_stream=result, model=model - ) + wrapper = AnthropicResponsesStreamWrapper(responses_stream=result, model=model) return wrapper.async_anthropic_sse_wrapper() if not isinstance(result, ResponsesAPIResponse): @@ -199,26 +197,24 @@ def anthropic_messages_handler( Coroutine[Any, Any, Union[AnthropicMessagesResponse, AsyncIterator[Any]]], ]: if _is_async: - return ( - LiteLLMMessagesToResponsesAPIHandler.async_anthropic_messages_handler( - max_tokens=max_tokens, - messages=messages, - model=model, - context_management=context_management, - metadata=metadata, - output_config=output_config, - stop_sequences=stop_sequences, - stream=stream, - system=system, - temperature=temperature, - thinking=thinking, - tool_choice=tool_choice, - tools=tools, - top_k=top_k, - top_p=top_p, - output_format=output_format, - **kwargs, - ) + return LiteLLMMessagesToResponsesAPIHandler.async_anthropic_messages_handler( + max_tokens=max_tokens, + messages=messages, + model=model, + context_management=context_management, + metadata=metadata, + output_config=output_config, + stop_sequences=stop_sequences, + stream=stream, + system=system, + temperature=temperature, + thinking=thinking, + tool_choice=tool_choice, + tools=tools, + top_k=top_k, + top_p=top_p, + output_format=output_format, + **kwargs, ) # Sync path @@ -245,9 +241,7 @@ def anthropic_messages_handler( result = litellm.responses(**responses_kwargs) if stream: - wrapper = AnthropicResponsesStreamWrapper( - responses_stream=result, model=model - ) + wrapper = AnthropicResponsesStreamWrapper(responses_stream=result, model=model) return wrapper.async_anthropic_sse_wrapper() if not isinstance(result, ResponsesAPIResponse): diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py index f400dc7804e7..0d02b4fa9694 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/streaming_iterator.py @@ -35,9 +35,7 @@ def __init__( # Map item_id -> content_block_index so we can stop the right block later self._item_id_to_block_index: Dict[str, int] = {} # Track open function_call items by item_id so we can emit tool_use start - self._pending_tool_ids: Dict[ - str, str - ] = {} # item_id -> call_id / name accumulator + self._pending_tool_ids: Dict[str, str] = {} # item_id -> call_id / name accumulator self._sent_message_start = False self._sent_message_stop = False self._chunk_queue: deque = deque() @@ -83,17 +81,11 @@ def _process_event(self, event: Any) -> None: # ---- content_block_start for a new output message item ---- if event_type == "response.output_item.added": - item = getattr(event, "item", None) or ( - event.get("item") if isinstance(event, dict) else None - ) + item = getattr(event, "item", None) or (event.get("item") if isinstance(event, dict) else None) if item is None: return - item_type = getattr(item, "type", None) or ( - item.get("type") if isinstance(item, dict) else None - ) - item_id = getattr(item, "id", None) or ( - item.get("id") if isinstance(item, dict) else None - ) + item_type = getattr(item, "type", None) or (item.get("type") if isinstance(item, dict) else None) + item_id = getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None) if item_type == "message": block_idx = self._next_block_index() @@ -108,15 +100,9 @@ def _process_event(self, event: Any) -> None: ) elif item_type == "function_call": call_id = ( - getattr(item, "call_id", None) - or (item.get("call_id") if isinstance(item, dict) else None) - or "" - ) - name = ( - getattr(item, "name", None) - or (item.get("name") if isinstance(item, dict) else None) - or "" + getattr(item, "call_id", None) or (item.get("call_id") if isinstance(item, dict) else None) or "" ) + name = getattr(item, "name", None) or (item.get("name") if isinstance(item, dict) else None) or "" block_idx = self._next_block_index() if item_id: self._item_id_to_block_index[item_id] = block_idx @@ -148,17 +134,9 @@ def _process_event(self, event: Any) -> None: # ---- text delta ---- if event_type == "response.output_text.delta": - item_id = getattr(event, "item_id", None) or ( - event.get("item_id") if isinstance(event, dict) else None - ) - delta = getattr(event, "delta", "") or ( - event.get("delta", "") if isinstance(event, dict) else "" - ) - block_idx = ( - self._item_id_to_block_index.get(item_id, -1) - if item_id - else self._current_block_index - ) + item_id = getattr(event, "item_id", None) or (event.get("item_id") if isinstance(event, dict) else None) + delta = getattr(event, "delta", "") or (event.get("delta", "") if isinstance(event, dict) else "") + block_idx = self._item_id_to_block_index.get(item_id, -1) if item_id else self._current_block_index if block_idx < 0: # Some providers (e.g. LMStudio) skip response.output_item.added, # so no text block is open yet; synthesize content_block_start @@ -184,12 +162,8 @@ def _process_event(self, event: Any) -> None: # ---- reasoning summary text delta ---- if event_type == "response.reasoning_summary_text.delta": - item_id = getattr(event, "item_id", None) or ( - event.get("item_id") if isinstance(event, dict) else None - ) - delta = getattr(event, "delta", "") or ( - event.get("delta", "") if isinstance(event, dict) else "" - ) + item_id = getattr(event, "item_id", None) or (event.get("item_id") if isinstance(event, dict) else None) + delta = getattr(event, "delta", "") or (event.get("delta", "") if isinstance(event, dict) else "") block_idx = ( self._item_id_to_block_index.get(item_id, self._current_block_index) if item_id @@ -206,12 +180,8 @@ def _process_event(self, event: Any) -> None: # ---- function call arguments delta ---- if event_type == "response.function_call_arguments.delta": - item_id = getattr(event, "item_id", None) or ( - event.get("item_id") if isinstance(event, dict) else None - ) - delta = getattr(event, "delta", "") or ( - event.get("delta", "") if isinstance(event, dict) else "" - ) + item_id = getattr(event, "item_id", None) or (event.get("item_id") if isinstance(event, dict) else None) + delta = getattr(event, "delta", "") or (event.get("delta", "") if isinstance(event, dict) else "") block_idx = ( self._item_id_to_block_index.get(item_id, self._current_block_index) if item_id @@ -228,14 +198,9 @@ def _process_event(self, event: Any) -> None: # ---- output item done -> content_block_stop ---- if event_type == "response.output_item.done": - item = getattr(event, "item", None) or ( - event.get("item") if isinstance(event, dict) else None - ) + item = getattr(event, "item", None) or (event.get("item") if isinstance(event, dict) else None) item_id = ( - getattr(item, "id", None) - or (item.get("id") if isinstance(item, dict) else None) - if item - else None + getattr(item, "id", None) or (item.get("id") if isinstance(item, dict) else None) if item else None ) block_idx = ( self._item_id_to_block_index.get(item_id, self._current_block_index) @@ -276,12 +241,8 @@ def _process_event(self, event: Any) -> None: cache_creation_tokens = getattr(usage, "input_tokens_details", None) # type: ignore[assignment] cache_read_tokens = getattr(usage, "output_tokens_details", None) # type: ignore[assignment] # Prefer direct cache fields if present - cache_creation_tokens = int( - getattr(usage, "cache_creation_input_tokens", 0) or 0 - ) - cache_read_tokens = int( - getattr(usage, "cache_read_input_tokens", 0) or 0 - ) + cache_creation_tokens = int(getattr(usage, "cache_creation_input_tokens", 0) or 0) + cache_read_tokens = int(getattr(usage, "cache_read_input_tokens", 0) or 0) # Check if tool_use was in the output to override stop_reason if response_obj is not None: @@ -337,9 +298,7 @@ async def __anext__(self) -> Dict[str, Any]: except StopAsyncIteration: pass except Exception as e: - verbose_logger.error( - f"AnthropicResponsesStreamWrapper error: {e}\n{traceback.format_exc()}" - ) + verbose_logger.error(f"AnthropicResponsesStreamWrapper error: {e}\n{traceback.format_exc()}") # Drain any remaining queued chunks if self._chunk_queue: diff --git a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py index 4fb1ddf5c46d..1a052f457c5a 100644 --- a/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py +++ b/litellm/llms/anthropic/experimental_pass_through/responses_adapters/transformation.py @@ -8,6 +8,9 @@ import json from typing import Any, Dict, List, Optional, Union, cast +from litellm.litellm_core_utils.reasoning_effort_utils import ( + reasoning_effort_from_thinking_budget, +) from litellm.llms.anthropic.experimental_pass_through.utils import ( is_reasoning_auto_summary_enabled, ) @@ -92,17 +95,11 @@ def translate_messages_to_responses_input( continue btype = block.get("type") if btype == "text": - user_parts.append( - {"type": "input_text", "text": block.get("text", "")} - ) + user_parts.append({"type": "input_text", "text": block.get("text", "")}) elif btype == "image": - url = self._translate_anthropic_image_source_to_url( - cast(dict, block.get("source", {})) - ) + url = self._translate_anthropic_image_source_to_url(cast(dict, block.get("source", {}))) if url: - user_parts.append( - {"type": "input_image", "image_url": url} - ) + user_parts.append({"type": "input_image", "image_url": url}) elif btype == "tool_result": tool_use_id = block.get("tool_use_id", "") inner = block.get("content") @@ -112,9 +109,7 @@ def translate_messages_to_responses_input( output_text = inner elif isinstance(inner, list): parts = [ - c.get("text", "") - for c in inner - if isinstance(c, dict) and c.get("type") == "text" + c.get("text", "") for c in inner if isinstance(c, dict) and c.get("type") == "text" ] output_text = "\n".join(parts) else: @@ -152,9 +147,7 @@ def translate_messages_to_responses_input( continue btype = block.get("type") if btype == "text": - asst_parts.append( - {"type": "output_text", "text": block.get("text", "")} - ) + asst_parts.append({"type": "output_text", "text": block.get("text", "")}) elif btype == "tool_use": # tool_use becomes a top-level function_call item input_items.append( @@ -168,9 +161,7 @@ def translate_messages_to_responses_input( elif btype == "thinking": thinking_text = block.get("thinking", "") if thinking_text: - asst_parts.append( - {"type": "output_text", "text": thinking_text} - ) + asst_parts.append({"type": "output_text", "text": thinking_text}) if asst_parts: input_items.append( { @@ -193,9 +184,7 @@ def translate_tools_to_responses_api( tool_type = tool_dict.get("type", "") tool_name = tool_dict.get("name", "") # web_search tool - if ( - isinstance(tool_type, str) and tool_type.startswith("web_search") - ) or tool_name == "web_search": + if (isinstance(tool_type, str) and tool_type.startswith("web_search")) or tool_name == "web_search": result.append({"type": "web_search_preview"}) continue func_tool: Dict[str, Any] = {"type": "function", "name": tool_name} @@ -257,11 +246,10 @@ def translate_thinking_to_reasoning( """ Convert Anthropic thinking param to Responses API reasoning param. - thinking.budget_tokens maps to reasoning effort: - >= 10000 -> high, >= 5000 -> medium, >= 2000 -> low, < 2000 -> minimal - - For adaptive thinking, uses output_config.effort if available, - otherwise defaults to medium. + ``thinking.budget_tokens`` is bucketed via the shared + ``reasoning_effort_from_thinking_budget`` thresholds. For adaptive + thinking, uses ``output_config.effort`` if available, otherwise defaults + to medium. """ if not isinstance(thinking, dict): return None @@ -274,15 +262,7 @@ def translate_thinking_to_reasoning( if isinstance(output_config, dict) and output_config.get("effort"): effort = output_config["effort"] elif thinking_type == "enabled": - budget = thinking.get("budget_tokens", 0) - if budget >= 10000: - effort = "high" - elif budget >= 5000: - effort = "medium" - elif budget >= 2000: - effort = "low" - else: - effort = "minimal" + effort = reasoning_effort_from_thinking_budget(thinking.get("budget_tokens", 0)) else: return None @@ -325,11 +305,7 @@ def translate_request( if isinstance(system, str): responses_kwargs["instructions"] = system elif isinstance(system, list): - text_parts = [ - b.get("text", "") - for b in system - if isinstance(b, dict) and b.get("type") == "text" - ] + text_parts = [b.get("text", "") for b in system if isinstance(b, dict) and b.get("type") == "text"] responses_kwargs["instructions"] = "\n".join(filter(None, text_parts)) # max_tokens -> max_output_tokens @@ -353,10 +329,8 @@ def translate_request( # tool_choice tool_choice = anthropic_request.get("tool_choice") if tool_choice: - responses_kwargs["tool_choice"] = ( - self.translate_tool_choice_to_responses_api( - cast(AnthropicMessagesToolChoice, tool_choice) - ) + responses_kwargs["tool_choice"] = self.translate_tool_choice_to_responses_api( + cast(AnthropicMessagesToolChoice, tool_choice) ) # thinking -> reasoning @@ -377,10 +351,7 @@ def translate_request( output_config = anthropic_request.get("output_config") if not isinstance(output_format, dict) and isinstance(output_config, dict): output_format = output_config.get("format") # type: ignore[assignment] - if ( - isinstance(output_format, dict) - and output_format.get("type") == "json_schema" - ): + if isinstance(output_format, dict) and output_format.get("type") == "json_schema": schema = output_format.get("schema") if schema: responses_kwargs["text"] = { @@ -395,9 +366,7 @@ def translate_request( # context_management: Anthropic dict -> OpenAI array context_management = anthropic_request.get("context_management") if isinstance(context_management, dict): - openai_cm = self.translate_context_management_to_responses_api( - context_management - ) + openai_cm = self.translate_context_management_to_responses_api(context_management) if openai_cm is not None: responses_kwargs["context_management"] = openai_cm @@ -447,9 +416,7 @@ def translate_response( for part in item.content: if getattr(part, "type", None) == "output_text": content.append( - AnthropicResponseContentBlockText( - type="text", text=getattr(part, "text", "") - ).model_dump() + AnthropicResponseContentBlockText(type="text", text=getattr(part, "text", "")).model_dump() ) elif isinstance(item, ResponseFunctionToolCall): @@ -473,9 +440,7 @@ def translate_response( for part in item.get("content", []): if isinstance(part, dict) and part.get("type") == "output_text": content.append( - AnthropicResponseContentBlockText( - type="text", text=part.get("text", "") - ).model_dump() + AnthropicResponseContentBlockText(type="text", text=part.get("text", "")).model_dump() ) elif item_type == "function_call": try: diff --git a/litellm/llms/anthropic/experimental_pass_through/utils.py b/litellm/llms/anthropic/experimental_pass_through/utils.py index 4fd68ef535f1..827cce89dab5 100644 --- a/litellm/llms/anthropic/experimental_pass_through/utils.py +++ b/litellm/llms/anthropic/experimental_pass_through/utils.py @@ -7,10 +7,7 @@ def is_reasoning_auto_summary_enabled() -> bool: """Check whether the default 'summary: detailed' injection is enabled (opt-in).""" - return ( - litellm.reasoning_auto_summary - or os.getenv("LITELLM_REASONING_AUTO_SUMMARY", "false").lower() == "true" - ) + return litellm.reasoning_auto_summary or os.getenv("LITELLM_REASONING_AUTO_SUMMARY", "false").lower() == "true" def normalize_reasoning_effort_value( @@ -34,9 +31,7 @@ def normalize_reasoning_effort_value( model_info: Optional[ModelInfo] = None try: - model_info = get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider) except Exception: model_info = None diff --git a/litellm/llms/anthropic/files/handler.py b/litellm/llms/anthropic/files/handler.py index 170cb086bb08..ccd12d1adb14 100644 --- a/litellm/llms/anthropic/files/handler.py +++ b/litellm/llms/anthropic/files/handler.py @@ -91,9 +91,7 @@ async def afile_content( # Construct the Anthropic batch results URL encoded_batch_id = encode_url_path_segment(batch_id, field_name="batch_id") - results_url = ( - f"{api_base.rstrip('/')}/v1/messages/batches/{encoded_batch_id}/results" - ) + results_url = f"{api_base.rstrip('/')}/v1/messages/batches/{encoded_batch_id}/results" # Prepare headers headers = { @@ -108,9 +106,7 @@ async def afile_content( anthropic_response.raise_for_status() # Transform Anthropic batch results to OpenAI format - transformed_content = self._transform_anthropic_batch_results_to_openai_format( - anthropic_response.content - ) + transformed_content = self._transform_anthropic_batch_results_to_openai_format(anthropic_response.content) # Create a new response with transformed content transformed_response = httpx.Response( @@ -131,9 +127,7 @@ def file_content( api_key: Optional[str] = None, timeout: Union[float, httpx.Timeout] = 600.0, max_retries: Optional[int] = None, - ) -> Union[ - HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent] - ]: + ) -> Union[HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent]]: """ Retrieve file content from Anthropic. @@ -169,9 +163,7 @@ def file_content( ) ) - def _transform_anthropic_batch_results_to_openai_format( - self, anthropic_content: bytes - ) -> bytes: + def _transform_anthropic_batch_results_to_openai_format(self, anthropic_content: bytes) -> bytes: """ Transform Anthropic batch results JSONL to OpenAI batch results JSONL format. @@ -214,11 +206,9 @@ def _transform_anthropic_batch_results_to_openai_format( # Transform Anthropic message to OpenAI format anthropic_message = result.get("message", {}) if anthropic_message: - openai_response_body = ( - self._transform_anthropic_message_to_openai_format( - anthropic_message=anthropic_message, - anthropic_config=anthropic_config, - ) + openai_response_body = self._transform_anthropic_message_to_openai_format( + anthropic_message=anthropic_message, + anthropic_config=anthropic_config, ) # Create OpenAI batch result format @@ -279,9 +269,7 @@ def _transform_anthropic_batch_results_to_openai_format( transformed_content += "\n" # Add trailing newline for JSONL format return transformed_content.encode("utf-8") except Exception as e: - verbose_logger.error( - f"Error transforming Anthropic batch results to OpenAI format: {e}" - ) + verbose_logger.error(f"Error transforming Anthropic batch results to OpenAI format: {e}") # Return original content if transformation fails return anthropic_content @@ -333,9 +321,7 @@ def _transform_anthropic_message_to_openai_format( ) # Convert ModelResponse to OpenAI format dict - it's already in OpenAI format - openai_body: OpenAIChatCompletionResponse = transformed_response.model_dump( - exclude_none=True - ) + openai_body: OpenAIChatCompletionResponse = transformed_response.model_dump(exclude_none=True) # Ensure id comes from anthropic_message if not set if not openai_body.get("id"): @@ -343,9 +329,7 @@ def _transform_anthropic_message_to_openai_format( return openai_body except Exception as e: - verbose_logger.error( - f"Error transforming Anthropic message to OpenAI format: {e}" - ) + verbose_logger.error(f"Error transforming Anthropic message to OpenAI format: {e}") # Return a basic error response if transformation fails error_response: OpenAIChatCompletionResponse = { "id": anthropic_message.get("id", ""), diff --git a/litellm/llms/anthropic/files/transformation.py b/litellm/llms/anthropic/files/transformation.py index 7ffb6beb4c7d..cf12ad9ab325 100644 --- a/litellm/llms/anthropic/files/transformation.py +++ b/litellm/llms/anthropic/files/transformation.py @@ -80,9 +80,7 @@ def get_error_class( return AnthropicError( status_code=status_code, message=error_message, - headers=( - cast(httpx.Headers, headers) if isinstance(headers, dict) else headers - ), + headers=(cast(httpx.Headers, headers) if isinstance(headers, dict) else headers), ) def validate_environment( @@ -111,9 +109,7 @@ def validate_environment( ) return headers - def get_supported_openai_params( - self, model: str - ) -> List[OpenAICreateFileRequestOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAICreateFileRequestOptionalParams]: return ["purpose"] def map_openai_params( @@ -184,10 +180,7 @@ def transform_retrieve_file_request( optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - api_base = ( - AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) - or ANTHROPIC_FILES_API_BASE - ) + api_base = AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) or ANTHROPIC_FILES_API_BASE encoded_file_id = encode_url_path_segment(file_id, field_name="file_id") return f"{api_base.rstrip('/')}/v1/files/{encoded_file_id}", {} @@ -206,10 +199,7 @@ def transform_delete_file_request( optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - api_base = ( - AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) - or ANTHROPIC_FILES_API_BASE - ) + api_base = AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) or ANTHROPIC_FILES_API_BASE encoded_file_id = encode_url_path_segment(file_id, field_name="file_id") return f"{api_base.rstrip('/')}/v1/files/{encoded_file_id}", {} @@ -233,10 +223,7 @@ def transform_list_files_request( optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - api_base = ( - AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) - or ANTHROPIC_FILES_API_BASE - ) + api_base = AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) or ANTHROPIC_FILES_API_BASE url = f"{api_base.rstrip('/')}/v1/files" params: Dict[str, Any] = {} if purpose: @@ -269,10 +256,7 @@ def transform_file_content_request( litellm_params: dict, ) -> tuple[str, dict]: file_id = file_content_request.get("file_id") - api_base = ( - AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) - or ANTHROPIC_FILES_API_BASE - ) + api_base = AnthropicModelInfo.get_api_base(litellm_params.get("api_base")) or ANTHROPIC_FILES_API_BASE encoded_file_id = encode_url_path_segment(file_id, field_name="file_id") return f"{api_base.rstrip('/')}/v1/files/{encoded_file_id}/content", {} diff --git a/litellm/llms/anthropic/skills/transformation.py b/litellm/llms/anthropic/skills/transformation.py index 2bfdf7ef4ba4..896182b47630 100644 --- a/litellm/llms/anthropic/skills/transformation.py +++ b/litellm/llms/anthropic/skills/transformation.py @@ -30,9 +30,7 @@ class AnthropicSkillsConfig(BaseSkillsAPIConfig): def custom_llm_provider(self) -> LlmProviders: return LlmProviders.ANTHROPIC - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """Add Anthropic-specific headers""" from litellm.llms.anthropic.common_utils import AnthropicModelInfo @@ -45,9 +43,7 @@ def validate_environment( auth_header = AnthropicModelInfo.get_auth_header(api_key, api_base) if auth_header is None: - raise ValueError( - "ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN is required for Skills API" - ) + raise ValueError("ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN is required for Skills API") headers.update(auth_header) headers["anthropic-version"] = "2023-06-01" @@ -122,9 +118,7 @@ def transform_list_skills_request( """Transform list skills request for Anthropic""" from litellm.llms.anthropic.common_utils import AnthropicModelInfo - api_base = AnthropicModelInfo.get_api_base( - litellm_params.api_base if litellm_params else None - ) + api_base = AnthropicModelInfo.get_api_base(litellm_params.api_base if litellm_params else None) url = self.get_complete_url(api_base=api_base, endpoint="skills") # Build query parameters @@ -162,9 +156,7 @@ def transform_get_skill_request( headers: dict, ) -> Tuple[str, Dict]: """Transform get skill request for Anthropic""" - url = self.get_complete_url( - api_base=api_base, endpoint="skills", skill_id=skill_id - ) + url = self.get_complete_url(api_base=api_base, endpoint="skills", skill_id=skill_id) verbose_logger.debug("Get skill request - URL: %s", url) @@ -189,9 +181,7 @@ def transform_delete_skill_request( headers: dict, ) -> Tuple[str, Dict]: """Transform delete skill request for Anthropic""" - url = self.get_complete_url( - api_base=api_base, endpoint="skills", skill_id=skill_id - ) + url = self.get_complete_url(api_base=api_base, endpoint="skills", skill_id=skill_id) verbose_logger.debug("Delete skill request - URL: %s", url) diff --git a/litellm/llms/apiserpent/search/defaults.py b/litellm/llms/apiserpent/search/defaults.py index 219178587d6b..3bd8e1f93f45 100644 --- a/litellm/llms/apiserpent/search/defaults.py +++ b/litellm/llms/apiserpent/search/defaults.py @@ -44,13 +44,9 @@ def __post_init__(self) -> None: # num's deep-search floor (NUM_MIN_DEEP) is endpoint-specific and enforced # in the transform layer; here we only bound the absolute range. if not NUM_MIN <= self.num <= NUM_MAX: - raise ValueError( - f"num must be between {NUM_MIN} and {NUM_MAX}, got {self.num}" - ) + raise ValueError(f"num must be between {NUM_MIN} and {NUM_MAX}, got {self.num}") if self.pages is not None and not PAGES_MIN <= self.pages <= PAGES_MAX: - raise ValueError( - f"pages must be between {PAGES_MIN} and {PAGES_MAX}, got {self.pages}" - ) + raise ValueError(f"pages must be between {PAGES_MIN} and {PAGES_MAX}, got {self.pages}") def to_request_params(self) -> Dict: """Return non-None fields as request params, booleans lowercased.""" diff --git a/litellm/llms/apiserpent/search/transformation.py b/litellm/llms/apiserpent/search/transformation.py index bc11875ba125..637b1472534f 100644 --- a/litellm/llms/apiserpent/search/transformation.py +++ b/litellm/llms/apiserpent/search/transformation.py @@ -61,9 +61,7 @@ def validate_environment( default_api_base=APISERPENT_BASE, ) if not api_key: - raise ValueError( - "APISERPENT_API_KEY is not set. Set `APISERPENT_API_KEY` environment variable." - ) + raise ValueError("APISERPENT_API_KEY is not set. Set `APISERPENT_API_KEY` environment variable.") headers["X-API-Key"] = api_key headers["Content-Type"] = "application/json" return headers @@ -82,14 +80,8 @@ def get_complete_url( changes the host. The ``endswith`` guard keeps this idempotent, since the handler re-invokes this method with the already-resolved URL as api_base. """ - base = ( - api_base or get_secret_str("APISERPENT_API_BASE") or APISERPENT_BASE - ).rstrip("/") - path = ( - DEEP_SEARCH_PATH - if self._is_deep_search(optional_params) - else QUICK_SEARCH_PATH - ) + base = (api_base or get_secret_str("APISERPENT_API_BASE") or APISERPENT_BASE).rstrip("/") + path = DEEP_SEARCH_PATH if self._is_deep_search(optional_params) else QUICK_SEARCH_PATH if not base.endswith(path): base = f"{base}{path}" @@ -125,9 +117,7 @@ def transform_search_request( overrides: Dict = {} if "max_results" in optional_params: num_min = NUM_MIN_DEEP if is_deep else NUM_MIN - overrides["num"] = max( - num_min, min(optional_params["max_results"], NUM_MAX) - ) + overrides["num"] = max(num_min, min(optional_params["max_results"], NUM_MAX)) if "country" in optional_params: overrides["country"] = cast(str, optional_params["country"]).lower() @@ -164,11 +154,7 @@ def transform_search_response( response_json = raw_response.json() raw_results = response_json.get("results") or {} - organic = ( - raw_results.get("organic", []) - if isinstance(raw_results, dict) - else raw_results - ) + organic = raw_results.get("organic", []) if isinstance(raw_results, dict) else raw_results results: List[SearchResult] = [] for result in organic: diff --git a/litellm/llms/aws_polly/text_to_speech/transformation.py b/litellm/llms/aws_polly/text_to_speech/transformation.py index caf657703974..c85bc9c40328 100644 --- a/litellm/llms/aws_polly/text_to_speech/transformation.py +++ b/litellm/llms/aws_polly/text_to_speech/transformation.py @@ -92,9 +92,9 @@ def dispatch_text_to_speech( base_llm_http_handler: The BaseLLMHTTPHandler instance from main.py """ # Get AWS region from kwargs or environment - aws_region_name = kwargs.get( - "aws_region_name" - ) or self._get_aws_region_name_for_polly(optional_params=optional_params) + aws_region_name = kwargs.get("aws_region_name") or self._get_aws_region_name_for_polly( + optional_params=optional_params + ) # Convert voice to string if it's a dict voice_str: Optional[str] = None @@ -263,9 +263,7 @@ def _sign_polly_request( from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest except ImportError: - raise ImportError( - "Missing boto3 to call AWS Polly. Run 'pip install boto3'." - ) + raise ImportError("Missing boto3 to call AWS Polly. Run 'pip install boto3'.") # Get AWS region aws_region_name = litellm_params.get("aws_region_name", self.DEFAULT_REGION) diff --git a/litellm/llms/azure/assistants.py b/litellm/llms/azure/assistants.py index 750087b722e6..08a04d0c8c71 100644 --- a/litellm/llms/azure/assistants.py +++ b/litellm/llms/azure/assistants.py @@ -203,11 +203,9 @@ async def a_add_message( litellm_params=litellm_params, ) - thread_message: OpenAIMessage = ( - await openai_client.beta.threads.messages.create( # type: ignore - thread_id, - **message_data, # type: ignore - ) + thread_message: OpenAIMessage = await openai_client.beta.threads.messages.create( # type: ignore + thread_id, + **message_data, # type: ignore ) response_obj: Optional[OpenAIMessage] = None @@ -916,9 +914,7 @@ async def async_create_assistants( litellm_params=litellm_params, ) - response = await azure_openai_client.beta.assistants.create( - **create_assistant_data - ) + response = await azure_openai_client.beta.assistants.create(**create_assistant_data) return response def create_assistants( @@ -984,9 +980,7 @@ async def async_delete_assistant( litellm_params=litellm_params, ) - response = await azure_openai_client.beta.assistants.delete( - assistant_id=assistant_id - ) + response = await azure_openai_client.beta.assistants.delete(assistant_id=assistant_id) return response def delete_assistant( diff --git a/litellm/llms/azure/audio_transcription/transformation.py b/litellm/llms/azure/audio_transcription/transformation.py index e478c8ebf350..77050ce6bcaf 100644 --- a/litellm/llms/azure/audio_transcription/transformation.py +++ b/litellm/llms/azure/audio_transcription/transformation.py @@ -41,9 +41,7 @@ class AzureSpeechAudioTranscriptionConfig(BaseAudioTranscriptionConfig): STT_ENDPOINT_PATH = "/speech/recognition/conversation/cognitiveservices/v1" DEFAULT_LANGUAGE = "en-US" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: return ["language", "response_format"] def map_openai_params( @@ -78,9 +76,7 @@ def validate_environment( validated_headers = headers.copy() validated_headers["Ocp-Apim-Subscription-Key"] = api_key - validated_headers["Content-Type"] = validated_headers.get( - "Content-Type", "audio/wav" - ) + validated_headers["Content-Type"] = validated_headers.get("Content-Type", "audio/wav") validated_headers["Accept"] = "application/json" return validated_headers @@ -108,9 +104,7 @@ def get_complete_url( base_url = self._resolve_stt_base_url(api_base=api_base) query_params = { "language": optional_params.get("language", self.DEFAULT_LANGUAGE), - "format": self._get_azure_response_format( - optional_params.get("response_format") - ), + "format": self._get_azure_response_format(optional_params.get("response_format")), } return f"{base_url}{self.STT_ENDPOINT_PATH}?{urlencode(query_params)}" @@ -136,10 +130,7 @@ def transform_audio_transcription_response( recognition_status = response_json.get("RecognitionStatus") if recognition_status is not None and recognition_status != "Success": raise AzureSpeechAudioTranscriptionException( - message=( - "Azure AI Speech transcription failed with " - f"RecognitionStatus={recognition_status}." - ), + message=(f"Azure AI Speech transcription failed with RecognitionStatus={recognition_status}."), status_code=raw_response.status_code, headers=raw_response.headers, ) @@ -164,9 +155,7 @@ def _resolve_stt_base_url(self, api_base: str) -> str: hostname = parsed_url.hostname or "" if self._is_cognitive_services_endpoint(hostname=hostname): - region = self._extract_region_from_hostname( - hostname=hostname, domain=self.COGNITIVE_SERVICES_DOMAIN - ) + region = self._extract_region_from_hostname(hostname=hostname, domain=self.COGNITIVE_SERVICES_DOMAIN) return self._build_stt_base_url(region=region) if self._is_stt_endpoint(hostname=hostname): @@ -184,14 +173,10 @@ def _resolve_stt_base_url(self, api_base: str) -> str: return api_base def _is_cognitive_services_endpoint(self, hostname: str) -> bool: - return hostname == self.COGNITIVE_SERVICES_DOMAIN or hostname.endswith( - f".{self.COGNITIVE_SERVICES_DOMAIN}" - ) + return hostname == self.COGNITIVE_SERVICES_DOMAIN or hostname.endswith(f".{self.COGNITIVE_SERVICES_DOMAIN}") def _is_stt_endpoint(self, hostname: str) -> bool: - return hostname == self.STT_SPEECH_DOMAIN or hostname.endswith( - f".{self.STT_SPEECH_DOMAIN}" - ) + return hostname == self.STT_SPEECH_DOMAIN or hostname.endswith(f".{self.STT_SPEECH_DOMAIN}") def _is_azure_openai_endpoint(self, hostname: str) -> bool: return hostname.endswith(".openai.azure.com") diff --git a/litellm/llms/azure/audio_transcriptions.py b/litellm/llms/azure/audio_transcriptions.py index 591fe9d03a2b..a39f86fd5b1d 100644 --- a/litellm/llms/azure/audio_transcriptions.py +++ b/litellm/llms/azure/audio_transcriptions.py @@ -141,19 +141,15 @@ async def async_audio_transcriptions( input=f"audio_file_{uuid.uuid4()}", api_key=async_azure_client.api_key, additional_args={ - "headers": { - "Authorization": f"Bearer {async_azure_client.api_key}" - }, + "headers": {"Authorization": f"Bearer {async_azure_client.api_key}"}, "api_base": async_azure_client._base_url._uri_reference, "atranscription": True, "complete_input_dict": data, }, ) - raw_response = ( - await async_azure_client.audio.transcriptions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = await async_azure_client.audio.transcriptions.with_raw_response.create( + **data, timeout=timeout ) # type: ignore headers = dict(raw_response.headers) @@ -171,9 +167,7 @@ async def async_audio_transcriptions( input=get_audio_file_name(audio_file), api_key=api_key, additional_args={ - "headers": { - "Authorization": f"Bearer {async_azure_client.api_key}" - }, + "headers": {"Authorization": f"Bearer {async_azure_client.api_key}"}, "api_base": async_azure_client._base_url._uri_reference, "atranscription": True, "complete_input_dict": data, diff --git a/litellm/llms/azure/azure.py b/litellm/llms/azure/azure.py index 8edab95ef6c4..ccb9eb8f5c83 100644 --- a/litellm/llms/azure/azure.py +++ b/litellm/llms/azure/azure.py @@ -68,9 +68,7 @@ def get_supported_openai_create_message_params(self): "metadata", ] - def map_openai_params_create_message_params( - self, non_default_params: dict, optional_params: dict - ): + def map_openai_params_create_message_params(self, non_default_params: dict, optional_params: dict): for param, value in non_default_params.items(): if param == "role": optional_params["role"] = value @@ -84,9 +82,7 @@ def map_openai_params_create_message_params( message="Azure only accepts content as a string.", status_code=400, ) - elif ( - param == "attachments" - ): # this is a v2 param. Azure currently supports the old 'file_id's param + elif param == "attachments": # this is a v2 param. Azure currently supports the old 'file_id's param file_ids: List[str] = [] if isinstance(value, list): for item in value: @@ -149,9 +145,7 @@ def make_sync_azure_openai_chat_completion_request( - call chat.completions.create by default """ try: - raw_response = azure_client.chat.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = azure_client.chat.completions.with_raw_response.create(**data, timeout=timeout) headers = dict(raw_response.headers) response = raw_response.parse() @@ -174,9 +168,7 @@ async def make_azure_openai_chat_completion_request( """ start_time = time.time() try: - raw_response = await azure_client.chat.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = await azure_client.chat.completions.with_raw_response.create(**data, timeout=timeout) headers = dict(raw_response.headers) response = raw_response.parse() @@ -215,9 +207,7 @@ def completion( optional_params["extra_headers"] = headers try: if model is None or messages is None: - raise AzureOpenAIError( - status_code=422, message="Missing model or messages" - ) + raise AzureOpenAIError(status_code=422, message="Missing model or messages") max_retries = optional_params.pop("max_retries", None) if max_retries is None: @@ -242,9 +232,7 @@ def completion( ) data = {"model": None, "messages": messages, **optional_params} - elif litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model( - model=litellm_params.get("base_model") or model - ): + elif litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model(model=litellm_params.get("base_model") or model): data = litellm.AzureOpenAIGPT5Config().transform_request( model=model, messages=messages, @@ -328,9 +316,7 @@ def completion( }, ) if not isinstance(max_retries, int): - raise AzureOpenAIError( - status_code=422, message="max retries must be an int" - ) + raise AzureOpenAIError(status_code=422, message="max retries must be an int") # init AzureOpenAI Client azure_client = self.get_azure_openai_client( api_version=api_version, @@ -420,9 +406,7 @@ async def acompletion( litellm_params=litellm_params, ) if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): - raise ValueError( - "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI" - ) + raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") ## LOGGING logging_obj.pre_call( input=data["messages"], @@ -524,9 +508,7 @@ def streaming( "max_retries": max_retries, "timeout": timeout, } - azure_client_params = select_azure_base_url_or_endpoint( - azure_client_params=azure_client_params - ) + azure_client_params = select_azure_base_url_or_endpoint(azure_client_params=azure_client_params) if api_key is not None: azure_client_params["api_key"] = api_key elif azure_ad_token is not None: @@ -604,9 +586,7 @@ async def async_streaming( litellm_params=litellm_params, ) if not isinstance(azure_client, (AsyncAzureOpenAI, AsyncOpenAI)): - raise ValueError( - "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI" - ) + raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") ## LOGGING logging_obj.pre_call( @@ -685,13 +665,9 @@ async def aembedding( litellm_params=litellm_params, ) if not isinstance(openai_aclient, (AsyncAzureOpenAI, AsyncOpenAI)): - raise ValueError( - "Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI" - ) + raise ValueError("Azure client is not an instance of AsyncAzureOpenAI or AsyncOpenAI") - raw_response = await openai_aclient.embeddings.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = await openai_aclient.embeddings.with_raw_response.create(**data, timeout=timeout) headers = dict(raw_response.headers) # Convert json.JSONDecodeError to AzureOpenAIError for two critical reasons: @@ -817,9 +793,7 @@ def embedding( ) ## COMPLETION CALL - raw_response = azure_client.embeddings.with_raw_response.create( - **data, timeout=timeout - ) # type: ignore + raw_response = azure_client.embeddings.with_raw_response.create(**data, timeout=timeout) # type: ignore headers = dict(raw_response.headers) response = raw_response.parse() if isinstance(response, str): @@ -851,9 +825,7 @@ def embedding( if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) error_text = error_response.text - raise AzureOpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise AzureOpenAIError(status_code=status_code, message=error_text, headers=error_headers) async def make_async_azure_httpx_request( self, @@ -897,9 +869,7 @@ async def make_async_azure_httpx_request( "2023-10-01-preview", ] ): # CREATE + POLL for azure dall-e-2 calls - api_base = modify_url( - original_url=api_base, new_path="/openai/images/generations:submit" - ) + api_base = modify_url(original_url=api_base, new_path="/openai/images/generations:submit") data.pop( "model", None @@ -944,9 +914,7 @@ async def make_async_azure_httpx_request( ) while response.json()["status"] not in ["succeeded", "failed"]: if time.time() - start_time > timeout_secs: - raise AzureOpenAIError( - status_code=408, message="Operation polling timed out." - ) + raise AzureOpenAIError(status_code=408, message="Operation polling timed out.") await asyncio.sleep(int(response.headers.get("retry-after") or 10)) response = await async_handler.get( @@ -1025,9 +993,7 @@ def make_sync_azure_httpx_request( "2023-10-01-preview", ] ): # CREATE + POLL for azure dall-e-2 calls - api_base = modify_url( - original_url=api_base, new_path="/openai/images/generations:submit" - ) + api_base = modify_url(original_url=api_base, new_path="/openai/images/generations:submit") data.pop( "model", None @@ -1064,9 +1030,7 @@ def make_sync_azure_httpx_request( ) while response.json()["status"] not in ["succeeded", "failed"]: if time.time() - start_time > timeout_secs: - raise AzureOpenAIError( - status_code=408, message="Operation polling timed out." - ) + raise AzureOpenAIError(status_code=408, message="Operation polling timed out.") time.sleep(int(response.headers.get("retry-after") or 10)) response = sync_handler.get( @@ -1117,9 +1081,7 @@ def create_azure_base_url( AzureFoundryMAIImageGenerationConfig, ) - api_base: str = azure_client_params.get( - "azure_endpoint", "" - ) # "https://example-endpoint.openai.azure.com" + api_base: str = azure_client_params.get("azure_endpoint", "") # "https://example-endpoint.openai.azure.com" if api_base.endswith("/"): api_base = api_base.rstrip("/") api_version: str = azure_client_params.get("api_version", "") @@ -1167,9 +1129,7 @@ async def aimage_generation( response: Optional[dict] = None try: # response = await azure_client.images.generate(**data, timeout=timeout) - api_base: str = azure_client_params.get( - "api_base", "" - ) # "https://example-endpoint.openai.azure.com" + api_base: str = azure_client_params.get("api_base", "") # "https://example-endpoint.openai.azure.com" if api_base.endswith("/"): api_base = api_base.rstrip("/") api_version: str = azure_client_params.get("api_version", "") @@ -1199,9 +1159,7 @@ async def aimage_generation( headers=headers, ) - provider_config = get_azure_image_generation_config( - data.get("model", "dall-e-2") - ) + provider_config = get_azure_image_generation_config(data.get("model", "dall-e-2")) if provider_config is not None: return provider_config.transform_image_generation_response( model=data.get("model", "dall-e-2"), @@ -1269,23 +1227,17 @@ def image_generation( and litellm_params is not None and litellm_params.get("base_model", None) is not None ): - model_response._hidden_params["model"] = litellm_params.get( - "base_model", None - ) + model_response._hidden_params["model"] = litellm_params.get("base_model", None) # Azure image generation API doesn't support extra_body parameter extra_body = optional_params.pop("extra_body", {}) flattened_params = {**optional_params, **extra_body} - base_model = ( - litellm_params.get("base_model", None) if litellm_params else None - ) + base_model = litellm_params.get("base_model", None) if litellm_params else None data = {"model": base_model or model, "prompt": prompt, **flattened_params} max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): - raise AzureOpenAIError( - status_code=422, message="max retries must be an int" - ) + raise AzureOpenAIError(status_code=422, message="max retries must be an int") if api_key is None and azure_ad_token_provider is not None: azure_ad_token = azure_ad_token_provider() @@ -1341,9 +1293,7 @@ def image_generation( data=data, headers=headers, ) - provider_config = get_azure_image_generation_config( - data.get("model", "dall-e-2") - ) + provider_config = get_azure_image_generation_config(data.get("model", "dall-e-2")) if isinstance(provider_config, AzureFoundryMAIImageGenerationConfig): return provider_config.transform_image_generation_response( model=data.get("model", "dall-e-2"), @@ -1529,14 +1479,10 @@ def get_headers( if ( completion.headers.get("x-ratelimit-remaining-requests", None) is not None ): # not provided for dall-e requests - response["x-ratelimit-remaining-requests"] = completion.headers[ - "x-ratelimit-remaining-requests" - ] + response["x-ratelimit-remaining-requests"] = completion.headers["x-ratelimit-remaining-requests"] if completion.headers.get("x-ratelimit-remaining-tokens", None) is not None: - response["x-ratelimit-remaining-tokens"] = completion.headers[ - "x-ratelimit-remaining-tokens" - ] + response["x-ratelimit-remaining-tokens"] = completion.headers["x-ratelimit-remaining-tokens"] if completion.headers.get("x-ms-region", None) is not None: response["x-ms-region"] = completion.headers["x-ms-region"] diff --git a/litellm/llms/azure/batches/handler.py b/litellm/llms/azure/batches/handler.py index ea6722839e68..808fb3d96004 100644 --- a/litellm/llms/azure/batches/handler.py +++ b/litellm/llms/azure/batches/handler.py @@ -47,20 +47,18 @@ def create_batch( api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ) -> Union[LiteLLMBatch, Coroutine[Any, Any, LiteLLMBatch]]: - azure_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, - litellm_params=litellm_params or {}, + azure_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + litellm_params=litellm_params or {}, + ) ) if azure_client is None: raise ValueError( @@ -75,9 +73,7 @@ def create_batch( return self.acreate_batch( # type: ignore create_batch_data=create_batch_data, azure_client=azure_client ) - response = cast(Union[AzureOpenAI, OpenAI], azure_client).batches.create( - **create_batch_data - ) # type: ignore[arg-type] + response = cast(Union[AzureOpenAI, OpenAI], azure_client).batches.create(**create_batch_data) # type: ignore[arg-type] return LiteLLMBatch(**response.model_dump()) async def aretrieve_batch( @@ -97,20 +93,18 @@ def retrieve_batch( api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ): - azure_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, - litellm_params=litellm_params or {}, + azure_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + litellm_params=litellm_params or {}, + ) ) if azure_client is None: raise ValueError( @@ -125,9 +119,7 @@ def retrieve_batch( return self.aretrieve_batch( # type: ignore retrieve_batch_data=retrieve_batch_data, client=azure_client ) - response = cast(Union[AzureOpenAI, OpenAI], azure_client).batches.retrieve( - **retrieve_batch_data - ) + response = cast(Union[AzureOpenAI, OpenAI], azure_client).batches.retrieve(**retrieve_batch_data) return LiteLLMBatch(**response.model_dump()) async def acancel_batch( @@ -147,20 +139,18 @@ def cancel_batch( api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ): - azure_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, - litellm_params=litellm_params or {}, + azure_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + litellm_params=litellm_params or {}, + ) ) if azure_client is None: raise ValueError( @@ -203,20 +193,18 @@ def list_batches( max_retries: Optional[int], after: Optional[str] = None, limit: Optional[int] = None, - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ): - azure_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, - litellm_params=litellm_params or {}, + azure_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + litellm_params=litellm_params or {}, + ) ) if azure_client is None: raise ValueError( diff --git a/litellm/llms/azure/chat/gpt_5_transformation.py b/litellm/llms/azure/chat/gpt_5_transformation.py index e94f50380c0a..f1bfd96de942 100644 --- a/litellm/llms/azure/chat/gpt_5_transformation.py +++ b/litellm/llms/azure/chat/gpt_5_transformation.py @@ -54,9 +54,7 @@ def is_model_gpt_5_model(cls, model: str) -> bool: # than a substring check) makes this boundary explicit and avoids any ambiguity # if future model names coincidentally contain "gpt-5-chat" as an interior run. _normalized = model.split("/")[-1] # strip provider prefix, e.g. "azure/" - return ( - "gpt-5" in model and not _normalized.startswith("gpt-5-chat") - ) or "gpt5_series" in model + return ("gpt-5" in model and not _normalized.startswith("gpt-5-chat")) or "gpt5_series" in model def get_supported_openai_params(self, model: str) -> List[str]: """Get supported parameters for Azure OpenAI GPT-5 models. @@ -79,9 +77,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: # Only gpt-5.2+ has been verified to support logprobs on Azure. # The base OpenAI class includes logprobs for gpt-5.1+, but Azure # hasn't verified support for gpt-5.1, so remove them unless gpt-5.2/5.4+. - if self._supports_reasoning_effort_level( - model, "none" - ) and not self.is_model_gpt_5_2_model(model): + if self._supports_reasoning_effort_level(model, "none") and not self.is_model_gpt_5_2_model(model): params = [p for p in params if p not in ["logprobs", "top_logprobs"]] elif self.is_model_gpt_5_2_model(model): azure_supported_params = ["logprobs", "top_logprobs"] @@ -97,9 +93,7 @@ def map_openai_params( drop_params: bool, api_version: str = "", ) -> dict: - reasoning_effort_value = non_default_params.get( - "reasoning_effort" - ) or optional_params.get("reasoning_effort") + reasoning_effort_value = non_default_params.get("reasoning_effort") or optional_params.get("reasoning_effort") effective_effort = _get_effort_level(reasoning_effort_value) # gpt-5.1/5.2/5.4 support reasoning_effort='none', but other gpt-5 models don't @@ -107,15 +101,10 @@ def map_openai_params( supports_none = self._supports_reasoning_effort_level(model, "none") if effective_effort == "none" and not supports_none: - if litellm.drop_params is True or ( - drop_params is not None and drop_params is True - ): + if litellm.drop_params is True or (drop_params is not None and drop_params is True): non_default_params = non_default_params.copy() optional_params = optional_params.copy() - if ( - _get_effort_level(non_default_params.get("reasoning_effort")) - == "none" - ): + if _get_effort_level(non_default_params.get("reasoning_effort")) == "none": non_default_params.pop("reasoning_effort") if _get_effort_level(optional_params.get("reasoning_effort")) == "none": optional_params.pop("reasoning_effort") diff --git a/litellm/llms/azure/chat/gpt_transformation.py b/litellm/llms/azure/chat/gpt_transformation.py index 69eda95be1be..50b3ba163266 100644 --- a/litellm/llms/azure/chat/gpt_transformation.py +++ b/litellm/llms/azure/chat/gpt_transformation.py @@ -128,9 +128,7 @@ def _is_response_format_supported_model(self, model: str) -> bool: return True - def _is_response_format_supported_api_version( - self, api_version_year: str, api_version_month: str - ) -> bool: + def _is_response_format_supported_api_version(self, api_version_year: str, api_version_month: str) -> bool: """ - check if api_version is supported for response_format - returns True if the API version is equal to or newer than the supported version @@ -178,25 +176,15 @@ def map_openai_params( tool_choice='required' is not supported as of 2024-05-01-preview """ ## check if api version supports this param ## - if ( - api_version_year is None - or api_version_month is None - or api_version_day is None - ): + if api_version_year is None or api_version_month is None or api_version_day is None: optional_params["tool_choice"] = value else: if ( api_version_year < "2023" or (api_version_year == "2023" and api_version_month < "12") - or ( - api_version_year == "2023" - and api_version_month == "12" - and api_version_day < "01" - ) + or (api_version_year == "2023" and api_version_month == "12" and api_version_day < "01") ): - if litellm.drop_params is True or ( - drop_params is not None and drop_params is True - ): + if litellm.drop_params is True or (drop_params is not None and drop_params is True): pass else: raise UnsupportedParamsError( @@ -206,9 +194,7 @@ def map_openai_params( elif value == "required" and ( api_version_year == "2024" and api_version_month <= "05" ): ## check if tool_choice value is supported ## - if litellm.drop_params is True or ( - drop_params is not None and drop_params is True - ): + if litellm.drop_params is True or (drop_params is not None and drop_params is True): pass else: raise UnsupportedParamsError( @@ -218,21 +204,16 @@ def map_openai_params( else: optional_params["tool_choice"] = value elif param == "response_format" and isinstance(value, dict): - _is_response_format_supported_model = ( - self._is_response_format_supported_model(model) - ) + _is_response_format_supported_model = self._is_response_format_supported_model(model) if api_version_year is None or api_version_month is None: is_response_format_supported_api_version = True else: - is_response_format_supported_api_version = ( - self._is_response_format_supported_api_version( - api_version_year, api_version_month - ) + is_response_format_supported_api_version = self._is_response_format_supported_api_version( + api_version_year, api_version_month ) is_response_format_supported = ( - is_response_format_supported_api_version - and _is_response_format_supported_model + is_response_format_supported_api_version and _is_response_format_supported_model ) optional_params = self._add_response_format_to_tools( @@ -312,12 +293,8 @@ def get_us_regions(self) -> List[str]: "westus4", ] - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return AzureOpenAIError( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return AzureOpenAIError(message=error_message, status_code=status_code, headers=headers) def validate_environment( self, diff --git a/litellm/llms/azure/chat/o_series_transformation.py b/litellm/llms/azure/chat/o_series_transformation.py index 0a73597a4e48..b9cf77b89d8c 100644 --- a/litellm/llms/azure/chat/o_series_transformation.py +++ b/litellm/llms/azure/chat/o_series_transformation.py @@ -27,9 +27,7 @@ def get_supported_openai_params(self, model: str) -> list: """ Get the supported OpenAI params for the Azure O-Series models """ - all_openai_params = litellm.OpenAIGPTConfig().get_supported_openai_params( - model=model - ) + all_openai_params = litellm.OpenAIGPTConfig().get_supported_openai_params(model=model) non_supported_params = [ "logprobs", "top_p", @@ -41,9 +39,7 @@ def get_supported_openai_params(self, model: str) -> list: o_series_only_param = self._get_o_series_only_params(model) all_openai_params.extend(o_series_only_param) - return [ - param for param in all_openai_params if param not in non_supported_params - ] + return [param for param in all_openai_params if param not in non_supported_params] def _get_o_series_only_params(self, model: str) -> list: """ @@ -83,9 +79,7 @@ def should_fake_stream( if stream is not True: return False - if ( - model and "o3" in model - ): # o3 models support streaming - https://github.com/BerriAI/litellm/issues/8274 + if model and "o3" in model: # o3 models support streaming - https://github.com/BerriAI/litellm/issues/8274 return False if model is not None: @@ -99,9 +93,7 @@ def should_fake_stream( ): # allow user to override default with model_info={"supports_native_streaming": true} return False except Exception as e: - verbose_logger.debug( - f"Error getting model info in AzureOpenAIO1Config: {e}" - ) + verbose_logger.debug(f"Error getting model info in AzureOpenAIO1Config: {e}") return True def is_o_series_model(self, model: str) -> bool: @@ -115,9 +107,5 @@ def transform_request( litellm_params: dict, headers: dict, ) -> dict: - model = model.replace( - "o_series/", "" - ) # handle o_series/my-random-deployment-name - return super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + model = model.replace("o_series/", "") # handle o_series/my-random-deployment-name + return super().transform_request(model, messages, optional_params, litellm_params, headers) diff --git a/litellm/llms/azure/common_utils.py b/litellm/llms/azure/common_utils.py index e1ac18589124..91f5793e2697 100644 --- a/litellm/llms/azure/common_utils.py +++ b/litellm/llms/azure/common_utils.py @@ -45,22 +45,14 @@ def __init__( def process_azure_headers(headers: Union[httpx.Headers, dict]) -> dict: openai_headers = {} if "x-ratelimit-limit-requests" in headers: - openai_headers["x-ratelimit-limit-requests"] = headers[ - "x-ratelimit-limit-requests" - ] + openai_headers["x-ratelimit-limit-requests"] = headers["x-ratelimit-limit-requests"] if "x-ratelimit-remaining-requests" in headers: - openai_headers["x-ratelimit-remaining-requests"] = headers[ - "x-ratelimit-remaining-requests" - ] + openai_headers["x-ratelimit-remaining-requests"] = headers["x-ratelimit-remaining-requests"] if "x-ratelimit-limit-tokens" in headers: openai_headers["x-ratelimit-limit-tokens"] = headers["x-ratelimit-limit-tokens"] if "x-ratelimit-remaining-tokens" in headers: - openai_headers["x-ratelimit-remaining-tokens"] = headers[ - "x-ratelimit-remaining-tokens" - ] - llm_response_headers = { - "{}-{}".format("llm_provider", k): v for k, v in headers.items() - } + openai_headers["x-ratelimit-remaining-tokens"] = headers["x-ratelimit-remaining-tokens"] + llm_response_headers = {"{}-{}".format("llm_provider", k): v for k, v in headers.items()} return {**llm_response_headers, **openai_headers} @@ -178,9 +170,7 @@ def get_azure_ad_token_from_oidc( """ if scope is None: scope = "https://cognitiveservices.azure.com/.default" - azure_authority_host = os.getenv( - "AZURE_AUTHORITY_HOST", "https://login.microsoftonline.com" - ) + azure_authority_host = os.getenv("AZURE_AUTHORITY_HOST", "https://login.microsoftonline.com") azure_client_id = azure_client_id or os.getenv("AZURE_CLIENT_ID") azure_tenant_id = azure_tenant_id or os.getenv("AZURE_TENANT_ID") if azure_client_id is None or azure_tenant_id is None: @@ -234,14 +224,10 @@ def get_azure_ad_token_from_oidc( azure_ad_token_expires_in = azure_ad_token_json.get("expires_in", None) if azure_ad_token_access_token is None: - raise AzureOpenAIError( - status_code=422, message="Azure AD Token access_token not returned" - ) + raise AzureOpenAIError(status_code=422, message="Azure AD Token access_token not returned") if azure_ad_token_expires_in is None: - raise AzureOpenAIError( - status_code=422, message="Azure AD Token expires_in not returned" - ) + raise AzureOpenAIError(status_code=422, message="Azure AD Token expires_in not returned") azure_ad_cache.set_cache( key=azure_ad_token_cache_key, @@ -294,14 +280,10 @@ def get_azure_ad_token( # Extract parameters # Use `or` instead of default parameter to handle cases where key exists but value is None azure_ad_token_provider = litellm_params.get("azure_ad_token_provider") - azure_ad_token = litellm_params.get("azure_ad_token") or get_secret_str( - "AZURE_AD_TOKEN" - ) + azure_ad_token = litellm_params.get("azure_ad_token") or get_secret_str("AZURE_AD_TOKEN") tenant_id = litellm_params.get("tenant_id") or os.getenv("AZURE_TENANT_ID") client_id = litellm_params.get("client_id") or os.getenv("AZURE_CLIENT_ID") - client_secret = litellm_params.get("client_secret") or os.getenv( - "AZURE_CLIENT_SECRET" - ) + client_secret = litellm_params.get("client_secret") or os.getenv("AZURE_CLIENT_SECRET") azure_username = litellm_params.get("azure_username") or os.getenv("AZURE_USERNAME") azure_password = litellm_params.get("azure_password") or os.getenv("AZURE_PASSWORD") scope = litellm_params.get("azure_scope") or os.getenv( @@ -312,9 +294,7 @@ def get_azure_ad_token( # Try to get token provider from Entra ID if azure_ad_token_provider is None and tenant_id and client_id and client_secret: - verbose_logger.debug( - "Using Azure AD Token Provider from Entra ID for Azure Auth" - ) + verbose_logger.debug("Using Azure AD Token Provider from Entra ID for Azure Auth") azure_ad_token_provider = get_azure_ad_token_from_entra_id( tenant_id=tenant_id, client_id=client_id, @@ -323,12 +303,7 @@ def get_azure_ad_token( ) # Try to get token provider from username and password - if ( - azure_ad_token_provider is None - and azure_username - and azure_password - and client_id - ): + if azure_ad_token_provider is None and azure_username and azure_password and client_id: verbose_logger.debug("Using Azure Username and Password for Azure Auth") azure_ad_token_provider = get_azure_ad_token_from_username_password( azure_username=azure_username, @@ -338,12 +313,7 @@ def get_azure_ad_token( ) # Try to get token from OIDC - if ( - client_id - and tenant_id - and azure_ad_token - and azure_ad_token.startswith("oidc/") - ): + if client_id and tenant_id and azure_ad_token and azure_ad_token.startswith("oidc/"): verbose_logger.debug("Using Azure OIDC Token for Azure Auth") azure_ad_token = get_azure_ad_token_from_oidc( azure_ad_token=azure_ad_token, @@ -352,10 +322,7 @@ def get_azure_ad_token( scope=scope, ) # Try to get token provider from service principal or DefaultAzureCredential - elif ( - azure_ad_token_provider is None - and litellm.enable_azure_ad_token_refresh is True - ): + elif azure_ad_token_provider is None and litellm.enable_azure_ad_token_refresh is True: verbose_logger.debug( "Using Azure AD token provider based on Service Principal with Secret workflow or DefaultAzureCredential for Azure Auth" ) @@ -374,10 +341,8 @@ def get_azure_ad_token( # try to get DefaultAzureCredential provider ######################################################### if azure_ad_token_provider is None and azure_ad_token is None: - azure_ad_token_provider = ( - BaseAzureLLM._try_get_default_azure_credential_provider( - scope=scope, - ) + azure_ad_token_provider = BaseAzureLLM._try_get_default_azure_credential_provider( + scope=scope, ) # Execute the token provider to get the token if available @@ -385,9 +350,7 @@ def get_azure_ad_token( try: token = azure_ad_token_provider() if not isinstance(token, str): - verbose_logger.error( - f"Azure AD token provider returned non-string value: {type(token)}" - ) + verbose_logger.error(f"Azure AD token provider returned non-string value: {type(token)}") raise TypeError(f"Azure AD token must be a string, got {type(token)}") else: azure_ad_token = token @@ -426,9 +389,7 @@ def _try_get_default_azure_credential_provider( azure_scope=scope, azure_credential=AzureCredentialType.DefaultAzureCredential, ) - verbose_logger.debug( - "Successfully obtained Azure AD token provider using DefaultAzureCredential" - ) + verbose_logger.debug("Successfully obtained Azure AD token provider using DefaultAzureCredential") return azure_ad_token_provider except Exception as e: verbose_logger.debug(f"DefaultAzureCredential failed: {str(e)}") @@ -439,16 +400,12 @@ def get_azure_openai_client( api_key: Optional[str], api_base: Optional[str], api_version: Optional[str] = None, - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, _is_async: bool = False, model: Optional[str] = None, ) -> Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]]: - openai_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None + openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None client_initialization_params: dict = locals() client_initialization_params["is_async"] = _is_async _lp = litellm_params or {} @@ -457,9 +414,7 @@ def get_azure_openai_client( _client_secret = _lp.get("client_secret") _azure_password = _lp.get("azure_password") client_initialization_params["azure_ad_token"] = ( - hashlib.sha256(_ad_token.encode()).hexdigest() - if isinstance(_ad_token, str) - else None + hashlib.sha256(_ad_token.encode()).hexdigest() if isinstance(_ad_token, str) else None ) client_initialization_params["azure_ad_token_provider"] = ( f"provider_id={id(_ad_provider) if callable(_ad_provider) else None}" @@ -476,9 +431,7 @@ def get_azure_openai_client( client_type="azure", ) if cached_client: - if isinstance( - cached_client, (AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI) - ): + if isinstance(cached_client, (AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI)): return cached_client azure_client_params = self.initialize_azure_sdk_client( @@ -527,9 +480,7 @@ async def _async_v1_api_key() -> str: if "http_client" in azure_client_params: v1_params["http_client"] = azure_client_params["http_client"] - verbose_logger.debug( - f"Using Azure v1 API with base_url: {v1_params['base_url']}" - ) + verbose_logger.debug(f"Using Azure v1 API with base_url: {v1_params['base_url']}") if _is_async is True: openai_client = AsyncOpenAI(**v1_params) # type: ignore @@ -574,49 +525,26 @@ def initialize_azure_sdk_client( # litellm_params sometimes contains the key, but the value is None # We should respect environment variables in this case - tenant_id = self._resolve_env_var( - litellm_params, "tenant_id", "AZURE_TENANT_ID" - ) - client_id = self._resolve_env_var( - litellm_params, "client_id", "AZURE_CLIENT_ID" - ) - client_secret = self._resolve_env_var( - litellm_params, "client_secret", "AZURE_CLIENT_SECRET" - ) - azure_username = self._resolve_env_var( - litellm_params, "azure_username", "AZURE_USERNAME" - ) - azure_password = self._resolve_env_var( - litellm_params, "azure_password", "AZURE_PASSWORD" - ) + tenant_id = self._resolve_env_var(litellm_params, "tenant_id", "AZURE_TENANT_ID") + client_id = self._resolve_env_var(litellm_params, "client_id", "AZURE_CLIENT_ID") + client_secret = self._resolve_env_var(litellm_params, "client_secret", "AZURE_CLIENT_SECRET") + azure_username = self._resolve_env_var(litellm_params, "azure_username", "AZURE_USERNAME") + azure_password = self._resolve_env_var(litellm_params, "azure_password", "AZURE_PASSWORD") scope = self._resolve_env_var(litellm_params, "azure_scope", "AZURE_SCOPE") if scope is None: scope = "https://cognitiveservices.azure.com/.default" max_retries = litellm_params.get("max_retries") timeout = litellm_params.get("timeout") - if ( - not api_key - and azure_ad_token_provider is None - and tenant_id - and client_id - and client_secret - ): - verbose_logger.debug( - "Using Azure AD Token Provider from Entra ID for Azure Auth" - ) + if not api_key and azure_ad_token_provider is None and tenant_id and client_id and client_secret: + verbose_logger.debug("Using Azure AD Token Provider from Entra ID for Azure Auth") azure_ad_token_provider = get_azure_ad_token_from_entra_id( tenant_id=tenant_id, client_id=client_id, client_secret=client_secret, scope=scope, ) - if ( - azure_ad_token_provider is None - and azure_username - and azure_password - and client_id - ): + if azure_ad_token_provider is None and azure_username and azure_password and client_id: verbose_logger.debug("Using Azure Username and Password for Azure Auth") azure_ad_token_provider = get_azure_ad_token_from_username_password( azure_username=azure_username, @@ -633,11 +561,7 @@ def initialize_azure_sdk_client( azure_tenant_id=tenant_id, scope=scope, ) - elif ( - not api_key - and azure_ad_token_provider is None - and litellm.enable_azure_ad_token_refresh is True - ): + elif not api_key and azure_ad_token_provider is None and litellm.enable_azure_ad_token_refresh is True: verbose_logger.debug( "Using Azure AD token provider based on Service Principal with Secret workflow for Azure Auth" ) @@ -648,9 +572,7 @@ def initialize_azure_sdk_client( except ValueError: verbose_logger.debug("Azure AD Token Provider could not be used.") if api_version is None: - api_version = os.getenv( - "AZURE_API_VERSION", litellm.AZURE_DEFAULT_API_VERSION - ) + api_version = os.getenv("AZURE_API_VERSION", litellm.AZURE_DEFAULT_API_VERSION) _api_key = api_key if _api_key is not None and isinstance(_api_key, str): @@ -682,9 +604,7 @@ def initialize_azure_sdk_client( # this decides if we should set azure_endpoint or base_url on Azure OpenAI Client # required to support GPT-4 vision enhancements, since base_url needs to be set on Azure OpenAI Client - azure_client_params = select_azure_base_url_or_endpoint( - azure_client_params=azure_client_params - ) + azure_client_params = select_azure_base_url_or_endpoint(azure_client_params=azure_client_params) return azure_client_params @@ -743,9 +663,7 @@ def _init_azure_client_for_cloudflare_ai_gateway( return client @staticmethod - def _base_validate_azure_environment( - headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def _base_validate_azure_environment(headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() # Check if api-key is already in headers; if so, use it @@ -798,10 +716,7 @@ def _get_base_azure_url( # Extract api_version or use default litellm_params = litellm_params or {} - api_version = ( - cast(Optional[str], litellm_params.get("api_version")) - or default_api_version - ) + api_version = cast(Optional[str], litellm_params.get("api_version")) or default_api_version # Create a new dictionary with existing params query_params = dict(original_url.params) @@ -820,11 +735,7 @@ def _get_base_azure_url( # ensure the request go to /openai/v1 and not just /openai if "/openai/v1" not in new_url: parsed_url = httpx.URL(new_url) - new_url = str( - parsed_url.copy_with( - path=parsed_url.path.replace("/openai", "/openai/v1") - ) - ) + new_url = str(parsed_url.copy_with(path=parsed_url.path.replace("/openai", "/openai/v1"))) # Use the new query_params dictionary final_url = httpx.URL(new_url).copy_with(params=query_params) @@ -837,9 +748,7 @@ def _is_azure_v1_api_version(api_version: Optional[str]) -> bool: return False return api_version in {"preview", "latest", "v1"} - def _resolve_env_var( - self, litellm_params: Dict[str, Any], param_key: str, env_var_key: str - ) -> Optional[str]: + def _resolve_env_var(self, litellm_params: Dict[str, Any], param_key: str, env_var_key: str) -> Optional[str]: """Resolve the environment variable for a given parameter key. The logic here is different from `params.get(key, os.getenv(env_var))` because @@ -865,9 +774,7 @@ def get_azure_credentials( ) -> AzureCredentials: """Resolve Azure credentials from params, litellm globals, and env vars.""" resolved_api_base = api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") - resolved_api_version = ( - api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") - ) + resolved_api_version = api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") resolved_api_key = ( api_key or litellm.api_key diff --git a/litellm/llms/azure/completion/handler.py b/litellm/llms/azure/completion/handler.py index b8d1ad71d46b..2c0b67a9e563 100644 --- a/litellm/llms/azure/completion/handler.py +++ b/litellm/llms/azure/completion/handler.py @@ -48,14 +48,10 @@ def completion( ): try: if model is None or messages is None: - raise AzureOpenAIError( - status_code=422, message="Missing model or messages" - ) + raise AzureOpenAIError(status_code=422, message="Missing model or messages") max_retries = optional_params.pop("max_retries", 2) - prompt = prompt_factory( - messages=messages, model=model, custom_llm_provider="azure_text" - ) + prompt = prompt_factory(messages=messages, model=model, custom_llm_provider="azure_text") ### CHECK IF CLOUDFLARE AI GATEWAY ### ### if so - set the model as part of the base url @@ -140,9 +136,7 @@ def completion( }, ) if not isinstance(max_retries, int): - raise AzureOpenAIError( - status_code=422, message="max retries must be an int" - ) + raise AzureOpenAIError(status_code=422, message="max retries must be an int") # init AzureOpenAI Client azure_client = self.get_azure_openai_client( api_key=api_key, @@ -160,9 +154,7 @@ def completion( message="azure_client is not an instance of AzureOpenAI", ) - raw_response = azure_client.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = azure_client.completions.with_raw_response.create(**data, timeout=timeout) response = raw_response.parse() stringified_response = response.model_dump() ## LOGGING @@ -176,11 +168,9 @@ def completion( "api_base": api_base, }, ) - return ( - openai_text_completion_config.convert_to_chat_model_response_object( - response_object=TextCompletionResponse(**stringified_response), - model_response_object=model_response, - ) + return openai_text_completion_config.convert_to_chat_model_response_object( + response_object=TextCompletionResponse(**stringified_response), + model_response_object=model_response, ) except AzureOpenAIError as e: raise e @@ -190,9 +180,7 @@ def completion( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise AzureOpenAIError( - status_code=status_code, message=str(e), headers=error_headers - ) + raise AzureOpenAIError(status_code=status_code, message=str(e), headers=error_headers) async def acompletion( self, @@ -239,9 +227,7 @@ async def acompletion( "complete_input_dict": data, }, ) - raw_response = await azure_client.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = await azure_client.completions.with_raw_response.create(**data, timeout=timeout) response = raw_response.parse() return openai_text_completion_config.convert_to_chat_model_response_object( response_object=response.model_dump(), @@ -255,9 +241,7 @@ async def acompletion( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise AzureOpenAIError( - status_code=status_code, message=str(e), headers=error_headers - ) + raise AzureOpenAIError(status_code=status_code, message=str(e), headers=error_headers) def streaming( self, @@ -274,9 +258,7 @@ def streaming( ): max_retries = data.pop("max_retries", 2) if not isinstance(max_retries, int): - raise AzureOpenAIError( - status_code=422, message="max retries must be an int" - ) + raise AzureOpenAIError(status_code=422, message="max retries must be an int") # init AzureOpenAI Client azure_client = self.get_azure_openai_client( api_version=api_version, @@ -304,9 +286,7 @@ def streaming( "complete_input_dict": data, }, ) - raw_response = azure_client.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = azure_client.completions.with_raw_response.create(**data, timeout=timeout) response = raw_response.parse() streamwrapper = CustomStreamWrapper( completion_stream=response, @@ -356,9 +336,7 @@ async def async_streaming( "complete_input_dict": data, }, ) - raw_response = await azure_client.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = await azure_client.completions.with_raw_response.create(**data, timeout=timeout) response = raw_response.parse() # return response streamwrapper = CustomStreamWrapper( @@ -374,6 +352,4 @@ async def async_streaming( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise AzureOpenAIError( - status_code=status_code, message=str(e), headers=error_headers - ) + raise AzureOpenAIError(status_code=status_code, message=str(e), headers=error_headers) diff --git a/litellm/llms/azure/containers/transformation.py b/litellm/llms/azure/containers/transformation.py index cd897511585f..30cd3421d1b8 100644 --- a/litellm/llms/azure/containers/transformation.py +++ b/litellm/llms/azure/containers/transformation.py @@ -43,9 +43,7 @@ def _normalize_api_base(api_base: Optional[str]) -> Optional[str]: path = parsed.path.rstrip("/") for ep in _AZURE_ENDPOINT_PATHS: if path.endswith(ep): - return urlunparse( - (parsed.scheme, parsed.netloc, path[: -len(ep)], "", "", "") - ) + return urlunparse((parsed.scheme, parsed.netloc, path[: -len(ep)], "", "", "")) return api_base @staticmethod diff --git a/litellm/llms/azure/exception_mapping.py b/litellm/llms/azure/exception_mapping.py index dec7e7e5c907..07d589021a7e 100644 --- a/litellm/llms/azure/exception_mapping.py +++ b/litellm/llms/azure/exception_mapping.py @@ -18,20 +18,12 @@ def create_content_policy_violation_error( """ Create a content policy violation error """ - azure_error, inner_error = AzureOpenAIExceptionMapping._extract_azure_error( - original_exception - ) + azure_error, inner_error = AzureOpenAIExceptionMapping._extract_azure_error(original_exception) # Prefer the provider message/type/code when present. - provider_message = ( - azure_error.get("message") if isinstance(azure_error, dict) else None - ) or message - provider_type = ( - azure_error.get("type") if isinstance(azure_error, dict) else None - ) - provider_code = ( - azure_error.get("code") if isinstance(azure_error, dict) else None - ) + provider_message = (azure_error.get("message") if isinstance(azure_error, dict) else None) or message + provider_type = azure_error.get("type") if isinstance(azure_error, dict) else None + provider_code = azure_error.get("code") if isinstance(azure_error, dict) else None # Keep the OpenAI-style body fields populated so downstream (proxy + SDK) # can surface `type` / `code` correctly. diff --git a/litellm/llms/azure/files/handler.py b/litellm/llms/azure/files/handler.py index cca83b8e6fdb..8b277bdd49a7 100644 --- a/litellm/llms/azure/files/handler.py +++ b/litellm/llms/azure/files/handler.py @@ -45,9 +45,7 @@ async def acreate_file( openai_client: Union[AsyncAzureOpenAI, AsyncOpenAI], ) -> OpenAIFileObject: verbose_logger.debug("create_file_data=%s", create_file_data) - response = await openai_client.files.create( - **self._prepare_create_file_data(create_file_data) - ) # type: ignore[arg-type] + response = await openai_client.files.create(**self._prepare_create_file_data(create_file_data)) # type: ignore[arg-type] verbose_logger.debug("create_file_response=%s", response) return OpenAIFileObject(**response.model_dump()) @@ -60,20 +58,18 @@ def create_file( api_version: Optional[str], timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ) -> Union[OpenAIFileObject, Coroutine[Any, Any, OpenAIFileObject]]: - openai_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - litellm_params=litellm_params or {}, - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, + openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + litellm_params=litellm_params or {}, + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + ) ) if openai_client is None: raise ValueError( @@ -85,9 +81,7 @@ def create_file( raise ValueError( "AzureOpenAI client is not an instance of AsyncAzureOpenAI. Make sure you passed an AsyncAzureOpenAI client." ) - return self.acreate_file( - create_file_data=create_file_data, openai_client=openai_client - ) + return self.acreate_file(create_file_data=create_file_data, openai_client=openai_client) response = cast(Union[AzureOpenAI, OpenAI], openai_client).files.create( **self._prepare_create_file_data(create_file_data) ) # type: ignore[arg-type] @@ -110,22 +104,18 @@ def file_content( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], api_version: Optional[str] = None, - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, - ) -> Union[ - HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent] - ]: - openai_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - litellm_params=litellm_params or {}, - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, + ) -> Union[HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent]]: + openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + litellm_params=litellm_params or {}, + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + ) ) if openai_client is None: raise ValueError( @@ -141,9 +131,7 @@ def file_content( file_content_request=file_content_request, openai_client=openai_client, ) - response = cast(Union[AzureOpenAI, OpenAI], openai_client).files.content( - **file_content_request - ) + response = cast(Union[AzureOpenAI, OpenAI], openai_client).files.content(**file_content_request) return HttpxBinaryResponseContent(response=response.response) @@ -164,20 +152,18 @@ def retrieve_file( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], api_version: Optional[str] = None, - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ): - openai_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - litellm_params=litellm_params or {}, - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, + openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + litellm_params=litellm_params or {}, + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + ) ) if openai_client is None: raise ValueError( @@ -218,20 +204,18 @@ def delete_file( max_retries: Optional[int], organization: Optional[str] = None, api_version: Optional[str] = None, - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ): - openai_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - litellm_params=litellm_params or {}, - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, + openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + litellm_params=litellm_params or {}, + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + ) ) if openai_client is None: raise ValueError( @@ -274,20 +258,18 @@ def list_files( max_retries: Optional[int], purpose: Optional[str] = None, api_version: Optional[str] = None, - client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = None, + client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = None, litellm_params: Optional[dict] = None, ): - openai_client: Optional[ - Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI] - ] = self.get_azure_openai_client( - litellm_params=litellm_params or {}, - api_key=api_key, - api_base=api_base, - api_version=api_version, - client=client, - _is_async=_is_async, + openai_client: Optional[Union[AzureOpenAI, AsyncAzureOpenAI, OpenAI, AsyncOpenAI]] = ( + self.get_azure_openai_client( + litellm_params=litellm_params or {}, + api_key=api_key, + api_base=api_base, + api_version=api_version, + client=client, + _is_async=_is_async, + ) ) if openai_client is None: raise ValueError( diff --git a/litellm/llms/azure/fine_tuning/handler.py b/litellm/llms/azure/fine_tuning/handler.py index 07d6455a6fbd..f4a4166c8b47 100644 --- a/litellm/llms/azure/fine_tuning/handler.py +++ b/litellm/llms/azure/fine_tuning/handler.py @@ -28,18 +28,14 @@ def _ensure_training_type(create_fine_tuning_job_data: Dict[str, Any]) -> None: if extra_body.get("trainingType") is None: extra_body["trainingType"] = 1 create_fine_tuning_job_data["extra_body"] = extra_body - verbose_logger.debug( - "Azure fine-tuning: defaulting trainingType=1 (supervised)" - ) + verbose_logger.debug("Azure fine-tuning: defaulting trainingType=1 (supervised)") async def acreate_fine_tuning_job( self, create_fine_tuning_job_data: dict, openai_client: Union[AsyncOpenAI, AsyncAzureOpenAI], ) -> LiteLLMFineTuningJob: - response = await openai_client.fine_tuning.jobs.create( - **create_fine_tuning_job_data - ) + response = await openai_client.fine_tuning.jobs.create(**create_fine_tuning_job_data) return _litellm_fine_tuning_job_from_response(response, is_azure=True) async def acancel_fine_tuning_job( @@ -47,9 +43,7 @@ async def acancel_fine_tuning_job( fine_tuning_job_id: str, openai_client: Union[AsyncOpenAI, AsyncAzureOpenAI], ) -> LiteLLMFineTuningJob: - response = await openai_client.fine_tuning.jobs.cancel( - fine_tuning_job_id=fine_tuning_job_id - ) + response = await openai_client.fine_tuning.jobs.cancel(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response, is_azure=True) async def aretrieve_fine_tuning_job( @@ -57,9 +51,7 @@ async def aretrieve_fine_tuning_job( fine_tuning_job_id: str, openai_client: Union[AsyncOpenAI, AsyncAzureOpenAI], ) -> LiteLLMFineTuningJob: - response = await openai_client.fine_tuning.jobs.retrieve( - fine_tuning_job_id=fine_tuning_job_id - ) + response = await openai_client.fine_tuning.jobs.retrieve(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response, is_azure=True) def create_fine_tuning_job( @@ -72,15 +64,11 @@ def create_fine_tuning_job( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: self._ensure_training_type(create_fine_tuning_job_data) - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -105,12 +93,8 @@ def create_fine_tuning_job( openai_client=openai_client, ) - verbose_logger.debug( - "creating fine tuning job, args= %s", create_fine_tuning_job_data - ) - response = cast(OpenAI, openai_client).fine_tuning.jobs.create( - **create_fine_tuning_job_data - ) + verbose_logger.debug("creating fine tuning job, args= %s", create_fine_tuning_job_data) + response = cast(OpenAI, openai_client).fine_tuning.jobs.create(**create_fine_tuning_job_data) return _litellm_fine_tuning_job_from_response(response, is_azure=True) def cancel_fine_tuning_job( @@ -123,13 +107,9 @@ def cancel_fine_tuning_job( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -154,9 +134,7 @@ def cancel_fine_tuning_job( openai_client=openai_client, ) - response = cast(OpenAI, openai_client).fine_tuning.jobs.cancel( - fine_tuning_job_id=fine_tuning_job_id - ) + response = cast(OpenAI, openai_client).fine_tuning.jobs.cancel(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response, is_azure=True) def retrieve_fine_tuning_job( @@ -169,13 +147,9 @@ def retrieve_fine_tuning_job( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -200,9 +174,7 @@ def retrieve_fine_tuning_job( openai_client=openai_client, ) - response = cast(OpenAI, openai_client).fine_tuning.jobs.retrieve( - fine_tuning_job_id=fine_tuning_job_id - ) + response = cast(OpenAI, openai_client).fine_tuning.jobs.retrieve(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response, is_azure=True) def get_openai_client( @@ -212,9 +184,7 @@ def get_openai_client( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, _is_async: bool = False, api_version: Optional[str] = None, litellm_params: Optional[dict] = None, diff --git a/litellm/llms/azure/image_edit/transformation.py b/litellm/llms/azure/image_edit/transformation.py index 72f1eef36c0f..d28d92a07707 100644 --- a/litellm/llms/azure/image_edit/transformation.py +++ b/litellm/llms/azure/image_edit/transformation.py @@ -65,9 +65,7 @@ def validate_environment( params = GenericLiteLLMParams(**(litellm_params or {})) if api_key is not None and params.api_key is None: params.api_key = api_key - return BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=params - ) + return BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=params) def get_complete_url( self, @@ -128,7 +126,5 @@ def get_complete_url( return str(final_url) - def finalize_image_edit_request_data( - self, data: dict, resolved_request_url: str - ) -> dict: + def finalize_image_edit_request_data(self, data: dict, resolved_request_url: str) -> dict: return self.azure_deployment_image_edit_form_data(data, resolved_request_url) diff --git a/litellm/llms/azure/passthrough/transformation.py b/litellm/llms/azure/passthrough/transformation.py index 9b1d95e53142..dabcd4a11830 100644 --- a/litellm/llms/azure/passthrough/transformation.py +++ b/litellm/llms/azure/passthrough/transformation.py @@ -62,9 +62,7 @@ def validate_environment( ) -> dict: return BaseAzureLLM._base_validate_azure_environment( headers=headers, - litellm_params=GenericLiteLLMParams( - **{**litellm_params, "api_key": api_key} - ), + litellm_params=GenericLiteLLMParams(**{**litellm_params, "api_key": api_key}), ) @staticmethod @@ -83,9 +81,7 @@ def get_api_key( def get_base_model(model: str) -> Optional[str]: return model - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: return super().get_models(api_key, api_base) def logging_non_streaming_response( diff --git a/litellm/llms/azure/realtime/handler.py b/litellm/llms/azure/realtime/handler.py index 9c8de6c06a14..86c1ed51b680 100644 --- a/litellm/llms/azure/realtime/handler.py +++ b/litellm/llms/azure/realtime/handler.py @@ -71,9 +71,7 @@ def _construct_url( if _is_ga: path = "/openai/v1/realtime" query_parts = [] - if intent != "transcription" and ( - query_params is None or "model" in query_params - ): + if intent != "transcription" and (query_params is None or "model" in query_params): query_parts.append(urlencode({"model": model})) else: # Default to beta path for backwards compatibility @@ -107,9 +105,7 @@ async def async_realtime( if api_base is None: raise ValueError("api_base is required for Azure OpenAI calls") - backend_uses_beta_protocol = ( - realtime_protocol is None or realtime_protocol.upper() not in ("GA", "V1") - ) + backend_uses_beta_protocol = realtime_protocol is None or realtime_protocol.upper() not in ("GA", "V1") if api_version is None and backend_uses_beta_protocol: raise ValueError("api_version is required for Azure OpenAI calls") @@ -140,9 +136,7 @@ async def async_realtime( request_data={"litellm_metadata": litellm_metadata or {}}, backend_uses_beta_protocol=backend_uses_beta_protocol, force_transcription_model=( - model - if (query_params or {}).get("intent") == "transcription" - else None + model if (query_params or {}).get("intent") == "transcription" else None ), ) await realtime_streaming.bidirectional_forward() @@ -150,7 +144,5 @@ async def async_realtime( except websockets.exceptions.InvalidStatusCode as e: # type: ignore await websocket.close(code=e.status_code, reason=_redact_string(str(e))) except Exception: - verbose_proxy_logger.exception( - "Error in AzureOpenAIRealtime.async_realtime" - ) + verbose_proxy_logger.exception("Error in AzureOpenAIRealtime.async_realtime") pass diff --git a/litellm/llms/azure/realtime/http_transformation.py b/litellm/llms/azure/realtime/http_transformation.py index d6bdbd24db43..55a860144234 100644 --- a/litellm/llms/azure/realtime/http_transformation.py +++ b/litellm/llms/azure/realtime/http_transformation.py @@ -14,9 +14,7 @@ def get_api_base(self, api_base: Optional[str], **kwargs) -> str: def get_api_key(self, api_key: Optional[str], **kwargs) -> str: return api_key or litellm.api_key or get_secret_str("AZURE_API_KEY") or "" - def get_complete_url( - self, api_base: Optional[str], model: str, api_version: Optional[str] = None - ) -> str: + def get_complete_url(self, api_base: Optional[str], model: str, api_version: Optional[str] = None) -> str: base = self.get_api_base(api_base).rstrip("/") version = api_version or get_secret_str("AZURE_API_VERSION") or "2024-12-17" return f"{base}/openai/realtime/client_secrets?api-version={version}" @@ -33,9 +31,7 @@ def validate_environment( "Content-Type": "application/json", } - def get_realtime_calls_url( - self, api_base: Optional[str], model: str, api_version: Optional[str] = None - ) -> str: + def get_realtime_calls_url(self, api_base: Optional[str], model: str, api_version: Optional[str] = None) -> str: base = self.get_api_base(api_base).rstrip("/") version = api_version or get_secret_str("AZURE_API_VERSION") or "2024-12-17" return f"{base}/openai/realtime/calls?api-version={version}" diff --git a/litellm/llms/azure/responses/o_series_transformation.py b/litellm/llms/azure/responses/o_series_transformation.py index 3a554e9e1940..2cc3e9143071 100644 --- a/litellm/llms/azure/responses/o_series_transformation.py +++ b/litellm/llms/azure/responses/o_series_transformation.py @@ -46,9 +46,7 @@ def get_supported_openai_params(self, model: str) -> list: # Filter out unsupported parameters for O-series models o_series_supported_params = [ - param - for param in base_supported_params - if param not in o_series_unsupported_params + param for param in base_supported_params if param not in o_series_unsupported_params ] return o_series_supported_params diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.py index 92ce5b492850..fef9b7d0154c 100644 --- a/litellm/llms/azure/responses/transformation.py +++ b/litellm/llms/azure/responses/transformation.py @@ -34,18 +34,10 @@ def get_supported_openai_params(self, model: str) -> list: Azure Responses API does not support context_management (compaction). """ base_supported_params = super().get_supported_openai_params(model) - return [ - param - for param in base_supported_params - if param not in self.AZURE_UNSUPPORTED_PARAMS - ] - - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: - return BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=litellm_params - ) + return [param for param in base_supported_params if param not in self.AZURE_UNSUPPORTED_PARAMS] + + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: + return BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=litellm_params) def get_stripped_model_name(self, model: str) -> str: # if "responses/" is in the model name, remove it @@ -82,22 +74,17 @@ def _handle_reasoning_item(self, item: Dict[str, Any]) -> Dict[str, Any]: return dict_reasoning_item except Exception as e: - verbose_logger.debug( - f"Failed to create ResponseReasoningItem, falling back to manual filtering: {e}" - ) + verbose_logger.debug(f"Failed to create ResponseReasoningItem, falling back to manual filtering: {e}") # Fallback: manually filter out known None fields filtered_item = { k: v for k, v in item.items() - if v is not None - or k not in {"status", "content", "encrypted_content"} + if v is not None or k not in {"status", "content", "encrypted_content"} } return filtered_item return item - def _validate_input_param( - self, input: Union[str, ResponseInputParam] - ) -> Union[str, ResponseInputParam]: + def _validate_input_param(self, input: Union[str, ResponseInputParam]) -> Union[str, ResponseInputParam]: """ Override parent method to also filter out 'status' field from message items. Azure OpenAI API does not accept 'status' field in input messages. @@ -209,11 +196,7 @@ def get_websocket_url( path = path[: -len(suffix)] break scheme = "wss" if parsed_url.scheme == "https" else "ws" - return str( - parsed_url.copy_with( - scheme=scheme, path=f"{path}/openai/v1/responses", query=None - ) - ) + return str(parsed_url.copy_with(scheme=scheme, path=f"{path}/openai/v1/responses", query=None)) def model_in_websocket_url(self) -> bool: # Azure sends the model in the response.create body, not the URL @@ -222,9 +205,7 @@ def model_in_websocket_url(self) -> bool: ######################################################### ########## DELETE RESPONSE API TRANSFORMATION ############## ######################################################### - def _construct_url_for_response_id_in_path( - self, api_base: str, response_id: str - ) -> str: + def _construct_url_for_response_id_in_path(self, api_base: str, response_id: str) -> str: """ Constructs a URL for the API request with the response_id in the path. """ @@ -236,9 +217,7 @@ def _construct_url_for_response_id_in_path( # Insert the response_id at the end of the path component # Remove trailing slash if present to avoid double slashes path = parsed_url.path.rstrip("/") - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") new_path = f"{path}/{encoded_response_id}" # Reconstruct the URL with all original components but with the modified path @@ -270,9 +249,7 @@ def transform_delete_response_api_request( This function handles URLs with query parameters by inserting the response_id at the correct location (before any query parameters). """ - delete_url = self._construct_url_for_response_id_in_path( - api_base=api_base, response_id=response_id - ) + delete_url = self._construct_url_for_response_id_in_path(api_base=api_base, response_id=response_id) data: Dict = {} verbose_logger.debug(f"delete response url={delete_url}") @@ -294,9 +271,7 @@ def transform_get_response_api_request( OpenAI API expects the following request - GET /v1/responses/{response_id} """ - get_url = self._construct_url_for_response_id_in_path( - api_base=api_base, response_id=response_id - ) + get_url = self._construct_url_for_response_id_in_path(api_base=api_base, response_id=response_id) data: Dict = {} verbose_logger.debug(f"get response url={get_url}") return get_url, data @@ -313,12 +288,7 @@ def transform_list_input_items_request( limit: int = 20, order: Literal["asc", "desc"] = "desc", ) -> Tuple[str, Dict]: - url = ( - self._construct_url_for_response_id_in_path( - api_base=api_base, response_id=response_id - ) - + "/input_items" - ) + url = self._construct_url_for_response_id_in_path(api_base=api_base, response_id=response_id) + "/input_items" params: Dict[str, Any] = {} if after is not None: params["after"] = after @@ -360,9 +330,7 @@ def transform_cancel_response_api_request( # Insert the response_id and /cancel at the end of the path component # Remove trailing slash if present to avoid double slashes path = parsed_url.path.rstrip("/") - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") new_path = f"{path}/{encoded_response_id}/cancel" # Reconstruct the URL with all original components but with the modified path @@ -394,7 +362,5 @@ def transform_cancel_response_api_response( except Exception: from litellm.llms.azure.chat.gpt_transformation import AzureOpenAIError - raise AzureOpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise AzureOpenAIError(message=raw_response.text, status_code=raw_response.status_code) return ResponsesAPIResponse(**raw_response_json) diff --git a/litellm/llms/azure/text_to_speech/transformation.py b/litellm/llms/azure/text_to_speech/transformation.py index a5dec243147f..c3e5f16b03af 100644 --- a/litellm/llms/azure/text_to_speech/transformation.py +++ b/litellm/llms/azure/text_to_speech/transformation.py @@ -86,10 +86,7 @@ def dispatch_text_to_speech( """ # Resolve api_base from multiple sources api_base = ( - api_base - or litellm_params_dict.get("api_base") - or litellm.api_base - or get_secret_str("AZURE_API_BASE") + api_base or litellm_params_dict.get("api_base") or litellm.api_base or get_secret_str("AZURE_API_BASE") ) # Resolve api_key from multiple sources (Azure-specific) @@ -337,9 +334,7 @@ def get_complete_url( # Check if it's a Cognitive Services endpoint (convert to TTS endpoint) if self._is_cognitive_services_endpoint(hostname=hostname): - region = self._extract_region_from_hostname( - hostname=hostname, domain=self.COGNITIVE_SERVICES_DOMAIN - ) + region = self._extract_region_from_hostname(hostname=hostname, domain=self.COGNITIVE_SERVICES_DOMAIN) return self._build_tts_url(region=region) # Check if it's already a TTS endpoint @@ -353,15 +348,11 @@ def get_complete_url( def _is_cognitive_services_endpoint(self, hostname: str) -> bool: """Check if hostname is a Cognitive Services endpoint""" - return hostname == self.COGNITIVE_SERVICES_DOMAIN or hostname.endswith( - f".{self.COGNITIVE_SERVICES_DOMAIN}" - ) + return hostname == self.COGNITIVE_SERVICES_DOMAIN or hostname.endswith(f".{self.COGNITIVE_SERVICES_DOMAIN}") def _is_tts_endpoint(self, hostname: str) -> bool: """Check if hostname is a TTS endpoint""" - return hostname == self.TTS_SPEECH_DOMAIN or hostname.endswith( - f".{self.TTS_SPEECH_DOMAIN}" - ) + return hostname == self.TTS_SPEECH_DOMAIN or hostname.endswith(f".{self.TTS_SPEECH_DOMAIN}") def _extract_region_from_hostname(self, hostname: str, domain: str) -> str: """ @@ -419,9 +410,7 @@ def transform_text_to_speech_request( azure_voice = voice or self.DEFAULT_VOICE # Get output format (already mapped in main.py) - output_format = optional_params.get( - "output_format", "audio-24khz-48kbitrate-mono-mp3" - ) + output_format = optional_params.get("output_format", "audio-24khz-48kbitrate-mono-mp3") headers["X-Microsoft-OutputFormat"] = output_format # Auto-detect SSML: if input contains , pass it through as-is diff --git a/litellm/llms/azure/vector_stores/transformation.py b/litellm/llms/azure/vector_stores/transformation.py index a98e7ae8cb64..c340294c6b45 100644 --- a/litellm/llms/azure/vector_stores/transformation.py +++ b/litellm/llms/azure/vector_stores/transformation.py @@ -17,9 +17,5 @@ def get_complete_url( route="/openai/vector_stores", ) - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: - return BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=litellm_params - ) + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: + return BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=litellm_params) diff --git a/litellm/llms/azure/videos/transformation.py b/litellm/llms/azure/videos/transformation.py index 1ee0e95fb0a5..92e7c91fed38 100644 --- a/litellm/llms/azure/videos/transformation.py +++ b/litellm/llms/azure/videos/transformation.py @@ -72,9 +72,7 @@ def validate_environment( # Use the base Azure validation method which properly handles: # 1. Credentials from litellm_credential_name via litellm_params # 2. Sets the correct "api-key" header (not "Authorization: Bearer") - return BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=litellm_params - ) + return BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=litellm_params) def get_complete_url( self, diff --git a/litellm/llms/azure_ai/agents/handler.py b/litellm/llms/azure_ai/agents/handler.py index 9bae8abce8e8..6083580ed450 100644 --- a/litellm/llms/azure_ai/agents/handler.py +++ b/litellm/llms/azure_ai/agents/handler.py @@ -73,32 +73,22 @@ def __init__(self): def _build_thread_url(self, api_base: str, api_version: str) -> str: return f"{api_base}/threads?api-version={api_version}" - def _build_messages_url( - self, api_base: str, thread_id: str, api_version: str - ) -> str: + def _build_messages_url(self, api_base: str, thread_id: str, api_version: str) -> str: encoded_thread_id = encode_url_path_segment(thread_id, field_name="thread_id") - return ( - f"{api_base}/threads/{encoded_thread_id}/messages?api-version={api_version}" - ) + return f"{api_base}/threads/{encoded_thread_id}/messages?api-version={api_version}" def _build_runs_url(self, api_base: str, thread_id: str, api_version: str) -> str: encoded_thread_id = encode_url_path_segment(thread_id, field_name="thread_id") return f"{api_base}/threads/{encoded_thread_id}/runs?api-version={api_version}" - def _build_run_status_url( - self, api_base: str, thread_id: str, run_id: str, api_version: str - ) -> str: + def _build_run_status_url(self, api_base: str, thread_id: str, run_id: str, api_version: str) -> str: encoded_thread_id = encode_url_path_segment(thread_id, field_name="thread_id") encoded_run_id = encode_url_path_segment(run_id, field_name="run_id") return f"{api_base}/threads/{encoded_thread_id}/runs/{encoded_run_id}?api-version={api_version}" - def _build_list_messages_url( - self, api_base: str, thread_id: str, api_version: str - ) -> str: + def _build_list_messages_url(self, api_base: str, thread_id: str, api_version: str) -> str: encoded_thread_id = encode_url_path_segment(thread_id, field_name="thread_id") - return ( - f"{api_base}/threads/{encoded_thread_id}/messages?api-version={api_version}" - ) + return f"{api_base}/threads/{encoded_thread_id}/messages?api-version={api_version}" def _build_create_thread_and_run_url(self, api_base: str, api_version: str) -> str: """URL for the create-thread-and-run endpoint (supports streaming).""" @@ -107,9 +97,7 @@ def _build_create_thread_and_run_url(self, api_base: str, api_version: str) -> s # ------------------------------------------------------------------------- # Response Helpers # ------------------------------------------------------------------------- - def _extract_content_from_messages( - self, messages_data: dict - ) -> Tuple[str, Optional[List[Dict[str, Any]]]]: + def _extract_content_from_messages(self, messages_data: dict) -> Tuple[str, Optional[List[Dict[str, Any]]]]: """Extract assistant content and annotations from the messages response. Returns (content, annotations) where annotations is a list of @@ -190,10 +178,7 @@ def _build_model_response( model_response.model = model # Store thread_id for conversation continuity - if ( - not hasattr(model_response, "_hidden_params") - or model_response._hidden_params is None - ): + if not hasattr(model_response, "_hidden_params") or model_response._hidden_params is None: model_response._hidden_params = {} model_response._hidden_params["thread_id"] = thread_id @@ -202,9 +187,7 @@ def _build_model_response( from litellm.utils import token_counter prompt_tokens = token_counter(model="gpt-3.5-turbo", messages=messages) - completion_tokens = token_counter( - model="gpt-3.5-turbo", text=content, count_response_tokens=True - ) + completion_tokens = token_counter(model="gpt-3.5-turbo", text=content, count_response_tokens=True) setattr( model_response, "usage", @@ -243,22 +226,16 @@ def _prepare_completion_params( if api_key: headers["Authorization"] = f"Bearer {api_key}" - api_version = optional_params.get( - "api_version", self.config.DEFAULT_API_VERSION - ) + api_version = optional_params.get("api_version", self.config.DEFAULT_API_VERSION) agent_id = self.config._get_agent_id(model, optional_params) thread_id = optional_params.get("thread_id") api_base = api_base.rstrip("/") - verbose_logger.debug( - f"Azure AI Agents completion - api_base: {api_base}, agent_id: {agent_id}" - ) + verbose_logger.debug(f"Azure AI Agents completion - api_base: {api_base}, agent_id: {agent_id}") return headers, api_version, agent_id, thread_id, api_base - def _check_response( - self, response: httpx.Response, expected_codes: List[int], error_msg: str - ): + def _check_response(self, response: httpx.Response, expected_codes: List[int], error_msg: str): """Check response status and raise error if not expected.""" if response.status_code not in expected_codes: raise AzureAIAgentsError( @@ -287,9 +264,7 @@ def completion( from litellm.llms.custom_httpx.http_handler import _get_httpx_client if client is None: - client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) ( headers, @@ -297,13 +272,9 @@ def completion( agent_id, thread_id, api_base, - ) = self._prepare_completion_params( - model, api_base, api_key, optional_params, headers - ) + ) = self._prepare_completion_params(model, api_base, api_key, optional_params, headers) - def make_request( - method: str, url: str, json_data: Optional[dict] = None - ) -> httpx.Response: + def make_request(method: str, url: str, json_data: Optional[dict] = None) -> httpx.Response: if method == "GET": return client.get(url=url, headers=headers) return client.post( @@ -323,9 +294,7 @@ def make_request( optional_params=optional_params, ) - return self._build_model_response( - model, content, model_response, thread_id, messages, annotations - ) + return self._build_model_response(model, content, model_response, thread_id, messages, annotations) def _execute_agent_flow_sync( self, @@ -341,12 +310,8 @@ def _execute_agent_flow_sync( # Step 1: Create thread if not provided if not thread_id: - verbose_logger.debug( - f"Creating thread at: {self._build_thread_url(api_base, api_version)}" - ) - response = make_request( - "POST", self._build_thread_url(api_base, api_version), {} - ) + verbose_logger.debug(f"Creating thread at: {self._build_thread_url(api_base, api_version)}") + response = make_request("POST", self._build_thread_url(api_base, api_version), {}) self._check_response(response, [200, 201], "Failed to create thread") thread_id = response.json()["id"] verbose_logger.debug(f"Created thread: {thread_id}") @@ -358,9 +323,7 @@ def _execute_agent_flow_sync( for msg in messages: if msg.get("role") in ["user", "system"]: url = self._build_messages_url(api_base, thread_id, api_version) - response = make_request( - "POST", url, {"role": "user", "content": msg.get("content", "")} - ) + response = make_request("POST", url, {"role": "user", "content": msg.get("content", "")}) self._check_response(response, [200, 201], "Failed to add message") # Step 3: Create run @@ -368,17 +331,13 @@ def _execute_agent_flow_sync( if "instructions" in optional_params: run_payload["instructions"] = optional_params["instructions"] - response = make_request( - "POST", self._build_runs_url(api_base, thread_id, api_version), run_payload - ) + response = make_request("POST", self._build_runs_url(api_base, thread_id, api_version), run_payload) self._check_response(response, [200, 201], "Failed to create run") run_id = response.json()["id"] verbose_logger.debug(f"Created run: {run_id}") # Step 4: Poll for completion - status_url = self._build_run_status_url( - api_base, thread_id, run_id, api_version - ) + status_url = self._build_run_status_url(api_base, thread_id, run_id, api_version) for _ in range(self.config.MAX_POLL_ATTEMPTS): response = make_request("GET", status_url) self._check_response(response, [200], "Failed to get run status") @@ -389,25 +348,15 @@ def _execute_agent_flow_sync( if status == "completed": break elif status in ["failed", "cancelled", "expired"]: - error_msg = ( - response.json() - .get("last_error", {}) - .get("message", "Unknown error") - ) - raise AzureAIAgentsError( - status_code=500, message=f"Run {status}: {error_msg}" - ) + error_msg = response.json().get("last_error", {}).get("message", "Unknown error") + raise AzureAIAgentsError(status_code=500, message=f"Run {status}: {error_msg}") time.sleep(self.config.POLL_INTERVAL_SECONDS) else: - raise AzureAIAgentsError( - status_code=408, message="Run timed out waiting for completion" - ) + raise AzureAIAgentsError(status_code=408, message="Run timed out waiting for completion") # Step 5: Get messages - response = make_request( - "GET", self._build_list_messages_url(api_base, thread_id, api_version) - ) + response = make_request("GET", self._build_list_messages_url(api_base, thread_id, api_version)) self._check_response(response, [200], "Failed to get messages") content, annotations = self._extract_content_from_messages(response.json()) @@ -446,13 +395,9 @@ async def acompletion( agent_id, thread_id, api_base, - ) = self._prepare_completion_params( - model, api_base, api_key, optional_params, headers - ) + ) = self._prepare_completion_params(model, api_base, api_key, optional_params, headers) - async def make_request( - method: str, url: str, json_data: Optional[dict] = None - ) -> httpx.Response: + async def make_request(method: str, url: str, json_data: Optional[dict] = None) -> httpx.Response: if method == "GET": return await client.get(url=url, headers=headers) return await client.post( @@ -472,9 +417,7 @@ async def make_request( optional_params=optional_params, ) - return self._build_model_response( - model, content, model_response, thread_id, messages, annotations - ) + return self._build_model_response(model, content, model_response, thread_id, messages, annotations) async def _execute_agent_flow_async( self, @@ -490,12 +433,8 @@ async def _execute_agent_flow_async( # Step 1: Create thread if not provided if not thread_id: - verbose_logger.debug( - f"Creating thread at: {self._build_thread_url(api_base, api_version)}" - ) - response = await make_request( - "POST", self._build_thread_url(api_base, api_version), {} - ) + verbose_logger.debug(f"Creating thread at: {self._build_thread_url(api_base, api_version)}") + response = await make_request("POST", self._build_thread_url(api_base, api_version), {}) self._check_response(response, [200, 201], "Failed to create thread") thread_id = response.json()["id"] verbose_logger.debug(f"Created thread: {thread_id}") @@ -507,9 +446,7 @@ async def _execute_agent_flow_async( for msg in messages: if msg.get("role") in ["user", "system"]: url = self._build_messages_url(api_base, thread_id, api_version) - response = await make_request( - "POST", url, {"role": "user", "content": msg.get("content", "")} - ) + response = await make_request("POST", url, {"role": "user", "content": msg.get("content", "")}) self._check_response(response, [200, 201], "Failed to add message") # Step 3: Create run @@ -517,17 +454,13 @@ async def _execute_agent_flow_async( if "instructions" in optional_params: run_payload["instructions"] = optional_params["instructions"] - response = await make_request( - "POST", self._build_runs_url(api_base, thread_id, api_version), run_payload - ) + response = await make_request("POST", self._build_runs_url(api_base, thread_id, api_version), run_payload) self._check_response(response, [200, 201], "Failed to create run") run_id = response.json()["id"] verbose_logger.debug(f"Created run: {run_id}") # Step 4: Poll for completion - status_url = self._build_run_status_url( - api_base, thread_id, run_id, api_version - ) + status_url = self._build_run_status_url(api_base, thread_id, run_id, api_version) for _ in range(self.config.MAX_POLL_ATTEMPTS): response = await make_request("GET", status_url) self._check_response(response, [200], "Failed to get run status") @@ -538,25 +471,15 @@ async def _execute_agent_flow_async( if status == "completed": break elif status in ["failed", "cancelled", "expired"]: - error_msg = ( - response.json() - .get("last_error", {}) - .get("message", "Unknown error") - ) - raise AzureAIAgentsError( - status_code=500, message=f"Run {status}: {error_msg}" - ) + error_msg = response.json().get("last_error", {}).get("message", "Unknown error") + raise AzureAIAgentsError(status_code=500, message=f"Run {status}: {error_msg}") await asyncio.sleep(self.config.POLL_INTERVAL_SECONDS) else: - raise AzureAIAgentsError( - status_code=408, message="Run timed out waiting for completion" - ) + raise AzureAIAgentsError(status_code=408, message="Run timed out waiting for completion") # Step 5: Get messages - response = await make_request( - "GET", self._build_list_messages_url(api_base, thread_id, api_version) - ) + response = await make_request("GET", self._build_list_messages_url(api_base, thread_id, api_version)) self._check_response(response, [200], "Failed to get messages") content, annotations = self._extract_content_from_messages(response.json()) @@ -587,17 +510,13 @@ async def acompletion_stream( agent_id, thread_id, api_base, - ) = self._prepare_completion_params( - model, api_base, api_key, optional_params, headers - ) + ) = self._prepare_completion_params(model, api_base, api_key, optional_params, headers) # Build payload for create-thread-and-run with streaming thread_messages = [] for msg in messages: if msg.get("role") in ["user", "system"]: - thread_messages.append( - {"role": "user", "content": msg.get("content", "")} - ) + thread_messages.append({"role": "user", "content": msg.get("content", "")}) payload: Dict[str, Any] = { "assistant_id": agent_id, @@ -699,9 +618,7 @@ async def _process_sse_stream( if current_event == "thread.message.completed": for content_item in data.get("content", []): if content_item.get("type") == "text": - raw_annotations = content_item.get("text", {}).get( - "annotations" - ) + raw_annotations = content_item.get("text", {}).get("annotations") transformed = self._transform_annotations(raw_annotations) if transformed: if collected_annotations is None: @@ -724,9 +641,7 @@ async def _process_sse_stream( StreamingChoices( finish_reason=None, index=0, - delta=Delta( - content=text_value, role="assistant" - ), + delta=Delta(content=text_value, role="assistant"), ) ], ) diff --git a/litellm/llms/azure_ai/agents/transformation.py b/litellm/llms/azure_ai/agents/transformation.py index 777509fa82ce..daf87b015797 100644 --- a/litellm/llms/azure_ai/agents/transformation.py +++ b/litellm/llms/azure_ai/agents/transformation.py @@ -178,9 +178,7 @@ def _get_agent_id(self, model: str, optional_params: dict) -> str: model format: "azure_ai/agents/" or "agents/" or just "" """ - agent_id = optional_params.get("agent_id") or optional_params.get( - "assistant_id" - ) + agent_id = optional_params.get("agent_id") or optional_params.get("assistant_id") if agent_id: return agent_id diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py index e24fc2097d2e..0716e5ae988b 100644 --- a/litellm/llms/azure_ai/anthropic/count_tokens/handler.py +++ b/litellm/llms/azure_ai/anthropic/count_tokens/handler.py @@ -56,9 +56,7 @@ async def handle_count_tokens_request( # Validate the request self.validate_request(model, messages) - verbose_logger.debug( - f"Processing Azure AI Anthropic CountTokens request for model: {model}" - ) + verbose_logger.debug(f"Processing Azure AI Anthropic CountTokens request for model: {model}") # Transform request to Anthropic format request_body = self.transform_request_to_count_tokens( @@ -82,14 +80,10 @@ async def handle_count_tokens_request( ) # Use LiteLLM's async httpx client - async_client = get_async_httpx_client( - llm_provider=litellm.LlmProviders.AZURE_AI - ) + async_client = get_async_httpx_client(llm_provider=litellm.LlmProviders.AZURE_AI) # Use provided timeout or fall back to litellm.request_timeout - request_timeout = ( - timeout if timeout is not None else litellm.request_timeout - ) + request_timeout = timeout if timeout is not None else litellm.request_timeout response = await async_client.post( endpoint_url, diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py b/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py index afdfe9bdee95..8e1ee73620ff 100644 --- a/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py +++ b/litellm/llms/azure_ai/anthropic/count_tokens/token_counter.py @@ -107,9 +107,7 @@ async def count_tokens( status_code=e.status_code, ) except Exception as e: - verbose_logger.warning( - f"Error calling Azure AI Anthropic CountTokens API: {e}" - ) + verbose_logger.warning(f"Error calling Azure AI Anthropic CountTokens API: {e}") return TokenCountResponse( total_tokens=0, request_model=request_model, diff --git a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py index 09b83b7c9719..5e1fb69f40d2 100644 --- a/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py +++ b/litellm/llms/azure_ai/anthropic/count_tokens/transformation.py @@ -56,9 +56,7 @@ def get_required_headers( litellm_params_obj = GenericLiteLLMParams(**litellm_params) # Get Azure auth headers (api-key or Authorization) - azure_headers = BaseAzureLLM._base_validate_azure_environment( - headers={}, litellm_params=litellm_params_obj - ) + azure_headers = BaseAzureLLM._base_validate_azure_environment(headers={}, litellm_params=litellm_params_obj) # Merge Azure auth headers headers.update(azure_headers) diff --git a/litellm/llms/azure_ai/anthropic/handler.py b/litellm/llms/azure_ai/anthropic/handler.py index f3a50b73c1a9..d510e5bd13ee 100644 --- a/litellm/llms/azure_ai/anthropic/handler.py +++ b/litellm/llms/azure_ai/anthropic/handler.py @@ -119,11 +119,7 @@ def completion( logger_fn=logger_fn, headers=headers, timeout=timeout, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), ) else: return self.acompletion_function( diff --git a/litellm/llms/azure_ai/anthropic/messages_transformation.py b/litellm/llms/azure_ai/anthropic/messages_transformation.py index 59b6ee2b4248..1de18701a2f3 100644 --- a/litellm/llms/azure_ai/anthropic/messages_transformation.py +++ b/litellm/llms/azure_ai/anthropic/messages_transformation.py @@ -49,9 +49,7 @@ def validate_anthropic_messages_environment( litellm_params_obj.api_key = api_key # Use Azure authentication logic - headers = BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=litellm_params_obj - ) + headers = BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=litellm_params_obj) # Azure Anthropic uses x-api-key header (not api-key) # Convert api-key to x-api-key if present @@ -118,9 +116,7 @@ def get_complete_url( return api_base - def _remove_scope_from_cache_control( - self, anthropic_messages_request: Dict - ) -> None: + def _remove_scope_from_cache_control(self, anthropic_messages_request: Dict) -> None: """ Remove `scope` field from cache_control for Azure AI Foundry. diff --git a/litellm/llms/azure_ai/anthropic/transformation.py b/litellm/llms/azure_ai/anthropic/transformation.py index 367ca75c196e..26323ba707dc 100644 --- a/litellm/llms/azure_ai/anthropic/transformation.py +++ b/litellm/llms/azure_ai/anthropic/transformation.py @@ -74,17 +74,13 @@ def validate_environment( litellm_params_obj.api_key = api_key # Use Azure authentication logic - headers = BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=litellm_params_obj - ) + headers = BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=litellm_params_obj) # Get tools and other anthropic-specific setup tools = optional_params.get("tools") prompt_caching_set = self.is_cache_control_set(messages=messages) computer_tool_used = self.is_computer_tool_used(tools=tools) - mcp_server_used = self.is_mcp_server_used( - mcp_servers=optional_params.get("mcp_servers") - ) + mcp_server_used = self.is_mcp_server_used(mcp_servers=optional_params.get("mcp_servers")) pdf_used = self.is_pdf_used(messages=messages) file_id_used = self.is_file_id_used(messages=messages) user_anthropic_beta_headers = self._get_user_anthropic_beta_headers( diff --git a/litellm/llms/azure_ai/azure_model_router/transformation.py b/litellm/llms/azure_ai/azure_model_router/transformation.py index e4174f41ad72..f30452838409 100644 --- a/litellm/llms/azure_ai/azure_model_router/transformation.py +++ b/litellm/llms/azure_ai/azure_model_router/transformation.py @@ -44,9 +44,7 @@ def transform_request( # Get base model name (strips routing prefixes like model_router/) base_model: str = AzureFoundryModelInfo.get_base_model(model) - return super().transform_request( - base_model, messages, optional_params, litellm_params, headers - ) + return super().transform_request(base_model, messages, optional_params, litellm_params, headers) def transform_response( self, @@ -90,9 +88,7 @@ def transform_response( ) return model_response - def calculate_additional_costs( - self, model: str, prompt_tokens: int, completion_tokens: int - ) -> Optional[dict]: + def calculate_additional_costs(self, model: str, prompt_tokens: int, completion_tokens: int) -> Optional[dict]: """ Calculate additional costs for Azure Model Router. @@ -110,9 +106,7 @@ def calculate_additional_costs( calculate_azure_model_router_flat_cost, ) - flat_cost = calculate_azure_model_router_flat_cost( - model=model, prompt_tokens=prompt_tokens - ) + flat_cost = calculate_azure_model_router_flat_cost(model=model, prompt_tokens=prompt_tokens) if flat_cost > 0: return {"Azure Model Router Flat Cost": flat_cost} diff --git a/litellm/llms/azure_ai/chat/transformation.py b/litellm/llms/azure_ai/chat/transformation.py index 008a8a766e9b..27a983470877 100644 --- a/litellm/llms/azure_ai/chat/transformation.py +++ b/litellm/llms/azure_ai/chat/transformation.py @@ -74,12 +74,8 @@ def validate_environment( headers["Authorization"] = f"Bearer {api_key}" else: # No api_key provided — fall back to Azure AD token-based auth - litellm_params_obj = GenericLiteLLMParams( - **(litellm_params if isinstance(litellm_params, dict) else {}) - ) - headers = BaseAzureLLM._base_validate_azure_environment( - headers=headers, litellm_params=litellm_params_obj - ) + litellm_params_obj = GenericLiteLLMParams(**(litellm_params if isinstance(litellm_params, dict) else {})) + headers = BaseAzureLLM._base_validate_azure_environment(headers=headers, litellm_params=litellm_params_obj) headers["Content-Type"] = "application/json" @@ -91,10 +87,7 @@ def _should_use_api_key_header(self, api_base: str) -> bool: """ parsed_url = urlparse(api_base) host = parsed_url.hostname - if host and ( - host.endswith(".services.ai.azure.com") - or host.endswith(".openai.azure.com") - ): + if host and (host.endswith(".services.ai.azure.com") or host.endswith(".openai.azure.com")): return True return False @@ -141,13 +134,9 @@ def get_complete_url( # Add the path to the base URL if "services.ai.azure.com" in api_base: - new_url = _add_path_to_api_base( - api_base=api_base, ending_path="/models/chat/completions" - ) + new_url = _add_path_to_api_base(api_base=api_base, ending_path="/models/chat/completions") else: - new_url = _add_path_to_api_base( - api_base=api_base, ending_path="/chat/completions" - ) + new_url = _add_path_to_api_base(api_base=api_base, ending_path="/chat/completions") # Use the new query_params dictionary final_url = httpx.URL(new_url).copy_with(params=query_params) @@ -217,11 +206,7 @@ def _get_openai_compatible_provider_info( dynamic_api_key = api_key or get_secret_str("AZURE_AI_API_KEY") if self._is_azure_openai_model(model=model, api_base=api_base): - verbose_logger.debug( - "Model={} is Azure OpenAI model. Setting custom_llm_provider='azure'.".format( - model - ) - ) + verbose_logger.debug("Model={} is Azure OpenAI model. Setting custom_llm_provider='azure'.".format(model)) custom_llm_provider = "azure" return api_base, dynamic_api_key, custom_llm_provider @@ -237,9 +222,7 @@ def transform_request( if extra_body and isinstance(extra_body, dict): optional_params.update(extra_body) optional_params.pop("max_retries", None) - return super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + return super().transform_request(model, messages, optional_params, litellm_params, headers) def transform_response( self, @@ -277,20 +260,13 @@ def should_retry_llm_api_inside_llm_translation_on_http_error( error_text = e.response.text if "Extra inputs are not permitted" in error_text: - if should_drop_params or self._error_has_tool_level_extra_fields( - error_text - ): + if should_drop_params or self._error_has_tool_level_extra_fields(error_text): return True if "unknown field: parameter index is not a valid field" in error_text: return True - if ( - AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value - in error_text - ): + if AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value in error_text: return True - return super().should_retry_llm_api_inside_llm_translation_on_http_error( - e=e, litellm_params=litellm_params - ) + return super().should_retry_llm_api_inside_llm_translation_on_http_error(e=e, litellm_params=litellm_params) def _error_has_tool_level_extra_fields(self, error_text: str) -> bool: return bool(re.search(r"tools\[\d+\]\.", error_text)) @@ -299,36 +275,21 @@ def _error_has_tool_level_extra_fields(self, error_text: str) -> bool: def max_retry_on_unprocessable_entity_error(self) -> int: return 2 - def transform_request_on_unprocessable_entity_error( - self, e: httpx.HTTPStatusError, request_data: dict - ) -> dict: + def transform_request_on_unprocessable_entity_error(self, e: httpx.HTTPStatusError, request_data: dict) -> dict: error_text = e.response.text _messages = cast(Optional[List[AllMessageValues]], request_data.get("messages")) - if ( - "unknown field: parameter index is not a valid field" in error_text - and _messages is not None - ): + if "unknown field: parameter index is not a valid field" in error_text and _messages is not None: litellm.remove_index_from_tool_calls( messages=_messages, ) - elif ( - AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value - in error_text - ): - request_data = self._drop_extra_params_from_request_data( - request_data, error_text - ) - if ( - "Extra inputs are not permitted" in error_text - and self._error_has_tool_level_extra_fields(error_text) - ): + elif AzureFoundryErrorStrings.SET_EXTRA_PARAMETERS_TO_PASS_THROUGH.value in error_text: + request_data = self._drop_extra_params_from_request_data(request_data, error_text) + if "Extra inputs are not permitted" in error_text and self._error_has_tool_level_extra_fields(error_text): request_data = self._drop_tool_level_extra_fields(request_data, error_text) data = drop_params_from_unprocessable_entity_error(e=e, data=request_data) return data - def _drop_tool_level_extra_fields( - self, request_data: dict, error_text: str - ) -> dict: + def _drop_tool_level_extra_fields(self, request_data: dict, error_text: str) -> dict: fields_to_drop = set(re.findall(r"tools\[\d+\]\.([\w-]+)", error_text)) tools = request_data.get("tools") if fields_to_drop and isinstance(tools, list): @@ -338,9 +299,7 @@ def _drop_tool_level_extra_fields( tool.pop(field, None) return request_data - def _drop_extra_params_from_request_data( - self, request_data: dict, error_text: str - ) -> dict: + def _drop_extra_params_from_request_data(self, request_data: dict, error_text: str) -> dict: params_to_drop = self._extract_params_to_drop_from_error_text(error_text) if params_to_drop: for param in params_to_drop: @@ -348,9 +307,7 @@ def _drop_extra_params_from_request_data( request_data.pop(param, None) return request_data - def _extract_params_to_drop_from_error_text( - self, error_text: str - ) -> Optional[List[str]]: + def _extract_params_to_drop_from_error_text(self, error_text: str) -> Optional[List[str]]: """ Error text looks like this" "Extra parameters ['stream_options', 'extra-parameters'] are not allowed when extra-parameters is not set or set to be 'error'. diff --git a/litellm/llms/azure_ai/common_utils.py b/litellm/llms/azure_ai/common_utils.py index ecb36b204276..9965aa693c39 100644 --- a/litellm/llms/azure_ai/common_utils.py +++ b/litellm/llms/azure_ai/common_utils.py @@ -43,18 +43,11 @@ def get_api_base(api_base: Optional[str] = None) -> Optional[str]: @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: - return ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("AZURE_AI_API_KEY") - ) + return api_key or litellm.api_key or litellm.openai_key or get_secret_str("AZURE_AI_API_KEY") @property def api_version(self, api_version: Optional[str] = None) -> Optional[str]: - api_version = ( - api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") - ) + api_version = api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") return api_version def get_token_counter(self) -> Optional[BaseTokenCounter]: @@ -73,9 +66,7 @@ def get_token_counter(self) -> Optional[BaseTokenCounter]: return AzureAIAnthropicTokenCounter() return None - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: """ Returns a list of models supported by Azure AI. @@ -171,6 +162,4 @@ def validate_environment( api_base: Optional[str] = None, ) -> dict: """Azure Foundry sends api key in query params""" - raise NotImplementedError( - "Azure Foundry does not support environment validation" - ) + raise NotImplementedError("Azure Foundry does not support environment validation") diff --git a/litellm/llms/azure_ai/cost_calculator.py b/litellm/llms/azure_ai/cost_calculator.py index 755d44fdef75..e9c8cac00784 100644 --- a/litellm/llms/azure_ai/cost_calculator.py +++ b/litellm/llms/azure_ai/cost_calculator.py @@ -28,11 +28,7 @@ def _is_azure_model_router(model: str) -> bool: bool: True if this is a model router model """ model_lower = model.lower() - return ( - "model-router" in model_lower - or "model_router" in model_lower - or model_lower == "azure-model-router" - ) + return "model-router" in model_lower or "model_router" in model_lower or model_lower == "azure-model-router" def calculate_azure_model_router_flat_cost(model: str, prompt_tokens: int) -> float: @@ -121,9 +117,7 @@ def cost_per_token( if is_router_request: # Use the request model for flat cost calculation if available, otherwise use response model router_model_for_calc = request_model if request_model else model - router_flat_cost = calculate_azure_model_router_flat_cost( - router_model_for_calc, usage.prompt_tokens - ) + router_flat_cost = calculate_azure_model_router_flat_cost(router_model_for_calc, usage.prompt_tokens) if router_flat_cost > 0: verbose_logger.debug( diff --git a/litellm/llms/azure_ai/embed/cohere_transformation.py b/litellm/llms/azure_ai/embed/cohere_transformation.py index bbbfb60fbdea..8a28d2f652a1 100644 --- a/litellm/llms/azure_ai/embed/cohere_transformation.py +++ b/litellm/llms/azure_ai/embed/cohere_transformation.py @@ -29,9 +29,7 @@ def _map_azure_model_group(self, model: str) -> str: return model - def _transform_request_image_embeddings( - self, input: List[str], optional_params: dict - ) -> ImageEmbeddingRequest: + def _transform_request_image_embeddings(self, input: List[str], optional_params: dict) -> ImageEmbeddingRequest: """ Assume all str in list is base64 encoded string """ @@ -60,13 +58,9 @@ def _transform_request( image_embedding_idx.append(idx) ## REMOVE IMAGE EMBEDDINGS FROM input list - filtered_input = [ - item for idx, item in enumerate(input) if idx not in image_embedding_idx - ] + filtered_input = [item for idx, item in enumerate(input) if idx not in image_embedding_idx] - v1_embeddings_request = EmbeddingCreateParams( - input=filtered_input, model=model, **optional_params - ) + v1_embeddings_request = EmbeddingCreateParams(input=filtered_input, model=model, **optional_params) image_embeddings_request = self._transform_request_image_embeddings( input=image_embeddings, optional_params=optional_params ) @@ -74,14 +68,10 @@ def _transform_request( return image_embeddings_request, v1_embeddings_request, image_embedding_idx def _transform_response(self, response: EmbeddingResponse) -> EmbeddingResponse: - additional_headers: Optional[dict] = response._hidden_params.get( - "additional_headers" - ) + additional_headers: Optional[dict] = response._hidden_params.get("additional_headers") if additional_headers: # CALCULATE USAGE - input_tokens: Optional[str] = additional_headers.get( - "llm_provider-num_tokens" - ) + input_tokens: Optional[str] = additional_headers.get("llm_provider-num_tokens") if input_tokens: if response.usage: response.usage.prompt_tokens = int(input_tokens) @@ -89,9 +79,7 @@ def _transform_response(self, response: EmbeddingResponse) -> EmbeddingResponse: response.usage = Usage(prompt_tokens=int(input_tokens)) # SET MODEL - base_model: Optional[str] = additional_headers.get( - "llm_provider-azureml-model-group" - ) + base_model: Optional[str] = additional_headers.get("llm_provider-azureml-model-group") if base_model: response.model = self._map_azure_model_group(base_model) diff --git a/litellm/llms/azure_ai/embed/handler.py b/litellm/llms/azure_ai/embed/handler.py index 67733d1ccb59..62c80bd2568f 100644 --- a/litellm/llms/azure_ai/embed/handler.py +++ b/litellm/llms/azure_ai/embed/handler.py @@ -26,10 +26,7 @@ def _process_response( input: List, ): combined_responses = [] - if ( - image_embedding_responses is not None - and text_embedding_responses is not None - ): + if image_embedding_responses is not None and text_embedding_responses is not None: # Combine and order the results text_idx = 0 image_idx = 0 @@ -148,9 +145,7 @@ async def async_embedding( image_embeddings_request, v1_embeddings_request, image_embeddings_idx, - ) = AzureAICohereConfig()._transform_request( - input=input, optional_params=optional_params, model=model - ) + ) = AzureAICohereConfig()._transform_request(input=input, optional_params=optional_params, model=model) image_embedding_responses: Optional[List] = None text_embedding_responses: Optional[List] = None @@ -236,9 +231,7 @@ def embedding( image_embeddings_request, v1_embeddings_request, image_embeddings_idx, - ) = AzureAICohereConfig()._transform_request( - input=input, optional_params=optional_params, model=model - ) + ) = AzureAICohereConfig()._transform_request(input=input, optional_params=optional_params, model=model) image_embedding_responses: Optional[List] = None text_embedding_responses: Optional[List] = None @@ -270,11 +263,7 @@ def embedding( optional_params, api_key, api_base, - client=( - client - if client is not None and isinstance(client, OpenAI) - else None - ), + client=(client if client is not None and isinstance(client, OpenAI) else None), aembedding=aembedding, shared_session=shared_session, ) diff --git a/litellm/llms/azure_ai/image_edit/mai_transformation.py b/litellm/llms/azure_ai/image_edit/mai_transformation.py index 75bfc913a8f3..aa1092b0a53d 100644 --- a/litellm/llms/azure_ai/image_edit/mai_transformation.py +++ b/litellm/llms/azure_ai/image_edit/mai_transformation.py @@ -77,13 +77,10 @@ def _validate_size_param(self, size: str) -> None: tuple(map(int, size.lower().split("x", 1))) return except ValueError: - raise ValueError( - f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024')." - ) + raise ValueError(f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024').") raise ValueError( - f"Unsupported size value: '{size}'. " - f"Use a known size (e.g., '1024x1024') or a custom 'WIDTHxHEIGHT' string." + f"Unsupported size value: '{size}'. Use a known size (e.g., '1024x1024') or a custom 'WIDTHxHEIGHT' string." ) def validate_environment( @@ -118,11 +115,7 @@ def get_complete_url( "Azure AI API base is required. Set AZURE_AI_API_BASE environment variable or pass api_base parameter." ) - api_version = ( - litellm_params.get("api_version") - or get_secret_str("AZURE_AI_API_VERSION") - or "preview" - ) + api_version = litellm_params.get("api_version") or get_secret_str("AZURE_AI_API_VERSION") or "preview" return AzureFoundryMAIImageGenerationConfig.get_mai_image_edit_url( api_base=api_base, @@ -145,11 +138,7 @@ def transform_image_edit_request( if prompt is not None: request_params["prompt"] = prompt - data_without_files = { - key: value - for key, value in request_params.items() - if key not in ["image", "mask"] - } + data_without_files = {key: value for key, value in request_params.items() if key not in ["image", "mask"]} files_list: List[Tuple[str, Any]] = [] if image is not None: @@ -174,16 +163,10 @@ def transform_image_edit_response( try: response = raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) if "usage" in response: - response["usage"] = ( - AzureFoundryMAIImageGenerationConfig.normalize_mai_image_usage( - response.get("usage") - ) - ) + response["usage"] = AzureFoundryMAIImageGenerationConfig.normalize_mai_image_usage(response.get("usage")) logging_obj.post_call( input="", diff --git a/litellm/llms/azure_ai/image_edit/transformation.py b/litellm/llms/azure_ai/image_edit/transformation.py index e778348c75bc..5393a0ba55f5 100644 --- a/litellm/llms/azure_ai/image_edit/transformation.py +++ b/litellm/llms/azure_ai/image_edit/transformation.py @@ -73,11 +73,7 @@ def get_complete_url( "Azure AI API base is required. Set AZURE_AI_API_BASE environment variable or pass api_base parameter." ) - api_version = ( - litellm_params.get("api_version") - or litellm.api_version - or get_secret_str("AZURE_AI_API_VERSION") - ) + api_version = litellm_params.get("api_version") or litellm.api_version or get_secret_str("AZURE_AI_API_VERSION") if api_version is None: # API version is mandatory for Azure AI Foundry raise ValueError( diff --git a/litellm/llms/azure_ai/image_generation/cost_calculator.py b/litellm/llms/azure_ai/image_generation/cost_calculator.py index f8c876bb5be3..f16afbc5971c 100644 --- a/litellm/llms/azure_ai/image_generation/cost_calculator.py +++ b/litellm/llms/azure_ai/image_generation/cost_calculator.py @@ -34,6 +34,4 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") diff --git a/litellm/llms/azure_ai/image_generation/flux_transformation.py b/litellm/llms/azure_ai/image_generation/flux_transformation.py index 6a1868d94cce..a883893ceba0 100644 --- a/litellm/llms/azure_ai/image_generation/flux_transformation.py +++ b/litellm/llms/azure_ai/image_generation/flux_transformation.py @@ -36,9 +36,7 @@ def get_flux2_image_generation_url( Complete URL for the FLUX 2 image generation endpoint """ if api_base is None: - raise ValueError( - "api_base is required for Azure AI FLUX 2 image generation" - ) + raise ValueError("api_base is required for Azure AI FLUX 2 image generation") api_base = api_base.rstrip("/") api_version = api_version or "preview" diff --git a/litellm/llms/azure_ai/image_generation/mai_transformation.py b/litellm/llms/azure_ai/image_generation/mai_transformation.py index 071ca9d98957..7e79ea0b976b 100644 --- a/litellm/llms/azure_ai/image_generation/mai_transformation.py +++ b/litellm/llms/azure_ai/image_generation/mai_transformation.py @@ -126,9 +126,7 @@ def normalize_mai_image_usage(usage: Optional[Dict[str, Any]]) -> Dict[str, Any] ) return normalized_usage - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return ["n", "size"] def map_openai_params( @@ -185,9 +183,7 @@ def _map_size_param(self, size: str, optional_params: dict) -> None: optional_params["width"] = width optional_params["height"] = height except ValueError: - raise ValueError( - f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024')." - ) + raise ValueError(f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024').") else: raise ValueError( f"Unsupported size value: '{size}'. " @@ -210,9 +206,7 @@ def transform_image_generation_response( try: response = raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) if "usage" in response: response["usage"] = self.normalize_mai_image_usage(response.get("usage")) diff --git a/litellm/llms/azure_ai/ocr/common_utils.py b/litellm/llms/azure_ai/ocr/common_utils.py index d736b8915320..d1d5b80b78d2 100644 --- a/litellm/llms/azure_ai/ocr/common_utils.py +++ b/litellm/llms/azure_ai/ocr/common_utils.py @@ -42,9 +42,7 @@ def get_azure_ai_ocr_config(model: str) -> Optional["BaseOCRConfig"]: # Check for Azure Document Intelligence models if "doc-intelligence" in model or "documentintelligence" in model: - verbose_logger.debug( - f"Routing {model} to Azure Document Intelligence OCR config" - ) + verbose_logger.debug(f"Routing {model} to Azure Document Intelligence OCR config") return AzureDocumentIntelligenceOCRConfig() # Default to Mistral-based OCR for other azure_ai models diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py index cc65ad706ab3..c67703f64d73 100644 --- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py +++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py @@ -126,9 +126,7 @@ def _normalize_pages_param(pages: Any) -> str: raise ValueError("`pages` must be integers, not booleans") if all(isinstance(p, int) for p in pages): if any(p < 0 for p in pages): - raise ValueError( - "`pages` integers must be >= 0 (Mistral 0-based indices)" - ) + raise ValueError("`pages` integers must be >= 0 (Mistral 0-based indices)") # Mistral 0-based -> Azure 1-based. return ",".join(str(p + 1) for p in sorted(set(pages))) if all(isinstance(p, str) for p in pages): @@ -140,10 +138,7 @@ def _normalize_pages_param(pages: Any) -> str: ) return joined - raise ValueError( - "`pages` must be a list[int] (0-based, Mistral-style) or a " - "string like '1-3,5,7-9'." - ) + raise ValueError("`pages` must be a list[int] (0-based, Mistral-style) or a string like '1-3,5,7-9'.") def validate_environment( self, @@ -294,9 +289,7 @@ def transform_ocr_request( Returns: OCRRequestData with JSON data """ - verbose_logger.debug( - f"Azure Document Intelligence transform_ocr_request - model: {model}" - ) + verbose_logger.debug(f"Azure Document Intelligence transform_ocr_request - model: {model}") if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") @@ -310,9 +303,7 @@ def transform_ocr_request( elif doc_type == "image_url": document_url = document.get("image_url", "") else: - raise ValueError( - f"Invalid document type: {doc_type}. Must be 'document_url' or 'image_url'" - ) + raise ValueError(f"Invalid document type: {doc_type}. Must be 'document_url' or 'image_url'") if not document_url: raise ValueError("Document URL is required") @@ -359,9 +350,7 @@ def _extract_page_markdown(self, page_data: Dict[str, Any]) -> str: # Join with newlines to preserve structure return "\n".join(text_lines) - def _convert_dimensions( - self, width: float, height: float, unit: str - ) -> OCRPageDimensions: + def _convert_dimensions(self, width: float, height: float, unit: str) -> OCRPageDimensions: """ Convert Azure DI dimensions to pixels. @@ -400,9 +389,7 @@ def _check_timeout(start_time: float, timeout_secs: int) -> None: TimeoutError: If operation has exceeded timeout """ if time.time() - start_time > timeout_secs: - raise TimeoutError( - f"Azure Document Intelligence operation polling timed out after {timeout_secs} seconds" - ) + raise TimeoutError(f"Azure Document Intelligence operation polling timed out after {timeout_secs} seconds") @staticmethod def _get_retry_after(response: httpx.Response) -> int: @@ -443,9 +430,7 @@ def _check_operation_status(response: httpx.Response) -> str: return "succeeded" elif status == "failed": error_msg = result.get("error", {}).get("message", "Unknown error") - raise ValueError( - f"Azure Document Intelligence analysis failed: {error_msg}" - ) + raise ValueError(f"Azure Document Intelligence analysis failed: {error_msg}") elif status in ["running", "notStarted"]: return "running" else: @@ -596,16 +581,12 @@ def transform_ocr_response( try: # Check if we got 202 Accepted (async operation started) if raw_response.status_code == 202: - verbose_logger.debug( - "Azure DI returned 202 Accepted, polling operation..." - ) + verbose_logger.debug("Azure DI returned 202 Accepted, polling operation...") # Get Operation-Location header operation_url = raw_response.headers.get("Operation-Location") if not operation_url: - raise ValueError( - "Azure Document Intelligence returned 202 but no Operation-Location header found" - ) + raise ValueError("Azure Document Intelligence returned 202 but no Operation-Location header found") # Reject cross-origin polling URLs — the auth headers # below would otherwise leak to whatever URL the upstream @@ -613,15 +594,11 @@ def transform_ocr_response( try: assert_same_origin(operation_url, str(raw_response.request.url)) except SSRFError as ssrf_err: - raise ValueError( - f"Azure Document Intelligence: rejected polling URL ({ssrf_err})" - ) + raise ValueError(f"Azure Document Intelligence: rejected polling URL ({ssrf_err})") # Get headers for polling (need auth) poll_headers = { - "Ocp-Apim-Subscription-Key": raw_response.request.headers.get( - "Ocp-Apim-Subscription-Key", "" - ) + "Ocp-Apim-Subscription-Key": raw_response.request.headers.get("Ocp-Apim-Subscription-Key", "") } # Get timeout from kwargs or use default @@ -637,16 +614,12 @@ def transform_ocr_response( # Now parse the completed response response_json = raw_response.json() - verbose_logger.debug( - f"Azure Document Intelligence response status: {response_json.get('status')}" - ) + verbose_logger.debug(f"Azure Document Intelligence response status: {response_json.get('status')}") # Check if request succeeded status = response_json.get("status") if status != "succeeded": - raise ValueError( - f"Azure Document Intelligence analysis failed with status: {status}" - ) + raise ValueError(f"Azure Document Intelligence analysis failed with status: {status}") # Extract analyze result analyze_result = response_json.get("analyzeResult", {}) @@ -665,20 +638,14 @@ def transform_ocr_response( width = azure_page.get("width", 8.5) height = azure_page.get("height", 11) unit = azure_page.get("unit", "inch") - dimensions = self._convert_dimensions( - width=width, height=height, unit=unit - ) + dimensions = self._convert_dimensions(width=width, height=height, unit=unit) # Build OCR page - ocr_page = OCRPage( - index=index, markdown=markdown, dimensions=dimensions - ) + ocr_page = OCRPage(index=index, markdown=markdown, dimensions=dimensions) mistral_pages.append(ocr_page) # Build usage info - usage_info = OCRUsageInfo( - pages_processed=len(mistral_pages), doc_size_bytes=None - ) + usage_info = OCRUsageInfo(pages_processed=len(mistral_pages), doc_size_bytes=None) # Return Mistral OCR response return OCRResponse( @@ -689,9 +656,7 @@ def transform_ocr_response( ) except Exception as e: - verbose_logger.error( - f"Error parsing Azure Document Intelligence response: {e}" - ) + verbose_logger.error(f"Error parsing Azure Document Intelligence response: {e}") raise e async def async_transform_ocr_response( @@ -718,30 +683,22 @@ async def async_transform_ocr_response( try: # Check if we got 202 Accepted (async operation started) if raw_response.status_code == 202: - verbose_logger.debug( - "Azure DI returned 202 Accepted, polling operation (async)..." - ) + verbose_logger.debug("Azure DI returned 202 Accepted, polling operation (async)...") # Get Operation-Location header operation_url = raw_response.headers.get("Operation-Location") if not operation_url: - raise ValueError( - "Azure Document Intelligence returned 202 but no Operation-Location header found" - ) + raise ValueError("Azure Document Intelligence returned 202 but no Operation-Location header found") # Reject cross-origin polling URLs (see sync path). VERIA-51. try: assert_same_origin(operation_url, str(raw_response.request.url)) except SSRFError as ssrf_err: - raise ValueError( - f"Azure Document Intelligence: rejected polling URL ({ssrf_err})" - ) + raise ValueError(f"Azure Document Intelligence: rejected polling URL ({ssrf_err})") # Get headers for polling (need auth) poll_headers = { - "Ocp-Apim-Subscription-Key": raw_response.request.headers.get( - "Ocp-Apim-Subscription-Key", "" - ) + "Ocp-Apim-Subscription-Key": raw_response.request.headers.get("Ocp-Apim-Subscription-Key", "") } # Get timeout from kwargs or use default @@ -757,16 +714,12 @@ async def async_transform_ocr_response( # Now parse the completed response response_json = raw_response.json() - verbose_logger.debug( - f"Azure Document Intelligence response status: {response_json.get('status')}" - ) + verbose_logger.debug(f"Azure Document Intelligence response status: {response_json.get('status')}") # Check if request succeeded status = response_json.get("status") if status != "succeeded": - raise ValueError( - f"Azure Document Intelligence analysis failed with status: {status}" - ) + raise ValueError(f"Azure Document Intelligence analysis failed with status: {status}") # Extract analyze result analyze_result = response_json.get("analyzeResult", {}) @@ -785,20 +738,14 @@ async def async_transform_ocr_response( width = azure_page.get("width", 8.5) height = azure_page.get("height", 11) unit = azure_page.get("unit", "inch") - dimensions = self._convert_dimensions( - width=width, height=height, unit=unit - ) + dimensions = self._convert_dimensions(width=width, height=height, unit=unit) # Build OCR page - ocr_page = OCRPage( - index=index, markdown=markdown, dimensions=dimensions - ) + ocr_page = OCRPage(index=index, markdown=markdown, dimensions=dimensions) mistral_pages.append(ocr_page) # Build usage info - usage_info = OCRUsageInfo( - pages_processed=len(mistral_pages), doc_size_bytes=None - ) + usage_info = OCRUsageInfo(pages_processed=len(mistral_pages), doc_size_bytes=None) # Return Mistral OCR response return OCRResponse( @@ -809,7 +756,5 @@ async def async_transform_ocr_response( ) except Exception as e: - verbose_logger.error( - f"Error parsing Azure Document Intelligence response (async): {e}" - ) + verbose_logger.error(f"Error parsing Azure Document Intelligence response (async): {e}") raise e diff --git a/litellm/llms/azure_ai/ocr/transformation.py b/litellm/llms/azure_ai/ocr/transformation.py index ee35fc289948..a57e3e869cfe 100644 --- a/litellm/llms/azure_ai/ocr/transformation.py +++ b/litellm/llms/azure_ai/ocr/transformation.py @@ -119,17 +119,13 @@ def _convert_url_to_data_uri_sync(self, url: str) -> str: Returns: Base64 data URI string """ - verbose_logger.debug( - f"Azure AI OCR: Converting URL to base64 data URI (sync): {url}" - ) + verbose_logger.debug(f"Azure AI OCR: Converting URL to base64 data URI (sync): {url}") # Fetch and convert to base64 data URI # convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = convert_url_to_base64(url=url) - verbose_logger.debug( - f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})" - ) + verbose_logger.debug(f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})") return data_uri @@ -146,17 +142,13 @@ async def _convert_url_to_data_uri_async(self, url: str) -> str: Returns: Base64 data URI string """ - verbose_logger.debug( - f"Azure AI OCR: Converting URL to base64 data URI (async): {url}" - ) + verbose_logger.debug(f"Azure AI OCR: Converting URL to base64 data URI (async): {url}") # Fetch and convert to base64 data URI asynchronously # async_convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = await async_convert_url_to_base64(url=url) - verbose_logger.debug( - f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})" - ) + verbose_logger.debug(f"Azure AI OCR: Converted URL to data URI (length: {len(data_uri)})") return data_uri @@ -184,9 +176,7 @@ def transform_ocr_request( Returns: OCRRequestData with JSON data """ - verbose_logger.debug( - f"Azure AI OCR transform_ocr_request (sync) - model: {model}" - ) + verbose_logger.debug(f"Azure AI OCR transform_ocr_request (sync) - model: {model}") if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") @@ -199,18 +189,14 @@ def transform_ocr_request( document_url = document.get("document_url", "") # If it's not already a data URI, convert it if document_url and not document_url.startswith("data:"): - verbose_logger.debug( - "Azure AI OCR: Converting document URL to base64 data URI (sync)" - ) + verbose_logger.debug("Azure AI OCR: Converting document URL to base64 data URI (sync)") data_uri = self._convert_url_to_data_uri_sync(url=document_url) transformed_document["document_url"] = data_uri elif doc_type == "image_url": image_url = document.get("image_url", "") # If it's not already a data URI, convert it if image_url and not image_url.startswith("data:"): - verbose_logger.debug( - "Azure AI OCR: Converting image URL to base64 data URI (sync)" - ) + verbose_logger.debug("Azure AI OCR: Converting image URL to base64 data URI (sync)") data_uri = self._convert_url_to_data_uri_sync(url=image_url) transformed_document["image_url"] = data_uri @@ -247,9 +233,7 @@ async def async_transform_ocr_request( Returns: OCRRequestData with JSON data """ - verbose_logger.debug( - f"Azure AI OCR async_transform_ocr_request - model: {model}" - ) + verbose_logger.debug(f"Azure AI OCR async_transform_ocr_request - model: {model}") if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") @@ -262,18 +246,14 @@ async def async_transform_ocr_request( document_url = document.get("document_url", "") # If it's not already a data URI, convert it if document_url and not document_url.startswith("data:"): - verbose_logger.debug( - "Azure AI OCR: Converting document URL to base64 data URI (async)" - ) + verbose_logger.debug("Azure AI OCR: Converting document URL to base64 data URI (async)") data_uri = await self._convert_url_to_data_uri_async(url=document_url) transformed_document["document_url"] = data_uri elif doc_type == "image_url": image_url = document.get("image_url", "") # If it's not already a data URI, convert it if image_url and not image_url.startswith("data:"): - verbose_logger.debug( - "Azure AI OCR: Converting image URL to base64 data URI (async)" - ) + verbose_logger.debug("Azure AI OCR: Converting image URL to base64 data URI (async)") data_uri = await self._convert_url_to_data_uri_async(url=image_url) transformed_document["image_url"] = data_uri diff --git a/litellm/llms/azure_ai/rerank/transformation.py b/litellm/llms/azure_ai/rerank/transformation.py index f64133afa8b8..928f53bd4858 100644 --- a/litellm/llms/azure_ai/rerank/transformation.py +++ b/litellm/llms/azure_ai/rerank/transformation.py @@ -41,9 +41,7 @@ def get_complete_url( # Allow callers to pass either full v1/v2 rerank endpoints: # - https://.services.ai.azure.com/v1/rerank # - https://.services.ai.azure.com/providers/cohere/v2/rerank - if normalized_path.endswith("/v1/rerank") or normalized_path.endswith( - "/v2/rerank" - ): + if normalized_path.endswith("/v1/rerank") or normalized_path.endswith("/v2/rerank"): return str(original_url.copy_with(path=normalized_path or "/")) # If callers pass just the version path (e.g. ".../v2" or ".../providers/cohere/v2"), append "/rerank" @@ -71,9 +69,7 @@ def validate_environment( api_key = get_secret_str("AZURE_AI_API_KEY") or litellm.azure_key if api_key is None: - raise ValueError( - "Azure AI API key is required. Please set 'AZURE_AI_API_KEY' or 'litellm.azure_key'" - ) + raise ValueError("Azure AI API key is required. Please set 'AZURE_AI_API_KEY' or 'litellm.azure_key'") default_headers = { "Authorization": f"Bearer {api_key}", @@ -109,9 +105,7 @@ def transform_rerank_response( optional_params=optional_params, litellm_params=litellm_params, ) - base_model = self._get_base_model( - rerank_response._hidden_params.get("llm_provider-azureml-model-group") - ) + base_model = self._get_base_model(rerank_response._hidden_params.get("llm_provider-azureml-model-group")) rerank_response._hidden_params["model"] = base_model return rerank_response diff --git a/litellm/llms/azure_ai/vector_stores/transformation.py b/litellm/llms/azure_ai/vector_stores/transformation.py index d1b93c9e7a3c..da6a4a93cd85 100644 --- a/litellm/llms/azure_ai/vector_stores/transformation.py +++ b/litellm/llms/azure_ai/vector_stores/transformation.py @@ -42,9 +42,7 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [("PUT", "/docs")], } - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: api_key = litellm_params.get("api_key") if api_key is None: raise ValueError("api_key is required") @@ -55,9 +53,7 @@ def get_auth_credentials( } } - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: basic_headers = self._base_validate_azure_environment(headers, litellm_params) basic_headers.update({"Content-Type": "application/json"}) return basic_headers @@ -252,7 +248,5 @@ def transform_create_vector_store_request( ) -> Tuple[str, Dict]: raise NotImplementedError - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: raise NotImplementedError diff --git a/litellm/llms/base.py b/litellm/llms/base.py index d639c91c1453..56d1643dd4e5 100644 --- a/litellm/llms/base.py +++ b/litellm/llms/base.py @@ -80,12 +80,8 @@ def validate_environment( ) -> Optional[Any]: # set up the environment required to run the model return None - def completion( - self, *args, **kwargs - ) -> Any: # logic for parsing in - calling - parsing out model completion calls + def completion(self, *args, **kwargs) -> Any: # logic for parsing in - calling - parsing out model completion calls return None - def embedding( - self, *args, **kwargs - ) -> Any: # logic for parsing in - calling - parsing out model embedding calls + def embedding(self, *args, **kwargs) -> Any: # logic for parsing in - calling - parsing out model embedding calls return None diff --git a/litellm/llms/base_llm/anthropic_messages/transformation.py b/litellm/llms/base_llm/anthropic_messages/transformation.py index 49aa563781f4..7f8403c02237 100644 --- a/litellm/llms/base_llm/anthropic_messages/transformation.py +++ b/litellm/llms/base_llm/anthropic_messages/transformation.py @@ -117,9 +117,7 @@ def get_error_class( ) -> "BaseLLMException": from litellm.llms.base_llm.chat.transformation import BaseLLMException - return BaseLLMException( - message=error_message, status_code=status_code, headers=headers - ) + return BaseLLMException(message=error_message, status_code=status_code, headers=headers) @property def max_retry_on_anthropic_messages_http_error(self) -> int: @@ -130,9 +128,7 @@ def max_retry_on_anthropic_messages_http_error(self) -> int: """ return 2 - def should_retry_anthropic_messages_on_http_error( - self, e: httpx.HTTPStatusError, litellm_params: dict - ) -> bool: + def should_retry_anthropic_messages_on_http_error(self, e: httpx.HTTPStatusError, litellm_params: dict) -> bool: """ When True, async_anthropic_messages_handler will transform the request body and issue one more attempt (bounded by max_retry_on_anthropic_messages_http_error). @@ -141,14 +137,9 @@ def should_retry_anthropic_messages_on_http_error( is_anthropic_invalid_thinking_signature_error, ) - return ( - e.response.status_code == 400 - and is_anthropic_invalid_thinking_signature_error(e.response.text) - ) + return e.response.status_code == 400 and is_anthropic_invalid_thinking_signature_error(e.response.text) - def transform_anthropic_messages_request_on_http_error( - self, e: httpx.HTTPStatusError, request_data: dict - ) -> dict: + def transform_anthropic_messages_request_on_http_error(self, e: httpx.HTTPStatusError, request_data: dict) -> dict: """ Mutates request_data in place when retrying after a recoverable HTTP error. """ @@ -157,9 +148,6 @@ def transform_anthropic_messages_request_on_http_error( strip_thinking_blocks_from_anthropic_messages_request_dict, ) - if ( - e.response.status_code == 400 - and is_anthropic_invalid_thinking_signature_error(e.response.text) - ): + if e.response.status_code == 400 and is_anthropic_invalid_thinking_signature_error(e.response.text): strip_thinking_blocks_from_anthropic_messages_request_dict(request_data) return request_data diff --git a/litellm/llms/base_llm/audio_transcription/transformation.py b/litellm/llms/base_llm/audio_transcription/transformation.py index 3574996e48e5..dc862b3dd925 100644 --- a/litellm/llms/base_llm/audio_transcription/transformation.py +++ b/litellm/llms/base_llm/audio_transcription/transformation.py @@ -37,9 +37,7 @@ class AudioTranscriptionRequestData: class BaseAudioTranscriptionConfig(BaseConfig, ABC): @abstractmethod - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: pass def get_complete_url( diff --git a/litellm/llms/base_llm/base_model_iterator.py b/litellm/llms/base_llm/base_model_iterator.py index 422ae947997f..905a3ebda42a 100644 --- a/litellm/llms/base_llm/base_model_iterator.py +++ b/litellm/llms/base_llm/base_model_iterator.py @@ -60,15 +60,11 @@ def convert_model_response_to_streaming( setattr(processed_chunk, "usage", usage) return processed_chunk except Exception as e: - raise ValueError( - f"Failed to convert ModelResponse to ModelResponseStream: {model_response}. Error: {e}" - ) + raise ValueError(f"Failed to convert ModelResponse to ModelResponseStream: {model_response}. Error: {e}") class BaseModelResponseIterator: - def __init__( - self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False - ): + def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False): self.streaming_response = streaming_response self.response_iterator = self.streaming_response self.json_mode = json_mode @@ -85,9 +81,7 @@ async def aclose(self) -> None: if self.http_response is not None: await self.http_response.aclose() - def chunk_parser( - self, chunk: dict - ) -> Union[GenericStreamingChunk, ModelResponseStream]: + def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]: return GenericStreamingChunk( text="", is_finished=False, @@ -104,9 +98,7 @@ def __iter__(self): @staticmethod def _string_to_dict_parser(str_line: str) -> Optional[dict]: stripped_json_chunk: Optional[dict] = None - stripped_chunk = litellm.CustomStreamWrapper._strip_sse_data_from_chunk( - str_line - ) + stripped_chunk = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(str_line) try: if stripped_chunk is not None: stripped_json_chunk = json.loads(stripped_chunk) @@ -116,13 +108,9 @@ def _string_to_dict_parser(str_line: str) -> Optional[dict]: stripped_json_chunk = None return stripped_json_chunk - def _handle_string_chunk( - self, str_line: str - ) -> Union[GenericStreamingChunk, ModelResponseStream]: + def _handle_string_chunk(self, str_line: str) -> Union[GenericStreamingChunk, ModelResponseStream]: # chunk is a str at this point - stripped_json_chunk = BaseModelResponseIterator._string_to_dict_parser( - str_line=str_line - ) + stripped_json_chunk = BaseModelResponseIterator._string_to_dict_parser(str_line=str_line) if "[DONE]" in str_line: return GenericStreamingChunk( text="", @@ -172,9 +160,7 @@ def __next__(self): except StopIteration: raise StopIteration except ValueError as e: - raise RuntimeError( - f"Error parsing chunk: {e},\nReceived chunk: {chunk}" - ) + raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") # Async iterator def __aiter__(self): @@ -212,15 +198,11 @@ async def __anext__(self): except StopAsyncIteration: raise StopAsyncIteration except ValueError as e: - raise RuntimeError( - f"Error parsing chunk: {e},\nReceived chunk: {chunk}" - ) + raise RuntimeError(f"Error parsing chunk: {e},\nReceived chunk: {chunk}") class MockResponseIterator: # for returning ai21 streaming responses - def __init__( - self, model_response: ModelResponse, json_mode: Optional[bool] = False - ): + def __init__(self, model_response: ModelResponse, json_mode: Optional[bool] = False): self.model_response = model_response self.json_mode = json_mode self.is_done = False diff --git a/litellm/llms/base_llm/base_utils.py b/litellm/llms/base_llm/base_utils.py index d2d3d5c0a967..8eded37595bc 100644 --- a/litellm/llms/base_llm/base_utils.py +++ b/litellm/llms/base_llm/base_utils.py @@ -51,9 +51,7 @@ def get_provider_info( return None @abstractmethod - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: """ Returns a list of models supported by this provider. """ @@ -132,9 +130,7 @@ def _convert_tool_response_to_message( return None -def _dict_to_response_format_helper( - response_format: dict, ref_template: Optional[str] = None -) -> dict: +def _dict_to_response_format_helper(response_format: dict, ref_template: Optional[str] = None) -> dict: if ref_template is not None and response_format.get("type") == "json_schema": # Deep copy to avoid modifying original modified_format = copy.deepcopy(response_format) diff --git a/litellm/llms/base_llm/chat/transformation.py b/litellm/llms/base_llm/chat/transformation.py index 4f7e98af780a..ab901a467e81 100644 --- a/litellm/llms/base_llm/chat/transformation.py +++ b/litellm/llms/base_llm/chat/transformation.py @@ -63,19 +63,13 @@ def __init__( if request: self.request = request else: - self.request = httpx.Request( - method="POST", url="https://docs.litellm.ai/docs" - ) + self.request = httpx.Request(method="POST", url="https://docs.litellm.ai/docs") if response: self.response = response else: - self.response = httpx.Response( - status_code=status_code, request=self.request - ) + self.response = httpx.Response(status_code=status_code, request=self.request) self.body = body - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class BaseConfig(ABC): @@ -108,22 +102,17 @@ def get_json_schema_from_pydantic_object( return type_to_response_format_param(response_format=response_format) def is_thinking_enabled(self, non_default_params: dict) -> bool: - return (non_default_params.get("thinking") or {}).get( - "type" - ) == "enabled" or non_default_params.get("reasoning_effort") is not None + return (non_default_params.get("thinking") or {}).get("type") == "enabled" or non_default_params.get( + "reasoning_effort" + ) is not None def is_max_tokens_in_request(self, non_default_params: dict) -> bool: """ OpenAI spec allows max_tokens or max_completion_tokens to be specified. """ - return ( - "max_tokens" in non_default_params - or "max_completion_tokens" in non_default_params - ) + return "max_tokens" in non_default_params or "max_completion_tokens" in non_default_params - def update_optional_params_with_thinking_tokens( - self, non_default_params: dict, optional_params: dict - ): + def update_optional_params_with_thinking_tokens(self, non_default_params: dict, optional_params: dict): """ Handles scenario where max tokens is not specified. For anthropic models (anthropic api/bedrock/vertex ai), this requires having the max tokens being set and being greater than the thinking token budget. @@ -133,16 +122,11 @@ def update_optional_params_with_thinking_tokens( """ is_thinking_enabled = self.is_thinking_enabled(optional_params) if is_thinking_enabled and ( - "max_tokens" not in non_default_params - and "max_completion_tokens" not in non_default_params + "max_tokens" not in non_default_params and "max_completion_tokens" not in non_default_params ): - thinking_token_budget = cast(dict, optional_params["thinking"]).get( - "budget_tokens", None - ) + thinking_token_budget = cast(dict, optional_params["thinking"]).get("budget_tokens", None) if thinking_token_budget is not None: - optional_params["max_tokens"] = ( - thinking_token_budget + DEFAULT_MAX_TOKENS - ) + optional_params["max_tokens"] = thinking_token_budget + DEFAULT_MAX_TOKENS def should_fake_stream( self, @@ -189,9 +173,7 @@ def should_retry_llm_api_inside_llm_translation_on_http_error( """ return False - def transform_request_on_unprocessable_entity_error( - self, e: httpx.HTTPStatusError, request_data: dict - ) -> dict: + def transform_request_on_unprocessable_entity_error(self, e: httpx.HTTPStatusError, request_data: dict) -> dict: """ Transform the request data on UnprocessableEntityError """ @@ -238,16 +220,12 @@ def _add_response_format_to_tools( if json_schema and not is_response_format_supported: _tool_choice = ChatCompletionToolChoiceObjectParam( type="function", - function=ChatCompletionToolChoiceFunctionParam( - name=RESPONSE_FORMAT_TOOL_NAME - ), + function=ChatCompletionToolChoiceFunctionParam(name=RESPONSE_FORMAT_TOOL_NAME), ) _tool = ChatCompletionToolParam( type="function", - function=ChatCompletionToolParamFunctionChunk( - name=RESPONSE_FORMAT_TOOL_NAME, parameters=json_schema - ), + function=ChatCompletionToolParamFunctionChunk(name=RESPONSE_FORMAT_TOOL_NAME, parameters=json_schema), ) optional_params.setdefault("tools", []) @@ -461,9 +439,7 @@ def apply_assembled_streaming_response_metadata( """Hook for providers to merge chunk metadata into assembled streaming responses.""" return None - def calculate_additional_costs( - self, model: str, prompt_tokens: int, completion_tokens: int - ) -> Optional[dict]: + def calculate_additional_costs(self, model: str, prompt_tokens: int, completion_tokens: int) -> Optional[dict]: """ Calculate any additional costs beyond standard token costs. diff --git a/litellm/llms/base_llm/embedding/transformation.py b/litellm/llms/base_llm/embedding/transformation.py index c03a8235b4ab..07ffbb99626c 100644 --- a/litellm/llms/base_llm/embedding/transformation.py +++ b/litellm/llms/base_llm/embedding/transformation.py @@ -66,9 +66,7 @@ def transform_request( litellm_params: dict, headers: dict, ) -> dict: - raise NotImplementedError( - "EmbeddingConfig does not need a request transformation for chat models" - ) + raise NotImplementedError("EmbeddingConfig does not need a request transformation for chat models") def transform_response( self, @@ -84,6 +82,4 @@ def transform_response( api_key: Optional[str] = None, json_mode: Optional[bool] = None, ) -> ModelResponse: - raise NotImplementedError( - "EmbeddingConfig does not need a response transformation for chat models" - ) + raise NotImplementedError("EmbeddingConfig does not need a response transformation for chat models") diff --git a/litellm/llms/base_llm/evals/transformation.py b/litellm/llms/base_llm/evals/transformation.py index 54dc2f7aae96..da8d7e12acbf 100644 --- a/litellm/llms/base_llm/evals/transformation.py +++ b/litellm/llms/base_llm/evals/transformation.py @@ -46,9 +46,7 @@ def custom_llm_provider(self) -> LlmProviders: pass @abstractmethod - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate and update headers with provider-specific requirements diff --git a/litellm/llms/base_llm/files/azure_blob_storage_backend.py b/litellm/llms/base_llm/files/azure_blob_storage_backend.py index a2155df40471..07dd339cac37 100644 --- a/litellm/llms/base_llm/files/azure_blob_storage_backend.py +++ b/litellm/llms/base_llm/files/azure_blob_storage_backend.py @@ -78,25 +78,19 @@ async def async_log_failure_event(self, *args, **kwargs): # Do nothing - this class is used for file storage, not logging pass - def _generate_file_name( - self, original_filename: str, file_naming_strategy: str - ) -> str: + def _generate_file_name(self, original_filename: str, file_naming_strategy: str) -> str: """Generate file name based on naming strategy.""" if file_naming_strategy == "original_filename": # Use original filename, but sanitize it return quote(original_filename, safe="") elif file_naming_strategy == "timestamp": # Use timestamp - extension = ( - original_filename.split(".")[-1] if "." in original_filename else "" - ) + extension = original_filename.split(".")[-1] if "." in original_filename else "" timestamp = int(time.time() * 1000) # milliseconds return f"{timestamp}.{extension}" if extension else str(timestamp) else: # default to "uuid" # Use UUID - extension = ( - original_filename.split(".")[-1] if "." in original_filename else "" - ) + extension = original_filename.split(".")[-1] if "." in original_filename else "" file_uuid = str(uuid.uuid4()) return f"{file_uuid}.{extension}" if extension else file_uuid @@ -138,33 +132,23 @@ async def upload_file( full_path=full_path, ) - verbose_logger.debug( - f"Successfully uploaded file to Azure Blob Storage: {storage_url}" - ) + verbose_logger.debug(f"Successfully uploaded file to Azure Blob Storage: {storage_url}") return storage_url except Exception as e: - verbose_logger.exception( - f"Error uploading file to Azure Blob Storage: {str(e)}" - ) + verbose_logger.exception(f"Error uploading file to Azure Blob Storage: {str(e)}") raise - async def _upload_file_with_account_key( - self, file_content: bytes, full_path: str - ) -> str: + async def _upload_file_with_account_key(self, file_content: bytes, full_path: str) -> str: """Upload file using Azure SDK with account key authentication.""" # Reuse the logger's service client method service_client = await self.get_service_client() - file_system_client = service_client.get_file_system_client( - file_system=self.azure_storage_file_system - ) + file_system_client = service_client.get_file_system_client(file_system=self.azure_storage_file_system) # Create filesystem (container) if it doesn't exist if not await file_system_client.exists(): await file_system_client.create_file_system() - verbose_logger.debug( - f"Created filesystem: {self.azure_storage_file_system}" - ) + verbose_logger.debug(f"Created filesystem: {self.azure_storage_file_system}") # Extract directory and filename (similar to logger's pattern) path_parts = full_path.split("/") @@ -186,18 +170,14 @@ async def _upload_file_with_account_key( # Create, append, and flush (same pattern as logger's upload_to_azure_data_lake_with_azure_account_key) await file_client.create_file() - await file_client.append_data( - data=file_content, offset=0, length=len(file_content) - ) + await file_client.append_data(data=file_content, offset=0, length=len(file_content)) await file_client.flush_data(position=len(file_content), offset=0) # Return blob URL (not DFS URL) blob_url = f"https://{self.azure_storage_account_name}.blob.core.windows.net/{self.azure_storage_file_system}/{full_path}" return blob_url - async def _upload_file_with_azure_ad( - self, file_content: bytes, full_path: str - ) -> str: + async def _upload_file_with_azure_ad(self, file_content: bytes, full_path: str) -> str: """Upload file using REST API with Azure AD authentication.""" # Reuse the logger's token management await self.set_valid_azure_ad_token() @@ -207,9 +187,7 @@ async def _upload_file_with_azure_ad( httpxSpecialProvider, ) - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) # Use DFS endpoint for upload base_url = f"https://{self.azure_storage_account_name}.dfs.core.windows.net/{self.azure_storage_file_system}/{full_path}" @@ -261,9 +239,7 @@ async def download_file(self, storage_url: str) -> bytes: container_and_path = storage_url.split(".blob.core.windows.net/", 1)[1] path_parts = container_and_path.split("/", 1) if len(path_parts) < 2: - raise ValueError( - f"Invalid Azure Blob Storage URL format: {storage_url}" - ) + raise ValueError(f"Invalid Azure Blob Storage URL format: {storage_url}") file_path = path_parts[1] # Path after container name if self.azure_storage_account_key: @@ -274,23 +250,17 @@ async def download_file(self, storage_url: str) -> bytes: return await self._download_file_with_azure_ad(file_path) except Exception as e: - verbose_logger.exception( - f"Error downloading file from Azure Blob Storage: {str(e)}" - ) + verbose_logger.exception(f"Error downloading file from Azure Blob Storage: {str(e)}") raise async def _download_file_with_account_key(self, file_path: str) -> bytes: """Download file using Azure SDK with account key.""" # Reuse the logger's service client method service_client = await self.get_service_client() - file_system_client = service_client.get_file_system_client( - file_system=self.azure_storage_file_system - ) + file_system_client = service_client.get_file_system_client(file_system=self.azure_storage_file_system) # Ensure filesystem exists (should already exist, but check for safety) if not await file_system_client.exists(): - raise ValueError( - f"Filesystem {self.azure_storage_file_system} does not exist" - ) + raise ValueError(f"Filesystem {self.azure_storage_file_system} does not exist") file_client = file_system_client.get_file_client(file_path) # Download file download_response = await file_client.download_file() @@ -308,9 +278,7 @@ async def _download_file_with_azure_ad(self, file_path: str) -> bytes: ) from litellm.constants import AZURE_STORAGE_MSFT_VERSION - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.LoggingCallback - ) + async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.LoggingCallback) # Use blob endpoint for download (simpler than DFS) blob_url = f"https://{self.azure_storage_account_name}.blob.core.windows.net/{self.azure_storage_file_system}/{file_path}" diff --git a/litellm/llms/base_llm/files/storage_backend_factory.py b/litellm/llms/base_llm/files/storage_backend_factory.py index 12047f1122e6..8fd918af0dce 100644 --- a/litellm/llms/base_llm/files/storage_backend_factory.py +++ b/litellm/llms/base_llm/files/storage_backend_factory.py @@ -34,7 +34,4 @@ def get_storage_backend(backend_type: str) -> BaseFileStorageBackend: if backend_type == "azure_storage": return AzureBlobStorageBackend() else: - raise ValueError( - f"Unsupported storage backend type: {backend_type}. " - f"Supported types: azure_storage" - ) + raise ValueError(f"Unsupported storage backend type: {backend_type}. Supported types: azure_storage") diff --git a/litellm/llms/base_llm/files/transformation.py b/litellm/llms/base_llm/files/transformation.py index 85016c7a5c41..a9b99eb06fcc 100644 --- a/litellm/llms/base_llm/files/transformation.py +++ b/litellm/llms/base_llm/files/transformation.py @@ -65,9 +65,7 @@ def file_upload_http_method(self) -> str: return "POST" @abstractmethod - def get_supported_openai_params( - self, model: str - ) -> List[OpenAICreateFileRequestOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAICreateFileRequestOptionalParams]: pass def get_complete_file_url( diff --git a/litellm/llms/base_llm/google_genai/transformation.py b/litellm/llms/base_llm/google_genai/transformation.py index 8fb7eb9fde05..965c174df6e9 100644 --- a/litellm/llms/base_llm/google_genai/transformation.py +++ b/litellm/llms/base_llm/google_genai/transformation.py @@ -58,9 +58,7 @@ def get_supported_generate_content_optional_params(self, model: str) -> List[str Returns: List of supported parameter names """ - raise NotImplementedError( - "get_supported_generate_content_optional_params is not implemented" - ) + raise NotImplementedError("get_supported_generate_content_optional_params is not implemented") def get_generate_content_request_top_level_fields(self) -> tuple[str, ...]: """ @@ -91,9 +89,7 @@ def map_generate_content_optional_params( Returns: Mapped parameters for the provider """ - raise NotImplementedError( - "map_generate_content_optional_params is not implemented" - ) + raise NotImplementedError("map_generate_content_optional_params is not implemented") @abstractmethod def validate_environment( @@ -201,9 +197,7 @@ def transform_generate_content_response( """ pass - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] - ) -> Exception: + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]) -> Exception: """ Get the appropriate exception class for the error. diff --git a/litellm/llms/base_llm/guardrail_translation/base_translation.py b/litellm/llms/base_llm/guardrail_translation/base_translation.py index 1efeb159a3e4..68db36b529e5 100644 --- a/litellm/llms/base_llm/guardrail_translation/base_translation.py +++ b/litellm/llms/base_llm/guardrail_translation/base_translation.py @@ -29,11 +29,7 @@ def transform_user_api_key_dict_to_metadata( return {} # Convert to dict if it's a Pydantic object - user_dict = ( - user_api_key_dict.model_dump() - if hasattr(user_api_key_dict, "model_dump") - else user_api_key_dict - ) + user_dict = user_api_key_dict.model_dump() if hasattr(user_api_key_dict, "model_dump") else user_api_key_dict if not isinstance(user_dict, dict): return {} diff --git a/litellm/llms/base_llm/image_edit/transformation.py b/litellm/llms/base_llm/image_edit/transformation.py index 92429573ff8b..4c18702bc6cb 100644 --- a/litellm/llms/base_llm/image_edit/transformation.py +++ b/litellm/llms/base_llm/image_edit/transformation.py @@ -102,9 +102,7 @@ def transform_image_edit_request( ) -> Tuple[Dict, RequestFiles]: pass - def finalize_image_edit_request_data( - self, data: dict, resolved_request_url: str - ) -> dict: + def finalize_image_edit_request_data(self, data: dict, resolved_request_url: str) -> dict: """ Last pass on the request dict after ``transform_image_edit_request``, using the exact URL string used for the HTTP POST (same as ``get_complete_url`` output). diff --git a/litellm/llms/base_llm/image_generation/transformation.py b/litellm/llms/base_llm/image_generation/transformation.py index 7f13e6f3b4cb..e80a970d806a 100644 --- a/litellm/llms/base_llm/image_generation/transformation.py +++ b/litellm/llms/base_llm/image_generation/transformation.py @@ -20,9 +20,7 @@ class BaseImageGenerationConfig(ABC): @abstractmethod - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: pass @abstractmethod diff --git a/litellm/llms/base_llm/image_variations/transformation.py b/litellm/llms/base_llm/image_variations/transformation.py index 60444d0fb749..23fc4dc88b9f 100644 --- a/litellm/llms/base_llm/image_variations/transformation.py +++ b/litellm/llms/base_llm/image_variations/transformation.py @@ -26,9 +26,7 @@ class BaseImageVariationConfig(BaseConfig, ABC): @abstractmethod - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageVariationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageVariationOptionalParams]: pass def get_complete_url( diff --git a/litellm/llms/base_llm/interactions/transformation.py b/litellm/llms/base_llm/interactions/transformation.py index be400628fd5d..3eba1858a239 100644 --- a/litellm/llms/base_llm/interactions/transformation.py +++ b/litellm/llms/base_llm/interactions/transformation.py @@ -86,9 +86,7 @@ def get_supported_params(self, model: str) -> List[str]: pass @abstractmethod - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate and prepare environment settings including headers. """ diff --git a/litellm/llms/base_llm/managed_resources/base_managed_resource.py b/litellm/llms/base_llm/managed_resources/base_managed_resource.py index c0c18aefdeb3..146a6aa6ae04 100644 --- a/litellm/llms/base_llm/managed_resources/base_managed_resource.py +++ b/litellm/llms/base_llm/managed_resources/base_managed_resource.py @@ -163,9 +163,7 @@ async def store_unified_resource_id( user_api_key_dict: User API key authentication details additional_db_fields: Additional fields to store in database """ - verbose_logger.info( - f"Storing LiteLLM Managed {self.resource_type} with id={unified_resource_id} in cache" - ) + verbose_logger.info(f"Storing LiteLLM Managed {self.resource_type} with id={unified_resource_id} in cache") # Prepare cache data cache_data = { @@ -256,9 +254,7 @@ async def get_unified_resource_id( # Check database table = getattr(self.prisma_client.db, self.table_name) - db_object = await table.find_first( - where={"unified_resource_id": unified_resource_id} - ) + db_object = await table.find_first(where={"unified_resource_id": unified_resource_id}) if db_object: return db_object.model_dump() @@ -282,14 +278,10 @@ async def delete_unified_resource_id( """ # Get old value from database table = getattr(self.prisma_client.db, self.table_name) - initial_value = await table.find_first( - where={"unified_resource_id": unified_resource_id} - ) + initial_value = await table.find_first(where={"unified_resource_id": unified_resource_id}) if initial_value is None: - raise Exception( - f"LiteLLM Managed {self.resource_type} with id={unified_resource_id} not found" - ) + raise Exception(f"LiteLLM Managed {self.resource_type} with id={unified_resource_id} not found") # Delete from cache await self.internal_usage_cache.async_set_cache( @@ -324,9 +316,7 @@ async def can_user_access_unified_resource_id( True if user has access, False otherwise """ # Use cached method instead of direct DB query - resource = await self.get_unified_resource_id( - unified_resource_id, litellm_parent_otel_span - ) + resource = await self.get_unified_resource_id(unified_resource_id, litellm_parent_otel_span) if resource: return can_access_resource( @@ -368,9 +358,7 @@ async def get_model_resource_id_mapping( for resource_id in resource_ids: # Get unified resource from cache/db - unified_resource_object = await self.get_unified_resource_id( - resource_id, litellm_parent_otel_span - ) + unified_resource_object = await self.get_unified_resource_id(resource_id, litellm_parent_otel_span) if unified_resource_object: model_mappings = unified_resource_object.get("model_mappings", {}) @@ -442,9 +430,7 @@ def generate_unified_resource_id( ) # Convert to URL-safe base64 and strip padding - base64_unified_id = ( - base64.urlsafe_b64encode(unified_id_format.encode()).decode().rstrip("=") - ) + base64_unified_id = base64.urlsafe_b64encode(unified_id_format.encode()).decode().rstrip("=") return base64_unified_id @@ -468,9 +454,7 @@ def extract_model_mappings_from_responses( hidden_params = getattr(resource_object, "_hidden_params", {}) or {} model_resource_id_mapping = hidden_params.get("model_resource_id_mapping") - if model_resource_id_mapping and isinstance( - model_resource_id_mapping, dict - ): + if model_resource_id_mapping and isinstance(model_resource_id_mapping, dict): model_mappings.update(model_resource_id_mapping) return model_mappings @@ -602,11 +586,8 @@ async def list_user_resources( except Exception as e: verbose_logger.warning( - f"Failed to parse {self.resource_type} object " - f"{resource.unified_resource_id}: {e}" + f"Failed to parse {self.resource_type} object {resource.unified_resource_id}: {e}" ) continue - return build_list_page( - resource_objects, has_more=len(resource_objects) == (limit or 20) - ) + return build_list_page(resource_objects, has_more=len(resource_objects) == (limit or 20)) diff --git a/litellm/llms/base_llm/managed_resources/isolation.py b/litellm/llms/base_llm/managed_resources/isolation.py index 62027f4272cf..fd1e24f3e1d9 100644 --- a/litellm/llms/base_llm/managed_resources/isolation.py +++ b/litellm/llms/base_llm/managed_resources/isolation.py @@ -89,11 +89,7 @@ def can_access_resource( return True team_id = user_api_key_dict.team_id - if ( - team_id is not None - and resource_team_id is not None - and resource_team_id == team_id - ): + if team_id is not None and resource_team_id is not None and resource_team_id == team_id: return True return False diff --git a/litellm/llms/base_llm/managed_resources/utils.py b/litellm/llms/base_llm/managed_resources/utils.py index e9a6aef689e5..a93f62764f9e 100644 --- a/litellm/llms/base_llm/managed_resources/utils.py +++ b/litellm/llms/base_llm/managed_resources/utils.py @@ -29,14 +29,10 @@ def resolve_passthrough_managed_id_provider( Splitting them would make a managed ID minted on ``azure`` fail to resolve when replayed on ``azure_ai`` and vice versa. """ - provider = str( - getattr(custom_llm_provider, "value", custom_llm_provider) or "" - ).lower() + provider = str(getattr(custom_llm_provider, "value", custom_llm_provider) or "").lower() if not provider: return None - if provider in PASSTHROUGH_MANAGED_ID_AZURE_PROVIDERS or provider.endswith( - (".azure", ".azure_ai") - ): + if provider in PASSTHROUGH_MANAGED_ID_AZURE_PROVIDERS or provider.endswith((".azure", ".azure_ai")): return "azure" if provider == "openai" or provider.endswith(".openai"): return "openai" @@ -391,12 +387,8 @@ def parse_unified_id( return { "resource_type": extract_resource_type_from_unified_id(decoded_id), "unified_uuid": extract_unified_uuid_from_unified_id(decoded_id), - "target_model_names": extract_target_model_names_from_unified_id( - decoded_id - ), - "provider_resource_id": extract_provider_resource_id_from_unified_id( - decoded_id - ), + "target_model_names": extract_target_model_names_from_unified_id(decoded_id), + "provider_resource_id": extract_provider_resource_id_from_unified_id(decoded_id), "model_id": extract_model_id_from_unified_id(decoded_id), } except Exception: diff --git a/litellm/llms/base_llm/ocr/transformation.py b/litellm/llms/base_llm/ocr/transformation.py index a2946c625064..a38e5bfdcd62 100644 --- a/litellm/llms/base_llm/ocr/transformation.py +++ b/litellm/llms/base_llm/ocr/transformation.py @@ -170,9 +170,7 @@ def transform_ocr_request( Returns: OCRRequestData with data and files fields """ - raise NotImplementedError( - "transform_ocr_request must be implemented by provider" - ) + raise NotImplementedError("transform_ocr_request must be implemented by provider") async def async_transform_ocr_request( self, @@ -218,9 +216,7 @@ def transform_ocr_response( Transform provider-specific OCR response to standard format. Override in provider-specific implementations. """ - raise NotImplementedError( - "transform_ocr_response must be implemented by provider" - ) + raise NotImplementedError("transform_ocr_response must be implemented by provider") async def async_transform_ocr_response( self, diff --git a/litellm/llms/base_llm/passthrough/transformation.py b/litellm/llms/base_llm/passthrough/transformation.py index 9d4396dce476..e243d36a86a2 100644 --- a/litellm/llms/base_llm/passthrough/transformation.py +++ b/litellm/llms/base_llm/passthrough/transformation.py @@ -95,9 +95,7 @@ def get_error_class( ) -> "BaseLLMException": from litellm.llms.base_llm.chat.transformation import BaseLLMException - return BaseLLMException( - status_code=status_code, message=error_message, headers=headers - ) + return BaseLLMException(status_code=status_code, message=error_message, headers=headers) def logging_non_streaming_response( self, diff --git a/litellm/llms/base_llm/realtime/http_transformation.py b/litellm/llms/base_llm/realtime/http_transformation.py index be1413a3c0b9..4c8cc30a8b36 100644 --- a/litellm/llms/base_llm/realtime/http_transformation.py +++ b/litellm/llms/base_llm/realtime/http_transformation.py @@ -54,9 +54,7 @@ def get_api_key( # ------------------------------------------------------------------ # @abstractmethod - def get_complete_url( - self, api_base: Optional[str], model: str, api_version: Optional[str] = None - ) -> str: + def get_complete_url(self, api_base: Optional[str], model: str, api_version: Optional[str] = None) -> str: """Return the full URL for POST /realtime/client_secrets.""" def get_transcription_session_url( @@ -86,9 +84,7 @@ def validate_environment( # realtime_calls endpoint # # ------------------------------------------------------------------ # - def get_realtime_calls_url( - self, api_base: Optional[str], model: str, api_version: Optional[str] = None - ) -> str: + def get_realtime_calls_url(self, api_base: Optional[str], model: str, api_version: Optional[str] = None) -> str: """Return the full URL for POST /realtime/calls (SDP exchange).""" base = (api_base or "").rstrip("/") return f"{base}/v1/realtime/calls" @@ -108,9 +104,7 @@ def get_realtime_calls_headers(self, ephemeral_key: str) -> dict: # Error handling # # ------------------------------------------------------------------ # - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] - ): + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]): """ Map HTTP errors to LiteLLM exception types. diff --git a/litellm/llms/base_llm/realtime/transformation.py b/litellm/llms/base_llm/realtime/transformation.py index b66bdbd2dd93..c24267ccc72f 100644 --- a/litellm/llms/base_llm/realtime/transformation.py +++ b/litellm/llms/base_llm/realtime/transformation.py @@ -30,9 +30,7 @@ def validate_environment( pass @abstractmethod - def get_complete_url( - self, api_base: Optional[str], model: str, api_key: Optional[str] = None - ) -> str: + def get_complete_url(self, api_base: Optional[str], model: str, api_key: Optional[str] = None) -> str: """ OPTIONAL @@ -71,9 +69,7 @@ def requires_session_configuration( ) -> bool: # initial configuration message sent to setup the realtime session return False - def session_configuration_request( - self, model: str - ) -> Optional[str]: # message sent to setup the realtime session + def session_configuration_request(self, model: str) -> Optional[str]: # message sent to setup the realtime session return None def transform_session_created_event( diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.py index c61ce52b530b..c6453745e5c9 100644 --- a/litellm/llms/base_llm/responses/transformation.py +++ b/litellm/llms/base_llm/responses/transformation.py @@ -96,9 +96,7 @@ def map_openai_params( pass @abstractmethod - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: return {} @abstractmethod @@ -270,9 +268,7 @@ def get_websocket_url( WebSocket path differs from their HTTP path (e.g. Azure uses /openai/v1/responses without api-version) should override this. """ - http_url = self.get_complete_url( - api_base=api_base, litellm_params=litellm_params - ) + http_url = self.get_complete_url(api_base=api_base, litellm_params=litellm_params) return http_url.replace("https://", "wss://").replace("http://", "ws://") def model_in_websocket_url(self) -> bool: @@ -359,7 +355,5 @@ def normalize_responses_api_request_dict(data: Dict[str, Any]) -> Dict[str, Any] return data return { **data, - "input": BaseResponsesAPIConfig.strip_custom_tool_call_namespace_from_responses_input( - data["input"] - ), + "input": BaseResponsesAPIConfig.strip_custom_tool_call_namespace_from_responses_input(data["input"]), } diff --git a/litellm/llms/base_llm/sandbox/transformation.py b/litellm/llms/base_llm/sandbox/transformation.py index 1c012a15fdb2..c807283ecd22 100644 --- a/litellm/llms/base_llm/sandbox/transformation.py +++ b/litellm/llms/base_llm/sandbox/transformation.py @@ -48,9 +48,7 @@ class BaseSandboxConfig: """Provider-agnostic sandbox operations.""" def validate_environment(self, api_key: str | None = None, **kwargs) -> str: - raise NotImplementedError( - "validate_environment must be implemented by provider" - ) + raise NotImplementedError("validate_environment must be implemented by provider") async def acreate_sandbox( self, @@ -89,8 +87,7 @@ async def _read_capped_lines(self, response: httpx.Response) -> list[str]: total += len(line.encode("utf-8")) if total > SANDBOX_MAX_OUTPUT_BYTES: raise ValueError( - f"Sandbox output exceeded {SANDBOX_MAX_OUTPUT_BYTES} bytes; aborting " - "to avoid unbounded memory use." + f"Sandbox output exceeded {SANDBOX_MAX_OUTPUT_BYTES} bytes; aborting to avoid unbounded memory use." ) lines.append(line) return lines diff --git a/litellm/llms/base_llm/search/transformation.py b/litellm/llms/base_llm/search/transformation.py index 1581d8bb0646..fdfac6f5f9f4 100644 --- a/litellm/llms/base_llm/search/transformation.py +++ b/litellm/llms/base_llm/search/transformation.py @@ -222,9 +222,7 @@ def transform_search_request( Returns: Dict with request data """ - raise NotImplementedError( - "transform_search_request must be implemented by provider" - ) + raise NotImplementedError("transform_search_request must be implemented by provider") def transform_search_response( self, @@ -236,9 +234,7 @@ def transform_search_response( Transform provider-specific Search response to standard format. Override in provider-specific implementations. """ - raise NotImplementedError( - "transform_search_response must be implemented by provider" - ) + raise NotImplementedError("transform_search_response must be implemented by provider") def get_error_class( self, diff --git a/litellm/llms/base_llm/skills/transformation.py b/litellm/llms/base_llm/skills/transformation.py index 017587c0b0cd..5bb181f59fbe 100644 --- a/litellm/llms/base_llm/skills/transformation.py +++ b/litellm/llms/base_llm/skills/transformation.py @@ -38,9 +38,7 @@ def custom_llm_provider(self) -> LlmProviders: pass @abstractmethod - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate and update headers with provider-specific requirements diff --git a/litellm/llms/base_llm/text_to_speech/transformation.py b/litellm/llms/base_llm/text_to_speech/transformation.py index 0e30ddae5fec..cbae6904ead5 100644 --- a/litellm/llms/base_llm/text_to_speech/transformation.py +++ b/litellm/llms/base_llm/text_to_speech/transformation.py @@ -137,9 +137,7 @@ def transform_text_to_speech_response( """ pass - def get_error_class( - self, error_message: str, status_code: int, headers: Dict - ) -> BaseLLMException: + def get_error_class(self, error_message: str, status_code: int, headers: Dict) -> BaseLLMException: from ..chat.transformation import BaseLLMException raise BaseLLMException( diff --git a/litellm/llms/base_llm/vector_store/transformation.py b/litellm/llms/base_llm/vector_store/transformation.py index 85a9c8382649..b222e3dd1601 100644 --- a/litellm/llms/base_llm/vector_store/transformation.py +++ b/litellm/llms/base_llm/vector_store/transformation.py @@ -27,9 +27,7 @@ class BaseVectorStoreConfig: - def get_supported_openai_params( - self, model: str - ) -> List[VECTOR_STORE_OPENAI_PARAMS]: + def get_supported_openai_params(self, model: str) -> List[VECTOR_STORE_OPENAI_PARAMS]: return [] def map_openai_params( @@ -41,9 +39,7 @@ def map_openai_params( return optional_params @abstractmethod - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: pass @abstractmethod @@ -104,15 +100,11 @@ def transform_create_vector_store_request( pass @abstractmethod - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: pass @abstractmethod - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: return {} @abstractmethod diff --git a/litellm/llms/base_llm/vector_store_files/transformation.py b/litellm/llms/base_llm/vector_store_files/transformation.py index 02915d013e50..e8799c56caef 100644 --- a/litellm/llms/base_llm/vector_store_files/transformation.py +++ b/litellm/llms/base_llm/vector_store_files/transformation.py @@ -52,9 +52,7 @@ def map_openai_params( return optional_params @abstractmethod - def get_auth_credentials( - self, litellm_params: Dict[str, Any] - ) -> VectorStoreFileAuthCredentials: ... + def get_auth_credentials(self, litellm_params: Dict[str, Any]) -> VectorStoreFileAuthCredentials: ... @abstractmethod def get_vector_store_file_endpoints_by_type( diff --git a/litellm/llms/base_llm/videos/transformation.py b/litellm/llms/base_llm/videos/transformation.py index 9b4cf7772802..e3a66af24a87 100644 --- a/litellm/llms/base_llm/videos/transformation.py +++ b/litellm/llms/base_llm/videos/transformation.py @@ -282,18 +282,14 @@ def transform_video_create_character_request( Returns: Tuple[str, list]: (url, files_list) for the multipart POST request """ - raise NotImplementedError( - "video create character is not supported for this provider" - ) + raise NotImplementedError("video create character is not supported for this provider") def transform_video_create_character_response( self, raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> CharacterObject: - raise NotImplementedError( - "video create character is not supported for this provider" - ) + raise NotImplementedError("video create character is not supported for this provider") def transform_video_get_character_request( self, @@ -308,18 +304,14 @@ def transform_video_get_character_request( Returns: Tuple[str, Dict]: (url, params) for the GET request """ - raise NotImplementedError( - "video get character is not supported for this provider" - ) + raise NotImplementedError("video get character is not supported for this provider") def transform_video_get_character_response( self, raw_response: httpx.Response, logging_obj: LiteLLMLoggingObj, ) -> CharacterObject: - raise NotImplementedError( - "video get character is not supported for this provider" - ) + raise NotImplementedError("video get character is not supported for this provider") def get_video_edit_prefetch_params( self, diff --git a/litellm/llms/baseten/chat.py b/litellm/llms/baseten/chat.py index 1e49b3460886..f5d52ef81ff4 100644 --- a/litellm/llms/baseten/chat.py +++ b/litellm/llms/baseten/chat.py @@ -82,9 +82,7 @@ def map_openai_params( optional_params[param] = value return optional_params - def _get_openai_compatible_provider_info( - self, api_base: str, api_key: str - ) -> tuple: + def _get_openai_compatible_provider_info(self, api_base: str, api_key: str) -> tuple: """ Get the OpenAI compatible provider info for Baseten """ diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.py index b71f37023e8f..380cc91ed98d 100644 --- a/litellm/llms/bedrock/base_aws_llm.py +++ b/litellm/llms/bedrock/base_aws_llm.py @@ -66,13 +66,9 @@ class AwsAuthError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://us-west-2.console.aws.amazon.com/bedrock" - ) + self.request = httpx.Request(method="POST", url="https://us-west-2.console.aws.amazon.com/bedrock") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class BaseAWSLLM: @@ -159,11 +155,7 @@ def _is_auth_with_web_identity_token( aws_role_name: Optional[str], aws_session_name: Optional[str], ) -> bool: - return ( - aws_web_identity_token is not None - and aws_role_name is not None - and aws_session_name is not None - ) + return aws_web_identity_token is not None and aws_role_name is not None and aws_session_name is not None @staticmethod def _is_auth_with_aws_role(aws_role_name: Optional[str]) -> bool: @@ -179,11 +171,7 @@ def _is_auth_with_aws_session_token_tuple( aws_secret_access_key: Optional[str], aws_session_token: Optional[str], ) -> bool: - return ( - aws_access_key_id is not None - and aws_secret_access_key is not None - and aws_session_token is not None - ) + return aws_access_key_id is not None and aws_secret_access_key is not None and aws_session_token is not None @staticmethod def _is_auth_with_access_key_and_secret_key( @@ -191,11 +179,7 @@ def _is_auth_with_access_key_and_secret_key( aws_secret_access_key: Optional[str], aws_region_name: Optional[str], ) -> bool: - return ( - aws_access_key_id is not None - and aws_secret_access_key is not None - and aws_region_name is not None - ) + return aws_access_key_id is not None and aws_secret_access_key is not None and aws_region_name is not None @tracer.wrap() def get_credentials( @@ -271,11 +255,7 @@ def get_credentials( aws_external_id, ) - args = { - k: v - for k, v in locals().items() - if k.startswith("aws_") or k == "ssl_verify" - } + args = {k: v for k, v in locals().items() if k.startswith("aws_") or k == "ssl_verify"} ######################################################### # Handle diff boto3 auth flows @@ -304,16 +284,12 @@ def get_credentials( elif self._is_auth_with_aws_role(aws_role_name): # Same role (IRSA/ECS/EC2): ambient creds via _get_or_set_cached_credentials like the # default env branch; never pre-read cache (must run _is_already_running_as_role first). - if self._is_already_running_as_role( - cast(str, aws_role_name), ssl_verify=ssl_verify - ): + if self._is_already_running_as_role(cast(str, aws_role_name), ssl_verify=ssl_verify): verbose_logger.debug( "Already running as target role %s, using ambient credentials", aws_role_name, ) - return self._get_or_set_cached_credentials( - args, self._auth_with_env_vars - ) + return self._get_or_set_cached_credentials(args, self._auth_with_env_vars) verbose_logger.debug("Using role assumption: calling _auth_with_aws_role") # If aws_session_name is not provided, generate a default one if aws_session_name is None: @@ -332,9 +308,7 @@ def get_credentials( return credentials elif self._is_auth_with_aws_profile(aws_profile_name): - credentials, _cache_ttl = self._auth_with_aws_profile( - cast(str, aws_profile_name) - ) + credentials, _cache_ttl = self._auth_with_aws_profile(cast(str, aws_profile_name)) return credentials elif self._is_auth_with_aws_session_token_tuple( aws_access_key_id, @@ -475,41 +449,23 @@ def get_bedrock_model_id( model_id = model_id.replace("invoke/", "", 1) if provider == "llama" and "llama/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="llama" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="llama") elif provider == "deepseek_r1" and "deepseek_r1/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="deepseek_r1" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="deepseek_r1") elif provider == "openai" and "openai/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="openai" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="openai") elif provider == "qwen2" and "qwen2/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="qwen2" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="qwen2") elif provider == "qwen3" and "qwen3/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="qwen3" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="qwen3") elif provider == "stability" and "stability/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="stability" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="stability") elif provider == "moonshot" and "moonshot/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="moonshot" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="moonshot") elif "nova-2/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="nova-2" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="nova-2") elif "nova/" in model_id: - model_id = BaseAWSLLM._get_model_id_from_model_with_spec( - model_id, spec="nova" - ) + model_id = BaseAWSLLM._get_model_id_from_model_with_spec(model_id, spec="nova") return model_id @staticmethod @@ -559,16 +515,12 @@ def get_bedrock_embedding_provider( parts = model.split(".") # Check if the second part (after potential region) is a known provider if len(parts) >= 2: - potential_provider = parts[ - 1 - ] # e.g., "twelvelabs" from "us.twelvelabs.marengo-embed-2-7-v1:0" + potential_provider = parts[1] # e.g., "twelvelabs" from "us.twelvelabs.marengo-embed-2-7-v1:0" if potential_provider in get_args(BEDROCK_EMBEDDING_PROVIDERS_LITERAL): return cast(BEDROCK_EMBEDDING_PROVIDERS_LITERAL, potential_provider) # Check if the first part is a known provider (standard format) - potential_provider = parts[ - 0 - ] # e.g., "cohere" from "cohere.embed-english-v3:0" + potential_provider = parts[0] # e.g., "cohere" from "cohere.embed-english-v3:0" if potential_provider in get_args(BEDROCK_EMBEDDING_PROVIDERS_LITERAL): return cast(BEDROCK_EMBEDDING_PROVIDERS_LITERAL, potential_provider) @@ -647,9 +599,7 @@ def _validate_aws_region_name(aws_region_name: Optional[str]) -> None: """ if aws_region_name is None: return - if not isinstance(aws_region_name, str) or not _VALID_AWS_REGION_PATTERN.match( - aws_region_name - ): + if not isinstance(aws_region_name, str) or not _VALID_AWS_REGION_PATTERN.match(aws_region_name): raise ValueError( f"Invalid AWS region format: {aws_region_name!r}. " "Region names must contain only lowercase letters, digits, and hyphens." @@ -705,15 +655,11 @@ def get_aws_region_name_for_non_llm_api_calls( # check env # litellm_aws_region_name = get_secret("AWS_REGION_NAME", None) - if litellm_aws_region_name is not None and isinstance( - litellm_aws_region_name, str - ): + if litellm_aws_region_name is not None and isinstance(litellm_aws_region_name, str): aws_region_name = litellm_aws_region_name standard_aws_region_name = get_secret("AWS_REGION", None) - if standard_aws_region_name is not None and isinstance( - standard_aws_region_name, str - ): + if standard_aws_region_name is not None and isinstance(standard_aws_region_name, str): aws_region_name = standard_aws_region_name if aws_region_name is None: @@ -796,9 +742,7 @@ def _is_already_running_as_role( import boto3 with tracer.trace("boto3.client(sts).get_caller_identity"): - sts_client = boto3.client( - "sts", verify=self._get_ssl_verify(ssl_verify) - ) + sts_client = boto3.client("sts", verify=self._get_ssl_verify(ssl_verify)) identity = sts_client.get_caller_identity() caller_arn = identity.get("Arn", "") @@ -817,9 +761,7 @@ def _is_already_running_as_role( return True except Exception as e: - verbose_logger.debug( - "Could not determine current role identity: %s", str(e) - ) + verbose_logger.debug("Could not determine current role identity: %s", str(e)) return False @@ -867,10 +809,7 @@ def _auth_with_web_identity_token( # references are expanded at load time, so such a reference reaching here is # caller-supplied input; reject it rather than expanding a process-environment # value for use as the token. - if ( - aws_web_identity_token.startswith("os.environ/") - or aws_web_identity_token in os.environ - ): + if aws_web_identity_token.startswith("os.environ/") or aws_web_identity_token in os.environ: raise AwsAuthError( message="Invalid web identity token reference.", status_code=400, @@ -951,15 +890,9 @@ def _auth_with_web_identity_token( assume_role_params["ExternalId"] = aws_external_id try: - sts_response = sts_client.assume_role_with_web_identity( - **assume_role_params - ) + sts_response = sts_client.assume_role_with_web_identity(**assume_role_params) except sts_client.exceptions.InvalidIdentityTokenException as e: - audience = ( - self._unverified_web_identity_audience(oidc_token) - if isinstance(oidc_token, str) - else None - ) + audience = self._unverified_web_identity_audience(oidc_token) if isinstance(oidc_token, str) else None detail = f" Token {audience}" if audience else "" raise AwsAuthError( status_code=401, @@ -1013,9 +946,7 @@ def _handle_irsa_cross_account( sts_client = boto3.client("sts", **irsa_sts_kwargs) # Manually assume the IRSA role with the session name - verbose_logger.debug( - f"Manually assuming IRSA role {irsa_role_arn} with session {aws_session_name}" - ) + verbose_logger.debug(f"Manually assuming IRSA role {irsa_role_arn} with session {aws_session_name}") irsa_response = sts_client.assume_role_with_web_identity( RoleArn=irsa_role_arn, RoleSessionName=aws_session_name, @@ -1045,9 +976,7 @@ def _handle_irsa_cross_account( verbose_logger.debug(f"Failed to get caller identity: {e}") # Now assume the target role - verbose_logger.debug( - f"Attempting to assume target role: {aws_role_name} with session: {aws_session_name}" - ) + verbose_logger.debug(f"Attempting to assume target role: {aws_role_name} with session: {aws_session_name}") assume_role_params = { "RoleArn": aws_role_name, "RoleSessionName": aws_session_name, @@ -1082,16 +1011,12 @@ def _handle_irsa_same_account( # Get current caller identity for debugging try: caller_identity = sts_client.get_caller_identity() - verbose_logger.debug( - f"Current IRSA identity: {caller_identity.get('Arn', 'unknown')}" - ) + verbose_logger.debug(f"Current IRSA identity: {caller_identity.get('Arn', 'unknown')}") except Exception as e: verbose_logger.debug(f"Failed to get caller identity: {e}") # Assume the role - verbose_logger.debug( - f"Attempting to assume role: {aws_role_name} with session: {aws_session_name}" - ) + verbose_logger.debug(f"Attempting to assume role: {aws_role_name} with session: {aws_session_name}") assume_role_params = { "RoleArn": aws_role_name, "RoleSessionName": aws_session_name, @@ -1103,9 +1028,7 @@ def _handle_irsa_same_account( return sts_client.assume_role(**assume_role_params) - def _extract_credentials_and_ttl( - self, sts_response: dict - ) -> Tuple[Credentials, Optional[int]]: + def _extract_credentials_and_ttl(self, sts_response: dict) -> Tuple[Credentials, Optional[int]]: """Extract credentials and TTL from STS response.""" from botocore.credentials import Credentials @@ -1117,9 +1040,7 @@ def _extract_credentials_and_ttl( ) expiration_time = sts_credentials["Expiration"] - ttl = int( - (expiration_time - datetime.now(expiration_time.tzinfo)).total_seconds() - ) + ttl = int((expiration_time - datetime.now(expiration_time.tzinfo)).total_seconds()) return credentials, ttl @@ -1148,17 +1069,10 @@ def _auth_with_aws_role( # If we have IRSA environment variables and no explicit credentials, # we need to use the web identity token flow - if ( - web_identity_token_file - and irsa_role_arn - and aws_access_key_id is None - and aws_secret_access_key is None - ): + if web_identity_token_file and irsa_role_arn and aws_access_key_id is None and aws_secret_access_key is None: # For cross-account role assumption with specific session names, # we need to manually assume the IRSA role first with the correct session name - verbose_logger.debug( - f"IRSA detected: using web identity token from {web_identity_token_file}" - ) + verbose_logger.debug(f"IRSA detected: using web identity token from {web_identity_token_file}") try: # Check if we need to do cross-account role assumption @@ -1185,9 +1099,7 @@ def _auth_with_aws_role( except Exception as e: verbose_logger.debug(f"Failed to assume role via IRSA: {e}") - if "AccessDenied" in str( - e - ) and "is not authorized to perform: sts:AssumeRole" in str(e): + if "AccessDenied" in str(e) and "is not authorized to perform: sts:AssumeRole" in str(e): # Provide a more helpful error message for trust policy issues verbose_logger.error( f"Access denied when trying to assume role {aws_role_name}. " @@ -1235,9 +1147,7 @@ def _auth_with_aws_role( # partition, and role name). This avoids silently using the # wrong identity when there is a genuine trust-policy or # permission misconfiguration. - if self._is_already_running_as_role( - aws_role_name, ssl_verify=ssl_verify - ): + if self._is_already_running_as_role(aws_role_name, ssl_verify=ssl_verify): verbose_logger.warning( "AssumeRole failed for %s (%s). " "Caller is already running as this role; " @@ -1248,8 +1158,7 @@ def _auth_with_aws_role( return self._auth_with_env_vars() # Genuine permission error — re-raise verbose_logger.error( - "AssumeRole AccessDenied for %s and caller is NOT " - "the same role. Re-raising. Error: %s", + "AssumeRole AccessDenied for %s and caller is NOT the same role. Re-raising. Error: %s", aws_role_name, error_str, ) @@ -1270,9 +1179,7 @@ def _auth_with_aws_role( return credentials, sts_ttl @tracer.wrap() - def _auth_with_aws_profile( - self, aws_profile_name: str - ) -> Tuple[Credentials, Optional[int]]: + def _auth_with_aws_profile(self, aws_profile_name: str) -> Tuple[Credentials, Optional[int]]: """ Authenticate with AWS profile """ @@ -1360,13 +1267,9 @@ def get_runtime_endpoint( env_aws_bedrock_runtime_endpoint = get_secret("AWS_BEDROCK_RUNTIME_ENDPOINT") if api_base is not None: endpoint_url = api_base - elif aws_bedrock_runtime_endpoint is not None and isinstance( - aws_bedrock_runtime_endpoint, str - ): + elif aws_bedrock_runtime_endpoint is not None and isinstance(aws_bedrock_runtime_endpoint, str): endpoint_url = aws_bedrock_runtime_endpoint - elif env_aws_bedrock_runtime_endpoint and isinstance( - env_aws_bedrock_runtime_endpoint, str - ): + elif env_aws_bedrock_runtime_endpoint and isinstance(env_aws_bedrock_runtime_endpoint, str): endpoint_url = env_aws_bedrock_runtime_endpoint else: endpoint_url = self._select_default_endpoint_url( @@ -1375,13 +1278,9 @@ def get_runtime_endpoint( ) # Determine proxy_endpoint_url - if aws_bedrock_runtime_endpoint is not None and isinstance( - aws_bedrock_runtime_endpoint, str - ): + if aws_bedrock_runtime_endpoint is not None and isinstance(aws_bedrock_runtime_endpoint, str): proxy_endpoint_url = aws_bedrock_runtime_endpoint - elif env_aws_bedrock_runtime_endpoint and isinstance( - env_aws_bedrock_runtime_endpoint, str - ): + elif env_aws_bedrock_runtime_endpoint and isinstance(env_aws_bedrock_runtime_endpoint, str): proxy_endpoint_url = env_aws_bedrock_runtime_endpoint else: proxy_endpoint_url = endpoint_url @@ -1477,21 +1376,15 @@ def get_request_headers( try: from botocore.awsrequest import AWSRequest except ImportError: - raise ImportError( - "Missing boto3 to call bedrock. Run 'pip install boto3'." - ) + raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") headers["Authorization"] = f"Bearer {aws_bearer_token}" - request = AWSRequest( - method="POST", url=endpoint_url, data=data, headers=headers - ) + request = AWSRequest(method="POST", url=endpoint_url, data=data, headers=headers) else: try: from botocore.auth import SigV4Auth from botocore.awsrequest import AWSRequest except ImportError: - raise ImportError( - "Missing boto3 to call bedrock. Run 'pip install boto3'." - ) + raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") # Filter headers for AWS signature calculation # AWS SigV4 only includes specific headers in signature calculation @@ -1541,11 +1434,7 @@ def _filter_headers_for_aws_signature(self, headers: dict) -> dict: if header_value is None: continue header_lower = header_name.lower() - if ( - header_lower in aws_headers - or header_lower.startswith("x-amz-") - or header_lower.startswith("x-amzn-") - ): + if header_lower in aws_headers or header_lower.startswith("x-amz-") or header_lower.startswith("x-amzn-"): aws_signature_headers[header_name] = header_value return aws_signature_headers @@ -1605,9 +1494,7 @@ def _sign_request( aws_web_identity_token = optional_params.get("aws_web_identity_token", None) aws_sts_endpoint = optional_params.get("aws_sts_endpoint", None) aws_external_id = optional_params.get("aws_external_id", None) - aws_region_name = self._get_aws_region_name( - optional_params=optional_params, model=model - ) + aws_region_name = self._get_aws_region_name(optional_params=optional_params, model=model) credentials: Credentials = self.get_credentials( aws_access_key_id=aws_access_key_id, @@ -1642,9 +1529,7 @@ def _sign_request( for header_name, header_value in headers.items(): if header_value is not None: request_headers_dict[header_name] = header_value - if ( - headers is not None and "Authorization" in headers - ): # prevent sigv4 from overwriting the auth header + if headers is not None and "Authorization" in headers: # prevent sigv4 from overwriting the auth header request_headers_dict["Authorization"] = headers["Authorization"] return request_headers_dict, request.body diff --git a/litellm/llms/bedrock/batches/handler.py b/litellm/llms/bedrock/batches/handler.py index c071f331337c..b0c7f1a3695c 100644 --- a/litellm/llms/bedrock/batches/handler.py +++ b/litellm/llms/bedrock/batches/handler.py @@ -41,9 +41,7 @@ def _extract_job_id_from_arn(arn: str) -> Optional[str]: return arn.rsplit("/", 1)[-1] or None -def _predict_output_file_uri( - output_prefix: str, input_uri: str, job_id: Optional[str] -) -> Optional[str]: +def _predict_output_file_uri(output_prefix: str, input_uri: str, job_id: Optional[str]) -> Optional[str]: """ Compute the deterministic per-job result file URI Bedrock writes to. @@ -85,9 +83,7 @@ class BedrockBatchesHandler: """ @staticmethod - def _handle_async_invoke_status( - batch_id: str, aws_region_name: str, logging_obj=None, **kwargs - ) -> "LiteLLMBatch": + def _handle_async_invoke_status(batch_id: str, aws_region_name: str, logging_obj=None, **kwargs) -> "LiteLLMBatch": """ Handle async invoke status check for AWS Bedrock. @@ -121,9 +117,7 @@ async def _async_get_status(): from litellm.types.utils import LiteLLMBatch openai_batch_metadata: OpenAIBatchMetadata = { - "output_file_id": status_response["outputDataConfig"][ - "s3OutputDataConfig" - ]["s3Uri"], + "output_file_id": status_response["outputDataConfig"]["s3OutputDataConfig"]["s3Uri"], "failure_message": status_response.get("failureMessage") or "", "model_arn": status_response["modelArn"], } @@ -135,11 +129,7 @@ async def _async_get_status(): created_at=status_response["submitTime"], in_progress_at=status_response["lastModifiedTime"], completed_at=status_response.get("endTime"), - failed_at=( - status_response.get("endTime") - if status_response["status"] == "failed" - else None - ), + failed_at=(status_response.get("endTime") if status_response["status"] == "failed" else None), request_counts=BatchRequestCounts( total=1, completed=1 if status_response["status"] == "completed" else 0, @@ -210,14 +200,10 @@ def _handle_model_invocation_job_status( try: import boto3 except ImportError as exc: - raise ImportError( - "Missing boto3 to call bedrock. Run 'pip install boto3'." - ) from exc + raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") from exc # Resolve region: explicit > parsed-from-ARN > us-east-1 (boto3 default). - region = ( - aws_region_name or _extract_region_from_bedrock_arn(batch_id) or "us-east-1" - ) + region = aws_region_name or _extract_region_from_bedrock_arn(batch_id) or "us-east-1" # Resolve credentials through the same path the rest of the bedrock # provider uses, so model_list / env / role-assumption configs are @@ -257,10 +243,7 @@ def _handle_model_invocation_job_status( api_key="", additional_args={ "complete_input_dict": {"jobIdentifier": batch_id}, - "api_base": ( - f"https://bedrock.{region}.amazonaws.com/" - f"model-invocation-job/{url_path_id}" - ), + "api_base": (f"https://bedrock.{region}.amazonaws.com/model-invocation-job/{url_path_id}"), }, ) @@ -280,16 +263,8 @@ def _handle_model_invocation_job_status( _BEDROCK_MIJ_STATUS_TO_OPENAI.get(bedrock_status, "in_progress"), ) - input_uri = ( - response.get("inputDataConfig", {}) - .get("s3InputDataConfig", {}) - .get("s3Uri", "") - ) - output_prefix = ( - response.get("outputDataConfig", {}) - .get("s3OutputDataConfig", {}) - .get("s3Uri", "") - ) + input_uri = response.get("inputDataConfig", {}).get("s3InputDataConfig", {}).get("s3Uri", "") + output_prefix = response.get("outputDataConfig", {}).get("s3OutputDataConfig", {}).get("s3Uri", "") # Bedrock returns the output *prefix* the user supplied at job creation. # Actual results land at //.out — we diff --git a/litellm/llms/bedrock/batches/transformation.py b/litellm/llms/bedrock/batches/transformation.py index 620bc91732d6..b0e28b6ba90a 100644 --- a/litellm/llms/bedrock/batches/transformation.py +++ b/litellm/llms/bedrock/batches/transformation.py @@ -74,9 +74,7 @@ def get_complete_batch_url( # Bedrock model invocation job endpoint # Format: https://bedrock.{region}.amazonaws.com/model-invocation-job - bedrock_endpoint = ( - f"https://bedrock.{aws_region_name}.amazonaws.com/model-invocation-job" - ) + bedrock_endpoint = f"https://bedrock.{aws_region_name}.amazonaws.com/model-invocation-job" return bedrock_endpoint @@ -106,9 +104,7 @@ def transform_create_batch_request( input_bucket, input_key = self.common_utils.parse_s3_uri(input_file_id) # Get output S3 configuration - output_bucket = litellm_params.get("s3_output_bucket_name") or os.getenv( - "AWS_S3_OUTPUT_BUCKET_NAME" - ) + output_bucket = litellm_params.get("s3_output_bucket_name") or os.getenv("AWS_S3_OUTPUT_BUCKET_NAME") if not output_bucket: # Use same bucket as input if no output bucket specified output_bucket = input_bucket @@ -126,9 +122,7 @@ def transform_create_batch_request( ) if not model: - raise ValueError( - "Could not determine Bedrock model ID. Please pass `model` in your request body." - ) + raise ValueError("Could not determine Bedrock model ID. Please pass `model` in your request body.") # Generate job name with the correct model ID using common utility job_name = self.common_utils.generate_unique_job_name(model, prefix="litellm") @@ -136,9 +130,7 @@ def transform_create_batch_request( # Build input data config input_data_config: BedrockInputDataConfig = { - "s3InputDataConfig": BedrockS3InputDataConfig( - s3Uri=f"s3://{input_bucket}/{input_key}" - ) + "s3InputDataConfig": BedrockS3InputDataConfig(s3Uri=f"s3://{input_bucket}/{input_key}") } # Build output data config @@ -147,15 +139,11 @@ def transform_create_batch_request( ) # Add optional KMS encryption key ID if provided - s3_encryption_key_id = litellm_params.get( - "s3_encryption_key_id" - ) or get_secret_str("AWS_S3_ENCRYPTION_KEY_ID") + s3_encryption_key_id = litellm_params.get("s3_encryption_key_id") or get_secret_str("AWS_S3_ENCRYPTION_KEY_ID") if s3_encryption_key_id: s3_output_config["s3EncryptionKeyId"] = s3_encryption_key_id - output_data_config: BedrockOutputDataConfig = { - "s3OutputDataConfig": s3_output_config - } + output_data_config: BedrockOutputDataConfig = {"s3OutputDataConfig": s3_output_config} # Create Bedrock batch request with proper typing bedrock_request: BedrockCreateBatchRequest = { @@ -176,7 +164,9 @@ def transform_create_batch_request( # For Bedrock, we need to return a pre-signed request with AWS auth headers # Use common utility for AWS signing - endpoint_url = f"https://bedrock.{self._get_aws_region_name(optional_params, model)}.amazonaws.com/model-invocation-job" + endpoint_url = ( + f"https://bedrock.{self._get_aws_region_name(optional_params, model)}.amazonaws.com/model-invocation-job" + ) signed_headers, signed_data = self.common_utils.sign_aws_request( service_name="bedrock", data=bedrock_request, @@ -264,9 +254,7 @@ def transform_create_batch_response( cancelling_at=None, cancelled_at=None, request_counts=None, - metadata=self._get_openai_compatible_batch_metadata( - original_request.get("metadata", {}) - ), + metadata=self._get_openai_compatible_batch_metadata(original_request.get("metadata", {})), ) @staticmethod @@ -328,9 +316,7 @@ def transform_retrieve_batch_request( import urllib.parse as _ul encoded_arn = _ul.quote(batch_id, safe="") - endpoint_url = ( - f"https://bedrock.{region}.amazonaws.com/model-invocation-job/{encoded_arn}" - ) + endpoint_url = f"https://bedrock.{region}.amazonaws.com/model-invocation-job/{encoded_arn}" # Use common utility for AWS signing signed_headers, _ = self.common_utils.sign_aws_request( @@ -363,9 +349,7 @@ def parse_timestamp(ts_str: Optional[str]) -> Optional[int]: return None created_at = parse_timestamp( - str(response_data.get("submitTime")) - if response_data.get("submitTime") is not None - else None + str(response_data.get("submitTime")) if response_data.get("submitTime") is not None else None ) in_progress_states = {"InProgress", "Validating", "Scheduled"} in_progress_at = ( @@ -378,36 +362,22 @@ def parse_timestamp(ts_str: Optional[str]) -> Optional[int]: else None ) completed_at = ( - parse_timestamp( - str(response_data.get("endTime")) - if response_data.get("endTime") is not None - else None - ) + parse_timestamp(str(response_data.get("endTime")) if response_data.get("endTime") is not None else None) if status_str in {"Completed", "PartiallyCompleted"} else None ) failed_at = ( - parse_timestamp( - str(response_data.get("endTime")) - if response_data.get("endTime") is not None - else None - ) + parse_timestamp(str(response_data.get("endTime")) if response_data.get("endTime") is not None else None) if status_str == "Failed" else None ) cancelled_at = ( - parse_timestamp( - str(response_data.get("endTime")) - if response_data.get("endTime") is not None - else None - ) + parse_timestamp(str(response_data.get("endTime")) if response_data.get("endTime") is not None else None) if status_str == "Stopped" else None ) expires_at = parse_timestamp( - str(response_data.get("jobExpirationTime")) - if response_data.get("jobExpirationTime") is not None - else None + str(response_data.get("jobExpirationTime")) if response_data.get("jobExpirationTime") is not None else None ) return ( @@ -539,9 +509,7 @@ def transform_retrieve_batch_response( input_file_id, output_file_id = self._extract_file_configs(response_data) # Extract errors and metadata - errors, enriched_metadata = self._extract_errors_and_metadata( - response_data, raw_response - ) + errors, enriched_metadata = self._extract_errors_and_metadata(response_data, raw_response) return LiteLLMBatch( id=job_arn, @@ -566,9 +534,7 @@ def transform_retrieve_batch_response( metadata=enriched_metadata, ) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[Dict, Headers] - ) -> BaseLLMException: + def get_error_class(self, error_message: str, status_code: int, headers: Union[Dict, Headers]) -> BaseLLMException: """ Get Bedrock-specific error class using common utility. """ diff --git a/litellm/llms/bedrock/chat/__init__.py b/litellm/llms/bedrock/chat/__init__.py index 8cd0e94e68e3..c1323b9192aa 100644 --- a/litellm/llms/bedrock/chat/__init__.py +++ b/litellm/llms/bedrock/chat/__init__.py @@ -9,9 +9,7 @@ ) -def get_bedrock_event_stream_decoder( - invoke_provider: Optional[str], model: str, sync_stream: bool, json_mode: bool -): +def get_bedrock_event_stream_decoder(invoke_provider: Optional[str], model: str, sync_stream: bool, json_mode: bool): if invoke_provider and invoke_provider == "anthropic": decoder: AWSEventStreamDecoder = AmazonAnthropicClaudeStreamDecoder( model=model, diff --git a/litellm/llms/bedrock/chat/agentcore/transformation.py b/litellm/llms/bedrock/chat/agentcore/transformation.py index 542af61dd3f2..356bc829677a 100644 --- a/litellm/llms/bedrock/chat/agentcore/transformation.py +++ b/litellm/llms/bedrock/chat/agentcore/transformation.py @@ -84,9 +84,7 @@ def get_complete_url( Get the complete url for the request """ ### SET RUNTIME ENDPOINT ### - aws_bedrock_runtime_endpoint = optional_params.get( - "aws_bedrock_runtime_endpoint", None - ) + aws_bedrock_runtime_endpoint = optional_params.get("aws_bedrock_runtime_endpoint", None) # Extract ARN from model string agent_runtime_arn = self._get_agent_runtime_arn(model) @@ -233,9 +231,7 @@ def transform_request( dict: Payload dict containing the prompt and (optionally) the OpenAI content list. """ - verbose_logger.debug( - f"AgentCore transform_request - optional_params keys: {list(optional_params.keys())}" - ) + verbose_logger.debug(f"AgentCore transform_request - optional_params keys: {list(optional_params.keys())}") # Use the last message content as the prompt prompt = convert_content_list_to_str(messages[-1]) @@ -250,8 +246,7 @@ def transform_request( if self._should_forward_multimodal_content(optional_params, litellm_params): last_content = messages[-1].get("content") if isinstance(last_content, list) and any( - isinstance(block, dict) and block.get("type") not in (None, "text") - for block in last_content + isinstance(block, dict) and block.get("type") not in (None, "text") for block in last_content ): # Copy so the payload never aliases messages[-1]["content"]; shallow, # not deep, to avoid cloning large base64 media on the request path. @@ -273,9 +268,7 @@ def transform_request( return payload @staticmethod - def _should_forward_multimodal_content( - optional_params: dict, litellm_params: dict - ) -> bool: + def _should_forward_multimodal_content(optional_params: dict, litellm_params: dict) -> bool: """Whether to forward raw OpenAI content blocks under ``payload["content"]``. Opt-in via the ``forward_multimodal_content`` litellm param (default ``False``) @@ -346,15 +339,9 @@ def _extract_content_from_message(self, message: AgentCoreMessage) -> str: if not isinstance(content_list, list): return "" - return "".join( - block["text"] - for block in content_list - if isinstance(block, dict) and "text" in block - ) + return "".join(block["text"] for block in content_list if isinstance(block, dict) and "text" in block) - def _calculate_usage( - self, model: str, messages: List[AllMessageValues], content: str - ) -> Optional[Usage]: + def _calculate_usage(self, model: str, messages: List[AllMessageValues], content: str) -> Optional[Usage]: """ Calculate token usage using LiteLLM's token counter. @@ -370,9 +357,7 @@ def _calculate_usage( from litellm.utils import token_counter prompt_tokens = token_counter(model=model, messages=messages) - completion_tokens = token_counter( - model=model, text=content, count_response_tokens=True - ) + completion_tokens = token_counter(model=model, text=content, count_response_tokens=True) total_tokens = prompt_tokens + completion_tokens verbose_logger.debug( @@ -402,9 +387,7 @@ def _parse_json_response(self, response_json: dict) -> AgentCoreParsedResponse: # Guard: if json.loads() returned a non-dict (e.g. array or primitive), # skip strategy matching and fall back to raw JSON string if not isinstance(response_json, dict): - verbose_logger.warning( - "AgentCore: JSON response is not a dict. Returning raw JSON as content." - ) + verbose_logger.warning("AgentCore: JSON response is not a dict. Returning raw JSON as content.") return AgentCoreParsedResponse( content=json.dumps(response_json), usage=None, @@ -465,9 +448,7 @@ def _parse_json_response(self, response_json: dict) -> AgentCoreParsedResponse: final_message=None, ) - def _get_parsed_response( - self, raw_response: httpx.Response - ) -> AgentCoreParsedResponse: + def _get_parsed_response(self, raw_response: httpx.Response) -> AgentCoreParsedResponse: """ Parse AgentCore response based on content type. @@ -491,9 +472,7 @@ def _get_parsed_response( # SSE stream response (text/event-stream or default) verbose_logger.debug("Parsing SSE stream response") response_text = raw_response.text - verbose_logger.debug( - f"AgentCore response (first 500 chars): {response_text[:500]}" - ) + verbose_logger.debug(f"AgentCore response (first 500 chars): {response_text[:500]}") return self._parse_sse_stream(response_text) def _parse_sse_stream(self, response_text: str) -> AgentCoreParsedResponse: @@ -527,9 +506,7 @@ def _parse_sse_stream(self, response_text: str) -> AgentCoreParsedResponse: # Process event data if "event" in data and isinstance(data["event"], dict): event_payload = data["event"] - verbose_logger.debug( - f"Event payload keys: {list(event_payload.keys())}" - ) + verbose_logger.debug(f"Event payload keys: {list(event_payload.keys())}") # Extract usage metadata if usage := self._extract_usage_from_event(data): @@ -541,17 +518,11 @@ def _parse_sse_stream(self, response_text: str) -> AgentCoreParsedResponse: content_blocks.append(text) # Build final content - content = ( - self._extract_content_from_message(final_message) - if final_message - else "".join(content_blocks) - ) + content = self._extract_content_from_message(final_message) if final_message else "".join(content_blocks) verbose_logger.debug(f"Final usage_data: {usage_data}") - return AgentCoreParsedResponse( - content=content, usage=usage_data, final_message=final_message - ) + return AgentCoreParsedResponse(content=content, usage=usage_data, final_message=final_message) def _stream_agentcore_response_sync( self, @@ -692,9 +663,7 @@ def get_sync_custom_stream_wrapper( ) if response.status_code != 200: - raise BedrockError( - status_code=response.status_code, message=str(response.read()) - ) + raise BedrockError(status_code=response.status_code, message=str(response.read())) # LOGGING logging_obj.post_call( @@ -708,8 +677,7 @@ def get_sync_custom_stream_wrapper( content_type = response.headers.get("content-type", "").lower() if "application/json" in content_type: verbose_logger.debug( - "AgentCore streaming: received JSON response instead of SSE, " - "converting to single-chunk stream" + "AgentCore streaming: received JSON response instead of SSE, converting to single-chunk stream" ) try: body = response.read() @@ -894,9 +862,7 @@ async def get_async_custom_stream_wrapper( ) if client is None or not isinstance(client, AsyncHTTPHandler): - client = get_async_httpx_client( - llm_provider=cast(Any, "bedrock"), params={} - ) + client = get_async_httpx_client(llm_provider=cast(Any, "bedrock"), params={}) verbose_logger.debug(f"Making async streaming request to: {api_base}") @@ -910,9 +876,7 @@ async def get_async_custom_stream_wrapper( ) if response.status_code != 200: - raise BedrockError( - status_code=response.status_code, message=str(await response.aread()) - ) + raise BedrockError(status_code=response.status_code, message=str(await response.aread())) # LOGGING logging_obj.post_call( @@ -926,8 +890,7 @@ async def get_async_custom_stream_wrapper( content_type = response.headers.get("content-type", "").lower() if "application/json" in content_type: verbose_logger.debug( - "AgentCore streaming: received JSON response instead of SSE, " - "converting to single-chunk stream" + "AgentCore streaming: received JSON response instead of SSE, converting to single-chunk stream" ) try: body = await response.aread() @@ -939,9 +902,7 @@ async def get_async_custom_stream_wrapper( ) parsed = self._parse_json_response(response_json) - async def _json_as_async_stream() -> AsyncGenerator[ - ModelResponseStream, None - ]: + async def _json_as_async_stream() -> AsyncGenerator[ModelResponseStream, None]: # Content chunk content_chunk = ModelResponseStream( id=f"chatcmpl-{uuid.uuid4()}", @@ -1054,9 +1015,7 @@ def transform_response( setattr(model_response, "usage", usage) else: # Calculate token usage using LiteLLM's token counter - verbose_logger.debug( - "No usage data from AgentCore - calculating tokens" - ) + verbose_logger.debug("No usage data from AgentCore - calculating tokens") calculated_usage = self._calculate_usage(model, messages, content) if calculated_usage: setattr(model_response, "usage", calculated_usage) @@ -1064,9 +1023,7 @@ def transform_response( return model_response except Exception as e: - verbose_logger.error( - f"Error processing Bedrock AgentCore response: {str(e)}" - ) + verbose_logger.error(f"Error processing Bedrock AgentCore response: {str(e)}") raise BedrockError( message=f"Error processing response: {str(e)}", status_code=raw_response.status_code, diff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.py index 040193f6bcc0..292f570cc4ed 100644 --- a/litellm/llms/bedrock/chat/converse_handler.py +++ b/litellm/llms/bedrock/chat/converse_handler.py @@ -46,33 +46,25 @@ def make_sync_call( ) if response.status_code != 200: - raise BedrockError( - status_code=response.status_code, message=str(response.read()) - ) + raise BedrockError(status_code=response.status_code, message=str(response.read())) if fake_stream: - model_response: ModelResponse = ( - litellm.AmazonConverseConfig()._transform_response( - model=model, - response=response, - model_response=litellm.ModelResponse(), - stream=True, - logging_obj=logging_obj, - optional_params={}, - api_key="", - data=data, - messages=messages, - encoding=litellm.encoding, - ) + model_response: ModelResponse = litellm.AmazonConverseConfig()._transform_response( + model=model, + response=response, + model_response=litellm.ModelResponse(), + stream=True, + logging_obj=logging_obj, + optional_params={}, + api_key="", + data=data, + messages=messages, + encoding=litellm.encoding, ) # type: ignore - completion_stream: Any = MockResponseIterator( - model_response=model_response, json_mode=json_mode - ) + completion_stream: Any = MockResponseIterator(model_response=model_response, json_mode=json_mode) else: decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) - completion_stream = decoder.iter_bytes( - response.iter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) # LOGGING logging_obj.post_call( @@ -215,9 +207,7 @@ async def async_completion( if isinstance(timeout, float) or isinstance(timeout, int): timeout = httpx.Timeout(timeout) _params["timeout"] = timeout - client = get_async_httpx_client( - params=_params, llm_provider=litellm.LlmProviders.BEDROCK - ) + client = get_async_httpx_client(params=_params, llm_provider=litellm.LlmProviders.BEDROCK) else: client = client # type: ignore @@ -296,10 +286,7 @@ def completion( break modelId = self.encode_model_id(model_id=_model_for_id) # Inject region extracted from model path so _get_aws_region_name picks it up - if ( - _region_from_model is not None - and "aws_region_name" not in optional_params - ): + if _region_from_model is not None and "aws_region_name" not in optional_params: optional_params["aws_region_name"] = _region_from_model fake_stream = litellm.AmazonConverseConfig().should_fake_stream( @@ -332,9 +319,7 @@ def completion( aws_external_id = optional_params.pop("aws_external_id", None) optional_params.pop("aws_region_name", None) - litellm_params["aws_region_name"] = ( - aws_region_name # [DO NOT DELETE] important for async calls - ) + litellm_params["aws_region_name"] = aws_region_name # [DO NOT DELETE] important for async calls credentials: Credentials = self.get_credentials( aws_access_key_id=aws_access_key_id, @@ -368,9 +353,7 @@ def completion( headers = {"Content-Type": "application/json", **extra_headers} # Filter beta headers in HTTP headers before making the request - headers = update_headers_with_filtered_beta( - headers=headers, provider="bedrock_converse" - ) + headers = update_headers_with_filtered_beta(headers=headers, provider="bedrock_converse") ### ROUTING (ASYNC, STREAMING, SYNC) if acompletion: if isinstance(client, HTTPHandler): @@ -458,11 +441,7 @@ def completion( if stream is not None and stream is True: completion_stream = make_sync_call( - client=( - client - if client is not None and isinstance(client, HTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, HTTPHandler) else None), api_base=proxy_endpoint_url, headers=prepped.headers, # type: ignore data=data, diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.py index a700c07d87a5..b135a116753d 100644 --- a/litellm/llms/bedrock/chat/converse_transformation.py +++ b/litellm/llms/bedrock/chat/converse_transformation.py @@ -167,8 +167,7 @@ def _convert_consecutive_user_messages_to_guarded_text( if isinstance(content, list): has_guarded_text = any( - isinstance(item, dict) and item.get("type") == "guarded_text" - for item in content + isinstance(item, dict) and item.get("type") == "guarded_text" for item in content ) if has_guarded_text: continue # Skip this message if it already has guarded_text @@ -329,13 +328,9 @@ def _is_nova_2_model(self, model: str) -> bool: # Check if the model is a Nova 2 model (matches nova-2-lite, nova-2-pro, etc.) # Also check for nova-2/ spec prefix for imported models - return model_without_region.startswith( - "amazon.nova-2-" - ) or model_without_region.startswith("nova-2/") + return model_without_region.startswith("amazon.nova-2-") or model_without_region.startswith("nova-2/") - def _map_web_search_options( - self, web_search_options: dict, model: str - ) -> Optional[BedrockToolBlock]: + def _map_web_search_options(self, web_search_options: dict, model: str) -> Optional[BedrockToolBlock]: """ Map web_search_options to Nova grounding systemTool. @@ -364,9 +359,7 @@ def _map_web_search_options( # (unlike Anthropic), so we just enable grounding with no options return BedrockToolBlock(systemTool={"name": "nova_grounding"}) - def _transform_reasoning_effort_to_reasoning_config( - self, reasoning_effort: str - ) -> dict: + def _transform_reasoning_effort_to_reasoning_config(self, reasoning_effort: str) -> dict: """ Transform reasoning_effort parameter to Nova 2 reasoningConfig structure. @@ -411,9 +404,7 @@ def _transform_reasoning_effort_to_reasoning_config( } } - def _handle_reasoning_effort_parameter( - self, model: str, reasoning_effort: str, optional_params: dict - ) -> None: + def _handle_reasoning_effort_parameter(self, model: str, reasoning_effort: str, optional_params: dict) -> None: """ Handle the reasoning_effort parameter based on the model type. @@ -425,9 +416,7 @@ def _handle_reasoning_effort_parameter( if "gpt-oss" in model: optional_params["reasoning_effort"] = reasoning_effort elif self._is_nova_2_model(model): - reasoning_config = self._transform_reasoning_effort_to_reasoning_config( - reasoning_effort - ) + reasoning_config = self._transform_reasoning_effort_to_reasoning_config(reasoning_effort) optional_params.update(reasoning_config) else: mapped_thinking = AnthropicConfig._map_reasoning_effort( @@ -441,9 +430,7 @@ def _handle_reasoning_effort_parameter( else: optional_params["thinking"] = mapped_thinking if AnthropicConfig._is_adaptive_thinking_model(model): - mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get( - reasoning_effort - ) + mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get(reasoning_effort) if mapped_effort is None: AnthropicConfig._raise_invalid_reasoning_effort( model=model, @@ -459,9 +446,7 @@ def _handle_reasoning_effort_parameter( output_config=existing_output_config, ) mapped_effort = existing_output_config["effort"] - self._validate_anthropic_adaptive_effort( - model=model, effort=mapped_effort - ) + self._validate_anthropic_adaptive_effort(model=model, effort=mapped_effort) optional_params["output_config"] = existing_output_config optional_params["_output_config_normalized"] = True @@ -523,9 +508,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: "parallel_tool_calls", ] - if ( - "arn" in model - ): # we can't infer the model from the arn, so just add all params + if "arn" in model: # we can't infer the model from the arn, so just add all params supported_params.append("tools") supported_params.append("tool_choice") supported_params.append("thinking") @@ -547,9 +530,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: or base_model.startswith("meta.llama3-3") or base_model.startswith("meta.llama4") or base_model.startswith("amazon.nova") - or supports_function_calling( - model=model, custom_llm_provider=self.custom_llm_provider - ) + or supports_function_calling(model=model, custom_llm_provider=self.custom_llm_provider) ): supported_params.append("tools") @@ -559,9 +540,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: if litellm.utils.supports_tool_choice( model=model, custom_llm_provider=self.custom_llm_provider - ) or litellm.utils.supports_tool_choice( - model=base_model, custom_llm_provider=self.custom_llm_provider - ): + ) or litellm.utils.supports_tool_choice(model=base_model, custom_llm_provider=self.custom_llm_provider): # only anthropic and mistral support tool choice config. otherwise (E.g. cohere) will fail the call - https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ToolChoice.html supported_params.append("tool_choice") @@ -580,9 +559,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: model=model, custom_llm_provider=self.custom_llm_provider, ) - or supports_reasoning( - model=base_model, custom_llm_provider=self.custom_llm_provider - ) + or supports_reasoning(model=base_model, custom_llm_provider=self.custom_llm_provider) ): supported_params.append("thinking") supported_params.append("reasoning_effort") @@ -611,9 +588,7 @@ def map_tool_choice_values( elif isinstance(tool_choice, dict): # only supported for anthropic + mistral models - https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ToolChoice.html specific_tool = SpecificToolChoiceBlock( - name=make_valid_bedrock_tool_name( - tool_choice.get("function", {}).get("name", "") - ) + name=make_valid_bedrock_tool_name(tool_choice.get("function", {}).get("name", "")) ) return ToolChoiceValuesBlock(tool=specific_tool) else: @@ -634,15 +609,9 @@ def get_supported_video_types(self) -> List[str]: return ["mp4", "mov", "mkv", "webm", "flv", "mpeg", "mpg", "wmv", "3gp"] def get_all_supported_content_types(self) -> List[str]: - return ( - self.get_supported_image_types() - + self.get_supported_document_types() - + self.get_supported_video_types() - ) + return self.get_supported_image_types() + self.get_supported_document_types() + self.get_supported_video_types() - def is_computer_use_tool_used( - self, tools: Optional[List[OpenAIChatCompletionToolParam]], model: str - ) -> bool: + def is_computer_use_tool_used(self, tools: Optional[List[OpenAIChatCompletionToolParam]], model: str) -> bool: """Check if computer use tools are being used in the request.""" if tools is None: return False @@ -655,9 +624,7 @@ def is_computer_use_tool_used( return True return False - def _transform_computer_use_tools( - self, computer_use_tools: List[OpenAIChatCompletionToolParam] - ) -> List[dict]: + def _transform_computer_use_tools(self, computer_use_tools: List[OpenAIChatCompletionToolParam]) -> List[dict]: """Transform computer use tools to Bedrock format.""" transformed_tools: List[dict] = [] @@ -699,9 +666,7 @@ def _transform_computer_use_tools( def _separate_computer_use_tools( self, tools: List[OpenAIChatCompletionToolParam], model: str - ) -> Tuple[ - List[OpenAIChatCompletionToolParam], List[OpenAIChatCompletionToolParam] - ]: + ) -> Tuple[List[OpenAIChatCompletionToolParam], List[OpenAIChatCompletionToolParam]]: """ Separate computer use tools from regular function tools. @@ -773,9 +738,7 @@ def _create_json_tool_call_for_response_format( return _tool @staticmethod - def _supports_native_structured_outputs( - model: str, custom_llm_provider: Optional[str] = None - ) -> bool: + def _supports_native_structured_outputs(model: str, custom_llm_provider: Optional[str] = None) -> bool: """Check if the Bedrock model supports native structured outputs (outputConfig.textFormat). Delegates to the standard ``supports_native_structured_output`` utility @@ -785,9 +748,7 @@ def _supports_native_structured_outputs( """ from litellm.utils import supports_native_structured_output - return supports_native_structured_output( - model=model, custom_llm_provider=custom_llm_provider - ) + return supports_native_structured_output(model=model, custom_llm_provider=custom_llm_provider) @staticmethod def _add_additional_properties_to_schema(schema: dict) -> dict: @@ -810,25 +771,18 @@ def _add_additional_properties_to_schema(schema: dict) -> dict: # Recurse into nested schemas if "properties" in result and isinstance(result["properties"], dict): result["properties"] = { - k: AmazonConverseConfig._add_additional_properties_to_schema(v) - for k, v in result["properties"].items() + k: AmazonConverseConfig._add_additional_properties_to_schema(v) for k, v in result["properties"].items() } if "items" in result and isinstance(result["items"], dict): - result["items"] = AmazonConverseConfig._add_additional_properties_to_schema( - result["items"] - ) + result["items"] = AmazonConverseConfig._add_additional_properties_to_schema(result["items"]) for defs_key in ("$defs", "definitions"): if defs_key in result and isinstance(result[defs_key], dict): result[defs_key] = { - k: AmazonConverseConfig._add_additional_properties_to_schema(v) - for k, v in result[defs_key].items() + k: AmazonConverseConfig._add_additional_properties_to_schema(v) for k, v in result[defs_key].items() } for key in ("anyOf", "allOf", "oneOf"): if key in result and isinstance(result[key], list): - result[key] = [ - AmazonConverseConfig._add_additional_properties_to_schema(item) - for item in result[key] - ] + result[key] = [AmazonConverseConfig._add_additional_properties_to_schema(item) for item in result[key]] return result @@ -858,9 +812,7 @@ def _create_output_config_for_response_format( } """ if json_schema is not None: - json_schema = AmazonConverseConfig._add_additional_properties_to_schema( - json_schema - ) + json_schema = AmazonConverseConfig._add_additional_properties_to_schema(json_schema) schema_str = json.dumps(json_schema) if json_schema is not None else "{}" json_schema_def: JsonSchemaDefinition = {"schema": schema_str} if name is not None: @@ -882,14 +834,9 @@ def _apply_tool_call_transformation( non_default_params: dict, optional_params: dict, ): - optional_params = self._add_tools_to_optional_params( - optional_params=optional_params, tools=tools - ) + optional_params = self._add_tools_to_optional_params(optional_params=optional_params, tools=tools) - if ( - "meta.llama3-3-70b-instruct-v1:0" in model - and non_default_params.get("stream", False) is True - ): + if "meta.llama3-3-70b-instruct-v1:0" in model and non_default_params.get("stream", False) is True: optional_params["fake_stream"] = True def map_openai_params( @@ -996,18 +943,14 @@ def _map_request_metadata_param(self, value: Any, optional_params: dict) -> None self._validate_request_metadata(value) # type: ignore optional_params["requestMetadata"] = value - def _map_context_management_param( - self, value: Union[dict, list], optional_params: dict - ) -> None: + def _map_context_management_param(self, value: Union[dict, list], optional_params: dict) -> None: # Match the dispatcher's ``_normalize_spec`` behavior: only run the # OpenAI→Anthropic mapper for list inputs. Dict inputs are already in # Anthropic-native shape (``{"edits": [...]}``) and should pass # through unchanged so an Anthropic-format ``context_management`` # value isn't silently dropped when the mapper can't classify it. if isinstance(value, list): - mapped = AnthropicConfig.map_openai_context_management_to_anthropic( - cast(Union[dict, list], value) - ) + mapped = AnthropicConfig.map_openai_context_management_to_anthropic(cast(Union[dict, list], value)) else: mapped = value # Skip when the mapper returned None for malformed input — leaving the @@ -1059,10 +1002,7 @@ def _translate_response_format_param( if "type" in value and value["type"] == "text": return optional_params - if ( - self._supports_native_structured_outputs(model, self.custom_llm_provider) - and json_schema is not None - ): + if self._supports_native_structured_outputs(model, self.custom_llm_provider) and json_schema is not None: # Use Bedrock's native structured outputs API (outputConfig.textFormat) # No synthetic tool injection, no fake_stream needed. # Requires an explicit schema — json_object with no schema falls through @@ -1080,14 +1020,10 @@ def _translate_response_format_param( json_schema=json_schema, description=description, ) - optional_params = self._add_tools_to_optional_params( - optional_params=optional_params, tools=[_tool] - ) + optional_params = self._add_tools_to_optional_params(optional_params=optional_params, tools=[_tool]) if ( - litellm.utils.supports_tool_choice( - model=model, custom_llm_provider=self.custom_llm_provider - ) + litellm.utils.supports_tool_choice(model=model, custom_llm_provider=self.custom_llm_provider) and not is_thinking_enabled ): optional_params["tool_choice"] = ToolChoiceValuesBlock( @@ -1105,9 +1041,7 @@ def _translate_response_format_param( optional_params["json_mode"] = True return optional_params - def update_optional_params_with_thinking_tokens( - self, non_default_params: dict, optional_params: dict - ): + def update_optional_params_with_thinking_tokens(self, non_default_params: dict, optional_params: dict): """ Handles scenario where max tokens is not specified. For anthropic models (anthropic api/bedrock/vertex ai), this requires having the max tokens being set and being greater than the thinking token budget. @@ -1125,13 +1059,9 @@ def update_optional_params_with_thinking_tokens( is_thinking_enabled = self.is_thinking_enabled(optional_params) is_max_tokens_in_request = self.is_max_tokens_in_request(non_default_params) if is_thinking_enabled and not is_max_tokens_in_request: - thinking_token_budget = cast(dict, optional_params["thinking"]).get( - "budget_tokens", None - ) + thinking_token_budget = cast(dict, optional_params["thinking"]).get("budget_tokens", None) if thinking_token_budget is not None: - optional_params["maxTokens"] = ( - thinking_token_budget + DEFAULT_MAX_TOKENS - ) + optional_params["maxTokens"] = thinking_token_budget + DEFAULT_MAX_TOKENS @overload def _get_cache_point_block( @@ -1197,23 +1127,15 @@ def _transform_system_message( if message["role"] == "system": system_prompt_indices.append(idx) if isinstance(message["content"], str) and message["content"]: - system_content_blocks.append( - SystemContentBlock(text=message["content"]) - ) - cache_block = self._get_cache_point_block( - message, block_type="system", model=model - ) + system_content_blocks.append(SystemContentBlock(text=message["content"])) + cache_block = self._get_cache_point_block(message, block_type="system", model=model) if cache_block: system_content_blocks.append(cache_block) elif isinstance(message["content"], list): for m in message["content"]: if m.get("type") == "text" and m.get("text"): - system_content_blocks.append( - SystemContentBlock(text=m["text"]) - ) - cache_block = self._get_cache_point_block( - m, block_type="system", model=model - ) + system_content_blocks.append(SystemContentBlock(text=m["text"])) + cache_block = self._get_cache_point_block(m, block_type="system", model=model) if cache_block: system_content_blocks.append(cache_block) if len(system_prompt_indices) > 0: @@ -1226,9 +1148,7 @@ def _transform_inference_params(self, inference_params: dict) -> InferenceConfig inference_params["topK"] = inference_params.pop("top_k") return InferenceConfig(**inference_params) - def _handle_top_k_value( - self, model: str, inference_params: dict, drop_params: bool = False - ) -> dict: + def _handle_top_k_value(self, model: str, inference_params: dict, drop_params: bool = False) -> dict: base_model = BedrockModelInfo.get_base_model(model) val_top_k = None @@ -1261,23 +1181,15 @@ def _prepare_request_params( # Consume the internal ``_output_config_normalized`` marker set by # ``_handle_reasoning_effort_parameter`` so it does not linger on the # caller's ``optional_params`` after the transformation returns. - anthropic_output_config_already_normalized = bool( - optional_params.pop("_output_config_normalized", False) - ) + anthropic_output_config_already_normalized = bool(optional_params.pop("_output_config_normalized", False)) # Filter out exception objects before deepcopy to prevent deepcopy failures # Exceptions should not be stored in optional_params (this is a defensive fix) cleaned_params = filter_exceptions_from_params(optional_params) inference_params = safe_deep_copy(cleaned_params) - supported_converse_params = list( - AmazonConverseConfig.__annotations__.keys() - ) + ["top_k"] + supported_converse_params = list(AmazonConverseConfig.__annotations__.keys()) + ["top_k"] supported_tool_call_params = ["tools", "tool_choice"] supported_config_params = list(self.get_config_blocks().keys()) - total_supported_params = ( - supported_converse_params - + supported_tool_call_params - + supported_config_params - ) + total_supported_params = supported_converse_params + supported_tool_call_params + supported_config_params inference_params.pop("json_mode", None) # used for handling json_schema # Anthropic-only ``output_config`` (snake_case) — re-attached to @@ -1299,18 +1211,14 @@ def _prepare_request_params( if request_metadata is not None: self._validate_request_metadata(request_metadata) - output_config: Optional[OutputConfigBlock] = inference_params.pop( - "outputConfig", None - ) + output_config: Optional[OutputConfigBlock] = inference_params.pop("outputConfig", None) base_model = BedrockModelInfo.get_base_model(model) if ( output_config is None and output_config_format is not None and output_config_format.get("type") == "json_schema" and base_model.startswith("anthropic") - and self._supports_native_structured_outputs( - model, self.custom_llm_provider - ) + and self._supports_native_structured_outputs(model, self.custom_llm_provider) ): output_config = self._create_output_config_for_response_format( json_schema=output_config_format.get("schema"), @@ -1328,17 +1236,11 @@ def _prepare_request_params( ) # keep supported params in 'inference_params', and set all model-specific params in 'additional_request_params' - additional_request_params = { - k: v for k, v in inference_params.items() if k not in total_supported_params - } - inference_params = { - k: v for k, v in inference_params.items() if k in total_supported_params - } + additional_request_params = {k: v for k, v in inference_params.items() if k not in total_supported_params} + inference_params = {k: v for k, v in inference_params.items() if k in total_supported_params} # Handle parallel_tool_calls configuration - parallel_tool_use_config = additional_request_params.pop( - "_parallel_tool_use_config", None - ) + parallel_tool_use_config = additional_request_params.pop("_parallel_tool_use_config", None) if parallel_tool_use_config is not None and is_claude_4_5_on_bedrock(model): for key, value in parallel_tool_use_config.items(): if ( @@ -1353,9 +1255,7 @@ def _prepare_request_params( additional_request_params.pop("parallel_tool_calls", None) # Only set the topK value in for models that support it - additional_request_params.update( - self._handle_top_k_value(model, inference_params, drop_params) - ) + additional_request_params.update(self._handle_top_k_value(model, inference_params, drop_params)) # Filter out internal/MCP-related parameters that shouldn't be sent to the API # These are LiteLLM internal parameters, not API parameters @@ -1364,18 +1264,11 @@ def _prepare_request_params( # Filter out non-serializable objects (exceptions, callables, logging objects, etc.) # from additional_request_params to prevent JSON serialization errors # This filters: Exception objects, callable objects (functions), Logging objects, etc. - additional_request_params = filter_exceptions_from_params( - additional_request_params - ) + additional_request_params = filter_exceptions_from_params(additional_request_params) - if anthropic_output_config is not None and isinstance( - anthropic_output_config, dict - ): + if anthropic_output_config is not None and isinstance(anthropic_output_config, dict): if base_model.startswith("anthropic"): - if ( - litellm.drop_params is True - and not AnthropicConfig._model_supports_effort_param(model) - ): + if litellm.drop_params is True and not AnthropicConfig._model_supports_effort_param(model): litellm.verbose_logger.warning( DROP_UNSUPPORTED_OUTPUT_CONFIG_WARNING, model, @@ -1388,9 +1281,7 @@ def _prepare_request_params( ) effort = anthropic_output_config.get("effort") if effort is not None: - self._validate_anthropic_adaptive_effort( - model=model, effort=effort - ) + self._validate_anthropic_adaptive_effort(model=model, effort=effort) additional_request_params["output_config"] = anthropic_output_config return ( @@ -1438,9 +1329,7 @@ def _process_tools_and_beta( # Only separate tools if computer use tools are actually present if filtered_tools and self.is_computer_use_tool_used(filtered_tools, model): # Separate computer use tools from regular function tools - computer_use_tools, regular_tools = self._separate_computer_use_tools( - filtered_tools, model - ) + computer_use_tools, regular_tools = self._separate_computer_use_tools(filtered_tools, model) # Process regular function tools using existing logic bedrock_tools = _bedrock_tools_pt(regular_tools, model=model) @@ -1505,9 +1394,7 @@ def _process_tools_and_beta( anthropic_beta_list.append(computer_use_header) # Transform computer use tools to proper Bedrock format - transformed_computer_tools = self._transform_computer_use_tools( - computer_use_tools - ) + transformed_computer_tools = self._transform_computer_use_tools(computer_use_tools) additional_request_params["tools"] = transformed_computer_tools else: # No computer use tools, process all tools as regular tools @@ -1565,11 +1452,7 @@ def _filter_context_management_for_bedrock_converse( additional_request_params.pop("context_management", None) return - compact_edits = [ - e - for e in edits - if isinstance(e, dict) and e.get("type") == COMPACT_EDIT_TYPE - ] + compact_edits = [e for e in edits if isinstance(e, dict) and e.get("type") == COMPACT_EDIT_TYPE] if compact_edits: compact_beta = ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value if compact_beta not in anthropic_beta_list: @@ -1594,15 +1477,9 @@ def _transform_request_helper( """ Bedrock doesn't support tool calling without `tools=` param specified. """ - if ( - "tools" not in optional_params - and messages is not None - and has_tool_call_blocks(messages) - ): + if "tools" not in optional_params and messages is not None and has_tool_call_blocks(messages): if litellm.modify_params: - optional_params["tools"] = add_dummy_tool( - custom_llm_provider="bedrock_converse" - ) + optional_params["tools"] = add_dummy_tool(custom_llm_provider="bedrock_converse") else: raise litellm.UnsupportedParamsError( message="Bedrock doesn't support tool calling without `tools=` param specified. Pass `tools=` param OR set `litellm.modify_params = True` // `litellm_settings::modify_params: True` to add dummy tool to the request.", @@ -1645,9 +1522,7 @@ def _transform_request_helper( ) # Append cachePoint to tools if cache_control_injection_points has tool_config - cache_injection_points = additional_request_params.pop( - "cache_control_injection_points", None - ) + cache_injection_points = additional_request_params.pop("cache_control_injection_points", None) if cache_injection_points and len(bedrock_tools) > 0: for point in cache_injection_points: if point.get("location") == "tool_config": @@ -1656,9 +1531,7 @@ def _transform_request_helper( bedrock_tool_config: Optional[ToolConfigBlock] = None if len(bedrock_tools) > 0: - tool_choice_values: ToolChoiceValuesBlock = inference_params.pop( - "tool_choice", None - ) + tool_choice_values: ToolChoiceValuesBlock = inference_params.pop("tool_choice", None) bedrock_tool_config = ToolConfigBlock( tools=bedrock_tools, ) @@ -1666,9 +1539,7 @@ def _transform_request_helper( bedrock_tool_config["toolChoice"] = tool_choice_values data: CommonRequestObject = { - "inferenceConfig": self._transform_inference_params( - inference_params=inference_params - ), + "inferenceConfig": self._transform_inference_params(inference_params=inference_params), } if additional_request_params: data["additionalModelRequestFields"] = additional_request_params @@ -1702,14 +1573,10 @@ async def _async_transform_request( litellm_params: dict, headers: Optional[dict] = None, ) -> RequestObject: - messages, system_content_blocks = self._transform_system_message( - messages, model=model - ) + messages, system_content_blocks = self._transform_system_message(messages, model=model) # Convert last user message to guarded_text if guardrailConfig is present - messages = self._convert_consecutive_user_messages_to_guarded_text( - messages, optional_params - ) + messages = self._convert_consecutive_user_messages_to_guarded_text(messages, optional_params) ## TRANSFORMATION ## _data: CommonRequestObject = self._transform_request_helper( @@ -1721,13 +1588,11 @@ async def _async_transform_request( drop_params=litellm_params.get("drop_params") is True, ) - bedrock_messages = ( - await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async( - messages=messages, - model=model, - llm_provider="bedrock_converse", - user_continue_message=litellm_params.pop("user_continue_message", None), - ) + bedrock_messages = await BedrockConverseMessagesProcessor._bedrock_converse_messages_pt_async( + messages=messages, + model=model, + llm_provider="bedrock_converse", + user_continue_message=litellm_params.pop("user_continue_message", None), ) data: RequestObject = {"messages": bedrock_messages, **_data} @@ -1761,14 +1626,10 @@ def _transform_request( litellm_params: dict, headers: Optional[dict] = None, ) -> RequestObject: - messages, system_content_blocks = self._transform_system_message( - messages, model=model - ) + messages, system_content_blocks = self._transform_system_message(messages, model=model) # Convert last user message to guarded_text if guardrailConfig is present - messages = self._convert_consecutive_user_messages_to_guarded_text( - messages, optional_params - ) + messages = self._convert_consecutive_user_messages_to_guarded_text(messages, optional_params) _data: CommonRequestObject = self._transform_request_helper( model=model, @@ -1818,9 +1679,7 @@ def transform_response( encoding=encoding, ) - def _transform_reasoning_content( - self, reasoning_content_blocks: List[BedrockConverseReasoningContentBlock] - ) -> str: + def _transform_reasoning_content(self, reasoning_content_blocks: List[BedrockConverseReasoningContentBlock]) -> str: """ Extract the reasoning text from the reasoning content blocks @@ -1836,9 +1695,7 @@ def _transform_thinking_blocks( self, thinking_blocks: List[BedrockConverseReasoningContentBlock] ) -> List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]: """Return a consistent format for thinking blocks between Anthropic and Bedrock.""" - thinking_blocks_list: List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] = [] + thinking_blocks_list: List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] = [] for block in thinking_blocks: if "reasoningText" in block: _thinking_block = ChatCompletionThinkingBlock(type="thinking") @@ -1880,18 +1737,10 @@ def _transform_usage( cache_creation_tokens=cache_creation_input_tokens, text_tokens=raw_input_tokens, ) - reasoning_tokens = ( - token_counter(text=reasoning_content, count_response_tokens=True) - if reasoning_content - else 0 - ) + reasoning_tokens = token_counter(text=reasoning_content, count_response_tokens=True) if reasoning_content else 0 completion_tokens_details = CompletionTokensDetailsWrapper( reasoning_tokens=reasoning_tokens, - text_tokens=( - output_tokens - reasoning_tokens - if reasoning_tokens > 0 - else output_tokens - ), + text_tokens=(output_tokens - reasoning_tokens if reasoning_tokens > 0 else output_tokens), ) openai_usage = Usage( prompt_tokens=input_tokens, @@ -1906,9 +1755,7 @@ def _transform_usage( def get_tool_call_names( self, - tools: Optional[ - Union[List[ToolBlock], List[OpenAIChatCompletionToolParam]] - ] = None, + tools: Optional[Union[List[ToolBlock], List[OpenAIChatCompletionToolParam]]] = None, ) -> List[str]: if tools is None: return [] @@ -1947,13 +1794,8 @@ def apply_tool_call_transformation_if_needed( try: tool_call_names = self.get_tool_call_names(tools) json_content = json.loads(message.content) - if ( - json_content.get("type") == "function" - and json_content.get("name") in tool_call_names - ): - tool_calls = [ - ChatCompletionMessageToolCall(function=Function(**json_content)) - ] + if json_content.get("type") == "function" and json_content.get("name") in tool_call_names: + tool_calls = [ChatCompletionMessageToolCall(function=Function(**json_content))] message.tool_calls = tool_calls message.content = None @@ -1982,9 +1824,7 @@ def _translate_message_content( """ content_str = "" tools: List[ChatCompletionToolCallChunk] = [] - reasoningContentBlocks: Optional[List[BedrockConverseReasoningContentBlock]] = ( - None - ) + reasoningContentBlocks: Optional[List[BedrockConverseReasoningContentBlock]] = None citationsContentBlocks: Optional[List[CitationsContentBlock]] = None for idx, content in enumerate(content_blocks): """ @@ -2001,9 +1841,7 @@ def _translate_message_content( if "toolUse" in content: ## check tool name was formatted by litellm _response_tool_name = content["toolUse"]["name"] - response_tool_name = get_bedrock_tool_name( - response_tool_name=_response_tool_name - ) + response_tool_name = get_bedrock_tool_name(response_tool_name=_response_tool_name) _function_chunk = ChatCompletionToolCallFunctionChunk( name=response_tool_name, arguments=json.dumps(content["toolUse"]["input"]), @@ -2123,11 +1961,7 @@ def _unwrap_bedrock_properties(json_str: str) -> str: """ try: response_data = json.loads(json_str) - if ( - isinstance(response_data, dict) - and "properties" in response_data - and len(response_data) == 1 - ): + if isinstance(response_data, dict) and "properties" in response_data and len(response_data) == 1: response_data = response_data["properties"] return json.dumps(response_data) except json.JSONDecodeError: @@ -2151,11 +1985,7 @@ def _filter_json_mode_tools( if not json_mode or not tools: return tools if tools else None - json_tool_indices = [ - i - for i, t in enumerate(tools) - if t["function"].get("name") == RESPONSE_FORMAT_TOOL_NAME - ] + json_tool_indices = [i for i, t in enumerate(tools) if t["function"].get("name") == RESPONSE_FORMAT_TOOL_NAME] if not json_tool_indices: # No json_tool_call found, return tools unchanged @@ -2163,14 +1993,10 @@ def _filter_json_mode_tools( if len(json_tool_indices) == len(tools): # All tools are json_tool_call — convert first one to content - verbose_logger.debug( - "Processing JSON tool call response for response_format" - ) + verbose_logger.debug("Processing JSON tool call response for response_format") json_mode_content_str: Optional[str] = tools[0]["function"].get("arguments") if json_mode_content_str is not None: - json_mode_content_str = AmazonConverseConfig._unwrap_bedrock_properties( - json_mode_content_str - ) + json_mode_content_str = AmazonConverseConfig._unwrap_bedrock_properties(json_mode_content_str) chat_completion_message["content"] = json_mode_content_str return None @@ -2180,13 +2006,9 @@ def _filter_json_mode_tools( first_idx = json_tool_indices[0] json_mode_args = tools[first_idx]["function"].get("arguments") if json_mode_args is not None: - json_mode_args = AmazonConverseConfig._unwrap_bedrock_properties( - json_mode_args - ) + json_mode_args = AmazonConverseConfig._unwrap_bedrock_properties(json_mode_args) existing = chat_completion_message.get("content") or "" - chat_completion_message["content"] = ( - existing + json_mode_args if existing else json_mode_args - ) + chat_completion_message["content"] = existing + json_mode_args if existing else json_mode_args real_tools = [t for i, t in enumerate(tools) if i not in json_tool_indices] return real_tools if real_tools else None @@ -2264,9 +2086,7 @@ def _transform_response( chat_completion_message: ChatCompletionResponseMessage = {"role": "assistant"} content_str = "" tools: List[ChatCompletionToolCallChunk] = [] - reasoningContentBlocks: Optional[List[BedrockConverseReasoningContentBlock]] = ( - None - ) + reasoningContentBlocks: Optional[List[BedrockConverseReasoningContentBlock]] = None citationsContentBlocks: Optional[List[CitationsContentBlock]] = None if message is not None: @@ -2285,13 +2105,9 @@ def _transform_response( provider_specific_fields["citationsContent"] = citationsContentBlocks if provider_specific_fields: - chat_completion_message["provider_specific_fields"] = ( - provider_specific_fields - ) + chat_completion_message["provider_specific_fields"] = provider_specific_fields - citations_text, annotations = self._transform_citations_to_annotations( - citationsContentBlocks - ) + citations_text, annotations = self._transform_citations_to_annotations(citationsContentBlocks) citations_included_in_content = False if citations_text: stripped_content = content_str.strip() @@ -2308,12 +2124,8 @@ def _transform_response( chat_completion_message["annotations"] = annotations if reasoningContentBlocks is not None: - chat_completion_message["reasoning_content"] = ( - self._transform_reasoning_content(reasoningContentBlocks) - ) - chat_completion_message["thinking_blocks"] = ( - self._transform_thinking_blocks(reasoningContentBlocks) - ) + chat_completion_message["reasoning_content"] = self._transform_reasoning_content(reasoningContentBlocks) + chat_completion_message["thinking_blocks"] = self._transform_thinking_blocks(reasoningContentBlocks) chat_completion_message["content"] = content_str filtered_tools = self._filter_json_mode_tools( json_mode=json_mode, diff --git a/litellm/llms/bedrock/chat/invoke_agent/transformation.py b/litellm/llms/bedrock/chat/invoke_agent/transformation.py index c88fa32b6a08..413cdad45e0a 100644 --- a/litellm/llms/bedrock/chat/invoke_agent/transformation.py +++ b/litellm/llms/bedrock/chat/invoke_agent/transformation.py @@ -90,21 +90,15 @@ def get_complete_url( endpoint_url, _ = self.get_runtime_endpoint( api_base=api_base, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, - aws_region_name=self._get_aws_region_name( - optional_params=optional_params, model=model - ), + aws_region_name=self._get_aws_region_name(optional_params=optional_params, model=model), endpoint_type="agent", ) agent_id, agent_alias_id = self._get_agent_id_and_alias_id(model) session_id = self._get_session_id(optional_params) encoded_agent_id = encode_url_path_segment(agent_id, field_name="agent_id") - encoded_agent_alias_id = encode_url_path_segment( - agent_alias_id, field_name="agent_alias_id" - ) - encoded_session_id = encode_url_path_segment( - session_id, field_name="session_id" - ) + encoded_agent_alias_id = encode_url_path_segment(agent_alias_id, field_name="agent_alias_id") + encoded_session_id = encode_url_path_segment(session_id, field_name="session_id") endpoint_url = f"{endpoint_url}/agents/{encoded_agent_id}/agentAliases/{encoded_agent_alias_id}/sessions/{encoded_session_id}/text" @@ -142,9 +136,7 @@ def _get_agent_id_and_alias_id(self, model: str) -> tuple[str, str]: # Split the model string by '/' and extract components parts = model.split("/") if len(parts) != 3 or parts[0] != "agent": - raise ValueError( - "Invalid model format. Expected format: 'model=agent/AGENT_ID/ALIAS_ID'" - ) + raise ValueError("Invalid model format. Expected format: 'model=agent/AGENT_ID/ALIAS_ID'") return parts[1], parts[2] # Return (agent_id, agent_alias_id) @@ -202,9 +194,7 @@ def _parse_aws_event_stream(self, raw_content: bytes) -> InvokeAgentEventList: parsed_event = { "headers": headers, "payload": { - "bytes": base64.b64encode( - message.encode("utf-8") - ).decode("utf-8") + "bytes": base64.b64encode(message.encode("utf-8")).decode("utf-8") }, # Re-encode for consistency } events.append(parsed_event) @@ -222,9 +212,7 @@ def _parse_aws_event_stream(self, raw_content: bytes) -> InvokeAgentEventList: } events.append(parsed_event) except json.JSONDecodeError as e: - verbose_logger.warning( - f"Failed to parse trace event JSON: {e}" - ) + verbose_logger.warning(f"Failed to parse trace event JSON: {e}") else: verbose_logger.debug(f"Unknown event type: {event_type}") @@ -241,9 +229,7 @@ def _parse_message_from_event(self, event, parser) -> Optional[str]: verbose_logger.debug(f"Response dict: {response_dict}") # Use the same response shape parsing as the existing decoder - parsed_response = parser.parse( - response_dict, self._get_response_stream_shape() - ) + parsed_response = parser.parse(response_dict, self._get_response_stream_shape()) verbose_logger.debug(f"Parsed response: {parsed_response}") if response_dict["status_code"] != 200: @@ -258,11 +244,7 @@ def _parse_message_from_event(self, event, parser) -> Optional[str]: error_message = exception_status + " " + error_message raise BedrockError( status_code=response_dict["status_code"], - message=( - json.dumps(error_message) - if isinstance(error_message, dict) - else error_message - ), + message=(json.dumps(error_message) if isinstance(error_message, dict) else error_message), ) if "chunk" in parsed_response: @@ -294,9 +276,7 @@ def _extract_headers_from_event(self, event) -> InvokeAgentEventHeaders: ) except Exception as e: verbose_logger.debug(f"Error extracting headers: {e}") - return InvokeAgentEventHeaders( - event_type="", content_type="", message_type="" - ) + return InvokeAgentEventHeaders(event_type="", content_type="", message_type="") def _get_response_stream_shape(self): from litellm.llms.bedrock.common_utils import get_bedrock_response_stream_shape @@ -311,9 +291,7 @@ def _extract_response_content(self, events: InvokeAgentEventList) -> str: headers = event.get("headers", {}) payload = event.get("payload") - event_type = headers.get( - "event_type" - ) # Note: using event_type not event-type + event_type = headers.get("event_type") # Note: using event_type not event-type if event_type == "chunk" and payload: # Extract base64 encoded content from chunk events @@ -321,9 +299,7 @@ def _extract_response_content(self, events: InvokeAgentEventList) -> str: encoded_bytes = chunk_payload.get("bytes", "") if encoded_bytes: try: - decoded_content = base64.b64decode(encoded_bytes).decode( - "utf-8" - ) + decoded_content = base64.b64decode(encoded_bytes).decode("utf-8") response_parts.append(decoded_content) except Exception as e: verbose_logger.warning(f"Failed to decode chunk content: {e}") @@ -383,22 +359,17 @@ def _extract_and_update_preprocessing_usage( self, trace_data: InvokeAgentTrace, usage_info: InvokeAgentUsage ) -> None: """Extract usage information from preprocessing trace.""" - pre_processing: Optional[InvokeAgentPreProcessingTrace] = trace_data.get( - "preProcessingTrace" - ) + pre_processing: Optional[InvokeAgentPreProcessingTrace] = trace_data.get("preProcessingTrace") if not pre_processing: return model_output: Optional[InvokeAgentModelInvocationOutput] = ( - pre_processing.get("modelInvocationOutput") - or InvokeAgentModelInvocationOutput() + pre_processing.get("modelInvocationOutput") or InvokeAgentModelInvocationOutput() ) if not model_output: return - metadata: Optional[InvokeAgentMetadata] = ( - model_output.get("metadata") or InvokeAgentMetadata() - ) + metadata: Optional[InvokeAgentMetadata] = model_output.get("metadata") or InvokeAgentMetadata() if not metadata: return @@ -409,19 +380,14 @@ def _extract_and_update_preprocessing_usage( usage_info["inputTokens"] += usage.get("inputTokens", 0) usage_info["outputTokens"] += usage.get("outputTokens", 0) - def _extract_orchestration_model( - self, trace_data: InvokeAgentTrace - ) -> Optional[str]: + def _extract_orchestration_model(self, trace_data: InvokeAgentTrace) -> Optional[str]: """Extract model information from orchestration trace.""" - orchestration_trace: Optional[InvokeAgentOrchestrationTrace] = trace_data.get( - "orchestrationTrace" - ) + orchestration_trace: Optional[InvokeAgentOrchestrationTrace] = trace_data.get("orchestrationTrace") if not orchestration_trace: return None model_invocation: Optional[InvokeAgentModelInvocationInput] = ( - orchestration_trace.get("modelInvocationInput") - or InvokeAgentModelInvocationInput() + orchestration_trace.get("modelInvocationInput") or InvokeAgentModelInvocationInput() ) if not model_invocation: return None @@ -454,8 +420,7 @@ def _build_model_response( usage = Usage( prompt_tokens=usage_info.get("inputTokens", 0), completion_tokens=usage_info.get("outputTokens", 0), - total_tokens=usage_info.get("inputTokens", 0) - + usage_info.get("outputTokens", 0), + total_tokens=usage_info.get("inputTokens", 0) + usage_info.get("outputTokens", 0), ) setattr(model_response, "usage", usage) @@ -478,9 +443,7 @@ def transform_response( try: # Get the raw binary content raw_content = raw_response.content - verbose_logger.debug( - f"Processing {len(raw_content)} bytes of AWS event stream data" - ) + verbose_logger.debug(f"Processing {len(raw_content)} bytes of AWS event stream data") # Parse the AWS event stream format events = self._parse_aws_event_stream(raw_content) @@ -501,9 +464,7 @@ def transform_response( ) except Exception as e: - verbose_logger.error( - f"Error processing Bedrock Invoke Agent response: {str(e)}" - ) + verbose_logger.error(f"Error processing Bedrock Invoke Agent response: {str(e)}") raise BedrockError( message=f"Error processing response: {str(e)}", status_code=raw_response.status_code, diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.py index 29e97068100a..b381b5a85fe9 100644 --- a/litellm/llms/bedrock/chat/invoke_handler.py +++ b/litellm/llms/bedrock/chat/invoke_handler.py @@ -75,9 +75,7 @@ get_bedrock_tool_name, ) -bedrock_tool_name_mappings: InMemoryCache = InMemoryCache( - max_size_in_memory=50, default_ttl=600 -) +bedrock_tool_name_mappings: InMemoryCache = InMemoryCache(max_size_in_memory=50, default_ttl=600) from litellm.llms.bedrock.chat.converse_transformation import AmazonConverseConfig from litellm.llms.bedrock.chat.invoke_transformations.amazon_openai_transformation import ( AmazonBedrockOpenAIConfig, @@ -162,9 +160,7 @@ def get_supported_openai_params(self) -> List[str]: "tool_choice", ] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: for param, value in non_default_params.items(): if param == "max_tokens" or param == "max_completion_tokens": optional_params["max_tokens"] = value @@ -206,9 +202,7 @@ async def make_call( llm_provider=litellm.LlmProviders.BEDROCK, params=( {"ssl_verify": logging_obj.litellm_params.get("ssl_verify")} - if logging_obj - and logging_obj.litellm_params - and logging_obj.litellm_params.get("ssl_verify") + if logging_obj and logging_obj.litellm_params and logging_obj.litellm_params.get("ssl_verify") else None ), ) # Create a new client if none provided @@ -225,45 +219,35 @@ async def make_call( raise BedrockError(status_code=response.status_code, message=response.text) if fake_stream: - model_response: ModelResponse = ( - litellm.AmazonConverseConfig()._transform_response( - model=model, - response=response, - model_response=litellm.ModelResponse(), - stream=True, - logging_obj=logging_obj, - optional_params={}, - api_key="", - data=data, - messages=messages, - encoding=litellm.encoding, - ) + model_response: ModelResponse = litellm.AmazonConverseConfig()._transform_response( + model=model, + response=response, + model_response=litellm.ModelResponse(), + stream=True, + logging_obj=logging_obj, + optional_params={}, + api_key="", + data=data, + messages=messages, + encoding=litellm.encoding, ) # type: ignore - completion_stream: Any = MockResponseIterator( - model_response=model_response, json_mode=json_mode - ) + completion_stream: Any = MockResponseIterator(model_response=model_response, json_mode=json_mode) elif bedrock_invoke_provider == "anthropic": decoder: AWSEventStreamDecoder = AmazonAnthropicClaudeStreamDecoder( model=model, sync_stream=False, json_mode=json_mode, ) - completion_stream = decoder.aiter_bytes( - response.aiter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.aiter_bytes(response.aiter_bytes(chunk_size=stream_chunk_size)) elif bedrock_invoke_provider == "deepseek_r1": decoder = AmazonDeepSeekR1StreamDecoder( model=model, sync_stream=False, ) - completion_stream = decoder.aiter_bytes( - response.aiter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.aiter_bytes(response.aiter_bytes(chunk_size=stream_chunk_size)) else: decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) - completion_stream = decoder.aiter_bytes( - response.aiter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.aiter_bytes(response.aiter_bytes(chunk_size=stream_chunk_size)) # LOGGING logging_obj.post_call( @@ -302,9 +286,7 @@ def make_sync_call( client = _get_httpx_client( params=( {"ssl_verify": logging_obj.litellm_params.get("ssl_verify")} - if logging_obj - and logging_obj.litellm_params - and logging_obj.litellm_params.get("ssl_verify") + if logging_obj and logging_obj.litellm_params and logging_obj.litellm_params.get("ssl_verify") else None ) ) @@ -321,45 +303,35 @@ def make_sync_call( raise BedrockError(status_code=response.status_code, message=response.text) if fake_stream: - model_response: ModelResponse = ( - litellm.AmazonConverseConfig()._transform_response( - model=model, - response=response, - model_response=litellm.ModelResponse(), - stream=True, - logging_obj=logging_obj, - optional_params={}, - api_key="", - data=data, - messages=messages, - encoding=litellm.encoding, - ) + model_response: ModelResponse = litellm.AmazonConverseConfig()._transform_response( + model=model, + response=response, + model_response=litellm.ModelResponse(), + stream=True, + logging_obj=logging_obj, + optional_params={}, + api_key="", + data=data, + messages=messages, + encoding=litellm.encoding, ) # type: ignore - completion_stream: Any = MockResponseIterator( - model_response=model_response, json_mode=json_mode - ) + completion_stream: Any = MockResponseIterator(model_response=model_response, json_mode=json_mode) elif bedrock_invoke_provider == "anthropic": decoder: AWSEventStreamDecoder = AmazonAnthropicClaudeStreamDecoder( model=model, sync_stream=True, json_mode=json_mode, ) - completion_stream = decoder.iter_bytes( - response.iter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) elif bedrock_invoke_provider == "deepseek_r1": decoder = AmazonDeepSeekR1StreamDecoder( model=model, sync_stream=True, ) - completion_stream = decoder.iter_bytes( - response.iter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) else: decoder = AWSEventStreamDecoder(model=model, json_mode=json_mode) - completion_stream = decoder.iter_bytes( - response.iter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) # LOGGING logging_obj.post_call( @@ -424,9 +396,7 @@ def is_claude_messages_api_model(model: str) -> bool: return any(indicator in model_lower for indicator in messages_api_indicators) - def convert_messages_to_prompt( - self, model, messages, provider, custom_prompt_dict - ) -> Tuple[str, Optional[list]]: + def convert_messages_to_prompt(self, model, messages, provider, custom_prompt_dict) -> Tuple[str, Optional[list]]: # handle anthropic prompts and amazon titan prompts prompt = "" chat_history: Optional[list] = None @@ -436,26 +406,18 @@ def convert_messages_to_prompt( model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details["roles"], - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), final_prompt_value=model_prompt_details.get("final_prompt_value", ""), messages=messages, ) return prompt, None ## ELSE if provider == "anthropic" or provider == "amazon": - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="bedrock" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="bedrock") elif provider == "mistral": - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="bedrock" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="bedrock") elif provider == "meta" or provider == "llama": - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="bedrock" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="bedrock") elif provider == "openai": # OpenAI uses messages directly, no prompt conversion needed # Return empty prompt as it won't be used @@ -522,20 +484,12 @@ def process_response( if "tools" in optional_params: _is_function_call = True for tool in optional_params["tools"]: - json_schemas[tool["function"]["name"]] = tool[ - "function" - ].get("parameters", None) + json_schemas[tool["function"]["name"]] = tool["function"].get("parameters", None) outputText = completion_response.get("content")[0].get("text", None) - if outputText is not None and contains_tag( - "invoke", outputText - ): # OUTPUT PARSE FUNCTION CALL + if outputText is not None and contains_tag("invoke", outputText): # OUTPUT PARSE FUNCTION CALL function_name = extract_between_tags("tool_name", outputText)[0] - function_arguments_str = extract_between_tags( - "invoke", outputText - )[0].strip() - function_arguments_str = ( - f"{function_arguments_str}" - ) + function_arguments_str = extract_between_tags("invoke", outputText)[0].strip() + function_arguments_str = f"{function_arguments_str}" function_arguments = parse_xml_params( function_arguments_str, json_schema=json_schemas.get( @@ -559,14 +513,8 @@ def process_response( model_response._hidden_params["original_response"] = ( outputText # allow user to access raw anthropic tool calling response ) - if ( - _is_function_call is True - and stream is not None - and stream is True - ): - print_verbose( - "INSIDE BEDROCK STREAMING TOOL CALLING CONDITION BLOCK" - ) + if _is_function_call is True and stream is not None and stream is True: + print_verbose("INSIDE BEDROCK STREAMING TOOL CALLING CONDITION BLOCK") # return an iterator streaming_model_response = ModelResponseStream() streaming_model_response.choices[0].finish_reason = getattr( @@ -576,35 +524,23 @@ def process_response( streaming_choice = litellm.utils.StreamingChoices() streaming_choice.index = model_response.choices[0].index _tool_calls = [] - print_verbose( - f"type of model_response.choices[0]: {type(model_response.choices[0])}" - ) - print_verbose( - f"type of streaming_choice: {type(streaming_choice)}" - ) + print_verbose(f"type of model_response.choices[0]: {type(model_response.choices[0])}") + print_verbose(f"type of streaming_choice: {type(streaming_choice)}") if isinstance(model_response.choices[0], litellm.Choices): if getattr( model_response.choices[0].message, "tool_calls", None - ) is not None and isinstance( - model_response.choices[0].message.tool_calls, list - ): - for tool_call in model_response.choices[ - 0 - ].message.tool_calls: + ) is not None and isinstance(model_response.choices[0].message.tool_calls, list): + for tool_call in model_response.choices[0].message.tool_calls: _tool_call = {**tool_call.dict(), "index": 0} _tool_calls.append(_tool_call) delta_obj = Delta( - content=getattr( - model_response.choices[0].message, "content", None - ), + content=getattr(model_response.choices[0].message, "content", None), role=model_response.choices[0].message.role, tool_calls=_tool_calls, ) streaming_choice.delta = delta_obj streaming_model_response.choices = [streaming_choice] - completion_stream = ModelResponseIterator( - model_response=streaming_model_response - ) + completion_stream = ModelResponseIterator(model_response=streaming_model_response) print_verbose( "Returns anthropic CustomStreamWrapper with 'cached_response' streaming object" ) @@ -628,21 +564,14 @@ def process_response( else: outputText = completion_response["completion"] - model_response.choices[0].finish_reason = completion_response[ - "stop_reason" - ] + model_response.choices[0].finish_reason = completion_response["stop_reason"] elif provider == "ai21": - outputText = ( - completion_response.get("completions")[0].get("data").get("text") - ) + outputText = completion_response.get("completions")[0].get("data").get("text") elif provider == "meta" or provider == "llama": outputText = completion_response["generation"] elif provider == "openai": # OpenAI imported models use OpenAI Chat Completions format - if ( - "choices" in completion_response - and len(completion_response["choices"]) > 0 - ): + if "choices" in completion_response and len(completion_response["choices"]) > 0: choice = completion_response["choices"][0] if "message" in choice: outputText = choice["message"].get("content") @@ -651,9 +580,7 @@ def process_response( # Set finish reason if "finish_reason" in choice: - model_response.choices[0].finish_reason = map_finish_reason( - choice["finish_reason"] - ) + model_response.choices[0].finish_reason = map_finish_reason(choice["finish_reason"]) # Set usage if available if "usage" in completion_response: @@ -666,16 +593,12 @@ def process_response( setattr(model_response, "usage", _usage) elif provider == "mistral": outputText = completion_response["outputs"][0]["text"] - model_response.choices[0].finish_reason = completion_response[ - "outputs" - ][0]["stop_reason"] + model_response.choices[0].finish_reason = completion_response["outputs"][0]["stop_reason"] else: # amazon titan outputText = completion_response.get("results")[0].get("outputText") except Exception as e: raise BedrockError( - message="Error processing={}, Received error={}".format( - response.text, str(e) - ), + message="Error processing={}, Received error={}".format(response.text, str(e)), status_code=422, ) @@ -698,9 +621,7 @@ def process_response( raise Exception() except Exception as e: raise BedrockError( - message="Error parsing received text={}.\nError-{}".format( - outputText, str(e) - ), + message="Error parsing received text={}.\nError-{}".format(outputText, str(e)), status_code=response.status_code, ) @@ -728,20 +649,11 @@ def process_response( ## CALCULATING USAGE - bedrock returns usage in the headers # Skip if usage was already set (e.g., from JSON response for OpenAI provider) - if ( - not hasattr(model_response, "usage") - or getattr(model_response, "usage", None) is None - ): - bedrock_input_tokens = response.headers.get( - "x-amzn-bedrock-input-token-count", None - ) - bedrock_output_tokens = response.headers.get( - "x-amzn-bedrock-output-token-count", None - ) + if not hasattr(model_response, "usage") or getattr(model_response, "usage", None) is None: + bedrock_input_tokens = response.headers.get("x-amzn-bedrock-input-token-count", None) + bedrock_output_tokens = response.headers.get("x-amzn-bedrock-output-token-count", None) - prompt_tokens = int( - bedrock_input_tokens or litellm.token_counter(messages=messages) - ) + prompt_tokens = int(bedrock_input_tokens or litellm.token_counter(messages=messages)) completion_tokens = int( bedrock_output_tokens @@ -821,15 +733,11 @@ def completion( # check env # litellm_aws_region_name = get_secret("AWS_REGION_NAME", None) - if litellm_aws_region_name is not None and isinstance( - litellm_aws_region_name, str - ): + if litellm_aws_region_name is not None and isinstance(litellm_aws_region_name, str): aws_region_name = litellm_aws_region_name standard_aws_region_name = get_secret("AWS_REGION", None) - if standard_aws_region_name is not None and isinstance( - standard_aws_region_name, str - ): + if standard_aws_region_name is not None and isinstance(standard_aws_region_name, str): aws_region_name = standard_aws_region_name if aws_region_name is None: @@ -857,18 +765,12 @@ def completion( if (stream is not None and stream is True) and provider != "ai21": endpoint_url = f"{endpoint_url}/model/{modelId}/invoke-with-response-stream" - proxy_endpoint_url = ( - f"{proxy_endpoint_url}/model/{modelId}/invoke-with-response-stream" - ) + proxy_endpoint_url = f"{proxy_endpoint_url}/model/{modelId}/invoke-with-response-stream" else: endpoint_url = f"{endpoint_url}/model/{modelId}/invoke" proxy_endpoint_url = f"{proxy_endpoint_url}/model/{modelId}/invoke" - if ( - acompletion - and provider == "anthropic" - and self.is_claude_messages_api_model(model) - ): + if acompletion and provider == "anthropic" and self.is_claude_messages_api_model(model): if isinstance(client, HTTPHandler): client = None return self._async_anthropic_messages_completion( @@ -892,9 +794,7 @@ def completion( stream_chunk_size=stream_chunk_size, ) # type: ignore[return-value] - prompt, chat_history = self.convert_messages_to_prompt( - model, messages, provider, custom_prompt_dict - ) + prompt, chat_history = self.convert_messages_to_prompt(model, messages, provider, custom_prompt_dict) inference_params = copy.deepcopy(optional_params) json_schemas: dict = {} if provider == "cohere": @@ -919,9 +819,7 @@ def completion( ): # completion(top_k=3) > anthropic_config(top_k=3) <- allows for dynamic variables to be passed in inference_params[k] = v if stream is True: - inference_params["stream"] = ( - True # cohere requires stream = True in inference params - ) + inference_params["stream"] = True # cohere requires stream = True in inference params data = json.dumps({"prompt": prompt, **inference_params}) elif provider == "anthropic": if self.is_claude_messages_api_model(model): @@ -934,13 +832,9 @@ def completion( system_prompt_idx.append(idx) if len(system_prompt_idx) > 0: inference_params["system"] = "\n".join(system_messages) - messages = [ - i for j, i in enumerate(messages) if j not in system_prompt_idx - ] + messages = [i for j, i in enumerate(messages) if j not in system_prompt_idx] # Format rest of message according to anthropic guidelines - messages = prompt_factory( - model=model, messages=messages, custom_llm_provider="anthropic_xml" - ) # type: ignore + messages = prompt_factory(model=model, messages=messages, custom_llm_provider="anthropic_xml") # type: ignore ## LOAD CONFIG config = litellm.AmazonAnthropicClaudeConfig.get_config() for k, v in config.items(): @@ -952,15 +846,10 @@ def completion( if "tools" in inference_params: _is_function_call = True for tool in inference_params["tools"]: - json_schemas[tool["function"]["name"]] = tool["function"].get( - "parameters", None - ) - tool_calling_system_prompt = construct_tool_use_system_prompt( - tools=inference_params["tools"] - ) + json_schemas[tool["function"]["name"]] = tool["function"].get("parameters", None) + tool_calling_system_prompt = construct_tool_use_system_prompt(tools=inference_params["tools"]) inference_params["system"] = ( - inference_params.get("system", "\n") - + tool_calling_system_prompt + inference_params.get("system", "\n") + tool_calling_system_prompt ) # add the anthropic tool calling prompt to the system prompt inference_params.pop("tools") data = json.dumps({"messages": messages, **inference_params}) @@ -1024,9 +913,7 @@ def completion( supported_params = openai_config.get_supported_openai_params(model=model) # Filter to only supported OpenAI params - filtered_params = { - k: v for k, v in inference_params.items() if k in supported_params - } + filtered_params = {k: v for k, v in inference_params.items() if k in supported_params} # OpenAI uses messages format, not prompt data = json.dumps({"messages": messages, **filtered_params}) @@ -1132,15 +1019,11 @@ def completion( ) if response.status_code != 200: - raise BedrockError( - status_code=response.status_code, message=str(response.read()) - ) + raise BedrockError(status_code=response.status_code, message=str(response.read())) decoder = AWSEventStreamDecoder(model=model) - completion_stream = decoder.iter_bytes( - response.iter_bytes(chunk_size=stream_chunk_size) - ) + completion_stream = decoder.iter_bytes(response.iter_bytes(chunk_size=stream_chunk_size)) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, model=model, @@ -1206,14 +1089,12 @@ async def _async_anthropic_messages_completion( client: Optional[AsyncHTTPHandler] = None, stream_chunk_size: Optional[int] = None, ) -> Union[ModelResponse, CustomStreamWrapper]: - transformed_request = ( - await litellm.AmazonAnthropicClaudeConfig().async_transform_request( - model=model, - messages=messages, - optional_params=optional_params, - litellm_params=litellm_params or {}, - headers=extra_headers or {}, - ) + transformed_request = await litellm.AmazonAnthropicClaudeConfig().async_transform_request( + model=model, + messages=messages, + optional_params=optional_params, + litellm_params=litellm_params or {}, + headers=extra_headers or {}, ) data = json.dumps(transformed_request) @@ -1300,9 +1181,7 @@ async def async_completion( if isinstance(timeout, float) or isinstance(timeout, int): timeout = httpx.Timeout(timeout) _params["timeout"] = timeout - client = get_async_httpx_client( - params=_params, llm_provider=litellm.LlmProviders.BEDROCK - ) # type: ignore + client = get_async_httpx_client(params=_params, llm_provider=litellm.LlmProviders.BEDROCK) # type: ignore else: client = client # type: ignore @@ -1441,19 +1320,13 @@ def extract_reasoning_content_str( def translate_thinking_blocks( self, thinking_block: BedrockConverseReasoningContentBlockDelta - ) -> Optional[ - List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] - ]: + ) -> Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]]: """ Translate the thinking blocks to a string """ - thinking_blocks_list: List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] = [] - _thinking_block: Optional[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] = None + thinking_blocks_list: List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] = [] + _thinking_block: Optional[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]] = None if "text" in thinking_block: _thinking_block = ChatCompletionThinkingBlock(type="thinking") @@ -1487,42 +1360,27 @@ def _handle_converse_start_event( ) -> Tuple[ Optional[ChatCompletionToolCallChunk], dict, - Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ], + Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]], ]: """Handle 'start' event in converse chunk parsing.""" tool_use: Optional[ChatCompletionToolCallChunk] = None provider_specific_fields: dict = {} - thinking_blocks: Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ] = None + thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]] = None self.content_blocks = [] # reset if start_obj is not None: if "toolUse" in start_obj and start_obj["toolUse"] is not None: ## check tool name was formatted by litellm _response_tool_name = start_obj["toolUse"]["name"] - response_tool_name = get_bedrock_tool_name( - response_tool_name=_response_tool_name - ) + response_tool_name = get_bedrock_tool_name(response_tool_name=_response_tool_name) self._current_tool_name = response_tool_name # When json_mode is True, suppress the internal json_tool_call # and convert its content to text in delta events instead - if ( - self.json_mode is True - and response_tool_name == RESPONSE_FORMAT_TOOL_NAME - ): + if self.json_mode is True and response_tool_name == RESPONSE_FORMAT_TOOL_NAME: return tool_use, provider_specific_fields, thinking_blocks - self.tool_calls_index = ( - 0 if self.tool_calls_index is None else self.tool_calls_index + 1 - ) + self.tool_calls_index = 0 if self.tool_calls_index is None else self.tool_calls_index + 1 tool_use = { "id": start_obj["toolUse"]["toolUseId"], "type": "function", @@ -1533,12 +1391,9 @@ def _handle_converse_start_event( "index": self.tool_calls_index, } elif ( - "reasoningContent" in start_obj - and start_obj["reasoningContent"] is not None + "reasoningContent" in start_obj and start_obj["reasoningContent"] is not None ): # redacted thinking can be in start object - thinking_blocks = self.translate_thinking_blocks( - start_obj["reasoningContent"] - ) + thinking_blocks = self.translate_thinking_blocks(start_obj["reasoningContent"]) provider_specific_fields = { "reasoningContent": start_obj["reasoningContent"], } @@ -1553,22 +1408,14 @@ def _handle_converse_delta_event( Optional[ChatCompletionToolCallChunk], dict, Optional[str], - Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ], + Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]], ]: """Handle 'delta' event in converse chunk parsing.""" text = "" tool_use: Optional[ChatCompletionToolCallChunk] = None provider_specific_fields: dict = {} reasoning_content: Optional[str] = None - thinking_blocks: Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ] = None + thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]] = None self.content_blocks.append(delta_obj) if "text" in delta_obj: @@ -1576,10 +1423,7 @@ def _handle_converse_delta_event( elif "toolUse" in delta_obj: # When json_mode is True and this is the internal json_tool_call, # convert tool input to text content instead of tool call arguments - if ( - self.json_mode is True - and self._current_tool_name == RESPONSE_FORMAT_TOOL_NAME - ): + if self.json_mode is True and self._current_tool_name == RESPONSE_FORMAT_TOOL_NAME: text = delta_obj["toolUse"]["input"] else: tool_use = { @@ -1589,30 +1433,16 @@ def _handle_converse_delta_event( "name": None, "arguments": delta_obj["toolUse"]["input"], }, - "index": ( - self.tool_calls_index - if self.tool_calls_index is not None - else index - ), + "index": (self.tool_calls_index if self.tool_calls_index is not None else index), } elif "reasoningContent" in delta_obj: provider_specific_fields = { "reasoningContent": delta_obj["reasoningContent"], } - reasoning_content = self.extract_reasoning_content_str( - delta_obj["reasoningContent"] - ) - thinking_blocks = self.translate_thinking_blocks( - delta_obj["reasoningContent"] - ) - if ( - thinking_blocks - and len(thinking_blocks) > 0 - and reasoning_content is None - ): - reasoning_content = ( - "" # set to non-empty string to ensure consistency with Anthropic - ) + reasoning_content = self.extract_reasoning_content_str(delta_obj["reasoningContent"]) + thinking_blocks = self.translate_thinking_blocks(delta_obj["reasoningContent"]) + if thinking_blocks and len(thinking_blocks) > 0 and reasoning_content is None: + reasoning_content = "" # set to non-empty string to ensure consistency with Anthropic elif "citationsContent" in delta_obj: # Handle Nova grounding citations in streaming responses provider_specific_fields = { @@ -1626,18 +1456,13 @@ def _handle_converse_delta_event( thinking_blocks, ) - def _handle_converse_stop_event( - self, index: int - ) -> Optional[ChatCompletionToolCallChunk]: + def _handle_converse_stop_event(self, index: int) -> Optional[ChatCompletionToolCallChunk]: """Handle stop/contentBlockIndex event in converse chunk parsing.""" tool_use: Optional[ChatCompletionToolCallChunk] = None # If the ending block was the internal json_tool_call, skip emitting # the empty-args tool chunk and reset tracking state - if ( - self.json_mode is True - and self._current_tool_name == RESPONSE_FORMAT_TOOL_NAME - ): + if self.json_mode is True and self._current_tool_name == RESPONSE_FORMAT_TOOL_NAME: self._current_tool_name = None return tool_use @@ -1651,11 +1476,7 @@ def _handle_converse_stop_event( "name": None, "arguments": "{}", }, - "index": ( - self.tool_calls_index - if self.tool_calls_index is not None - else index - ), + "index": (self.tool_calls_index if self.tool_calls_index is not None else index), } return tool_use @@ -1672,13 +1493,9 @@ def converse_chunk_parser(self, chunk_data: dict) -> ModelResponseStream: usage: Optional[Usage] = None provider_specific_fields: dict = {} reasoning_content: Optional[str] = None - thinking_blocks: Optional[ - List[ - Union[ - ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock - ] - ] - ] = None + thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]] = ( + None + ) content_block_index = int(chunk_data.get("contentBlockIndex", 0)) if "start" in chunk_data: @@ -1697,9 +1514,7 @@ def converse_chunk_parser(self, chunk_data: dict) -> ModelResponseStream: reasoning_content, thinking_blocks, ) = self._handle_converse_delta_event(delta_obj, content_block_index) - elif ( - "contentBlockIndex" in chunk_data - ): # stop block, no 'start' or 'delta' object + elif "contentBlockIndex" in chunk_data: # stop block, no 'start' or 'delta' object tool_use = self._handle_converse_stop_event(content_block_index) elif "stopReason" in chunk_data: finish_reason = map_finish_reason(chunk_data.get("stopReason", "stop")) @@ -1719,11 +1534,7 @@ def converse_chunk_parser(self, chunk_data: dict) -> ModelResponseStream: content=text, role="assistant", tool_calls=[tool_use] if tool_use else None, - provider_specific_fields=( - provider_specific_fields - if provider_specific_fields - else None - ), + provider_specific_fields=(provider_specific_fields if provider_specific_fields else None), thinking_blocks=thinking_blocks, reasoning_content=reasoning_content, ), @@ -1739,9 +1550,7 @@ def converse_chunk_parser(self, chunk_data: dict) -> ModelResponseStream: except Exception as e: raise Exception("Received streaming error - {}".format(str(e))) - def _chunk_parser( - self, chunk_data: dict - ) -> Union[GChunk, ModelResponseStream, dict]: + def _chunk_parser(self, chunk_data: dict) -> Union[GChunk, ModelResponseStream, dict]: text = "" is_finished = False finish_reason = "" @@ -1767,10 +1576,7 @@ def _chunk_parser( return self.converse_chunk_parser(chunk_data=_chunk_data) ######## bedrock.mistral mappings ############### elif "outputs" in chunk_data: - if ( - len(chunk_data["outputs"]) == 1 - and chunk_data["outputs"][0].get("text", None) is not None - ): + if len(chunk_data["outputs"]) == 1 and chunk_data["outputs"][0].get("text", None) is not None: text = chunk_data["outputs"][0]["text"] stop_reason = chunk_data.get("stop_reason", None) if stop_reason is not None: @@ -1799,9 +1605,7 @@ def _chunk_parser( tool_use=None, ) - def iter_bytes( - self, iterator: Iterator[bytes] - ) -> Iterator[Union[GChunk, ModelResponseStream, dict]]: + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[Union[GChunk, ModelResponseStream, dict]]: """Given an iterator that yields lines, iterate over it & yield every event encountered""" from botocore.eventstream import EventStreamBuffer @@ -1897,9 +1701,7 @@ def __init__( sync_stream=sync_stream, ) - def _chunk_parser( - self, chunk_data: dict - ) -> Union[GChunk, ModelResponseStream, dict]: + def _chunk_parser(self, chunk_data: dict) -> Union[GChunk, ModelResponseStream, dict]: return self.deepseek_model_response_iterator.chunk_parser(chunk=chunk_data) @@ -1933,9 +1735,7 @@ def _handle_json_mode_chunk( """ tool_use: Optional[ChatCompletionToolCallChunk] = None if self.json_mode is True and tool_calls is not None: - message = litellm.AnthropicConfig()._convert_tool_response_to_message( - tool_calls=tool_calls - ) + message = litellm.AnthropicConfig()._convert_tool_response_to_message(tool_calls=tool_calls) if message is not None: text = message.content or "" tool_use = None @@ -1971,9 +1771,7 @@ def _chunk_parser(self, chunk_data: ModelResponse) -> GChunk: text=text, tool_use=tool_use, is_finished=True, - finish_reason=map_finish_reason( - finish_reason=chunk_data.choices[0].finish_reason or "" - ), + finish_reason=map_finish_reason(finish_reason=chunk_data.choices[0].finish_reason or ""), usage=ChatCompletionUsageBlock( prompt_tokens=chunk_usage.prompt_tokens, completion_tokens=chunk_usage.completion_tokens, diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_cohere_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_cohere_transformation.py index 9c2c95e6cea9..8b411b7b576b 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_cohere_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_cohere_transformation.py @@ -54,9 +54,7 @@ def get_config(cls): } def get_supported_openai_params(self, model: str) -> List[str]: - supported_params = CohereChatConfig.get_supported_openai_params( - self, model=model - ) + supported_params = CohereChatConfig.get_supported_openai_params(self, model=model) return supported_params def map_openai_params( diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_deepseek_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_deepseek_transformation.py index 0fe84b0ce0c3..d3025e13a996 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_deepseek_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_deepseek_transformation.py @@ -57,18 +57,11 @@ def transform_response( json_mode, ) prompt = cast(Optional[str], request_data.get("prompt")) - message_content = cast( - Optional[str], cast(Choices, response.choices[0]).message.get("content") - ) + message_content = cast(Optional[str], cast(Choices, response.choices[0]).message.get("content")) if prompt and prompt.strip().endswith("") and message_content: message_content_with_reasoning_token = "" + message_content - reasoning, content = _parse_content_for_reasoning( - message_content_with_reasoning_token - ) - provider_specific_fields = ( - cast(Choices, response.choices[0]).message.provider_specific_fields - or {} - ) + reasoning, content = _parse_content_for_reasoning(message_content_with_reasoning_token) + provider_specific_fields = cast(Choices, response.choices[0]).message.provider_specific_fields or {} if reasoning: provider_specific_fields["reasoning_content"] = reasoning @@ -96,9 +89,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: typed_chunk = AmazonDeepSeekR1StreamingResponse(**chunk) # type: ignore generated_content = typed_chunk["generation"] if generated_content == "" and not self.has_finished_thinking: - verbose_logger.debug( - "Deepseek r1: received, setting has_finished_thinking to True" - ) + verbose_logger.debug("Deepseek r1: received, setting has_finished_thinking to True") generated_content = "" self.has_finished_thinking = True @@ -115,16 +106,8 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: StreamingChoices( finish_reason=typed_chunk["stop_reason"], delta=Delta( - content=( - generated_content - if self.has_finished_thinking - else None - ), - reasoning_content=( - generated_content - if not self.has_finished_thinking - else None - ), + content=(generated_content if self.has_finished_thinking else None), + reasoning_content=(generated_content if not self.has_finished_thinking else None), ), ) ], diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py index 3992de4d4fc4..58dfa17a7222 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_mistral_transformation.py @@ -87,9 +87,7 @@ def map_openai_params( return optional_params @staticmethod - def get_outputText( - completion_response: dict, model_response: "ModelResponse" - ) -> str: + def get_outputText(completion_response: dict, model_response: "ModelResponse") -> str: """This function extracts the output text from a bedrock mistral completion. As a side effect, it updates the finish reason for a model response. @@ -103,17 +101,11 @@ def get_outputText( """ if "choices" in completion_response: outputText = completion_response["choices"][0]["message"]["content"] - model_response.choices[0].finish_reason = completion_response["choices"][0][ - "finish_reason" - ] + model_response.choices[0].finish_reason = completion_response["choices"][0]["finish_reason"] elif "outputs" in completion_response: outputText = completion_response["outputs"][0]["text"] - model_response.choices[0].finish_reason = completion_response["outputs"][0][ - "stop_reason" - ] + model_response.choices[0].finish_reason = completion_response["outputs"][0]["stop_reason"] else: - raise BedrockError( - message="Unexpected mistral completion response", status_code=400 - ) + raise BedrockError(message="Unexpected mistral completion response", status_code=400) return outputText diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py index 3aeb65b58c70..0532d677e5a6 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_moonshot_transformation.py @@ -101,9 +101,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: "stop", ] # Bedrock doesn't support stopSequences - base_openai_params = super( - MoonshotChatConfig, self - ).get_supported_openai_params(model=model) + base_openai_params = super(MoonshotChatConfig, self).get_supported_openai_params(model=model) final_params: List[str] = [] for param in base_openai_params: if param not in excluded_params: @@ -168,9 +166,7 @@ def transform_request( headers=headers, ) - def _extract_reasoning_from_content( - self, content: str - ) -> tuple[Optional[str], str]: + def _extract_reasoning_from_content(self, content: str) -> tuple[Optional[str], str]: """ Extract reasoning content from tags in the response. @@ -187,9 +183,7 @@ def _extract_reasoning_from_content( return None, content # Match ... tags - reasoning_match = re.match( - r"(.*?)\s*(.*)", content, re.DOTALL - ) + reasoning_match = re.match(r"(.*?)\s*(.*)", content, re.DOTALL) if reasoning_match: reasoning_content = reasoning_match.group(1).strip() @@ -241,11 +235,7 @@ def transform_response( if model_response.choices and len(model_response.choices) > 0: for choice in model_response.choices: # Only process Choices (not StreamingChoices) which have message attribute - if ( - isinstance(choice, Choices) - and choice.message - and choice.message.content - ): + if isinstance(choice, Choices) and choice.message and choice.message.content: ( reasoning_content, main_content, diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_nova_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_nova_transformation.py index 3506c8f1cc07..acfa5021507a 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_nova_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_nova_transformation.py @@ -37,9 +37,7 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - return AmazonConverseConfig.map_openai_params( - self, non_default_params, optional_params, model, drop_params - ) + return AmazonConverseConfig.map_openai_params(self, non_default_params, optional_params, model, drop_params) def transform_request( self, @@ -57,13 +55,9 @@ def transform_request( litellm_params=litellm_params, headers=headers, ) - _bedrock_invoke_nova_request = BedrockInvokeNovaRequest( - **_transformed_nova_request - ) + _bedrock_invoke_nova_request = BedrockInvokeNovaRequest(**_transformed_nova_request) self._remove_empty_system_messages(_bedrock_invoke_nova_request) - bedrock_invoke_nova_request = self._filter_allowed_fields( - _bedrock_invoke_nova_request - ) + bedrock_invoke_nova_request = self._filter_allowed_fields(_bedrock_invoke_nova_request) return bedrock_invoke_nova_request def transform_response( @@ -95,20 +89,14 @@ def transform_response( json_mode, ) - def _filter_allowed_fields( - self, bedrock_invoke_nova_request: BedrockInvokeNovaRequest - ) -> dict: + def _filter_allowed_fields(self, bedrock_invoke_nova_request: BedrockInvokeNovaRequest) -> dict: """ Filter out fields that are not allowed in the `BedrockInvokeNovaRequest` dataclass. """ allowed_fields = set(BedrockInvokeNovaRequest.__annotations__.keys()) - return { - k: v for k, v in bedrock_invoke_nova_request.items() if k in allowed_fields - } + return {k: v for k, v in bedrock_invoke_nova_request.items() if k in allowed_fields} - def _remove_empty_system_messages( - self, bedrock_invoke_nova_request: BedrockInvokeNovaRequest - ) -> None: + def _remove_empty_system_messages(self, bedrock_invoke_nova_request: BedrockInvokeNovaRequest) -> None: """ In-place remove empty `system` messages from the request. diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py index 7b64c6066d00..d3f9d8bffb8f 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_openai_transformation.py @@ -82,14 +82,10 @@ def get_complete_url( model_id = self._get_openai_model_id(model) # Get AWS region - aws_region_name = self._get_aws_region_name( - optional_params=optional_params, model=model - ) + aws_region_name = self._get_aws_region_name(optional_params=optional_params, model=model) # Get runtime endpoint - aws_bedrock_runtime_endpoint = optional_params.get( - "aws_bedrock_runtime_endpoint", None - ) + aws_bedrock_runtime_endpoint = optional_params.get("aws_bedrock_runtime_endpoint", None) endpoint_url, proxy_endpoint_url = self.get_runtime_endpoint( api_base=api_base, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, @@ -101,9 +97,7 @@ def get_complete_url( # Build the invoke URL if stream: - endpoint_url = ( - f"{endpoint_url}/model/{model_id}/invoke-with-response-stream" - ) + endpoint_url = f"{endpoint_url}/model/{model_id}/invoke-with-response-stream" else: endpoint_url = f"{endpoint_url}/model/{model_id}/invoke" @@ -153,11 +147,7 @@ def transform_request( optional_params.pop("stream", None) # Remove AWS-specific params that shouldn't be in the request body - inference_params = { - k: v - for k, v in optional_params.items() - if k not in self.aws_authentication_params - } + inference_params = {k: v for k, v in optional_params.items() if k not in self.aws_authentication_params} # Use parent class transform_request for OpenAI format return super().transform_request( diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py index c65e9e0b0832..d63642c806fb 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen2_transformation.py @@ -57,9 +57,7 @@ def transform_response( response_data = raw_response # Extract the generated text - Qwen2 uses "text" field, but also support "generation" for compatibility - generated_text = response_data.get("generation", "") or response_data.get( - "text", "" - ) + generated_text = response_data.get("generation", "") or response_data.get("text", "") # Clean up the response (remove assistant start token if present) if generated_text.startswith("<|im_start|>assistant\n"): diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py index 6325c388181c..762631cac5eb 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_qwen3_transformation.py @@ -134,9 +134,7 @@ def _convert_messages_to_prompt(self, messages: List[AllMessageValues]) -> str: text_content.append(item.get("text", "")) elif item.get("type") == "image_url": # For Qwen3, we can include image placeholders - text_content.append( - "<|vision_start|><|image_pad|><|vision_end|>" - ) + text_content.append("<|vision_start|><|image_pad|><|vision_end|>") content = "".join(text_content) prompt_parts.append(f"<|im_start|>user\n{content}<|im_end|>") elif role == "assistant": @@ -144,9 +142,7 @@ def _convert_messages_to_prompt(self, messages: List[AllMessageValues]) -> str: # Handle tool calls for tool_call in tool_calls: function_name = tool_call.get("function", {}).get("name", "") - function_args = tool_call.get("function", {}).get( - "arguments", "" - ) + function_args = tool_call.get("function", {}).get("arguments", "") prompt_parts.append( f'<|im_start|>assistant\n\n{{"name": "{function_name}", "arguments": "{function_args}"}}\n<|im_end|>' ) diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_titan_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_titan_transformation.py index 367fb84d1ac6..ff9a2ee0c6de 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_titan_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_titan_transformation.py @@ -105,9 +105,7 @@ def map_openai_params( if k == "temperature": optional_params["temperature"] = v if k == "stop": - filtered_stop = self._map_and_modify_arg( - {"stop": v}, provider="bedrock", model=model, stop=v - ) + filtered_stop = self._map_and_modify_arg({"stop": v}, provider="bedrock", model=model, stop=v) optional_params["stopSequences"] = filtered_stop["stop"] if k == "top_p": optional_params["topP"] = v diff --git a/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py index 889480d31a57..6d25bb323094 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/amazon_twelvelabs_pegasus_transformation.py @@ -63,9 +63,7 @@ def map_openai_params( if param == "temperature": optional_params["temperature"] = value if param == "response_format": - optional_params["responseFormat"] = self._normalize_response_format( - value - ) + optional_params["responseFormat"] = self._normalize_response_format(value) return optional_params def _normalize_response_format(self, value: Any) -> Any: @@ -131,15 +129,11 @@ def transform_request( return request_data def _build_media_source(self, optional_params: dict) -> Optional[dict]: - direct_source = optional_params.get("mediaSource") or optional_params.get( - "media_source" - ) + direct_source = optional_params.get("mediaSource") or optional_params.get("media_source") if isinstance(direct_source, dict): return direct_source - base64_input = optional_params.get("video_base64") or optional_params.get( - "base64_string" - ) + base64_input = optional_params.get("video_base64") or optional_params.get("base64_string") if base64_input: return {"base64String": get_base64_str(base64_input)} @@ -235,8 +229,7 @@ def transform_response( if ( message_content and hasattr(model_response.choices[0], "message") - and getattr(model_response.choices[0].message, "tool_calls", None) - is None + and getattr(model_response.choices[0].message, "tool_calls", None) is None ): model_response.choices[0].message.content = message_content # type: ignore model_response.choices[0].finish_reason = finish_reason @@ -249,16 +242,10 @@ def transform_response( ) # Calculate usage from headers - bedrock_input_tokens = raw_response.headers.get( - "x-amzn-bedrock-input-token-count", None - ) - bedrock_output_tokens = raw_response.headers.get( - "x-amzn-bedrock-output-token-count", None - ) + bedrock_input_tokens = raw_response.headers.get("x-amzn-bedrock-input-token-count", None) + bedrock_output_tokens = raw_response.headers.get("x-amzn-bedrock-output-token-count", None) - prompt_tokens = int( - bedrock_input_tokens or litellm.token_counter(messages=messages) - ) + prompt_tokens = int(bedrock_input_tokens or litellm.token_counter(messages=messages)) completion_tokens = int( bedrock_output_tokens diff --git a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py index 79153c3ceffb..60d532eb8c5b 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py @@ -88,9 +88,7 @@ def map_openai_params( # ``_clamp_adaptive_reasoning_effort_for_bedrock`` so adaptive Claude # requests degrade ``xhigh`` -> ``max`` rather than 400-ing on # models like Opus 4.6 that don't natively advertise xhigh. - self._clamp_adaptive_reasoning_effort_for_bedrock( - model=original_model, params=non_default_params - ) + self._clamp_adaptive_reasoning_effort_for_bedrock(model=original_model, params=non_default_params) optional_params = AnthropicConfig.map_openai_params( self, @@ -190,11 +188,7 @@ def _build_bedrock_anthropic_request_base( litellm_params: dict, headers: dict, ) -> dict: - filtered_params = { - k: v - for k, v in optional_params.items() - if k not in self.aws_authentication_params - } + filtered_params = {k: v for k, v in optional_params.items() if k not in self.aws_authentication_params} output_config = filtered_params.get("output_config") if isinstance(output_config, dict): filtered_params["output_config"] = dict(output_config) @@ -217,9 +211,7 @@ def _build_bedrock_anthropic_request_base( anthropic_request.pop("stream", None) anthropic_request.pop("stream_chunk_size", None) output_format = anthropic_request.pop("output_format", None) - output_config_format = pop_bedrock_invoke_output_config_format( - anthropic_request - ) + output_config_format = pop_bedrock_invoke_output_config_format(anthropic_request) if output_format: convert_bedrock_invoke_output_format_to_inline_schema( output_format=output_format, @@ -280,9 +272,7 @@ def _compute_bedrock_invoke_beta_headers( ) beta_set.update(auto_betas) - if tool_search_used and not ( - programmatic_tool_calling_used or input_examples_used - ): + if tool_search_used and not (programmatic_tool_calling_used or input_examples_used): beta_set.discard(ANTHROPIC_TOOL_SEARCH_BETA_HEADER) if "opus-4" in model.lower() or "opus_4" in model.lower(): beta_set.add("tool-search-tool-2025-10-19") @@ -332,9 +322,7 @@ def _convert_document_url_sources_to_base64(self, anthropic_request: dict) -> No "data": image_chunk["data"], } - async def _async_convert_document_url_sources_to_base64( - self, anthropic_request: dict - ) -> None: + async def _async_convert_document_url_sources_to_base64(self, anthropic_request: dict) -> None: """ Async version of document URL conversion for async completion paths. """ @@ -390,9 +378,7 @@ def _normalize_bedrock_tool_search_tools(self, optional_params: dict) -> dict: if tool_type == "tool_search_tool_regex_20251119": normalized_tool = tool.copy() normalized_tool["type"] = "tool_search_tool_regex" - normalized_tool["name"] = normalized_tool.get( - "name", "tool_search_tool_regex" - ) + normalized_tool["name"] = normalized_tool.get("name", "tool_search_tool_regex") normalized_tools.append(normalized_tool) continue normalized_tools.append(tool) diff --git a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py index 8fc2375c224c..bbe16e267137 100644 --- a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py +++ b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py @@ -95,16 +95,12 @@ def get_complete_url( endpoint_url, proxy_endpoint_url = self.get_runtime_endpoint( api_base=api_base, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, - aws_region_name=self._get_aws_region_name( - optional_params=optional_params, model=model - ), + aws_region_name=self._get_aws_region_name(optional_params=optional_params, model=model), ) if (stream is not None and stream is True) and provider != "ai21": endpoint_url = f"{endpoint_url}/model/{modelId}/invoke-with-response-stream" - proxy_endpoint_url = ( - f"{proxy_endpoint_url}/model/{modelId}/invoke-with-response-stream" - ) + proxy_endpoint_url = f"{proxy_endpoint_url}/model/{modelId}/invoke-with-response-stream" else: endpoint_url = f"{endpoint_url}/model/{modelId}/invoke" proxy_endpoint_url = f"{proxy_endpoint_url}/model/{modelId}/invoke" @@ -163,11 +159,7 @@ def transform_request( custom_prompt_dict=custom_prompt_dict, ) inference_params = copy.deepcopy(optional_params) - inference_params = { - k: v - for k, v in inference_params.items() - if k not in self.aws_authentication_params - } + inference_params = {k: v for k, v in inference_params.items() if k not in self.aws_authentication_params} request_data: dict = {} if provider == "cohere": if model.startswith("cohere.command-r"): @@ -183,19 +175,15 @@ def transform_request( config = litellm.AmazonCohereConfig.get_config() self._apply_config_to_params(config, inference_params) if stream is True: - inference_params["stream"] = ( - True # cohere requires stream = True in inference params - ) + inference_params["stream"] = True # cohere requires stream = True in inference params request_data = {"prompt": prompt, **inference_params} elif provider == "anthropic": - transformed_request = ( - litellm.AmazonAnthropicClaudeConfig().transform_request( - model=model, - messages=messages, - optional_params=optional_params, - litellm_params=litellm_params, - headers=headers, - ) + transformed_request = litellm.AmazonAnthropicClaudeConfig().transform_request( + model=model, + messages=messages, + optional_params=optional_params, + litellm_params=litellm_params, + headers=headers, ) return transformed_request @@ -274,9 +262,7 @@ def transform_response( try: completion_response = raw_response.json() except Exception: - raise BedrockError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise BedrockError(message=raw_response.text, status_code=raw_response.status_code) verbose_logger.debug( "bedrock invoke response % s", json.dumps(completion_response, indent=4, default=str), @@ -333,22 +319,16 @@ def transform_response( json_mode=json_mode, ) elif provider == "ai21": - outputText = ( - completion_response.get("completions")[0].get("data").get("text") - ) + outputText = completion_response.get("completions")[0].get("data").get("text") elif provider == "meta" or provider == "llama" or provider == "deepseek_r1": outputText = completion_response["generation"] elif provider == "mistral": - outputText = litellm.AmazonMistralConfig.get_outputText( - completion_response, model_response - ) + outputText = litellm.AmazonMistralConfig.get_outputText(completion_response, model_response) else: # amazon titan outputText = completion_response.get("results")[0].get("outputText") except Exception as e: raise BedrockError( - message="Error processing={}, Received error={}".format( - raw_response.text, str(e) - ), + message="Error processing={}, Received error={}".format(raw_response.text, str(e)), status_code=422, ) @@ -371,23 +351,15 @@ def transform_response( raise Exception() except Exception as e: raise BedrockError( - message="Error parsing received text={}.\nError-{}".format( - outputText, str(e) - ), + message="Error parsing received text={}.\nError-{}".format(outputText, str(e)), status_code=raw_response.status_code, ) ## CALCULATING USAGE - bedrock returns usage in the headers - bedrock_input_tokens = raw_response.headers.get( - "x-amzn-bedrock-input-token-count", None - ) - bedrock_output_tokens = raw_response.headers.get( - "x-amzn-bedrock-output-token-count", None - ) + bedrock_input_tokens = raw_response.headers.get("x-amzn-bedrock-input-token-count", None) + bedrock_output_tokens = raw_response.headers.get("x-amzn-bedrock-output-token-count", None) - prompt_tokens = int( - bedrock_input_tokens or litellm.token_counter(messages=messages) - ) + prompt_tokens = int(bedrock_input_tokens or litellm.token_counter(messages=messages)) completion_tokens = int( bedrock_output_tokens @@ -565,9 +537,7 @@ def _get_provider_from_model_path( return cast(litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL, provider) return None - def convert_messages_to_prompt( - self, model, messages, provider, custom_prompt_dict - ) -> Tuple[str, Optional[list]]: + def convert_messages_to_prompt(self, model, messages, provider, custom_prompt_dict) -> Tuple[str, Optional[list]]: # handle anthropic prompts and amazon titan prompts prompt = "" chat_history: Optional[list] = None @@ -577,26 +547,18 @@ def convert_messages_to_prompt( model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details["roles"], - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), final_prompt_value=model_prompt_details.get("final_prompt_value", ""), messages=messages, ) return prompt, None ## ELSE if provider == "anthropic" or provider == "amazon": - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="bedrock" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="bedrock") elif provider == "mistral": - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="bedrock" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="bedrock") elif provider == "meta" or provider == "llama": - prompt = prompt_factory( - model=model, messages=messages, custom_llm_provider="bedrock" - ) + prompt = prompt_factory(model=model, messages=messages, custom_llm_provider="bedrock") elif provider == "cohere": prompt, chat_history = cohere_message_pt(messages=messages) elif provider == "deepseek_r1": diff --git a/litellm/llms/bedrock/chat/mantle/transformation.py b/litellm/llms/bedrock/chat/mantle/transformation.py index 93306025b025..d84e077c37b6 100644 --- a/litellm/llms/bedrock/chat/mantle/transformation.py +++ b/litellm/llms/bedrock/chat/mantle/transformation.py @@ -45,9 +45,7 @@ def get_complete_url( region = self._get_aws_region_name(optional_params=optional_params, model=model) return build_mantle_messages_url( api_base=api_base, - aws_bedrock_runtime_endpoint=optional_params.get( - "aws_bedrock_runtime_endpoint" - ), + aws_bedrock_runtime_endpoint=optional_params.get("aws_bedrock_runtime_endpoint"), region=region, ) diff --git a/litellm/llms/bedrock/claude_platform/common_utils.py b/litellm/llms/bedrock/claude_platform/common_utils.py index 3abb8710de75..b93577e2bcae 100644 --- a/litellm/llms/bedrock/claude_platform/common_utils.py +++ b/litellm/llms/bedrock/claude_platform/common_utils.py @@ -4,9 +4,7 @@ from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM from litellm.secret_managers.main import get_secret_str -CLAUDE_PLATFORM_SERVICE_NAME: Literal["aws-external-anthropic"] = ( - "aws-external-anthropic" -) +CLAUDE_PLATFORM_SERVICE_NAME: Literal["aws-external-anthropic"] = "aws-external-anthropic" CLAUDE_PLATFORM_BEDROCK_ROUTE = "claude_platform/" @@ -28,14 +26,10 @@ def _get_workspace_id(optional_params: dict, litellm_params: dict) -> Optional[s or litellm_params.get("anthropic-workspace-id") ) if workspace_id is None: - workspace_id = optional_params.get( - "anthropic_workspace_id" - ) or litellm_params.get("anthropic_workspace_id") + workspace_id = optional_params.get("anthropic_workspace_id") or litellm_params.get("anthropic_workspace_id") if workspace_id is not None: return str(workspace_id) - return get_secret_str("ANTHROPIC_AWS_WORKSPACE_ID") or get_secret_str( - "ANTHROPIC_WORKSPACE_ID" - ) + return get_secret_str("ANTHROPIC_AWS_WORKSPACE_ID") or get_secret_str("ANTHROPIC_WORKSPACE_ID") def _get_required_aws_region_name(self, optional_params: dict) -> str: aws_region_name = ( @@ -73,9 +67,7 @@ def get_complete_url( ) if api_base is None: aws_region_name = self._get_required_aws_region_name(optional_params) - api_base = ( - f"https://{CLAUDE_PLATFORM_SERVICE_NAME}.{aws_region_name}.api.aws" - ) + api_base = f"https://{CLAUDE_PLATFORM_SERVICE_NAME}.{aws_region_name}.api.aws" if not api_base.endswith("/v1/messages"): api_base = f"{api_base.rstrip('/')}/v1/messages" return api_base diff --git a/litellm/llms/bedrock/claude_platform/messages_transformation.py b/litellm/llms/bedrock/claude_platform/messages_transformation.py index 661581963229..1b0d21a724ca 100644 --- a/litellm/llms/bedrock/claude_platform/messages_transformation.py +++ b/litellm/llms/bedrock/claude_platform/messages_transformation.py @@ -11,9 +11,7 @@ from .common_utils import BedrockClaudePlatformMixin, strip_claude_platform_route -class BedrockClaudePlatformMessagesConfig( - BedrockClaudePlatformMixin, AnthropicMessagesConfig -): +class BedrockClaudePlatformMessagesConfig(BedrockClaudePlatformMixin, AnthropicMessagesConfig): def validate_anthropic_messages_environment( self, headers: dict, @@ -38,9 +36,7 @@ def validate_anthropic_messages_environment( resolved_api_key = api_key or get_secret_str("ANTHROPIC_AWS_API_KEY") headers = { **headers, - "anthropic-version": headers.get( - "anthropic-version", DEFAULT_ANTHROPIC_API_VERSION - ), + "anthropic-version": headers.get("anthropic-version", DEFAULT_ANTHROPIC_API_VERSION), "content-type": headers.get("content-type", "application/json"), "anthropic-workspace-id": workspace_id, } diff --git a/litellm/llms/bedrock/claude_platform/transformation.py b/litellm/llms/bedrock/claude_platform/transformation.py index c20dc63444fa..0868d9bddfed 100644 --- a/litellm/llms/bedrock/claude_platform/transformation.py +++ b/litellm/llms/bedrock/claude_platform/transformation.py @@ -45,39 +45,21 @@ def validate_environment( anthropic_headers = self.get_anthropic_headers( api_key=api_key, auth_token=None, - computer_tool_used=self.is_computer_tool_used( - tools=optional_params.get("tools") - ), + computer_tool_used=self.is_computer_tool_used(tools=optional_params.get("tools")), prompt_caching_set=self.is_cache_control_set(messages=messages), pdf_used=self.is_pdf_used(messages=messages), file_id_used=self.is_file_id_used(messages=messages), - mcp_server_used=self.is_mcp_server_used( - mcp_servers=optional_params.get("mcp_servers") - ), - web_search_tool_used=self.is_web_search_tool_used( - tools=optional_params.get("tools") - ), - tool_search_used=self.is_tool_search_used( - tools=optional_params.get("tools") - ), - programmatic_tool_calling_used=self.is_programmatic_tool_calling_used( - tools=optional_params.get("tools") - ), - input_examples_used=self.is_input_examples_used( - tools=optional_params.get("tools") - ), - effort_used=self.is_effort_used( - optional_params=optional_params, model=model - ), + mcp_server_used=self.is_mcp_server_used(mcp_servers=optional_params.get("mcp_servers")), + web_search_tool_used=self.is_web_search_tool_used(tools=optional_params.get("tools")), + tool_search_used=self.is_tool_search_used(tools=optional_params.get("tools")), + programmatic_tool_calling_used=self.is_programmatic_tool_calling_used(tools=optional_params.get("tools")), + input_examples_used=self.is_input_examples_used(tools=optional_params.get("tools")), + effort_used=self.is_effort_used(optional_params=optional_params, model=model), user_anthropic_beta_headers=self._get_user_anthropic_beta_headers( anthropic_beta_header=headers.get("anthropic-beta") ), - code_execution_tool_used=self.is_code_execution_tool_used( - tools=optional_params.get("tools") - ), - container_with_skills_used=self.is_container_with_skills_used( - optional_params=optional_params - ), + code_execution_tool_used=self.is_code_execution_tool_used(tools=optional_params.get("tools")), + container_with_skills_used=self.is_container_with_skills_used(optional_params=optional_params), ) anthropic_headers["anthropic-workspace-id"] = workspace_id return {**headers, **anthropic_headers} diff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.py index 44312eb39264..467e1050c993 100644 --- a/litellm/llms/bedrock/common_utils.py +++ b/litellm/llms/bedrock/common_utils.py @@ -431,11 +431,7 @@ def init_bedrock_client( config = boto3.session.Config() # type: ignore ### CHECK STS ### - if ( - aws_web_identity_token is not None - and aws_role_name is not None - and aws_session_name is not None - ): + if aws_web_identity_token is not None and aws_role_name is not None and aws_session_name is not None: oidc_token = get_secret(aws_web_identity_token) if oidc_token is None: @@ -474,9 +470,7 @@ def init_bedrock_client( verify=ssl_verify, ) - sts_response = sts_client.assume_role( - RoleArn=aws_role_name, RoleSessionName=aws_session_name - ) + sts_response = sts_client.assume_role(RoleArn=aws_role_name, RoleSessionName=aws_session_name) client = boto3.client( service_name="bedrock-runtime", @@ -523,9 +517,7 @@ def init_bedrock_client( verify=ssl_verify, ) if extra_headers: - client.meta.events.register( - "before-sign.bedrock-runtime.*", add_custom_header(extra_headers) - ) + client.meta.events.register("before-sign.bedrock-runtime.*", add_custom_header(extra_headers)) return client @@ -568,9 +560,7 @@ def get_bedrock_tool_name(response_tool_name: str) -> str: """ if response_tool_name in litellm.bedrock_tool_name_mappings.cache_dict: - response_tool_name = litellm.bedrock_tool_name_mappings.cache_dict[ - response_tool_name - ] + response_tool_name = litellm.bedrock_tool_name_mappings.cache_dict[response_tool_name] return response_tool_name @@ -687,10 +677,7 @@ def get_bedrock_base_model(model: str) -> str: if potential_region in get_bedrock_cross_region_inference_regions(): return model.split(".", 1)[1] - elif ( - alt_potential_region in _get_all_bedrock_regions() - and len(model.split("/", 1)) > 1 - ): + elif alt_potential_region in _get_all_bedrock_regions() and len(model.split("/", 1)) > 1: return model.split("/", 1)[1] return model @@ -754,10 +741,7 @@ def normalize_bedrock_opus_output_config_effort(model: str, output_config: Any) if ceiling is None: return - if ( - _BEDROCK_OUTPUT_CONFIG_EFFORT_ORDER[effort] - > _BEDROCK_OUTPUT_CONFIG_EFFORT_ORDER[ceiling] - ): + if _BEDROCK_OUTPUT_CONFIG_EFFORT_ORDER[effort] > _BEDROCK_OUTPUT_CONFIG_EFFORT_ORDER[ceiling]: output_config["effort"] = ceiling @@ -821,9 +805,7 @@ def validate_environment( ) -> dict: return headers - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: return [] # def get_provider_info(self, model: str) -> Optional[ProviderSpecificModelInfo]: @@ -923,9 +905,7 @@ def get_bedrock_route( # Check for nova spec prefixes (nova/ and nova-2/) _model_after_bedrock = model.replace("bedrock/", "", 1) - if _model_after_bedrock.startswith( - "nova-2/" - ) or _model_after_bedrock.startswith("nova/"): + if _model_after_bedrock.startswith("nova-2/") or _model_after_bedrock.startswith("nova/"): return "converse" if is_bedrock_application_inference_profile_arn(model): @@ -933,10 +913,7 @@ def get_bedrock_route( base_model = BedrockModelInfo.get_base_model(model) alt_model = BedrockModelInfo.get_non_litellm_routing_model_name(model=model) - if ( - base_model in litellm.bedrock_converse_models - or alt_model in litellm.bedrock_converse_models - ): + if base_model in litellm.bedrock_converse_models or alt_model in litellm.bedrock_converse_models: return "converse" return "invoke" @@ -962,9 +939,7 @@ def get_claude_platform_model(model: str) -> str: return model.replace("claude_platform/", "", 1) @staticmethod - def map_claude_platform_auth_params( - passed_params: dict, optional_params: dict - ) -> dict: + def map_claude_platform_auth_params(passed_params: dict, optional_params: dict) -> dict: """ Map Claude Platform route auth params that are not OpenAI request params. """ @@ -1100,9 +1075,7 @@ def get_bedrock_chat_config(model: str): The appropriate Bedrock config class instance """ bedrock_route = BedrockModelInfo.get_bedrock_route(model) - bedrock_invoke_provider = litellm.BedrockLLM.get_bedrock_invoke_provider( - model=model - ) + bedrock_invoke_provider = litellm.BedrockLLM.get_bedrock_invoke_provider(model=model) base_model = BedrockModelInfo.get_base_model(model) # Handle explicit routes first @@ -1135,10 +1108,7 @@ def get_bedrock_chat_config(model: str): if bedrock_invoke_provider == "amazon": return litellm.AmazonTitanConfig() elif bedrock_invoke_provider == "anthropic": - if ( - base_model - in litellm.AmazonAnthropicConfig.get_legacy_anthropic_model_names() - ): + if base_model in litellm.AmazonAnthropicConfig.get_legacy_anthropic_model_names(): return litellm.AmazonAnthropicConfig() else: return litellm.AmazonAnthropicClaudeConfig() @@ -1224,9 +1194,7 @@ def build_bedrock_stream_error( if exception_type is not None and response_stream_shape is not None: member = response_stream_shape.members.get(exception_type) if member is not None: - modeled_status = ( - (member.metadata or {}).get("error", {}).get("httpStatusCode") - ) + modeled_status = (member.metadata or {}).get("error", {}).get("httpStatusCode") if modeled_status is not None: status_code = int(modeled_status) @@ -1296,9 +1264,7 @@ def get_anthropic_beta_from_headers(headers: dict) -> List[str]: # Try to parse as JSON array first (e.g., '["interleaved-thinking-2025-05-14", "claude-code-20250219"]') if isinstance(anthropic_beta_header, str): anthropic_beta_header = anthropic_beta_header.strip() - if anthropic_beta_header.startswith("[") and anthropic_beta_header.endswith( - "]" - ): + if anthropic_beta_header.startswith("[") and anthropic_beta_header.endswith("]"): try: parsed = json.loads(anthropic_beta_header) if isinstance(parsed, list): @@ -1360,9 +1326,7 @@ def parse_s3_uri(self, s3_uri: str) -> tuple: return s3_parts[0], s3_parts[1] # bucket, key - def extract_model_from_s3_file_path( - self, s3_uri: str, optional_params: dict - ) -> str: + def extract_model_from_s3_file_path(self, s3_uri: str, optional_params: dict) -> str: """ Extract model ID from S3 file path. @@ -1371,9 +1335,7 @@ def extract_model_from_s3_file_path( """ # Check if model is provided in optional_params first if "model" in optional_params and optional_params["model"]: - return self.get_bedrock_model_id_from_litellm_model( - optional_params["model"] - ) + return self.get_bedrock_model_id_from_litellm_model(optional_params["model"]) # Extract model from S3 URI path # Expected format: s3://bucket/litellm-bedrock-files-{model}-{uuid}.jsonl @@ -1426,9 +1388,7 @@ def sign_aws_request( raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") # Get AWS credentials using existing methods - aws_region_name = self._base_aws._get_aws_region_name( - optional_params=optional_params, model="" - ) + aws_region_name = self._base_aws._get_aws_region_name(optional_params=optional_params, model="") credentials = self._base_aws.get_credentials( aws_access_key_id=optional_params.get("aws_access_key_id"), aws_secret_access_key=optional_params.get("aws_secret_access_key"), @@ -1459,19 +1419,13 @@ def sign_aws_request( # Create AWS request and sign it sigv4 = SigV4Auth(credentials, service_name, aws_region_name) - request = AWSRequest( - method=method_upper, url=endpoint_url, data=request_data, headers=headers - ) + request = AWSRequest(method=method_upper, url=endpoint_url, data=request_data, headers=headers) sigv4.add_auth(request) prepped = request.prepare() return ( dict(prepped.headers), - ( - request_data.encode("utf-8") - if isinstance(request_data, str) - else request_data - ), + (request_data.encode("utf-8") if isinstance(request_data, str) else request_data), ) def generate_unique_job_name(self, model: str, prefix: str = "litellm") -> str: @@ -1520,14 +1474,10 @@ def get_s3_bucket_and_key_from_config( # Get bucket name bucket_name = ( - litellm_params.get("s3_bucket_name") - or optional_params.get("s3_bucket_name") - or os.getenv(bucket_env_var) + litellm_params.get("s3_bucket_name") or optional_params.get("s3_bucket_name") or os.getenv(bucket_env_var) ) if not bucket_name: - raise ValueError( - f"S3 bucket name is required. Set 's3_bucket_name' parameter or {bucket_env_var} env var" - ) + raise ValueError(f"S3 bucket name is required. Set 's3_bucket_name' parameter or {bucket_env_var} env var") # Generate unique object key timestamp = int(time.time()) @@ -1542,6 +1492,4 @@ def get_error_class( """ Get Bedrock-specific error class. """ - return BedrockError( - status_code=status_code, message=error_message, headers=headers - ) + return BedrockError(status_code=status_code, message=error_message, headers=headers) diff --git a/litellm/llms/bedrock/cost_calculation.py b/litellm/llms/bedrock/cost_calculation.py index ac99d4e36e7f..9a164d02eeb0 100644 --- a/litellm/llms/bedrock/cost_calculation.py +++ b/litellm/llms/bedrock/cost_calculation.py @@ -11,9 +11,7 @@ from litellm.types.utils import Usage -def cost_per_token( - model: str, usage: "Usage", service_tier: Optional[str] = None -) -> Tuple[float, float]: +def cost_per_token(model: str, usage: "Usage", service_tier: Optional[str] = None) -> Tuple[float, float]: """ Calculates the cost per token for a given model, prompt tokens, and completion tokens. diff --git a/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py b/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py index eb7755574aca..1ea870a1d324 100644 --- a/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py +++ b/litellm/llms/bedrock/count_tokens/bedrock_token_counter.py @@ -88,9 +88,7 @@ async def count_tokens( original_response=result, ) except BedrockError as e: - verbose_logger.warning( - f"Bedrock CountTokens API error: status={e.status_code}, message={e.message}" - ) + verbose_logger.warning(f"Bedrock CountTokens API error: status={e.status_code}, message={e.message}") return TokenCountResponse( total_tokens=0, request_model=request_model, diff --git a/litellm/llms/bedrock/count_tokens/handler.py b/litellm/llms/bedrock/count_tokens/handler.py index 8c227c853cc9..2c40e14129d5 100644 --- a/litellm/llms/bedrock/count_tokens/handler.py +++ b/litellm/llms/bedrock/count_tokens/handler.py @@ -43,9 +43,7 @@ async def handle_count_tokens_request( # Validate the request self.validate_count_tokens_request(request_data) - verbose_logger.debug( - f"Processing CountTokens request for resolved model: {resolved_model}" - ) + verbose_logger.debug(f"Processing CountTokens request for resolved model: {resolved_model}") # Get AWS region using existing LiteLLM function aws_region_name = self._get_aws_region_name( @@ -57,17 +55,13 @@ async def handle_count_tokens_request( verbose_logger.debug(f"Retrieved AWS region: {aws_region_name}") # Transform request to Bedrock format (supports both Converse and InvokeModel) - bedrock_request = self.transform_anthropic_to_bedrock_count_tokens( - request_data=request_data - ) + bedrock_request = self.transform_anthropic_to_bedrock_count_tokens(request_data=request_data) verbose_logger.debug(f"Transformed request: {bedrock_request}") # Get endpoint URL using simplified function api_base = litellm_params.get("api_base", None) - aws_bedrock_runtime_endpoint = litellm_params.get( - "aws_bedrock_runtime_endpoint", None - ) + aws_bedrock_runtime_endpoint = litellm_params.get("aws_bedrock_runtime_endpoint", None) endpoint_url = self.get_bedrock_count_tokens_endpoint( model=resolved_model, aws_region_name=aws_region_name, @@ -91,9 +85,7 @@ async def handle_count_tokens_request( api_key=api_key, ) - async_client = get_async_httpx_client( - llm_provider=litellm.LlmProviders.BEDROCK - ) + async_client = get_async_httpx_client(llm_provider=litellm.LlmProviders.BEDROCK) response = await async_client.post( endpoint_url, @@ -117,9 +109,7 @@ async def handle_count_tokens_request( verbose_logger.debug(f"Bedrock response: {bedrock_response}") # Transform response back to expected format - final_response = self.transform_bedrock_response_to_anthropic( - bedrock_response - ) + final_response = self.transform_bedrock_response_to_anthropic(bedrock_response) verbose_logger.debug(f"Final response: {final_response}") diff --git a/litellm/llms/bedrock/count_tokens/transformation.py b/litellm/llms/bedrock/count_tokens/transformation.py index bdef3349e00a..38eaf13893df 100644 --- a/litellm/llms/bedrock/count_tokens/transformation.py +++ b/litellm/llms/bedrock/count_tokens/transformation.py @@ -47,9 +47,7 @@ def _detect_input_type(self, request_data: Dict[str, Any]) -> str: if not isinstance(message, dict): continue content = message.get("content") - if isinstance(content, list) and any( - isinstance(block, dict) and "type" in block for block in content - ): + if isinstance(content, list) and any(isinstance(block, dict) and "type" in block for block in content): return "invokeModel" return "converse" @@ -97,9 +95,7 @@ def transform_anthropic_to_bedrock_count_tokens( else: return self._transform_to_invoke_model_format(request_data) - def _transform_to_converse_format( - self, request_data: Dict[str, Any] - ) -> Dict[str, Any]: + def _transform_to_converse_format(self, request_data: Dict[str, Any]) -> Dict[str, Any]: """Transform to Converse input format, including system and tools.""" messages = request_data.get("messages", []) system = request_data.get("system") @@ -141,16 +137,10 @@ def _transform_system(self, system: Optional[Any]) -> List[Dict[str, Any]]: return [{"text": system}] if isinstance(system, list): # Already in blocks format (e.g. [{"type": "text", "text": "..."}]) - return [ - {"text": block.get("text", "")} - for block in system - if isinstance(block, dict) - ] + return [{"text": block.get("text", "")} for block in system if isinstance(block, dict)] return [] - def _transform_tools( - self, tools: Optional[List[Dict[str, Any]]] - ) -> Optional[Dict[str, Any]]: + def _transform_tools(self, tools: Optional[List[Dict[str, Any]]]) -> Optional[Dict[str, Any]]: """Transform Anthropic tools to Bedrock toolConfig format.""" if not tools: return None @@ -165,9 +155,7 @@ def _transform_tools( name = name[:64] description = tool.get("description") or name - input_schema = tool.get( - "input_schema", {"type": "object", "properties": {}} - ) + input_schema = tool.get("input_schema", {"type": "object", "properties": {}}) bedrock_tools.append( { @@ -181,9 +169,7 @@ def _transform_tools( return {"tools": bedrock_tools} - def _transform_to_invoke_model_format( - self, request_data: Dict[str, Any] - ) -> Dict[str, Any]: + def _transform_to_invoke_model_format(self, request_data: Dict[str, Any]) -> Dict[str, Any]: """Transform to InvokeModel input format.""" import base64 import json @@ -196,9 +182,7 @@ def _transform_to_invoke_model_format( # Bedrock validates the body against the model's InvokeModel schema; # Anthropic Messages bodies require these fields. body_data.setdefault("anthropic_version", "bedrock-2023-05-31") - body_data.setdefault( - "max_tokens", DEFAULT_ANTHROPIC_INVOKE_MODEL_MAX_TOKENS - ) + body_data.setdefault("max_tokens", DEFAULT_ANTHROPIC_INVOKE_MODEL_MAX_TOKENS) # The CountTokens API expects invokeModel.body as a base64-encoded blob encoded_body = base64.b64encode(json.dumps(body_data).encode()).decode() @@ -240,9 +224,7 @@ def get_bedrock_count_tokens_endpoint( return endpoint - def transform_bedrock_response_to_anthropic( - self, bedrock_response: Dict[str, Any] - ) -> Dict[str, Any]: + def transform_bedrock_response_to_anthropic(self, bedrock_response: Dict[str, Any]) -> Dict[str, Any]: """ Transform Bedrock CountTokens response to Anthropic format. diff --git a/litellm/llms/bedrock/embed/amazon_nova_transformation.py b/litellm/llms/bedrock/embed/amazon_nova_transformation.py index c20b52a6e0da..58519d0d0615 100644 --- a/litellm/llms/bedrock/embed/amazon_nova_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_nova_transformation.py @@ -40,9 +40,7 @@ def get_supported_openai_params(self) -> List[str]: "dimensions", ] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: """Map OpenAI-style parameters to Nova parameters.""" for k, v in non_default_params.items(): if k == "dimensions": @@ -70,9 +68,7 @@ def _parse_data_url(self, data_url: str) -> tuple: # Split by comma to separate metadata from data # Format: data:image/jpeg;base64, if "," not in data_url: - raise ValueError( - f"Invalid data URL format (missing comma): {data_url[:50]}..." - ) + raise ValueError(f"Invalid data URL format (missing comma): {data_url[:50]}...") metadata, base64_data = data_url.split(",", 1) @@ -129,9 +125,7 @@ def _transform_request( if "dimensions" in embedding_params: embedding_params["embeddingDimension"] = embedding_params.pop("dimensions") elif "embedding_dimension" in embedding_params: - embedding_params["embeddingDimension"] = embedding_params.pop( - "embedding_dimension" - ) + embedding_params["embeddingDimension"] = embedding_params.pop("embedding_dimension") # Add required embeddingPurpose if not provided (required by Nova API) if "embeddingPurpose" not in embedding_params: @@ -322,9 +316,7 @@ def _transform_response( return EmbeddingResponse(data=embeddings, model=model, usage=usage) - def _transform_async_invoke_response( - self, response: dict, model: str - ) -> EmbeddingResponse: + def _transform_async_invoke_response(self, response: dict, model: str) -> EmbeddingResponse: """ Transform async invoke response (invocation ARN) to OpenAI format. diff --git a/litellm/llms/bedrock/embed/amazon_titan_g1_transformation.py b/litellm/llms/bedrock/embed/amazon_titan_g1_transformation.py index 64a79b732739..57cbb3263ded 100644 --- a/litellm/llms/bedrock/embed/amazon_titan_g1_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_titan_g1_transformation.py @@ -53,19 +53,13 @@ def get_config(cls): def get_supported_openai_params(self) -> List[str]: return [] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: return optional_params - def _transform_request( - self, input: str, inference_params: dict - ) -> AmazonTitanG1EmbeddingRequest: + def _transform_request(self, input: str, inference_params: dict) -> AmazonTitanG1EmbeddingRequest: return AmazonTitanG1EmbeddingRequest(inputText=input) - def _transform_response( - self, response_list: List[dict], model: str - ) -> EmbeddingResponse: + def _transform_response(self, response_list: List[dict], model: str) -> EmbeddingResponse: total_prompt_tokens = 0 transformed_responses: List[Embedding] = [] diff --git a/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py b/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py index 2713f54e623d..878d5f7e850d 100644 --- a/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_titan_multimodal_transformation.py @@ -33,26 +33,18 @@ def __init__(self) -> None: def get_supported_openai_params(self) -> List[str]: return ["dimensions"] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: for k, v in non_default_params.items(): if k == "dimensions": - optional_params["embeddingConfig"] = ( - AmazonTitanMultimodalEmbeddingConfig(outputEmbeddingLength=v) - ) + optional_params["embeddingConfig"] = AmazonTitanMultimodalEmbeddingConfig(outputEmbeddingLength=v) return optional_params - def _transform_request( - self, input: str, inference_params: dict - ) -> AmazonTitanMultimodalEmbeddingRequest: + def _transform_request(self, input: str, inference_params: dict) -> AmazonTitanMultimodalEmbeddingRequest: ## check if b64 encoded str or not ## is_encoded = is_base64_encoded(input) if is_encoded: # check if string is b64 encoded image or not b64_str = get_base64_str(input) - transformed_request = AmazonTitanMultimodalEmbeddingRequest( - inputImage=b64_str - ) + transformed_request = AmazonTitanMultimodalEmbeddingRequest(inputImage=b64_str) else: transformed_request = AmazonTitanMultimodalEmbeddingRequest(inputText=input) diff --git a/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py b/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py index ca0b95cd64e5..2c7b0ba465af 100644 --- a/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py +++ b/litellm/llms/bedrock/embed/amazon_titan_v2_transformation.py @@ -30,9 +30,7 @@ class AmazonTitanV2Config: normalize: Optional[bool] = None dimensions: Optional[int] = None - def __init__( - self, normalize: Optional[bool] = None, dimensions: Optional[int] = None - ) -> None: + def __init__(self, normalize: Optional[bool] = None, dimensions: Optional[int] = None) -> None: locals_ = locals().copy() for key, value in locals_.items(): if key != "self" and value is not None: @@ -59,9 +57,7 @@ def get_config(cls): def get_supported_openai_params(self) -> List[str]: return ["dimensions", "encoding_format"] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: for k, v in non_default_params.items(): if k == "dimensions": optional_params["dimensions"] = v @@ -77,14 +73,10 @@ def map_openai_params( optional_params["embeddingTypes"] = ["float"] return optional_params - def _transform_request( - self, input: str, inference_params: dict - ) -> AmazonTitanV2EmbeddingRequest: + def _transform_request(self, input: str, inference_params: dict) -> AmazonTitanV2EmbeddingRequest: return AmazonTitanV2EmbeddingRequest(inputText=input, **inference_params) # type: ignore - def _transform_response( - self, response_list: List[dict], model: str - ) -> EmbeddingResponse: + def _transform_response(self, response_list: List[dict], model: str) -> EmbeddingResponse: total_prompt_tokens = 0 transformed_responses: List[Embedding] = [] @@ -96,16 +88,10 @@ def _transform_response( # Otherwise, use float data from embeddingsByType or fallback to embedding field embedding_data: Union[List[float], List[int]] - if ( - "embeddingsByType" in _parsed_response - and "binary" in _parsed_response["embeddingsByType"] - ): + if "embeddingsByType" in _parsed_response and "binary" in _parsed_response["embeddingsByType"]: # Use binary data if available (for encoding_format="base64") embedding_data = _parsed_response["embeddingsByType"]["binary"] - elif ( - "embeddingsByType" in _parsed_response - and "float" in _parsed_response["embeddingsByType"] - ): + elif "embeddingsByType" in _parsed_response and "float" in _parsed_response["embeddingsByType"]: # Use float data from embeddingsByType embedding_data = _parsed_response["embeddingsByType"]["float"] elif "embedding" in _parsed_response: diff --git a/litellm/llms/bedrock/embed/cohere_transformation.py b/litellm/llms/bedrock/embed/cohere_transformation.py index 9570ff1a14c3..ac3130ea4347 100644 --- a/litellm/llms/bedrock/embed/cohere_transformation.py +++ b/litellm/llms/bedrock/embed/cohere_transformation.py @@ -17,9 +17,7 @@ def __init__(self) -> None: def get_supported_openai_params(self) -> List[str]: return ["encoding_format", "dimensions"] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: for k, v in non_default_params.items(): if k == "encoding_format": optional_params["embedding_types"] = v if isinstance(v, list) else [v] @@ -30,12 +28,8 @@ def map_openai_params( def _is_v3_model(self, model: str) -> bool: return "3" in model - def _transform_request( - self, model: str, input: List[str], inference_params: dict - ) -> CohereEmbeddingRequest: - transformed_request = CohereEmbeddingConfig()._transform_request( - model, input, inference_params - ) + def _transform_request(self, model: str, input: List[str], inference_params: dict) -> CohereEmbeddingRequest: + transformed_request = CohereEmbeddingConfig()._transform_request(model, input, inference_params) new_transformed_request = CohereEmbeddingRequest( input_type=transformed_request["input_type"], diff --git a/litellm/llms/bedrock/embed/embedding.py b/litellm/llms/bedrock/embed/embedding.py index e07ccb8c11bd..ff138709ac02 100644 --- a/litellm/llms/bedrock/embed/embedding.py +++ b/litellm/llms/bedrock/embed/embedding.py @@ -63,15 +63,11 @@ def _load_credentials( # check env # litellm_aws_region_name = get_secret("AWS_REGION_NAME", None) - if litellm_aws_region_name is not None and isinstance( - litellm_aws_region_name, str - ): + if litellm_aws_region_name is not None and isinstance(litellm_aws_region_name, str): aws_region_name = litellm_aws_region_name standard_aws_region_name = get_secret("AWS_REGION", None) - if standard_aws_region_name is not None and isinstance( - standard_aws_region_name, str - ): + if standard_aws_region_name is not None and isinstance(standard_aws_region_name, str): aws_region_name = standard_aws_region_name if aws_region_name is None: @@ -135,16 +131,12 @@ async def _make_async_call( if isinstance(timeout, float) or isinstance(timeout, int): timeout = httpx.Timeout(timeout) _params["timeout"] = timeout - client = get_async_httpx_client( - params=_params, llm_provider=litellm.LlmProviders.BEDROCK - ) + client = get_async_httpx_client(params=_params, llm_provider=litellm.LlmProviders.BEDROCK) else: client = client try: - response = await client.post( - url=api_base, headers=headers, data=json.dumps(data) - ) # type: ignore + response = await client.post(url=api_base, headers=headers, data=json.dumps(data)) # type: ignore response.raise_for_status() except httpx.HTTPStatusError as err: error_code = err.response.status_code @@ -168,22 +160,14 @@ def _transform_response( returned_response: Optional[EmbeddingResponse] = None # Handle async invoke responses (single response with invocationArn) - if ( - is_async_invoke - and len(response_list) == 1 - and "invocationArn" in response_list[0] - ): + if is_async_invoke and len(response_list) == 1 and "invocationArn" in response_list[0]: if provider == "twelvelabs": - returned_response = ( - TwelveLabsMarengoEmbeddingConfig()._transform_async_invoke_response( - response=response_list[0], model=model - ) + returned_response = TwelveLabsMarengoEmbeddingConfig()._transform_async_invoke_response( + response=response_list[0], model=model ) elif provider == "nova": - returned_response = ( - AmazonNovaEmbeddingConfig()._transform_async_invoke_response( - response=response_list[0], model=model - ) + returned_response = AmazonNovaEmbeddingConfig()._transform_async_invoke_response( + response=response_list[0], model=model ) else: # For other providers, create a generic async response @@ -213,28 +197,18 @@ def _transform_response( else: # Handle regular invoke responses if model == "amazon.titan-embed-image-v1": - returned_response = ( - AmazonTitanMultimodalEmbeddingG1Config()._transform_response( - response_list=response_list, model=model, batch_data=batch_data - ) + returned_response = AmazonTitanMultimodalEmbeddingG1Config()._transform_response( + response_list=response_list, model=model, batch_data=batch_data ) elif model == "amazon.titan-embed-text-v1": - returned_response = AmazonTitanG1Config()._transform_response( - response_list=response_list, model=model - ) + returned_response = AmazonTitanG1Config()._transform_response(response_list=response_list, model=model) elif model == "amazon.titan-embed-text-v2:0": - returned_response = AmazonTitanV2Config()._transform_response( - response_list=response_list, model=model - ) + returned_response = AmazonTitanV2Config()._transform_response(response_list=response_list, model=model) elif model == "amazon.titan-embed-g1-text-02": - returned_response = AmazonTitanG1Config()._transform_response( - response_list=response_list, model=model - ) + returned_response = AmazonTitanG1Config()._transform_response(response_list=response_list, model=model) elif provider == "twelvelabs": - returned_response = ( - TwelveLabsMarengoEmbeddingConfig()._transform_response( - response_list=response_list, model=model - ) + returned_response = TwelveLabsMarengoEmbeddingConfig()._transform_response( + response_list=response_list, model=model ) elif provider == "nova": returned_response = AmazonNovaEmbeddingConfig()._transform_response( @@ -245,11 +219,7 @@ def _transform_response( # Validate returned response ########################################################## if returned_response is None: - raise Exception( - "Unable to map model response to known provider format. model={}".format( - model - ) - ) + raise Exception("Unable to map model response to known provider format. model={}".format(model)) return returned_response def _single_func_embeddings( @@ -293,9 +263,7 @@ def _single_func_embeddings( "headers": prepped.headers, }, ) - headers_for_request = ( - dict(prepped.headers) if hasattr(prepped, "headers") else {} - ) + headers_for_request = dict(prepped.headers) if hasattr(prepped, "headers") else {} response = self._make_sync_call( client=client, timeout=timeout, @@ -365,9 +333,7 @@ async def _async_single_func_embeddings( ) # Convert CaseInsensitiveDict to regular dict for httpx compatibility # This ensures custom headers are properly forwarded, especially with IAM roles and custom api_base - headers_for_request = ( - dict(prepped.headers) if hasattr(prepped, "headers") else {} - ) + headers_for_request = dict(prepped.headers) if hasattr(prepped, "headers") else {} response = await self._make_async_call( client=client, timeout=timeout, @@ -414,9 +380,7 @@ def embeddings( credentials, aws_region_name = self._load_credentials(optional_params) ### TRANSFORMATION ### - unencoded_model_id = ( - optional_params.pop("model_id", None) or model - ) # default to model if not passed + unencoded_model_id = optional_params.pop("model_id", None) or model # default to model if not passed modelId = urllib.parse.quote(unencoded_model_id, safe="") aws_region_name = self._get_aws_region_name( optional_params={"aws_region_name": aws_region_name}, @@ -435,13 +399,9 @@ def embeddings( ) inference_params = copy.deepcopy(optional_params) inference_params = { - k: v - for k, v in inference_params.items() - if k.lower() not in self.aws_authentication_params + k: v for k, v in inference_params.items() if k.lower() not in self.aws_authentication_params } - inference_params.pop( - "user", None - ) # make sure user is not passed in for bedrock call + inference_params.pop("user", None) # make sure user is not passed in for bedrock call data: Optional[CohereEmbeddingRequest] = None batch_data: Optional[List] = None @@ -491,14 +451,12 @@ def embeddings( elif provider == "twelvelabs": batch_data = [] for i in input: - twelvelabs_request = ( - TwelveLabsMarengoEmbeddingConfig()._transform_request( - input=i, - inference_params=inference_params, - async_invoke_route=has_async_invoke, - model_id=modelId, - output_s3_uri=inference_params.get("output_s3_uri"), - ) + twelvelabs_request = TwelveLabsMarengoEmbeddingConfig()._transform_request( + input=i, + inference_params=inference_params, + async_invoke_route=has_async_invoke, + model_id=modelId, + output_s3_uri=inference_params.get("output_s3_uri"), ) batch_data.append(twelvelabs_request) elif provider == "nova": @@ -516,9 +474,7 @@ def embeddings( ### SET RUNTIME ENDPOINT ### endpoint_url, proxy_endpoint_url = self.get_runtime_endpoint( api_base=api_base, - aws_bedrock_runtime_endpoint=optional_params.pop( - "aws_bedrock_runtime_endpoint", None - ), + aws_bedrock_runtime_endpoint=optional_params.pop("aws_bedrock_runtime_endpoint", None), aws_region_name=aws_region_name, ) if has_async_invoke: @@ -529,11 +485,7 @@ def embeddings( if batch_data is not None: if aembedding: return self._async_single_func_embeddings( # type: ignore - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), timeout=timeout, batch_data=batch_data, credentials=credentials, @@ -547,11 +499,7 @@ def embeddings( is_async_invoke=has_async_invoke, ) returned_response = self._single_func_embeddings( - client=( - client - if client is not None and isinstance(client, HTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, HTTPHandler) else None), timeout=timeout, batch_data=batch_data, credentials=credentials, @@ -586,9 +534,7 @@ def embeddings( ## ROUTING ## # Convert CaseInsensitiveDict to regular dict for httpx compatibility - headers_for_request = ( - dict(prepped.headers) if hasattr(prepped, "headers") else {} - ) + headers_for_request = dict(prepped.headers) if hasattr(prepped, "headers") else {} return cohere_embedding( model=model, input=input, @@ -665,9 +611,7 @@ async def _get_async_invoke_status( if logging_obj is not None: # Create custom curl command for GET request masked_headers = logging_obj._get_masked_headers(prepped.headers) - formatted_headers = " ".join( - [f"-H '{k}: {v}'" for k, v in masked_headers.items()] - ) + formatted_headers = " ".join([f"-H '{k}: {v}'" for k, v in masked_headers.items()]) custom_curl = "\n\nGET Request Sent from LiteLLM:\n" custom_curl += "curl -X GET \\\n" custom_curl += f"{prepped.url} \\\n" @@ -697,15 +641,11 @@ async def _get_async_invoke_status( input=invocation_arn, api_key="", original_response=response, - additional_args={ - "complete_input_dict": {"invocation_arn": invocation_arn} - }, + additional_args={"complete_input_dict": {"invocation_arn": invocation_arn}}, ) # Parse response if response.status_code == 200: return response.json() else: - raise Exception( - f"Failed to get async invoke status: {response.status_code} - {response.text}" - ) + raise Exception(f"Failed to get async invoke status: {response.status_code} - {response.text}") diff --git a/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py b/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py index 56339ed2230d..56ac2c005606 100644 --- a/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py +++ b/litellm/llms/bedrock/embed/twelvelabs_marengo_transformation.py @@ -43,9 +43,7 @@ def get_supported_openai_params(self) -> List[str]: "input_type", ] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: for k, v in non_default_params.items(): if k == "encoding_format": # TwelveLabs doesn't have encoding_format, but we can map it to embeddingOption @@ -93,9 +91,7 @@ def _transform_request( # Get input_type or default to "text" input_type = cast( TWELVELABS_EMBEDDING_INPUT_TYPES, - inference_params.get("inputType") - or inference_params.get("input_type") - or "text", + inference_params.get("inputType") or inference_params.get("input_type") or "text", ) # Validate that async-invoke is used for video/audio @@ -105,9 +101,7 @@ def _transform_request( f"Use model format: 'bedrock/async_invoke/model_id'" ) - transformed_request: TwelveLabsMarengoEmbeddingRequest = { - "inputType": input_type - } + transformed_request: TwelveLabsMarengoEmbeddingRequest = {"inputType": input_type} if input_type == "text": transformed_request["inputText"] = input @@ -194,9 +188,7 @@ def _wrap_async_invoke_request( ), ) - def _transform_response( - self, response_list: List[dict], model: str - ) -> EmbeddingResponse: + def _transform_response(self, response_list: List[dict], model: str) -> EmbeddingResponse: """ Transform TwelveLabs response to OpenAI format. Handles the actual TwelveLabs response format: {"data": [{"embedding": [...]}]} @@ -253,9 +245,7 @@ def _transform_response( return EmbeddingResponse(data=embeddings, model=model, usage=usage) - def _transform_async_invoke_response( - self, response: dict, model: str - ) -> EmbeddingResponse: + def _transform_async_invoke_response(self, response: dict, model: str) -> EmbeddingResponse: """ Transform async invoke response (invocation ARN) to OpenAI format. diff --git a/litellm/llms/bedrock/files/handler.py b/litellm/llms/bedrock/files/handler.py index b6aae2159c1f..8c6282d627e8 100644 --- a/litellm/llms/bedrock/files/handler.py +++ b/litellm/llms/bedrock/files/handler.py @@ -61,9 +61,7 @@ def _parse_s3_uri( allow_legacy_cloud_file_ids=allow_legacy_cloud_file_ids, ) - def _get_configured_s3_bucket_name( - self, litellm_params: Mapping[str, object] - ) -> str: + def _get_configured_s3_bucket_name(self, litellm_params: Mapping[str, object]) -> str: from .transformation import get_configured_s3_bucket_name return get_configured_s3_bucket_name(litellm_params) @@ -100,15 +98,11 @@ async def afile_content( bucket_name, object_key = self._parse_s3_uri( s3_uri=s3_uri, configured_bucket_name=configured_bucket_name, - allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids( - optional_params - ), + allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(optional_params), ) # Get AWS credentials - aws_region_name = self._get_aws_region_name( - optional_params=optional_params, model="" - ) + aws_region_name = self._get_aws_region_name(optional_params=optional_params, model="") credentials: Credentials = self.get_credentials( aws_access_key_id=optional_params.get("aws_access_key_id"), aws_secret_access_key=optional_params.get("aws_secret_access_key"), @@ -136,9 +130,7 @@ async def afile_content( response = s3_client.get_object(Bucket=bucket_name, Key=object_key) file_content = response["Body"].read() except Exception as e: - raise ValueError( - f"Failed to download file from S3: {s3_uri}. Error: {str(e)}" - ) + raise ValueError(f"Failed to download file from S3: {s3_uri}. Error: {str(e)}") # Create mock HTTP response mock_response = httpx.Response( @@ -158,9 +150,7 @@ def file_content( optional_params: dict, timeout: Union[float, httpx.Timeout], max_retries: Optional[int], - ) -> Union[ - HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent] - ]: + ) -> Union[HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent]]: """ Download file content from S3 bucket for Bedrock files. Supports both sync and async operations. diff --git a/litellm/llms/bedrock/files/transformation.py b/litellm/llms/bedrock/files/transformation.py index 6cfaa88275d2..d4865a1c87a1 100644 --- a/litellm/llms/bedrock/files/transformation.py +++ b/litellm/llms/bedrock/files/transformation.py @@ -119,9 +119,7 @@ def get_configured_s3_bucket_name(litellm_params: Mapping[str, object]) -> str: environment; never a request-supplied param, since the bucket is what `validate_managed_cloud_file_id` checks file ids against. """ - trusted_model_credentials = litellm_params.get( - "_litellm_internal_model_credentials" - ) + trusted_model_credentials = litellm_params.get("_litellm_internal_model_credentials") bucket_name: str | None = None if isinstance(trusted_model_credentials, MappingProxyType): snapshot: dict[str, object] = {} @@ -224,18 +222,12 @@ def _get_s3_object_name_from_batch_jsonl( if _model.startswith("bedrock/"): _model = _model[8:] - safe_model = sanitize_cloud_object_component( - _model.replace(":", "-"), fallback="model" - ) + safe_model = sanitize_cloud_object_component(_model.replace(":", "-"), fallback="model") - object_name = ( - f"{BEDROCK_MANAGED_S3_BATCH_PREFIX}{safe_model}-{uuid.uuid4()}.jsonl" - ) + object_name = f"{BEDROCK_MANAGED_S3_BATCH_PREFIX}{safe_model}-{uuid.uuid4()}.jsonl" return object_name - def get_object_name( - self, extracted_file_data: ExtractedFileData, purpose: str - ) -> str: + def get_object_name(self, extracted_file_data: ExtractedFileData, purpose: str) -> str: """ Get the object name for the request """ @@ -246,14 +238,10 @@ def get_object_name( if purpose == "batch": ## 1. If jsonl, check if there's a model name - file_content = self._get_content_from_openai_file( - extracted_file_data_content - ) + file_content = self._get_content_from_openai_file(extracted_file_data_content) # Split into lines and parse each line as JSON - openai_jsonl_content = [ - json.loads(line) for line in file_content.splitlines() if line.strip() - ] + openai_jsonl_content = [json.loads(line) for line in file_content.splitlines() if line.strip()] if len(openai_jsonl_content) > 0: return self._get_s3_object_name_from_batch_jsonl(openai_jsonl_content) @@ -277,21 +265,15 @@ def get_complete_file_url( """ Get the complete S3 URL for the file upload request """ - bucket_name = litellm_params.get("s3_bucket_name") or os.getenv( - "AWS_S3_BUCKET_NAME" - ) + bucket_name = litellm_params.get("s3_bucket_name") or os.getenv("AWS_S3_BUCKET_NAME") if not bucket_name: raise ValueError( "S3 bucket_name is required. Set 's3_bucket_name' in litellm_params or AWS_S3_BUCKET_NAME env var" ) bucket_name, object_prefix = split_configured_cloud_bucket_name(bucket_name) - s3_region_name = litellm_params.get("s3_region_name") or optional_params.get( - "s3_region_name" - ) - aws_region_name = s3_region_name or self._get_aws_region_name( - optional_params, model - ) + s3_region_name = litellm_params.get("s3_region_name") or optional_params.get("s3_region_name") + aws_region_name = s3_region_name or self._get_aws_region_name(optional_params, model) file_data = data.get("file") purpose = data.get("purpose") @@ -307,15 +289,12 @@ def get_complete_file_url( # S3 endpoint URL format s3_endpoint_url = ( - optional_params.get("s3_endpoint_url") - or f"https://s3.{aws_region_name}.amazonaws.com" + optional_params.get("s3_endpoint_url") or f"https://s3.{aws_region_name}.amazonaws.com" ).rstrip("/") return f"{s3_endpoint_url}/{bucket_name}/{encoded_object_name}" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAICreateFileRequestOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAICreateFileRequestOptionalParams]: return [] def map_openai_params( @@ -489,10 +468,7 @@ def _coerce_embedding_input_to_string(raw_input: Any, model: str = "") -> str: without duplicating the type-shaping logic. """ if raw_input is None: - raise ValueError( - "Embedding batch record is missing required `input` field: " - f"model={model}" - ) + raise ValueError(f"Embedding batch record is missing required `input` field: model={model}") # Bedrock InvokeModel for Titan v2 takes exactly one string `inputText` # per call. Pre-tokenized inputs and multi-element string lists are @@ -564,26 +540,18 @@ def _map_openai_embedding_to_bedrock_params( "embedding models in https://github.com/BerriAI/litellm/issues." ) - input_text = self._coerce_embedding_input_to_string( - openai_request_body.get("input"), model=_model - ) + input_text = self._coerce_embedding_input_to_string(openai_request_body.get("input"), model=_model) # Map OpenAI-style params (dimensions, encoding_format) onto the # Titan v2 schema (dimensions, embeddingTypes) via the embed config # so this stays in sync with the synchronous /v1/embeddings path. - non_default_params = { - k: v for k, v in openai_request_body.items() if k not in ("model", "input") - } + non_default_params = {k: v for k, v in openai_request_body.items() if k not in ("model", "input")} titan_config = AmazonTitanV2Config() inference_params = titan_config.map_openai_params( non_default_params=non_default_params, optional_params={}, ) - return dict( - titan_config._transform_request( - input=input_text, inference_params=inference_params - ) - ) + return dict(titan_config._transform_request(input=input_text, inference_params=inference_params)) def _map_openai_to_bedrock_params( self, @@ -602,11 +570,7 @@ def _map_openai_to_bedrock_params( _model = openai_request_body.get("model", "") messages = openai_request_body.get("messages", []) - optional_params = { - k: v - for k, v in openai_request_body.items() - if k not in ["model", "messages"] - } + optional_params = {k: v for k, v in openai_request_body.items() if k not in ["model", "messages"]} # --- Anthropic: use existing AmazonAnthropicClaudeConfig --- if provider == LlmProviders.ANTHROPIC: @@ -707,18 +671,12 @@ def _transform_openai_jsonl_content_to_bedrock_jsonl_content( # `_map_openai_to_bedrock_params`) so the chat helper keeps its # narrow contract and the embedding helper can evolve independently. if self._is_embedding_record(_openai_jsonl_content): - model_input = self._map_openai_embedding_to_bedrock_params( - openai_request_body=openai_body - ) + model_input = self._map_openai_embedding_to_bedrock_params(openai_request_body=openai_body) else: - model_input = self._map_openai_to_bedrock_params( - openai_request_body=openai_body, provider=provider - ) + model_input = self._map_openai_to_bedrock_params(openai_request_body=openai_body, provider=provider) # Create Bedrock batch record - record_id = _openai_jsonl_content.get( - "custom_id", f"CALL{str(idx).zfill(7)}" - ) + record_id = _openai_jsonl_content.get("custom_id", f"CALL{str(idx).zfill(7)}") bedrock_record = {"recordId": record_id, "modelInput": model_input} bedrock_jsonl_content.append(bedrock_record) @@ -750,19 +708,9 @@ def transform_create_file_request( extracted_file_data=extracted_file_data, ): ## Transform JSONL content to Bedrock format - original_file_content = self._get_content_from_openai_file( - extracted_file_data_content - ) - openai_jsonl_content = [ - json.loads(line) - for line in original_file_content.splitlines() - if line.strip() - ] - bedrock_jsonl_content = ( - self._transform_openai_jsonl_content_to_bedrock_jsonl_content( - openai_jsonl_content - ) - ) + original_file_content = self._get_content_from_openai_file(extracted_file_data_content) + openai_jsonl_content = [json.loads(line) for line in original_file_content.splitlines() if line.strip()] + bedrock_jsonl_content = self._transform_openai_jsonl_content_to_bedrock_jsonl_content(openai_jsonl_content) file_content = "\n".join(json.dumps(item) for item in bedrock_jsonl_content) elif isinstance(extracted_file_data_content, bytes): file_content = extracted_file_data_content.decode("utf-8") @@ -784,9 +732,7 @@ def transform_create_file_request( # s3_region_name always wins for S3 operations (same priority as in # get_complete_file_url above). Overwrite aws_region_name unconditionally # so the SigV4 region matches the URL region, avoiding SignatureDoesNotMatch. - s3_region_name = litellm_params.get("s3_region_name") or optional_params.get( - "s3_region_name" - ) + s3_region_name = litellm_params.get("s3_region_name") or optional_params.get("s3_region_name") if s3_region_name: optional_params = {**optional_params, "aws_region_name": s3_region_name} @@ -827,9 +773,7 @@ def _sign_s3_request( raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") # Get AWS credentials using existing methods - aws_region_name = self._get_aws_region_name( - optional_params=optional_params, model="" - ) + aws_region_name = self._get_aws_region_name(optional_params=optional_params, model="") credentials = self.get_credentials( aws_access_key_id=optional_params.get("aws_access_key_id"), aws_secret_access_key=optional_params.get("aws_secret_access_key"), @@ -866,9 +810,7 @@ def _sign_s3_request( ) # Get region name for non-LLM API calls (same as s3_v2.py) - signing_region = self.get_aws_region_name_for_non_llm_api_calls( - aws_region_name=aws_region_name - ) + signing_region = self.get_aws_region_name_for_non_llm_api_calls(aws_region_name=aws_region_name) SigV4Auth(credentials, "s3", signing_region).add_auth(aws_request) @@ -969,12 +911,8 @@ def transform_create_file_response( object="file", ) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[Dict, Headers] - ) -> BaseLLMException: - return BedrockError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[Dict, Headers]) -> BaseLLMException: + return BedrockError(status_code=status_code, message=error_message, headers=headers) def transform_retrieve_file_request( self, @@ -1047,9 +985,7 @@ def transform_file_content_request( scheme="s3://", configured_bucket_name=get_configured_s3_bucket_name(litellm_params), allowed_object_prefixes=BEDROCK_MANAGED_S3_PREFIXES, - allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids( - litellm_params - ), + allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(litellm_params), ) # The shared file-content handler passes optional_params={}, so AWS @@ -1061,18 +997,11 @@ def transform_file_content_request( merged_params.update(optional_params) request_params = _BedrockS3RequestParams.model_validate(merged_params) - region_preference = ( - request_params.s3_region_name or request_params.aws_region_name - ) + region_preference = request_params.s3_region_name or request_params.aws_region_name region_params: dict[str, str | None] = {"aws_region_name": region_preference} - aws_region_name = self._get_aws_region_name( - optional_params=region_params, model="" - ) + aws_region_name = self._get_aws_region_name(optional_params=region_params, model="") - s3_endpoint_url = ( - request_params.s3_endpoint_url - or f"https://s3.{aws_region_name}.amazonaws.com" - ).rstrip("/") + s3_endpoint_url = (request_params.s3_endpoint_url or f"https://s3.{aws_region_name}.amazonaws.com").rstrip("/") url = f"{s3_endpoint_url}/{bucket_name}/{encode_s3_object_key_for_url(object_key)}" litellm_params[S3_SIGNED_GET_HEADERS_PARAM] = self._sign_s3_get_request( @@ -1154,32 +1083,18 @@ def transform_openai_file_content_to_bedrock_file_content( file_content = self._get_content_from_openai_file(openai_file_content) # Split into lines and parse each line as JSON - openai_jsonl_content = [ - json.loads(line) for line in file_content.splitlines() if line.strip() - ] - bedrock_jsonl_content = ( - self._transform_openai_jsonl_content_to_bedrock_jsonl_content( - openai_jsonl_content - ) - ) - bedrock_jsonl_string = "\n".join( - json.dumps(item) for item in bedrock_jsonl_content - ) - object_name = self._get_s3_object_name( - openai_jsonl_content=openai_jsonl_content - ) + openai_jsonl_content = [json.loads(line) for line in file_content.splitlines() if line.strip()] + bedrock_jsonl_content = self._transform_openai_jsonl_content_to_bedrock_jsonl_content(openai_jsonl_content) + bedrock_jsonl_string = "\n".join(json.dumps(item) for item in bedrock_jsonl_content) + object_name = self._get_s3_object_name(openai_jsonl_content=openai_jsonl_content) return bedrock_jsonl_string, object_name - def _transform_openai_jsonl_content_to_bedrock_jsonl_content( - self, openai_jsonl_content: List[Dict[str, Any]] - ): + def _transform_openai_jsonl_content_to_bedrock_jsonl_content(self, openai_jsonl_content: List[Dict[str, Any]]): """ Delegate to the main BedrockFilesConfig transformation method """ config = BedrockFilesConfig() - return config._transform_openai_jsonl_content_to_bedrock_jsonl_content( - openai_jsonl_content - ) + return config._transform_openai_jsonl_content_to_bedrock_jsonl_content(openai_jsonl_content) def _get_s3_object_name( self, @@ -1194,12 +1109,8 @@ def _get_s3_object_name( # Remove bedrock/ prefix if present if _model.startswith("bedrock/"): _model = _model[8:] - safe_model = sanitize_cloud_object_component( - _model.replace(":", "-"), fallback="model" - ) - object_name = ( - f"{BEDROCK_MANAGED_S3_BATCH_PREFIX}{safe_model}-{uuid.uuid4()}.jsonl" - ) + safe_model = sanitize_cloud_object_component(_model.replace(":", "-"), fallback="model") + object_name = f"{BEDROCK_MANAGED_S3_BATCH_PREFIX}{safe_model}-{uuid.uuid4()}.jsonl" return object_name def _get_content_from_openai_file(self, openai_file_content: FileTypes) -> str: diff --git a/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py b/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py index 836a3c606ee8..1008924ab0e0 100644 --- a/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py +++ b/litellm/llms/bedrock/image_edit/amazon_nova_canvas_image_edit_transformation.py @@ -315,13 +315,7 @@ def transform_image_edit_request( _size = op.pop("size", None) width = op.pop("width", None) height = op.pop("height", None) - if ( - width is None - and height is None - and _size is not None - and isinstance(_size, str) - and "x" in _size - ): + if width is None and height is None and _size is not None and isinstance(_size, str) and "x" in _size: w, h = _size.split("x", 1) try: width, height = int(w), int(h) @@ -356,8 +350,7 @@ def transform_image_edit_request( "OUTPAINTING", ): raise ValueError( - f"Amazon Nova Canvas {task_type} requires a text prompt. " - "Pass a non-empty `prompt` in your request." + f"Amazon Nova Canvas {task_type} requires a text prompt. Pass a non-empty `prompt` in your request." ) text = prompt if prompt is not None and prompt != "" else " " negative_text = op.pop("negativeText", None) @@ -455,9 +448,9 @@ def transform_image_edit_response( model_info = get_model_info(model, custom_llm_provider="bedrock") cost_per_image = model_info.get("output_cost_per_image", 0) if cost_per_image is not None and model_response.data: - model_response._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = float(cost_per_image) * len(model_response.data) + model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float( + cost_per_image + ) * len(model_response.data) except Exception: pass diff --git a/litellm/llms/bedrock/image_edit/handler.py b/litellm/llms/bedrock/image_edit/handler.py index 04fa5f803bb1..01a40c0e4759 100644 --- a/litellm/llms/bedrock/image_edit/handler.py +++ b/litellm/llms/bedrock/image_edit/handler.py @@ -58,9 +58,7 @@ class BedrockImageEdit(BaseAWSLLM): def get_config_class(cls, model: str | None): if BedrockStabilityImageEditConfig._is_stability_edit_model(model): return BedrockStabilityImageEditConfig - if BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model( - model - ): + if BedrockAmazonNovaCanvasImageEditConfig._is_nova_canvas_image_edit_model(model): return BedrockAmazonNovaCanvasImageEditConfig raise ValueError( f"Unsupported Bedrock image-edit model: {model!r}. " @@ -102,11 +100,7 @@ def image_edit( logging_obj=logging_obj, prompt=prompt, model_response=model_response, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), ) if client is None or not isinstance(client, HTTPHandler): @@ -204,9 +198,7 @@ def _prepare_request( Returns: BedrockImageEditPreparedRequest: The prepared request object """ - boto3_credentials_info = self._get_boto_credentials_from_optional_params( - optional_params, model - ) + boto3_credentials_info = self._get_boto_credentials_from_optional_params(optional_params, model) # Use the existing ARN-aware provider detection method bedrock_provider = self.get_bedrock_invoke_provider(model) diff --git a/litellm/llms/bedrock/image_edit/stability_transformation.py b/litellm/llms/bedrock/image_edit/stability_transformation.py index e76b2885a885..0b45aba219f3 100644 --- a/litellm/llms/bedrock/image_edit/stability_transformation.py +++ b/litellm/llms/bedrock/image_edit/stability_transformation.py @@ -122,9 +122,7 @@ def map_openai_params( if k in param_mapping: # Map param if mapping exists and value is valid if k == "size" and v in OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO: - mapped_params[param_mapping[k]] = ( - OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] - ) # type: ignore + mapped_params[param_mapping[k]] = OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] # type: ignore # Don't copy "size" itself to final dict elif k == "n": # Store for logic but do not add to outgoing params @@ -211,9 +209,7 @@ def transform_image_edit_request( if isinstance(value, list) and len(value) > 0: file_value = value[0] - if hasattr(file_value, "read") and callable( - getattr(file_value, "read", None) - ): + if hasattr(file_value, "read") and callable(getattr(file_value, "read", None)): file_bytes = file_value.read() # type: ignore elif isinstance(file_value, bytes): file_bytes = file_value @@ -338,9 +334,9 @@ def transform_image_edit_response( model_info = get_model_info(model, custom_llm_provider="bedrock") cost_per_image = model_info.get("output_cost_per_image", 0) if cost_per_image is not None: - model_response._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = float(cost_per_image) + model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float( + cost_per_image + ) return model_response diff --git a/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py b/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py index 9e06a8e747d3..626baf707a5f 100644 --- a/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_nova_canvas_transformation.py @@ -60,9 +60,7 @@ def _is_nova_model(cls, model: Optional[str] = None) -> bool: return False @classmethod - def transform_request_body( - cls, text: str, optional_params: dict - ) -> AmazonNovaCanvasRequestBase: + def transform_request_body(cls, text: str, optional_params: dict) -> AmazonNovaCanvasRequestBase: """ Transform the request body for Amazon Nova Canvas model """ @@ -75,9 +73,7 @@ def transform_request_body( image_generation_config = {**image_generation_config, **optional_params} if task_type == "TEXT_IMAGE": - text_to_image_params: Dict[str, Any] = image_generation_config.pop( - "textToImageParams", {} - ) + text_to_image_params: Dict[str, Any] = image_generation_config.pop("textToImageParams", {}) text_to_image_params = {"text": text, **text_to_image_params} try: text_to_image_params_typed = AmazonNovaCanvasTextToImageParams( @@ -89,9 +85,7 @@ def transform_request_body( ) try: - image_generation_config_typed = AmazonNovaCanvasImageGenerationConfig( - **image_generation_config - ) + image_generation_config_typed = AmazonNovaCanvasImageGenerationConfig(**image_generation_config) except Exception as e: raise ValueError( f"Error transforming image generation config: {e}. Got params: {image_generation_config}, Expected params: {AmazonNovaCanvasImageGenerationConfig.__annotations__}" @@ -103,18 +97,16 @@ def transform_request_body( imageGenerationConfig=image_generation_config_typed, ) if task_type == "COLOR_GUIDED_GENERATION": - color_guided_generation_params: Dict[str, Any] = ( - image_generation_config.pop("colorGuidedGenerationParams", {}) + color_guided_generation_params: Dict[str, Any] = image_generation_config.pop( + "colorGuidedGenerationParams", {} ) color_guided_generation_params = { "text": text, **color_guided_generation_params, } try: - color_guided_generation_params_typed = ( - AmazonNovaCanvasColorGuidedGenerationParams( - **color_guided_generation_params # type: ignore - ) + color_guided_generation_params_typed = AmazonNovaCanvasColorGuidedGenerationParams( + **color_guided_generation_params # type: ignore ) except Exception as e: raise ValueError( @@ -122,9 +114,7 @@ def transform_request_body( ) try: - image_generation_config_typed = AmazonNovaCanvasImageGenerationConfig( - **image_generation_config - ) + image_generation_config_typed = AmazonNovaCanvasImageGenerationConfig(**image_generation_config) except Exception as e: raise ValueError( f"Error transforming image generation config: {e}. Got params: {image_generation_config}, Expected params: {AmazonNovaCanvasImageGenerationConfig.__annotations__}" @@ -136,9 +126,7 @@ def transform_request_body( imageGenerationConfig=image_generation_config_typed, ) if task_type == "INPAINTING": - inpainting_params: Dict[str, Any] = image_generation_config.pop( - "inpaintingParams", {} - ) + inpainting_params: Dict[str, Any] = image_generation_config.pop("inpaintingParams", {}) inpainting_params = {"text": text, **inpainting_params} try: inpainting_params_typed = AmazonNovaCanvasInpaintingParams( @@ -150,9 +138,7 @@ def transform_request_body( ) try: - image_generation_config_typed = AmazonNovaCanvasImageGenerationConfig( - **image_generation_config - ) + image_generation_config_typed = AmazonNovaCanvasImageGenerationConfig(**image_generation_config) except Exception as e: raise ValueError( f"Error transforming image generation config: {e}. Got params: {image_generation_config}, Expected params: {AmazonNovaCanvasImageGenerationConfig.__annotations__}" diff --git a/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py b/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py index 1d88aaf35f75..0e8214fd81f1 100644 --- a/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_stability1_transformation.py @@ -100,9 +100,7 @@ def transform_request_body( optional_params: dict, ) -> dict: inference_params = copy.deepcopy(optional_params) - inference_params.pop( - "user", None - ) # make sure user is not passed in for bedrock call + inference_params.pop("user", None) # make sure user is not passed in for bedrock call prompt = text.replace(os.linesep, " ") ## LOAD CONFIG diff --git a/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py b/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py index 8aff24fe9a7a..a54496799418 100644 --- a/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_stability3_transformation.py @@ -67,9 +67,7 @@ def _is_stability_3_model(cls, model: Optional[str] = None) -> bool: return False @classmethod - def transform_request_body( - cls, text: str, optional_params: dict - ) -> AmazonStability3TextToImageRequest: + def transform_request_body(cls, text: str, optional_params: dict) -> AmazonStability3TextToImageRequest: """ Transform the request body for the Stability 3 models """ diff --git a/litellm/llms/bedrock/image_generation/amazon_titan_transformation.py b/litellm/llms/bedrock/image_generation/amazon_titan_transformation.py index 65411cabdcf1..5a975b6ab11a 100644 --- a/litellm/llms/bedrock/image_generation/amazon_titan_transformation.py +++ b/litellm/llms/bedrock/image_generation/amazon_titan_transformation.py @@ -90,9 +90,7 @@ def map_openai_params( image_generation_config["height"] = int(height) elif k == "n" and v is not None: image_generation_config["numberOfImages"] = v - elif ( - k == "quality" and v is not None - ): # 'auto', 'hd', 'standard', 'high', 'medium', 'low' + elif k == "quality" and v is not None: # 'auto', 'hd', 'standard', 'high', 'medium', 'low' if v in ("hd", "premium", "high"): image_generation_config["quality"] = "premium" elif v in ("standard", "medium", "low"): @@ -116,9 +114,7 @@ def transform_request_body( if negative_text: text_to_image_params["negativeText"] = negative_text task_type = optional_params.pop("taskType", "TEXT_IMAGE") - user_specified_image_generation_config = optional_params.pop( - "imageGenerationConfig", {} - ) + user_specified_image_generation_config = optional_params.pop("imageGenerationConfig", {}) image_generation_config = { **image_generation_config, **user_specified_image_generation_config, @@ -126,9 +122,7 @@ def transform_request_body( return AmazonTitanImageGenerationRequestBody( taskType=task_type, textToImageParams=AmazonTitanTextToImageParams(**text_to_image_params), # type: ignore - imageGenerationConfig=AmazonNovaCanvasImageGenerationConfig( - **image_generation_config - ), + imageGenerationConfig=AmazonNovaCanvasImageGenerationConfig(**image_generation_config), ) @classmethod diff --git a/litellm/llms/bedrock/image_generation/image_handler.py b/litellm/llms/bedrock/image_generation/image_handler.py index 0c594d0b1422..03e40565d950 100644 --- a/litellm/llms/bedrock/image_generation/image_handler.py +++ b/litellm/llms/bedrock/image_generation/image_handler.py @@ -105,11 +105,7 @@ def image_generation( logging_obj=logging_obj, prompt=prompt, model_response=model_response, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), ) if client is None or not isinstance(client, HTTPHandler): @@ -224,9 +220,7 @@ def _prepare_request( prepped (httpx.Request): The prepared request object body (bytes): The request body """ - boto3_credentials_info = self._get_boto_credentials_from_optional_params( - optional_params, model - ) + boto3_credentials_info = self._get_boto_credentials_from_optional_params(optional_params, model) # Use the existing ARN-aware provider detection method bedrock_provider = self.get_bedrock_invoke_provider(model) @@ -300,9 +294,7 @@ def _get_request_body( dict: The request body to use for the Bedrock Image Generation API """ config_class = self.get_config_class(model=model) - request_body = config_class.transform_request_body( - text=prompt, optional_params=optional_params - ) + request_body = config_class.transform_request_body(text=prompt, optional_params=optional_params) return dict(request_body) def _transform_response_dict_to_openai_response( diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py index 42c3bd517a91..f5309d521a95 100644 --- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py +++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py @@ -14,7 +14,12 @@ import litellm from litellm.anthropic_beta_headers_manager import filter_and_transform_beta_headers -from litellm.constants import BEDROCK_MIN_THINKING_BUDGET_TOKENS +from litellm.constants import ( + BEDROCK_MIN_THINKING_BUDGET_TOKENS, + DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET, + DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET, + DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET, +) from litellm.litellm_core_utils.litellm_logging import verbose_logger from litellm.llms.anthropic.chat.transformation import ( DROP_UNSUPPORTED_OUTPUT_CONFIG_WARNING, @@ -72,14 +77,51 @@ class AmazonAnthropicClaudeMessagesConfig( DEFAULT_BEDROCK_ANTHROPIC_API_VERSION = "bedrock-2023-05-31" - BEDROCK_INVOKE_ALLOWED_TOP_LEVEL_FIELDS = frozenset( - BedrockInvokeAnthropicMessagesRequest.__annotations__.keys() - ) + BEDROCK_INVOKE_ALLOWED_TOP_LEVEL_FIELDS = frozenset(BedrockInvokeAnthropicMessagesRequest.__annotations__.keys()) def __init__(self, **kwargs): BaseAnthropicMessagesConfig.__init__(self, **kwargs) AmazonInvokeConfig.__init__(self, **kwargs) + @staticmethod + def _as_system_content_blocks(value: Any) -> list[Any]: + if value is None: + return [] + if isinstance(value, list): + return list(value) + if isinstance(value, str): + return [{"type": "text", "text": value}] + return [value] + + def _normalize_system_role_messages_for_bedrock(self, anthropic_messages_request: dict) -> None: + """Bedrock Invoke rejects ``role: "system"`` entries inside ``messages`` on + some Claude aliases; Anthropic Messages carries that content in the + top-level ``system`` field. Move any such entries into ``system`` before + the Invoke request is built.""" + messages = anthropic_messages_request.get("messages") + if not isinstance(messages, list): + return + system_role_messages = [m for m in messages if isinstance(m, dict) and m.get("role") == "system"] + if not system_role_messages: + return + + anthropic_messages_request["messages"] = [ + m for m in messages if not (isinstance(m, dict) and m.get("role") == "system") + ] + system_content = [ + block + for source in ( + anthropic_messages_request.get("system"), + *(m.get("content") for m in system_role_messages), + ) + for block in self._as_system_content_blocks(source) + ] + filtered_system = self._filter_billing_headers_from_system(system_content) + if filtered_system: + anthropic_messages_request["system"] = filtered_system + else: + anthropic_messages_request.pop("system", None) + def validate_anthropic_messages_environment( self, headers: dict, @@ -134,9 +176,7 @@ def get_complete_url( stream=stream, ) - def _remove_ttl_from_cache_control( - self, anthropic_messages_request: Dict, model: Optional[str] = None - ) -> None: + def _remove_ttl_from_cache_control(self, anthropic_messages_request: Dict, model: Optional[str] = None) -> None: """ Remove unsupported fields from cache_control for Bedrock. @@ -195,8 +235,9 @@ def _supports_extended_thinking_on_bedrock(self, model: str) -> bool: """ Check if the model supports extended thinking beta headers on Bedrock. - On 3rd-party platforms (e.g., Amazon Bedrock), extended thinking is only - supported on: Claude Opus 4.5, Claude Opus 4.1, Opus 4, or Sonnet 4. + On 3rd-party platforms (e.g., Amazon Bedrock), extended thinking is supported + on the adaptive-thinking models (sourced from the cost map) plus the legacy + non-adaptive set: Claude Opus 4.5, Claude Opus 4.1, Opus 4, or Sonnet 4. Ref: https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking @@ -206,10 +247,11 @@ def _supports_extended_thinking_on_bedrock(self, model: str) -> bool: Returns: True if the model supports extended thinking on Bedrock """ - model_lower = model.lower() + if AnthropicModelInfo._is_adaptive_thinking_model(model): + return True - # Supported models on Bedrock for extended thinking - supported_patterns = [ + model_lower = model.lower() + non_adaptive_patterns = [ "opus-4.5", "opus_4.5", "opus-4-5", @@ -222,21 +264,9 @@ def _supports_extended_thinking_on_bedrock(self, model: str) -> bool: "opus_4", # Opus 4 "sonnet-4", "sonnet_4", # Sonnet 4 - "sonnet-4.6", - "sonnet_4.6", - "sonnet-4-6", - "sonnet_4_6", - "opus-4.6", - "opus_4.6", - "opus-4-6", - "opus_4_6", - "opus-4.7", - "opus_4.7", - "opus-4-7", - "opus_4_7", ] - return any(pattern in model_lower for pattern in supported_patterns) + return any(pattern in model_lower for pattern in non_adaptive_patterns) def _ensure_thinking_for_clear_thinking_context_management( self, @@ -261,23 +291,27 @@ def _ensure_thinking_for_clear_thinking_context_management( edits = cm.get("edits") if not isinstance(edits, list): return False - needs_thinking = any( - isinstance(e, dict) and e.get("type") == "clear_thinking_20251015" - for e in edits - ) + needs_thinking = any(isinstance(e, dict) and e.get("type") == "clear_thinking_20251015" for e in edits) if not needs_thinking: return False if not self._supports_extended_thinking_on_bedrock(model): return False + is_adaptive_thinking_model = AnthropicModelInfo._is_adaptive_thinking_model(model) + thinking = anthropic_messages_request.get("thinking") if isinstance(thinking, dict): t = thinking.get("type") - if t in ("enabled", "adaptive"): + if t == "adaptive": + return False + if t == "enabled" and not is_adaptive_thinking_model: return False - # ``disabled`` or unknown — replace with enabled so clear_thinking is valid + if t == "enabled": + budget_tokens = self._resolve_clear_thinking_budget_tokens(thinking.get("budget_tokens")) + self._inject_adaptive_thinking_for_clear_thinking(anthropic_messages_request, budget_tokens, model) + return True verbose_logger.debug( - "Bedrock clear_thinking_20251015: replacing thinking=%s with minimal enabled thinking", + "Bedrock clear_thinking_20251015: replacing thinking=%s with minimal thinking config", thinking, ) @@ -292,6 +326,10 @@ def _ensure_thinking_for_clear_thinking_context_management( ) return False + if is_adaptive_thinking_model: + self._inject_adaptive_thinking_for_clear_thinking(anthropic_messages_request, budget, model) + return True + anthropic_messages_request["thinking"] = { "type": "enabled", "budget_tokens": budget, @@ -302,6 +340,44 @@ def _ensure_thinking_for_clear_thinking_context_management( ) return True + @staticmethod + def _resolve_clear_thinking_budget_tokens(budget_tokens: int | None) -> int: + """Honor an explicit ``budget_tokens`` (including ``0``); only fall back to + the Bedrock minimum when the caller omitted it. A truthiness check would + wrongly treat an explicit ``0`` as missing.""" + if budget_tokens is None: + return BEDROCK_MIN_THINKING_BUDGET_TOKENS + return int(budget_tokens) + + @staticmethod + def _effort_from_thinking_budget(budget_tokens: int) -> str: + if budget_tokens >= DEFAULT_REASONING_EFFORT_XHIGH_THINKING_BUDGET: + return "xhigh" + if budget_tokens >= DEFAULT_REASONING_EFFORT_HIGH_THINKING_BUDGET: + return "high" + if budget_tokens >= DEFAULT_REASONING_EFFORT_MEDIUM_THINKING_BUDGET: + return "medium" + return "low" + + def _inject_adaptive_thinking_for_clear_thinking( + self, anthropic_messages_request: dict, budget_tokens: int, model: str + ) -> None: + """Adaptive-thinking models (Opus 4.7/4.8, Fable 5) reject + ``thinking.type=enabled`` on Bedrock. Use ``thinking.type=adaptive`` plus + an ``output_config.effort`` derived from the budget so ``clear_thinking`` + stays valid without the legacy shape.""" + output_config = anthropic_messages_request.get("output_config") + if not isinstance(output_config, dict): + output_config = {} + output_config.setdefault("effort", self._effort_from_thinking_budget(budget_tokens)) + anthropic_messages_request["output_config"] = output_config + anthropic_messages_request["thinking"] = {"type": "adaptive"} + verbose_logger.debug( + "Bedrock clear_thinking_20251015: injected adaptive thinking with effort=%s for model=%s", + output_config.get("effort"), + model, + ) + def _is_claude_opus_4_5(self, model: str) -> bool: """ Check if the model is Claude Opus 4.5. @@ -408,9 +484,7 @@ def _get_tool_search_beta_header_for_bedrock( input_examples_used: Whether input examples are used beta_set: The set of beta headers to modify in-place """ - if tool_search_used and not ( - programmatic_tool_calling_used or input_examples_used - ): + if tool_search_used and not (programmatic_tool_calling_used or input_examples_used): beta_set.discard(ANTHROPIC_TOOL_SEARCH_BETA_HEADER) if self._supports_tool_search_on_bedrock(model): beta_set.add("tool-search-tool-2025-10-19") @@ -442,11 +516,7 @@ def _filter_context_management_for_bedrock_invoke( anthropic_messages_request.pop("context_management", None) return - compact_edits = [ - e - for e in edits - if isinstance(e, dict) and e.get("type") == "compact_20260112" - ] + compact_edits = [e for e in edits if isinstance(e, dict) and e.get("type") == "compact_20260112"] if compact_edits: beta_set.add(ANTHROPIC_BETA_HEADER_VALUES.COMPACT_2026_01_12.value) anthropic_messages_request["context_management"] = { @@ -469,9 +539,7 @@ def _get_bedrock_invoke_anthropic_beta_headers( tools = anthropic_messages_optional_request_params.get("tools") messages_typed = cast(List[AllMessageValues], messages) tool_search_used = anthropic_model_info.is_tool_search_used(tools) - programmatic_tool_calling_used = ( - anthropic_model_info.is_programmatic_tool_calling_used(tools) - ) + programmatic_tool_calling_used = anthropic_model_info.is_programmatic_tool_calling_used(tools) input_examples_used = anthropic_model_info.is_input_examples_used(tools) user_beta_set = set(get_anthropic_beta_from_headers(headers)) @@ -515,9 +583,7 @@ def _get_bedrock_invoke_anthropic_beta_headers( ) dropped_user_betas = sorted( - b - for b in user_beta_set - if not filter_and_transform_beta_headers([b], provider="bedrock") + b for b in user_beta_set if not filter_and_transform_beta_headers([b], provider="bedrock") ) if dropped_user_betas: verbose_logger.warning( @@ -543,9 +609,7 @@ def _strip_unsupported_bedrock_invoke_fields( return {k: v for k, v in anthropic_messages_request.items() if k in allowed} @staticmethod - def _clamp_adaptive_reasoning_effort_for_bedrock( - model: str, optional_params: Dict - ) -> None: + def _clamp_adaptive_reasoning_effort_for_bedrock(model: str, optional_params: Dict) -> None: """Lower ``reasoning_effort`` to the Bedrock effort ceiling before validation. The shared ``/v1/messages`` effort gate rejects tiers a model does not @@ -584,15 +648,14 @@ def transform_anthropic_messages_request( litellm_params=litellm_params, headers=headers, ) + self._normalize_system_role_messages_for_bedrock(anthropic_messages_request) ######################################################### ############## BEDROCK Invoke SPECIFIC TRANSFORMATION ### ######################################################### # 1. anthropic_version is required for all claude models if "anthropic_version" not in anthropic_messages_request: - anthropic_messages_request["anthropic_version"] = ( - self.DEFAULT_BEDROCK_ANTHROPIC_API_VERSION - ) + anthropic_messages_request["anthropic_version"] = self.DEFAULT_BEDROCK_ANTHROPIC_API_VERSION # 2. `stream` is not allowed in request body for bedrock invoke if "stream" in anthropic_messages_request: @@ -602,17 +665,13 @@ def transform_anthropic_messages_request( if "model" in anthropic_messages_request: anthropic_messages_request.pop("model", None) - injected_thinking_for_clear_thinking = ( - self._ensure_thinking_for_clear_thinking_context_management( - anthropic_messages_request=anthropic_messages_request, - model=model, - ) + injected_thinking_for_clear_thinking = self._ensure_thinking_for_clear_thinking_context_management( + anthropic_messages_request=anthropic_messages_request, + model=model, ) # 4. Remove `ttl` field from cache_control in messages (Bedrock doesn't support it for older models) - self._remove_ttl_from_cache_control( - anthropic_messages_request=anthropic_messages_request, model=model - ) + self._remove_ttl_from_cache_control(anthropic_messages_request=anthropic_messages_request, model=model) # 5. Convert structured-output params to inline schema. # Bedrock Invoke doesn't support top-level `output_format`; its @@ -623,9 +682,7 @@ def transform_anthropic_messages_request( if isinstance(existing_output_config, dict): anthropic_messages_request["output_config"] = dict(existing_output_config) output_format = anthropic_messages_request.pop("output_format", None) - output_config_format = pop_bedrock_invoke_output_config_format( - anthropic_messages_request - ) + output_config_format = pop_bedrock_invoke_output_config_format(anthropic_messages_request) if output_format: convert_bedrock_invoke_output_format_to_inline_schema( output_format=output_format, @@ -699,9 +756,7 @@ def transform_anthropic_messages_request( # Catches Anthropic-only extensions (output_config, speed, mcp_servers, ...) # and any future additions Claude Code may start sending. ``context_management`` # has already been pre-filtered to its Bedrock-supported subset above. - anthropic_messages_request = self._strip_unsupported_bedrock_invoke_fields( - anthropic_messages_request - ) + anthropic_messages_request = self._strip_unsupported_bedrock_invoke_fields(anthropic_messages_request) return anthropic_messages_request @@ -727,9 +782,7 @@ def get_async_streaming_response_iterator( async def bedrock_sse_wrapper( self, - completion_stream: AsyncIterator[ - Union[bytes, GenericStreamingChunk, ModelResponseStream, dict] - ], + completion_stream: AsyncIterator[Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]], litellm_logging_obj: LiteLLMLoggingObj, request_body: dict, ): @@ -782,9 +835,7 @@ def _merge_message_start_cache_into_delta_usage( @staticmethod async def _promote_message_stop_usage( - completion_stream: AsyncIterator[ - Union[bytes, GenericStreamingChunk, ModelResponseStream, dict] - ], + completion_stream: AsyncIterator[Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]], ) -> AsyncIterator[Union[bytes, GenericStreamingChunk, ModelResponseStream, dict]]: """ Promote cache usage fields onto message_delta from message_stop (and, @@ -830,9 +881,7 @@ async def _promote_message_stop_usage( raw_input = stop_usage.get("input_tokens") if raw_input is not None: - delta_usage["input_tokens"] = ( - raw_input if isinstance(raw_input, int) else 0 - ) + delta_usage["input_tokens"] = raw_input if isinstance(raw_input, int) else 0 AmazonAnthropicClaudeMessagesConfig._merge_message_start_cache_into_delta_usage( delta_usage, start_usage_snapshot @@ -873,9 +922,7 @@ def __init__( super().__init__(model=model) self.DEFAULT_CHUNK_SIZE = 1024 - def _chunk_parser( - self, chunk_data: dict - ) -> Union[GChunk, ModelResponseStream, dict]: + def _chunk_parser(self, chunk_data: dict) -> Union[GChunk, ModelResponseStream, dict]: """ Parse the chunk data into anthropic /messages format @@ -883,18 +930,12 @@ def _chunk_parser( the Anthropic `/v1/messages` specification so callers receive a consistent response shape when streaming. """ - amazon_bedrock_invocation_metrics = chunk_data.pop( - "amazon-bedrock-invocationMetrics", {} - ) + amazon_bedrock_invocation_metrics = chunk_data.pop("amazon-bedrock-invocationMetrics", {}) if amazon_bedrock_invocation_metrics: anthropic_usage = {} if "inputTokenCount" in amazon_bedrock_invocation_metrics: - anthropic_usage["input_tokens"] = amazon_bedrock_invocation_metrics[ - "inputTokenCount" - ] + anthropic_usage["input_tokens"] = amazon_bedrock_invocation_metrics["inputTokenCount"] if "outputTokenCount" in amazon_bedrock_invocation_metrics: - anthropic_usage["output_tokens"] = amazon_bedrock_invocation_metrics[ - "outputTokenCount" - ] + anthropic_usage["output_tokens"] = amazon_bedrock_invocation_metrics["outputTokenCount"] chunk_data["usage"] = anthropic_usage return chunk_data diff --git a/litellm/llms/bedrock/messages/mantle_transformation.py b/litellm/llms/bedrock/messages/mantle_transformation.py index 94e7f90b7198..a8a7b7ed1d50 100644 --- a/litellm/llms/bedrock/messages/mantle_transformation.py +++ b/litellm/llms/bedrock/messages/mantle_transformation.py @@ -42,9 +42,7 @@ def get_complete_url( region = self._get_aws_region_name(optional_params=optional_params, model=model) return build_mantle_messages_url( api_base=api_base, - aws_bedrock_runtime_endpoint=optional_params.get( - "aws_bedrock_runtime_endpoint" - ), + aws_bedrock_runtime_endpoint=optional_params.get("aws_bedrock_runtime_endpoint"), region=region, ) diff --git a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py index 0522bb249e12..137f1e333ebf 100644 --- a/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py +++ b/litellm/llms/bedrock/passthrough/guardrail_translation/handler.py @@ -269,9 +269,7 @@ async def de_anonymize_event_stream( payload_dict = _json.loads(payload_bytes) texts = [ (group_key, container[key]) - for group_key, container, key in _collect_stream_delta_text_holders( - payload_dict.get("delta") - ) + for group_key, container, key in _collect_stream_delta_text_holders(payload_dict.get("delta")) ] except Exception as e: verbose_proxy_logger.debug( @@ -304,9 +302,7 @@ async def de_anonymize_event_stream( "output": { "message": { "role": "assistant", - "content": [ - {"text": "".join(group_texts[gk])} for gk in active_groups - ], + "content": [{"text": "".join(group_texts[gk])} for gk in active_groups], } }, "stopReason": "end_turn", @@ -328,9 +324,7 @@ async def de_anonymize_event_stream( try: processed_blocks = processed["output"]["message"]["content"] # type: ignore[index] - de_anonymized_texts = [ - processed_blocks[i]["text"] for i in range(len(active_groups)) - ] + de_anonymized_texts = [processed_blocks[i]["text"] for i in range(len(active_groups))] except (KeyError, IndexError, TypeError): return body_bytes @@ -362,9 +356,7 @@ async def de_anonymize_event_stream( headers_bytes = frame_raw[12 : 12 + orig_hdrs_len] try: - payload_dict = _json.loads( - frame_raw[12 + orig_hdrs_len : orig_total - 4] - ) + payload_dict = _json.loads(frame_raw[12 + orig_hdrs_len : orig_total - 4]) for local_idx, (_, container, key) in enumerate( _collect_stream_delta_text_holders(payload_dict.get("delta")) ): @@ -384,9 +376,7 @@ async def de_anonymize_event_stream( msg_crc_val = esm_crc32(part_for_msg_crc, prelude_crc_val) & 0xFFFFFFFF msg_crc_b = struct.pack("!I", msg_crc_val) - result_parts.append( - prelude + prelude_crc_b + headers_bytes + new_payload + msg_crc_b - ) + result_parts.append(prelude + prelude_crc_b + headers_bytes + new_payload + msg_crc_b) result_parts.append(trailing_bytes) return b"".join(result_parts) @@ -458,13 +448,9 @@ async def process_output_response( return response output_message = ( - response.get("output", {}).get("message", {}) - if isinstance(response.get("output"), dict) - else {} - ) - content_blocks = ( - output_message.get("content") if isinstance(output_message, dict) else None + response.get("output", {}).get("message", {}) if isinstance(response.get("output"), dict) else {} ) + content_blocks = output_message.get("content") if isinstance(output_message, dict) else None if not isinstance(content_blocks, list): return response @@ -475,13 +461,8 @@ async def process_output_response( return response effective_request_data = request_data or {} - if ( - "litellm_metadata" not in effective_request_data - and user_api_key_dict is not None - ): - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + if "litellm_metadata" not in effective_request_data and user_api_key_dict is not None: + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: effective_request_data = { **effective_request_data, diff --git a/litellm/llms/bedrock/passthrough/transformation.py b/litellm/llms/bedrock/passthrough/transformation.py index 846af65c0f93..cc8840526f09 100644 --- a/litellm/llms/bedrock/passthrough/transformation.py +++ b/litellm/llms/bedrock/passthrough/transformation.py @@ -16,9 +16,7 @@ from litellm.types.utils import CostResponseTypes -class BedrockPassthroughConfig( - BaseAWSLLM, BedrockModelInfo, BedrockEventStreamDecoderBase, BasePassthroughConfig -): +class BedrockPassthroughConfig(BaseAWSLLM, BedrockModelInfo, BedrockEventStreamDecoderBase, BasePassthroughConfig): def is_streaming_request(self, endpoint: str, request_data: dict) -> bool: return "stream" in endpoint @@ -43,9 +41,7 @@ def _encode_model_id_for_endpoint(self, model_id: str) -> str: # Create a temporary endpoint with the model_id to check if encoding is needed temp_endpoint = f"/model/{model_id}/converse" - encoded_temp_endpoint = CommonUtils.encode_bedrock_runtime_modelid_arn( - temp_endpoint - ) + encoded_temp_endpoint = CommonUtils.encode_bedrock_runtime_modelid_arn(temp_endpoint) # Extract the encoded model_id from the temporary endpoint encoded_model_id_match = re.search(r"/model/([^/]+)/", encoded_temp_endpoint) @@ -73,9 +69,7 @@ def get_complete_url( model_id=model_id, ) - aws_bedrock_runtime_endpoint = optional_params.get( - "aws_bedrock_runtime_endpoint" - ) + aws_bedrock_runtime_endpoint = optional_params.get("aws_bedrock_runtime_endpoint") endpoint_url, _ = self.get_runtime_endpoint( api_base=api_base, aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint, @@ -202,9 +196,7 @@ def handle_logging_collected_chunks( if "invoke" in endpoint: invoke_provider = AmazonInvokeConfig.get_bedrock_invoke_provider(model) if invoke_provider is None: - raise ValueError( - f"Invalid invoke provider: {invoke_provider}, for model: {model}" - ) + raise ValueError(f"Invalid invoke provider: {invoke_provider}, for model: {model}") obj = get_bedrock_event_stream_decoder( invoke_provider=invoke_provider, model=model, @@ -225,9 +217,9 @@ def handle_logging_collected_chunks( message = json.loads(chunk) translated_chunk = obj._chunk_parser(chunk_data=message) - if isinstance( - translated_chunk, dict - ) and generic_chunk_has_all_required_fields(cast(dict, translated_chunk)): + if isinstance(translated_chunk, dict) and generic_chunk_has_all_required_fields( + cast(dict, translated_chunk) + ): chunk_obj = convert_generic_chunk_to_model_response_stream( cast(GenericStreamingChunk, translated_chunk) ) diff --git a/litellm/llms/bedrock/realtime/handler.py b/litellm/llms/bedrock/realtime/handler.py index 5d22f4b3cd95..6db2571090a0 100644 --- a/litellm/llms/bedrock/realtime/handler.py +++ b/litellm/llms/bedrock/realtime/handler.py @@ -62,9 +62,7 @@ async def async_realtime( EnvironmentCredentialsResolver, ) except ImportError: - raise ImportError( - "Missing aws_sdk_bedrock_runtime. Install with: pip install aws-sdk-bedrock-runtime" - ) + raise ImportError("Missing aws_sdk_bedrock_runtime. Install with: pip install aws-sdk-bedrock-runtime") # Get AWS region if aws_region_name is None: @@ -81,9 +79,7 @@ async def async_realtime( else: endpoint_uri = f"https://bedrock-runtime.{aws_region_name}.amazonaws.com" - verbose_proxy_logger.debug( - f"Bedrock Realtime: Connecting to {endpoint_uri} with model {model}" - ) + verbose_proxy_logger.debug(f"Bedrock Realtime: Connecting to {endpoint_uri} with model {model}") # Initialize Bedrock client with aws_sdk_bedrock_runtime config = Config( @@ -97,15 +93,11 @@ async def async_realtime( try: # Initialize the bidirectional stream - bedrock_stream = ( - await bedrock_client.invoke_model_with_bidirectional_stream( - InvokeModelWithBidirectionalStreamOperationInput(model_id=model) - ) + bedrock_stream = await bedrock_client.invoke_model_with_bidirectional_stream( + InvokeModelWithBidirectionalStreamOperationInput(model_id=model) ) - verbose_proxy_logger.debug( - "Bedrock Realtime: Bidirectional stream established" - ) + verbose_proxy_logger.debug("Bedrock Realtime: Bidirectional stream established") # Track state for transformation session_state = { @@ -148,13 +140,9 @@ async def async_realtime( ) except Exception as e: - verbose_proxy_logger.exception( - f"Error in BedrockRealtime.async_realtime: {e}" - ) + verbose_proxy_logger.exception(f"Error in BedrockRealtime.async_realtime: {e}") try: - await websocket.close( - code=1011, reason=_redact_string(f"Internal error: {str(e)}") - ) + await websocket.close(code=1011, reason=_redact_string(f"Internal error: {str(e)}")) except Exception: pass raise @@ -177,35 +165,25 @@ async def _forward_client_to_bedrock( while True: # Receive message from client message = await client_ws.receive_text() - verbose_proxy_logger.debug( - f"Bedrock Realtime: Received from client: {message[:200]}" - ) + verbose_proxy_logger.debug(f"Bedrock Realtime: Received from client: {message[:200]}") # Transform OpenAI format to Bedrock format transformed_messages = transformation_config.transform_realtime_request( message=message, model=model, - session_configuration_request=session_state.get( - "session_configuration_request" - ), + session_configuration_request=session_state.get("session_configuration_request"), ) # Send transformed messages to Bedrock for bedrock_message in transformed_messages: event = InvokeModelWithBidirectionalStreamInputChunk( - value=BidirectionalInputPayloadPart( - bytes_=bedrock_message.encode("utf-8") - ) + value=BidirectionalInputPayloadPart(bytes_=bedrock_message.encode("utf-8")) ) await bedrock_stream.input_stream.send(event) - verbose_proxy_logger.debug( - f"Bedrock Realtime: Sent to Bedrock: {bedrock_message[:200]}" - ) + verbose_proxy_logger.debug(f"Bedrock Realtime: Sent to Bedrock: {bedrock_message[:200]}") except Exception as e: - verbose_proxy_logger.debug( - f"Client to Bedrock forwarding ended: {e}", exc_info=True - ) + verbose_proxy_logger.debug(f"Client to Bedrock forwarding ended: {e}", exc_info=True) # Close the Bedrock stream input try: await bedrock_stream.input_stream.close() @@ -230,29 +208,19 @@ async def _forward_bedrock_to_client( if result.value and result.value.bytes_: bedrock_response = result.value.bytes_.decode("utf-8") - verbose_proxy_logger.debug( - f"Bedrock Realtime: Received from Bedrock: {bedrock_response[:200]}" - ) + verbose_proxy_logger.debug(f"Bedrock Realtime: Received from Bedrock: {bedrock_response[:200]}") # Transform Bedrock format to OpenAI format from litellm.types.realtime import RealtimeResponseTransformInput realtime_response_transform_input: RealtimeResponseTransformInput = { - "current_output_item_id": session_state.get( - "current_output_item_id" - ), + "current_output_item_id": session_state.get("current_output_item_id"), "current_response_id": session_state.get("current_response_id"), - "current_conversation_id": session_state.get( - "current_conversation_id" - ), - "current_delta_chunks": session_state.get( - "current_delta_chunks" - ), + "current_conversation_id": session_state.get("current_conversation_id"), + "current_delta_chunks": session_state.get("current_delta_chunks"), "current_item_chunks": session_state.get("current_item_chunks"), "current_delta_type": session_state.get("current_delta_type"), - "session_configuration_request": session_state.get( - "session_configuration_request" - ), + "session_configuration_request": session_state.get("session_configuration_request"), } transformed_response = transformation_config.transform_realtime_response( @@ -265,27 +233,13 @@ async def _forward_bedrock_to_client( # Update session state session_state.update( { - "current_output_item_id": transformed_response.get( - "current_output_item_id" - ), - "current_response_id": transformed_response.get( - "current_response_id" - ), - "current_conversation_id": transformed_response.get( - "current_conversation_id" - ), - "current_delta_chunks": transformed_response.get( - "current_delta_chunks" - ), - "current_item_chunks": transformed_response.get( - "current_item_chunks" - ), - "current_delta_type": transformed_response.get( - "current_delta_type" - ), - "session_configuration_request": transformed_response.get( - "session_configuration_request" - ), + "current_output_item_id": transformed_response.get("current_output_item_id"), + "current_response_id": transformed_response.get("current_response_id"), + "current_conversation_id": transformed_response.get("current_conversation_id"), + "current_delta_chunks": transformed_response.get("current_delta_chunks"), + "current_item_chunks": transformed_response.get("current_item_chunks"), + "current_delta_type": transformed_response.get("current_delta_type"), + "session_configuration_request": transformed_response.get("session_configuration_request"), } ) @@ -294,14 +248,10 @@ async def _forward_bedrock_to_client( for openai_message in openai_messages: message_json = json.dumps(openai_message) await client_ws.send_text(message_json) - verbose_proxy_logger.debug( - f"Bedrock Realtime: Sent to client: {message_json[:200]}" - ) + verbose_proxy_logger.debug(f"Bedrock Realtime: Sent to client: {message_json[:200]}") except Exception as e: - verbose_proxy_logger.debug( - f"Bedrock to client forwarding ended: {e}", exc_info=True - ) + verbose_proxy_logger.debug(f"Bedrock to client forwarding ended: {e}", exc_info=True) # Close the client WebSocket try: await client_ws.close() diff --git a/litellm/llms/bedrock/realtime/transformation.py b/litellm/llms/bedrock/realtime/transformation.py index 9124a8c21b4b..498567a4ecfc 100644 --- a/litellm/llms/bedrock/realtime/transformation.py +++ b/litellm/llms/bedrock/realtime/transformation.py @@ -70,15 +70,11 @@ def __init__(self): # Text configuration self.text_media_type = "text/plain" - def validate_environment( - self, headers: dict, model: str, api_key: Optional[str] = None - ) -> dict: + def validate_environment(self, headers: dict, model: str, api_key: Optional[str] = None) -> dict: """Validate environment - no special validation needed for Bedrock.""" return headers - def get_complete_url( - self, api_base: Optional[str], model: str, api_key: Optional[str] = None - ) -> str: + def get_complete_url(self, api_base: Optional[str], model: str, api_key: Optional[str] = None) -> str: """Get complete URL - handled by aws_sdk_bedrock_runtime.""" return api_base or "" @@ -86,9 +82,7 @@ def requires_session_configuration(self) -> bool: """Bedrock requires session configuration.""" return True - def session_configuration_request( - self, model: str, tools: Optional[List[dict]] = None - ) -> str: + def session_configuration_request(self, model: str, tools: Optional[List[dict]] = None) -> str: """ Create initial session configuration for Bedrock Nova Sonic. @@ -126,19 +120,13 @@ def session_configuration_request( # Add tool configuration if tools are provided if tools: - prompt_start_config["toolUseOutputConfiguration"] = { - "mediaType": "application/json" - } - prompt_start_config["toolConfiguration"] = { - "tools": self._transform_tools_to_bedrock_format(tools) - } + prompt_start_config["toolUseOutputConfiguration"] = {"mediaType": "application/json"} + prompt_start_config["toolConfiguration"] = {"tools": self._transform_tools_to_bedrock_format(tools)} prompt_start = {"event": {"promptStart": prompt_start_config}} # Return as a marker that we've sent the configuration - return json.dumps( - {"session_start": session_start, "prompt_start": prompt_start} - ) + return json.dumps({"session_start": session_start, "prompt_start": prompt_start}) def _transform_tools_to_bedrock_format(self, tools: List[dict]) -> List[dict]: """ @@ -158,17 +146,13 @@ def _transform_tools_to_bedrock_format(self, tools: List[dict]) -> List[dict]: "toolSpec": { "name": function.get("name", ""), "description": function.get("description", ""), - "inputSchema": { - "json": json.dumps(function.get("parameters", {})) - }, + "inputSchema": {"json": json.dumps(function.get("parameters", {}))}, } } bedrock_tools.append(bedrock_tool) return bedrock_tools - def _map_audio_format_to_sample_rate( - self, audio_format: str, is_output: bool = True - ) -> int: + def _map_audio_format_to_sample_rate(self, audio_format: str, is_output: bool = True) -> int: """ Map OpenAI audio format to sample rate. @@ -213,16 +197,12 @@ def transform_session_update_event(self, json_message: dict) -> List[str]: self.voice_id = session_config["voice"] if "output_audio_format" in session_config: output_format = session_config["output_audio_format"] - self.output_sample_rate_hertz = self._map_audio_format_to_sample_rate( - output_format, is_output=True - ) + self.output_sample_rate_hertz = self._map_audio_format_to_sample_rate(output_format, is_output=True) # Update audio input configuration from session if provided if "input_audio_format" in session_config: input_format = session_config["input_audio_format"] - self.input_sample_rate_hertz = self._map_audio_format_to_sample_rate( - input_format, is_output=False - ) + self.input_sample_rate_hertz = self._map_audio_format_to_sample_rate(input_format, is_output=False) # Allow direct override of sample rates if provided (custom extension) if "output_sample_rate_hertz" in session_config: @@ -262,12 +242,8 @@ def transform_session_update_event(self, json_message: dict) -> List[str]: # Add tool configuration if tools are provided tools = session_config.get("tools") if tools: - prompt_start_config["toolUseOutputConfiguration"] = { - "mediaType": "application/json" - } - prompt_start_config["toolConfiguration"] = { - "tools": self._transform_tools_to_bedrock_format(tools) - } + prompt_start_config["toolUseOutputConfiguration"] = {"mediaType": "application/json"} + prompt_start_config["toolConfiguration"] = {"tools": self._transform_tools_to_bedrock_format(tools)} prompt_start = {"event": {"promptStart": prompt_start_config}} messages.append(json.dumps(prompt_start)) @@ -317,9 +293,7 @@ def transform_session_update_event(self, json_message: dict) -> List[str]: return messages - def transform_input_audio_buffer_append_event( - self, json_message: dict - ) -> List[str]: + def transform_input_audio_buffer_append_event(self, json_message: dict) -> List[str]: """ Transform input_audio_buffer.append event to Bedrock audio input. @@ -371,9 +345,7 @@ def transform_input_audio_buffer_append_event( return messages - def transform_input_audio_buffer_commit_event( - self, json_message: dict - ) -> List[str]: + def transform_input_audio_buffer_commit_event(self, json_message: dict) -> List[str]: """ Transform input_audio_buffer.commit event to Bedrock audio content end. @@ -418,9 +390,7 @@ def transform_conversation_item_create_event(self, json_message: dict) -> List[s # Handle tool result if item_type == "function_call_output": - return self.transform_conversation_item_create_tool_result_event( - json_message - ) + return self.transform_conversation_item_create_tool_result_event(json_message) # Handle regular message if item_type == "message": @@ -438,9 +408,7 @@ def transform_conversation_item_create_event(self, json_message: dict) -> List[s "type": "TEXT", "interactive": True, "role": "USER", - "textInputConfiguration": { - "mediaType": self.text_media_type - }, + "textInputConfiguration": {"mediaType": self.text_media_type}, } } } @@ -622,9 +590,7 @@ def transform_content_start_event( # Determine content type content_type = content_start.get("type", "TEXT") - current_delta_type: ALL_DELTA_TYPES = ( - "text" if content_type == "TEXT" else "audio" - ) + current_delta_type: ALL_DELTA_TYPES = "text" if content_type == "TEXT" else "audio" returned_messages: List[OpenAIRealtimeEvents] = [] @@ -666,9 +632,7 @@ def transform_content_start_event( event_id=f"event_{uuid.uuid4()}", item_id=current_output_item_id, part=( - {"type": "text", "text": ""} - if current_delta_type == "text" - else {"type": "audio", "transcript": ""} + {"type": "text", "text": ""} if current_delta_type == "text" else {"type": "audio", "transcript": ""} ), response_id=current_response_id, ) @@ -793,9 +757,7 @@ def transform_content_end_event( # Accumulate text accumulated_text = "" if current_delta_chunks: - accumulated_text = "".join( - [chunk.get("delta", "") for chunk in current_delta_chunks] - ) + accumulated_text = "".join([chunk.get("delta", "") for chunk in current_delta_chunks]) text_done = OpenAIRealtimeResponseTextDone( type="response.text.done", @@ -938,11 +900,7 @@ def transform_tool_use_event( tool_input = {} if "input" in tool_use: try: - tool_input = ( - json.loads(tool_use["input"]) - if isinstance(tool_use["input"], str) - else tool_use["input"] - ) + tool_input = json.loads(tool_use["input"]) if isinstance(tool_use["input"], str) else tool_use["input"] except json.JSONDecodeError: tool_input = {} @@ -970,9 +928,7 @@ def transform_tool_use_event( tool_name, ) - def transform_conversation_item_create_tool_result_event( - self, json_message: dict - ) -> List[str]: + def transform_conversation_item_create_tool_result_event(self, json_message: dict) -> List[str]: """ Transform conversation.item.create with tool result to Bedrock format. @@ -1016,9 +972,7 @@ def transform_conversation_item_create_tool_result_event( "toolResult": { "promptName": self.prompt_name, "contentName": tool_content_name, - "content": ( - output if isinstance(output, str) else json.dumps(output) - ), + "content": (output if isinstance(output, str) else json.dumps(output)), } } } @@ -1060,53 +1014,27 @@ def transform_realtime_response( json_message = json.loads(message) except json.JSONDecodeError: message_preview = ( - message[:200].decode("utf-8", errors="replace") - if isinstance(message, bytes) - else message[:200] + message[:200].decode("utf-8", errors="replace") if isinstance(message, bytes) else message[:200] ) verbose_logger.warning(f"Invalid JSON message: {message_preview}") return { "response": [], - "current_output_item_id": realtime_response_transform_input.get( - "current_output_item_id" - ), - "current_response_id": realtime_response_transform_input.get( - "current_response_id" - ), - "current_delta_chunks": realtime_response_transform_input.get( - "current_delta_chunks" - ), - "current_conversation_id": realtime_response_transform_input.get( - "current_conversation_id" - ), - "current_item_chunks": realtime_response_transform_input.get( - "current_item_chunks" - ), - "current_delta_type": realtime_response_transform_input.get( - "current_delta_type" - ), - "session_configuration_request": realtime_response_transform_input.get( - "session_configuration_request" - ), + "current_output_item_id": realtime_response_transform_input.get("current_output_item_id"), + "current_response_id": realtime_response_transform_input.get("current_response_id"), + "current_delta_chunks": realtime_response_transform_input.get("current_delta_chunks"), + "current_conversation_id": realtime_response_transform_input.get("current_conversation_id"), + "current_item_chunks": realtime_response_transform_input.get("current_item_chunks"), + "current_delta_type": realtime_response_transform_input.get("current_delta_type"), + "session_configuration_request": realtime_response_transform_input.get("session_configuration_request"), } # Extract state - current_output_item_id = realtime_response_transform_input.get( - "current_output_item_id" - ) - current_response_id = realtime_response_transform_input.get( - "current_response_id" - ) - current_conversation_id = realtime_response_transform_input.get( - "current_conversation_id" - ) - current_delta_chunks = realtime_response_transform_input.get( - "current_delta_chunks" - ) + current_output_item_id = realtime_response_transform_input.get("current_output_item_id") + current_response_id = realtime_response_transform_input.get("current_response_id") + current_conversation_id = realtime_response_transform_input.get("current_conversation_id") + current_delta_chunks = realtime_response_transform_input.get("current_delta_chunks") current_delta_type = realtime_response_transform_input.get("current_delta_type") - session_configuration_request = realtime_response_transform_input.get( - "session_configuration_request" - ) + session_configuration_request = realtime_response_transform_input.get("session_configuration_request") returned_messages: List[OpenAIRealtimeEvents] = [] @@ -1115,9 +1043,7 @@ def transform_realtime_response( # Route to appropriate transformation method if "sessionStart" in event: - session_created = self.transform_session_start_event( - event, model, logging_obj - ) + session_created = self.transform_session_start_event(event, model, logging_obj) returned_messages.append(session_created) session_configuration_request = json.dumps({"configured": True}) @@ -1146,9 +1072,7 @@ def transform_realtime_response( returned_messages.extend(events) elif "audioOutput" in event: - events = self.transform_audio_output_event( - event, current_output_item_id, current_response_id - ) + events = self.transform_audio_output_event(event, current_output_item_id, current_response_id) returned_messages.extend(events) elif "contentEnd" in event: @@ -1175,9 +1099,7 @@ def transform_realtime_response( current_output_item_id, current_response_id, current_delta_type, - ) = self.transform_prompt_end_event( - event, current_response_id, current_conversation_id - ) + ) = self.transform_prompt_end_event(event, current_response_id, current_conversation_id) returned_messages.extend(events) return { @@ -1186,9 +1108,7 @@ def transform_realtime_response( "current_response_id": current_response_id, "current_delta_chunks": current_delta_chunks, "current_conversation_id": current_conversation_id, - "current_item_chunks": realtime_response_transform_input.get( - "current_item_chunks" - ), + "current_item_chunks": realtime_response_transform_input.get("current_item_chunks"), "current_delta_type": current_delta_type, "session_configuration_request": session_configuration_request, } diff --git a/litellm/llms/bedrock/rerank/handler.py b/litellm/llms/bedrock/rerank/handler.py index 276c6f23c331..1728f52a413c 100644 --- a/litellm/llms/bedrock/rerank/handler.py +++ b/litellm/llms/bedrock/rerank/handler.py @@ -99,9 +99,7 @@ def rerank( return self.arerank( prepared_request, timeout=timeout, - client=client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None, + client=client if client is not None and isinstance(client, AsyncHTTPHandler) else None, ) # type: ignore if client is None or not isinstance(client, HTTPHandler): @@ -142,9 +140,7 @@ def _prepare_request( from botocore.awsrequest import AWSRequest except ImportError: raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.") - boto3_credentials_info = self._get_boto_credentials_from_optional_params( - optional_params, model - ) + boto3_credentials_info = self._get_boto_credentials_from_optional_params(optional_params, model) ### SET RUNTIME ENDPOINT ### _, proxy_endpoint_url = self.get_runtime_endpoint( @@ -152,9 +148,7 @@ def _prepare_request( aws_bedrock_runtime_endpoint=boto3_credentials_info.aws_bedrock_runtime_endpoint, aws_region_name=boto3_credentials_info.aws_region_name, ) - proxy_endpoint_url = proxy_endpoint_url.replace( - "bedrock-runtime", "bedrock-agent-runtime" - ) + proxy_endpoint_url = proxy_endpoint_url.replace("bedrock-runtime", "bedrock-agent-runtime") proxy_endpoint_url = f"{proxy_endpoint_url}/rerank" sigv4 = SigV4Auth( boto3_credentials_info.credentials, @@ -167,9 +161,7 @@ def _prepare_request( headers = {"Content-Type": "application/json"} if extra_headers is not None: headers = {"Content-Type": "application/json", **extra_headers} - request = AWSRequest( - method="POST", url=proxy_endpoint_url, data=body, headers=headers - ) + request = AWSRequest(method="POST", url=proxy_endpoint_url, data=body, headers=headers) sigv4.add_auth(request) if ( extra_headers is not None and "Authorization" in extra_headers diff --git a/litellm/llms/bedrock/rerank/transformation.py b/litellm/llms/bedrock/rerank/transformation.py index b5d33eda49f3..38625a269398 100644 --- a/litellm/llms/bedrock/rerank/transformation.py +++ b/litellm/llms/bedrock/rerank/transformation.py @@ -29,9 +29,7 @@ class BedrockRerankConfig: - def _transform_sources( - self, documents: List[Union[str, dict]] - ) -> List[BedrockRerankSource]: + def _transform_sources(self, documents: List[Union[str, dict]]) -> List[BedrockRerankSource]: """ Transform the sources from RerankRequest format to Bedrock format. """ @@ -50,9 +48,7 @@ def _transform_sources( else: _sources.append( BedrockRerankSource( - inlineDocumentSource=BedrockRerankInlineDocumentSource( - jsonDocument=document, type="JSON" - ), + inlineDocumentSource=BedrockRerankInlineDocumentSource(jsonDocument=document, type="JSON"), type="INLINE", ) ) @@ -73,9 +69,7 @@ def _transform_request(self, request_data: RerankRequest) -> BedrockRerankReques ], rerankingConfiguration=BedrockRerankConfiguration( bedrockRerankingConfiguration=BedrockRerankBedrockRerankingConfiguration( - modelConfiguration=BedrockRerankModelConfiguration( - modelArn=request_data.model - ), + modelConfiguration=BedrockRerankModelConfiguration(modelArn=request_data.model), numberOfResults=request_data.top_n or len(request_data.documents), ), type="BEDROCK_RERANKING_MODEL", @@ -90,9 +84,7 @@ def _transform_response(self, response: dict) -> RerankResponse: example input: {"results":[{"index":0,"relevanceScore":0.6847912669181824},{"index":1,"relevanceScore":0.5980774760246277}]} """ - _billed_units = RerankBilledUnits( - **response.get("usage", {"search_units": 1}) - ) # by default 1 search unit + _billed_units = RerankBilledUnits(**response.get("usage", {"search_units": 1})) # by default 1 search unit _tokens = RerankTokens(**response.get("usage", {})) rerank_meta = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens) diff --git a/litellm/llms/bedrock/vector_stores/transformation.py b/litellm/llms/bedrock/vector_stores/transformation.py index a479d1480644..c1b124caec10 100644 --- a/litellm/llms/bedrock/vector_stores/transformation.py +++ b/litellm/llms/bedrock/vector_stores/transformation.py @@ -38,9 +38,7 @@ def __init__(self) -> None: BaseVectorStoreConfig.__init__(self) BaseAWSLLM.__init__(self) - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: return {} def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: @@ -49,9 +47,7 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [], } - def get_supported_openai_params( - self, model: str - ) -> List[VECTOR_STORE_OPENAI_PARAMS]: + def get_supported_openai_params(self, model: str) -> List[VECTOR_STORE_OPENAI_PARAMS]: return ["filters", "max_num_results", "ranking_options"] def _map_operator_to_aws(self, operator: str) -> str: @@ -176,9 +172,7 @@ def map_openai_params( return optional_params - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: headers = headers or {} headers.setdefault("Content-Type", "application/json") return headers @@ -187,12 +181,8 @@ def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str aws_region_name = litellm_params.get("aws_region_name") endpoint_url, _ = self.get_runtime_endpoint( api_base=api_base, - aws_bedrock_runtime_endpoint=litellm_params.get( - "aws_bedrock_runtime_endpoint" - ), - aws_region_name=self.get_aws_region_name_for_non_llm_api_calls( - aws_region_name=aws_region_name - ), + aws_bedrock_runtime_endpoint=litellm_params.get("aws_bedrock_runtime_endpoint"), + aws_region_name=self.get_aws_region_name_for_non_llm_api_calls(aws_region_name=aws_region_name), endpoint_type="agent", ) return f"{endpoint_url}/knowledgebases" @@ -210,9 +200,7 @@ def transform_search_vector_store_request( if isinstance(query, list): query = " ".join(query) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}/retrieve" request_body: Dict[str, Any] = { @@ -223,43 +211,28 @@ def transform_search_vector_store_request( if isinstance(extra_body, dict): retrieval_config = deepcopy( - extra_body.get("retrievalConfiguration") - or extra_body.get("retrieval_configuration") - or {} + extra_body.get("retrievalConfiguration") or extra_body.get("retrieval_configuration") or {} ) max_results = vector_store_search_optional_params.get("max_num_results") if max_results is not None: - existing_number_of_results = retrieval_config.get( - "vectorSearchConfiguration", {} - ).get("numberOfResults") - if ( - existing_number_of_results is not None - and existing_number_of_results != max_results - ): + existing_number_of_results = retrieval_config.get("vectorSearchConfiguration", {}).get("numberOfResults") + if existing_number_of_results is not None and existing_number_of_results != max_results: verbose_logger.debug( "Overriding extra_body retrievalConfiguration.vectorSearchConfiguration.numberOfResults (%s) with max_num_results=%s", existing_number_of_results, max_results, ) - retrieval_config.setdefault("vectorSearchConfiguration", {})[ - "numberOfResults" - ] = max_results + retrieval_config.setdefault("vectorSearchConfiguration", {})["numberOfResults"] = max_results filters = vector_store_search_optional_params.get("filters") if filters is not None: - existing_filter = retrieval_config.get("vectorSearchConfiguration", {}).get( - "filter" - ) + existing_filter = retrieval_config.get("vectorSearchConfiguration", {}).get("filter") if existing_filter is not None and existing_filter != filters: verbose_logger.debug( "Overriding extra_body retrievalConfiguration.vectorSearchConfiguration.filter with filters from vector_store_search_optional_params" ) - retrieval_config.setdefault("vectorSearchConfiguration", {})["filter"] = ( - filters - ) + retrieval_config.setdefault("vectorSearchConfiguration", {})["filter"] = filters if retrieval_config: - request_body["retrievalConfiguration"] = cast( - BedrockKBRetrievalConfiguration, retrieval_config - ) + request_body["retrievalConfiguration"] = cast(BedrockKBRetrievalConfiguration, retrieval_config) litellm_logging_obj.model_call_details["query"] = query return url, request_body @@ -290,11 +263,7 @@ def _get_file_id_from_metadata(self, metadata: Dict[str, Any]) -> str: if source_uri: return source_uri - chunk_id = ( - metadata.get("x-amz-bedrock-kb-chunk-id", "unknown") - if metadata - else "unknown" - ) + chunk_id = metadata.get("x-amz-bedrock-kb-chunk-id", "unknown") if metadata else "unknown" return f"bedrock-kb-{chunk_id}" def _get_filename_from_metadata(self, metadata: Dict[str, Any]) -> str: @@ -308,9 +277,7 @@ def _get_filename_from_metadata(self, metadata: Dict[str, Any]) -> str: try: parsed_uri = urlparse(source_uri) filename = ( - parsed_uri.path.split("/")[-1] - if parsed_uri.path and parsed_uri.path != "/" - else parsed_uri.netloc + parsed_uri.path.split("/")[-1] if parsed_uri.path and parsed_uri.path != "/" else parsed_uri.netloc ) if not filename or filename == "/": filename = parsed_uri.netloc @@ -318,11 +285,7 @@ def _get_filename_from_metadata(self, metadata: Dict[str, Any]) -> str: except Exception: return source_uri - data_source_id = ( - metadata.get("x-amz-bedrock-kb-data-source-id", "unknown") - if metadata - else "unknown" - ) + data_source_id = metadata.get("x-amz-bedrock-kb-data-source-id", "unknown") if metadata else "unknown" return f"bedrock-kb-document-{data_source_id}" def _get_attributes_from_metadata(self, metadata: Dict[str, Any]) -> Dict[str, Any]: diff --git a/litellm/llms/bedrock_mantle/chat/transformation.py b/litellm/llms/bedrock_mantle/chat/transformation.py index f688cea10f16..8fc720daa29e 100644 --- a/litellm/llms/bedrock_mantle/chat/transformation.py +++ b/litellm/llms/bedrock_mantle/chat/transformation.py @@ -97,15 +97,11 @@ def validate_environment( def get_supported_openai_params(self, model: str) -> list: base_params = super().get_supported_openai_params(model) try: - if litellm.supports_reasoning( - model=model, custom_llm_provider=self.custom_llm_provider - ): + if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider): if "reasoning_effort" not in base_params: base_params.append("reasoning_effort") except Exception as e: - verbose_logger.debug( - f"BedrockMantleChatConfig: error checking reasoning support: {e}" - ) + verbose_logger.debug(f"BedrockMantleChatConfig: error checking reasoning support: {e}") return base_params def get_model_response_iterator( diff --git a/litellm/llms/bedrock_mantle/common_utils.py b/litellm/llms/bedrock_mantle/common_utils.py index d517ab940ce1..eedb57ea3864 100644 --- a/litellm/llms/bedrock_mantle/common_utils.py +++ b/litellm/llms/bedrock_mantle/common_utils.py @@ -28,9 +28,7 @@ BEDROCK_MANTLE_DEFAULT_REGION = "us-east-1" # Standard Mantle host: https://bedrock-mantle..api.aws (group 1 = region). -MANTLE_HOST_RE = re.compile( - r"^https?://bedrock-mantle\.([^/.]+)\.api\.aws", re.IGNORECASE -) +MANTLE_HOST_RE = re.compile(r"^https?://bedrock-mantle\.([^/.]+)\.api\.aws", re.IGNORECASE) class BedrockMantleAuthMixin: @@ -38,11 +36,7 @@ class BedrockMantleAuthMixin: @staticmethod def _resolve_bearer_token(api_key: str | None) -> str | None: - return ( - api_key - or get_secret_str("BEDROCK_MANTLE_API_KEY") - or get_secret_str("AWS_BEARER_TOKEN_BEDROCK") - ) + return api_key or get_secret_str("BEDROCK_MANTLE_API_KEY") or get_secret_str("AWS_BEARER_TOKEN_BEDROCK") @staticmethod def _resolve_region(params: dict) -> str: diff --git a/litellm/llms/bedrock_mantle/responses/transformation.py b/litellm/llms/bedrock_mantle/responses/transformation.py index 2e30f85fd0e5..31975444a311 100644 --- a/litellm/llms/bedrock_mantle/responses/transformation.py +++ b/litellm/llms/bedrock_mantle/responses/transformation.py @@ -40,9 +40,7 @@ ) # Per Bedrock Mantle Responses API validation errors. -_BEDROCK_MANTLE_SUPPORTED_RESPONSE_TOOL_TYPES = frozenset( - {"function", "mcp", "custom", "namespace", "tool_search"} -) +_BEDROCK_MANTLE_SUPPORTED_RESPONSE_TOOL_TYPES = frozenset({"function", "mcp", "custom", "namespace", "tool_search"}) class BedrockMantleResponsesAPIConfig(BedrockMantleAuthMixin, OpenAIResponsesAPIConfig): @@ -65,11 +63,7 @@ def get_complete_url( litellm_params: dict, ) -> str: region = self._resolve_region({**litellm_params, "api_base": api_base}) - base = ( - api_base - or get_secret_str("BEDROCK_MANTLE_API_BASE") - or f"https://bedrock-mantle.{region}.api.aws" - ) + base = api_base or get_secret_str("BEDROCK_MANTLE_API_BASE") or f"https://bedrock-mantle.{region}.api.aws" base = base.rstrip("/") for suffix in _BASE_SUFFIXES_TO_STRIP: if base.endswith(suffix): @@ -83,9 +77,7 @@ def get_complete_url( path = "/openai/v1/responses" if self.use_openai_path else "/v1/responses" return f"{base}{path}" - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() bearer = self._resolve_bearer_token(litellm_params.api_key) if bearer: @@ -117,8 +109,7 @@ def _filter_unsupported_tools(tools: List[Any]) -> List[Any]: if dropped_types: verbose_logger.warning( - "Bedrock Mantle Responses API: dropping unsupported tool type(s) " - "%s (supported: %s).", + "Bedrock Mantle Responses API: dropping unsupported tool type(s) %s (supported: %s).", sorted(set(dropped_types)), sorted(_BEDROCK_MANTLE_SUPPORTED_RESPONSE_TOOL_TYPES), ) diff --git a/litellm/llms/black_forest_labs/common_utils.py b/litellm/llms/black_forest_labs/common_utils.py index 237208693f70..71c090936798 100644 --- a/litellm/llms/black_forest_labs/common_utils.py +++ b/litellm/llms/black_forest_labs/common_utils.py @@ -46,9 +46,7 @@ def assert_bfl_polling_url(polling_url: str) -> None: message="Rejected polling URL: scheme must be https", ) - if host != _BFL_REGISTERED_DOMAIN and not host.endswith( - "." + _BFL_REGISTERED_DOMAIN - ): + if host != _BFL_REGISTERED_DOMAIN and not host.endswith("." + _BFL_REGISTERED_DOMAIN): raise BlackForestLabsError( status_code=502, message="Rejected polling URL: host is not within the bfl.ai domain", diff --git a/litellm/llms/black_forest_labs/image_edit/transformation.py b/litellm/llms/black_forest_labs/image_edit/transformation.py index 309e00ade62c..a80ca491d741 100644 --- a/litellm/llms/black_forest_labs/image_edit/transformation.py +++ b/litellm/llms/black_forest_labs/image_edit/transformation.py @@ -134,9 +134,7 @@ def validate_environment( BFL uses x-key header for authentication. """ final_api_key: Optional[str] = ( - api_key - or get_secret_str("BFL_API_KEY") - or get_secret_str("BLACK_FOREST_LABS_API_KEY") + api_key or get_secret_str("BFL_API_KEY") or get_secret_str("BLACK_FOREST_LABS_API_KEY") ) if not final_api_key: @@ -171,8 +169,7 @@ def _get_model_endpoint(self, model: str) -> str: return IMAGE_EDIT_MODELS[model_name] raise ValueError( - f"Unknown BFL image edit model: {model_name}. " - f"Supported models: {list(IMAGE_EDIT_MODELS.keys())}" + f"Unknown BFL image edit model: {model_name}. Supported models: {list(IMAGE_EDIT_MODELS.keys())}" ) def get_complete_url( @@ -205,9 +202,7 @@ def _read_image_bytes( return image elif isinstance(image, list): # If it's a list, take the first image - return self._read_image_bytes( - image[0], depth=depth + 1, max_depth=max_depth - ) + return self._read_image_bytes(image[0], depth=depth + 1, max_depth=max_depth) elif isinstance(image, str): if image.startswith(("http://", "https://")): response = safe_get(litellm.module_level_client, image, timeout=60.0) @@ -229,8 +224,7 @@ def _read_image_bytes( return data else: raise ValueError( - f"Unsupported image type: {type(image)}. " - "Expected bytes, str (URL or file path), or file-like object." + f"Unsupported image type: {type(image)}. Expected bytes, str (URL or file path), or file-like object." ) def transform_image_edit_request( diff --git a/litellm/llms/black_forest_labs/image_generation/transformation.py b/litellm/llms/black_forest_labs/image_generation/transformation.py index 18c7c173300f..7176247b4beb 100644 --- a/litellm/llms/black_forest_labs/image_generation/transformation.py +++ b/litellm/llms/black_forest_labs/image_generation/transformation.py @@ -50,9 +50,7 @@ class BlackForestLabsImageGenerationConfig(BaseImageGenerationConfig): This class only handles data transformation. """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Return list of OpenAI params supported by Black Forest Labs. @@ -136,9 +134,7 @@ def _map_size_param(self, size: str, optional_params: dict) -> None: optional_params["width"] = width optional_params["height"] = height except ValueError: - raise ValueError( - f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024')." - ) + raise ValueError(f"Invalid size format: '{size}'. Expected format 'WIDTHxHEIGHT' (e.g., '1024x1024').") def validate_environment( self, @@ -156,9 +152,7 @@ def validate_environment( BFL uses x-key header for authentication. """ final_api_key: Optional[str] = ( - api_key - or get_secret_str("BFL_API_KEY") - or get_secret_str("BLACK_FOREST_LABS_API_KEY") + api_key or get_secret_str("BFL_API_KEY") or get_secret_str("BLACK_FOREST_LABS_API_KEY") ) if not final_api_key: diff --git a/litellm/llms/brave/search/transformation.py b/litellm/llms/brave/search/transformation.py index 8ffe7dcb1263..54fb574087cf 100644 --- a/litellm/llms/brave/search/transformation.py +++ b/litellm/llms/brave/search/transformation.py @@ -124,9 +124,7 @@ def validate_environment( ) if not api_key: - raise ValueError( - "BRAVE_API_KEY is not set. Set `BRAVE_API_KEY` environment variable." - ) + raise ValueError("BRAVE_API_KEY is not set. Set `BRAVE_API_KEY` environment variable.") headers["X-Subscription-Token"] = api_key headers["Accept"] = "application/json" @@ -197,10 +195,7 @@ def transform_search_request( # Only include "include_fetch_metadata" if it is not explicitly set to False # This parameter results (more often than not) in a timestamp which we can use for last_updated - if ( - "include_fetch_metadata" in optional_params - and optional_params["include_fetch_metadata"] is False - ): + if "include_fetch_metadata" in optional_params and optional_params["include_fetch_metadata"] is False: request_data["include_fetch_metadata"] = False else: request_data["include_fetch_metadata"] = True @@ -215,19 +210,14 @@ def transform_search_request( # Convert to multiple "site:domain" clauses, joined by OR domains = optional_params["search_domain_filter"] if isinstance(domains, list) and len(domains) > 0: - request_data["q"] = self._append_domain_filters( - request_data["q"], domains - ) + request_data["q"] = self._append_domain_filters(request_data["q"], domains) # Convert to dict before dynamic key assignments result_data = dict(request_data) # Pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # Store params in special key for URL building (Brave Search API uses GET not POST) @@ -277,9 +267,7 @@ def transform_search_response( url = result.get("url", "") snippet = result.get("description", "") date = to_yyyy_mm_dd(result.get("page_age") or result.get("age")) - last_updated = to_yyyy_mm_dd( - result.get("fetched_content_timestamp", "") - ) + last_updated = to_yyyy_mm_dd(result.get("fetched_content_timestamp", "")) search_result = SearchResult( title=title, diff --git a/litellm/llms/bytez/chat/transformation.py b/litellm/llms/bytez/chat/transformation.py index 7d9afe01fa6f..e5d91c6533f2 100644 --- a/litellm/llms/bytez/chat/transformation.py +++ b/litellm/llms/bytez/chat/transformation.py @@ -132,9 +132,7 @@ def validate_environment( ) if not messages: - raise Exception( - "kwarg `messages` must be an array of messages that follow the openai chat standard" - ) + raise Exception("kwarg `messages` must be an array of messages that follow the openai chat standard") if not api_key: raise Exception("Missing api_key, make sure you pass in your api key") @@ -273,9 +271,7 @@ def get_sync_custom_stream_wrapper( timeout=STREAMING_TIMEOUT, ) except httpx.HTTPStatusError as e: - raise BytezError( - status_code=e.response.status_code, message=e.response.text - ) + raise BytezError(status_code=e.response.status_code, message=e.response.text) if response.status_code != 200: raise BytezError(status_code=response.status_code, message=response.text) @@ -317,9 +313,7 @@ async def get_async_custom_stream_wrapper( timeout=STREAMING_TIMEOUT, ) except httpx.HTTPStatusError as e: - raise BytezError( - status_code=e.response.status_code, message=e.response.text - ) + raise BytezError(status_code=e.response.status_code, message=e.response.text) if response.status_code != 200: raise BytezError(status_code=response.status_code, message=response.text) @@ -447,9 +441,7 @@ def _adapt_string_only_content_to_lists(messages: List[Dict]): elif isinstance(content_item, dict): new_content_items.append(content_item) else: - raise Exception( - "`content` can only contain strings or openai content dicts" - ) + raise Exception("`content` can only contain strings or openai content dicts") new_content += new_content_items else: diff --git a/litellm/llms/chatgpt/authenticator.py b/litellm/llms/chatgpt/authenticator.py index e35b04a3fb38..277bcfa18d0c 100644 --- a/litellm/llms/chatgpt/authenticator.py +++ b/litellm/llms/chatgpt/authenticator.py @@ -34,17 +34,11 @@ def __init__(self) -> None: "CHATGPT_TOKEN_DIR", os.path.expanduser("~/.config/litellm/chatgpt"), ) - self.auth_file = os.path.join( - self.token_dir, os.getenv("CHATGPT_AUTH_FILE", "auth.json") - ) + self.auth_file = os.path.join(self.token_dir, os.getenv("CHATGPT_AUTH_FILE", "auth.json")) self._ensure_token_dir() def get_api_base(self) -> str: - return ( - os.getenv("CHATGPT_API_BASE") - or os.getenv("OPENAI_CHATGPT_API_BASE") - or CHATGPT_API_BASE - ) + return os.getenv("CHATGPT_API_BASE") or os.getenv("OPENAI_CHATGPT_API_BASE") or CHATGPT_API_BASE def get_access_token(self) -> str: auth_data = self._read_auth_file() @@ -58,9 +52,7 @@ def get_access_token(self) -> str: refreshed = self._refresh_tokens(refresh_token) return refreshed["access_token"] except RefreshAccessTokenError as exc: - verbose_logger.warning( - "ChatGPT refresh token failed, re-login required: %s", exc - ) + verbose_logger.warning("ChatGPT refresh token failed, re-login required: %s", exc) cooldown_remaining = self._get_device_code_cooldown_remaining(auth_data) if cooldown_remaining > 0: @@ -149,9 +141,7 @@ def _extract_account_id(self, token: Optional[str]) -> Optional[str]: return None def _login_device_code(self) -> Dict[str, str]: - cooldown_remaining = self._get_device_code_cooldown_remaining( - self._read_auth_file() - ) + cooldown_remaining = self._get_device_code_cooldown_remaining(self._read_auth_file()) if cooldown_remaining > 0: token = self._wait_for_access_token(cooldown_remaining) if token: @@ -206,9 +196,7 @@ def _request_device_code(self) -> Dict[str, str]: "interval": str(interval or "5"), } - def _poll_for_authorization_code( - self, device_code: Dict[str, str] - ) -> Dict[str, str]: + def _poll_for_authorization_code(self, device_code: Dict[str, str]) -> Dict[str, str]: client = _get_httpx_client() interval = int(device_code.get("interval", "5")) start_time = time.time() @@ -286,9 +274,7 @@ def _exchange_code_for_tokens(self, code_data: Dict[str, str]) -> Dict[str, str] status_code=400, ) - if not all( - key in data for key in ("access_token", "refresh_token", "id_token") - ): + if not all(key in data for key in ("access_token", "refresh_token", "id_token")): raise GetAccessTokenError( message=f"Token exchange response missing fields: {data}", status_code=400, @@ -354,9 +340,7 @@ def _build_auth_record(self, tokens: Dict[str, str]) -> Dict[str, Any]: "account_id": account_id, } - def _get_device_code_cooldown_remaining( - self, auth_data: Optional[Dict[str, Any]] - ) -> float: + def _get_device_code_cooldown_remaining(self, auth_data: Optional[Dict[str, Any]]) -> float: if not auth_data: return 0.0 requested_at = auth_data.get("device_code_requested_at") @@ -383,9 +367,7 @@ def _wait_for_access_token(self, timeout_seconds: float) -> Optional[str]: access_token = auth_data.get("access_token") if access_token and not self._is_token_expired(auth_data, access_token): return access_token - sleep_for = min( - DEVICE_CODE_POLL_SLEEP_SECONDS, max(0.0, deadline - time.time()) - ) + sleep_for = min(DEVICE_CODE_POLL_SLEEP_SECONDS, max(0.0, deadline - time.time())) if sleep_for <= 0: break time.sleep(sleep_for) diff --git a/litellm/llms/chatgpt/chat/streaming_utils.py b/litellm/llms/chatgpt/chat/streaming_utils.py index a08fecd96251..3232b452a37c 100644 --- a/litellm/llms/chatgpt/chat/streaming_utils.py +++ b/litellm/llms/chatgpt/chat/streaming_utils.py @@ -24,9 +24,7 @@ def __init__(self, stream: Any): self._stream = stream self._seen_ids: Dict[str, int] = {} # tool_call_id -> assigned_index self._next_index: int = 0 - self._last_id: Optional[str] = ( - None # tracks which tool call the next delta belongs to - ) + self._last_id: Optional[str] = None # tracks which tool call the next delta belongs to def __getattr__(self, name: str) -> Any: return getattr(self._stream, name) diff --git a/litellm/llms/chatgpt/chat/transformation.py b/litellm/llms/chatgpt/chat/transformation.py index e6480398c7e4..9b0d8dc2e653 100644 --- a/litellm/llms/chatgpt/chat/transformation.py +++ b/litellm/llms/chatgpt/chat/transformation.py @@ -57,9 +57,7 @@ def validate_environment( account_id = self.authenticator.get_account_id() session_id = ensure_chatgpt_session_id(litellm_params) - default_headers = get_chatgpt_default_headers( - api_key or "", account_id, session_id - ) + default_headers = get_chatgpt_default_headers(api_key or "", account_id, session_id) return {**default_headers, **validated_headers} def post_stream_processing(self, stream: Any) -> Any: @@ -72,8 +70,6 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - optional_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + optional_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) optional_params.setdefault("stream", False) return optional_params diff --git a/litellm/llms/chatgpt/common_utils.py b/litellm/llms/chatgpt/common_utils.py index 830414d9cadb..8afef4b3828b 100644 --- a/litellm/llms/chatgpt/common_utils.py +++ b/litellm/llms/chatgpt/common_utils.py @@ -161,11 +161,7 @@ def _terminal_user_agent() -> str: token = f"WezTerm/{wezterm_version}" if wezterm_version else "WezTerm" return _sanitize_user_agent_token(token) or "WezTerm" - if ( - os.getenv("ITERM_SESSION_ID") - or os.getenv("ITERM_PROFILE") - or os.getenv("ITERM_PROFILE_NAME") - ): + if os.getenv("ITERM_SESSION_ID") or os.getenv("ITERM_PROFILE") or os.getenv("ITERM_PROFILE_NAME"): return "iTerm.app" if os.getenv("TERM_SESSION_ID"): @@ -225,9 +221,7 @@ def get_chatgpt_user_agent(originator: str) -> str: terminal_ua = _terminal_user_agent() suffix = os.getenv("CHATGPT_USER_AGENT_SUFFIX", "").strip() suffix = f" ({suffix})" if suffix else "" - candidate = ( - f"{originator}/{version} ({os_type} {os_version}; {arch}) {terminal_ua}{suffix}" - ) + candidate = f"{originator}/{version} ({os_type} {os_version}; {arch}) {terminal_ua}{suffix}" return _safe_header_value(candidate) or DEFAULT_USER_AGENT diff --git a/litellm/llms/chatgpt/responses/transformation.py b/litellm/llms/chatgpt/responses/transformation.py index 56b61b66c840..8b5fae4ef356 100644 --- a/litellm/llms/chatgpt/responses/transformation.py +++ b/litellm/llms/chatgpt/responses/transformation.py @@ -55,9 +55,7 @@ def validate_environment( account_id = self.authenticator.get_account_id() session_id = ensure_chatgpt_session_id(litellm_params) - default_headers = get_chatgpt_default_headers( - access_token, account_id, session_id - ) + default_headers = get_chatgpt_default_headers(access_token, account_id, session_id) return {**default_headers, **headers} def transform_responses_api_request( @@ -79,9 +77,7 @@ def transform_responses_api_request( existing_instructions = request.get("instructions") if existing_instructions: if base_instructions not in existing_instructions: - request["instructions"] = ( - f"{base_instructions}\n\n{existing_instructions}" - ) + request["instructions"] = f"{base_instructions}\n\n{existing_instructions}" else: request["instructions"] = base_instructions request["store"] = False @@ -114,9 +110,7 @@ def transform_response_api_response( logging_obj: Any, ): body_text = raw_response.text or "" - if not self._should_parse_as_sse( - raw_response=raw_response, body_text=body_text - ): + if not self._should_parse_as_sse(raw_response=raw_response, body_text=body_text): return super().transform_response_api_response( model=model, raw_response=raw_response, @@ -128,18 +122,14 @@ def transform_response_api_response( additional_args={"complete_input_dict": {}}, ) - completed_response, error_message = self._extract_completed_response_from_sse( - body_text=body_text - ) + completed_response, error_message = self._extract_completed_response_from_sse(body_text=body_text) if completed_response is None: raise OpenAIError( message=error_message or raw_response.text, status_code=raw_response.status_code, ) - self._attach_response_headers( - completed_response=completed_response, raw_response=raw_response - ) + self._attach_response_headers(completed_response=completed_response, raw_response=raw_response) return completed_response def _should_parse_as_sse(self, raw_response: Any, body_text: str) -> bool: @@ -213,22 +203,16 @@ def _build_completed_response_from_chunk( return None response_payload = dict(response_payload) if not response_payload.get("output") and streamed_output_items: - response_payload["output"] = [ - item for _, item in sorted(streamed_output_items.items()) - ] + response_payload["output"] = [item for _, item in sorted(streamed_output_items.items())] if "created_at" in response_payload: - response_payload["created_at"] = _safe_convert_created_field( - response_payload["created_at"] - ) + response_payload["created_at"] = _safe_convert_created_field(response_payload["created_at"]) try: return ResponsesAPIResponse(**response_payload) except Exception: return ResponsesAPIResponse.model_construct(**response_payload) def _extract_error_message(self, parsed_chunk: Dict[str, Any]) -> Optional[str]: - error_obj = parsed_chunk.get("error") or ( - parsed_chunk.get("response") or {} - ).get("error") + error_obj = parsed_chunk.get("error") or (parsed_chunk.get("response") or {}).get("error") if error_obj is None: return None if isinstance(error_obj, dict): diff --git a/litellm/llms/clarifai/chat/transformation.py b/litellm/llms/clarifai/chat/transformation.py index d07f6eba0576..95c0444924b3 100644 --- a/litellm/llms/clarifai/chat/transformation.py +++ b/litellm/llms/clarifai/chat/transformation.py @@ -71,13 +71,9 @@ def _get_openai_compatible_provider_info( dynamic_api_key = api_key or get_secret_str("CLARIFAI_API_KEY") or "" return api_base, dynamic_api_key - def transform_request( - self, model, messages, optional_params, litellm_params, headers - ): + def transform_request(self, model, messages, optional_params, litellm_params, headers): model = self.get_base_model(model) or model - return super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + return super().transform_request(model, messages, optional_params, litellm_params, headers) def transform_response( self, diff --git a/litellm/llms/cloudflare/chat/transformation.py b/litellm/llms/cloudflare/chat/transformation.py index 68f08741cc5c..df8ac884a32a 100644 --- a/litellm/llms/cloudflare/chat/transformation.py +++ b/litellm/llms/cloudflare/chat/transformation.py @@ -48,9 +48,7 @@ def get_complete_url( @staticmethod def _resolve_api_base(api_base: Optional[str]) -> str: if not api_base: - account_id = normalize_nonempty_secret_str( - get_secret_str("CLOUDFLARE_ACCOUNT_ID") - ) + account_id = normalize_nonempty_secret_str(get_secret_str("CLOUDFLARE_ACCOUNT_ID")) if account_id is None: raise ValueError( "Missing CLOUDFLARE_ACCOUNT_ID - set CLOUDFLARE_ACCOUNT_ID in the environment or pass api_base explicitly" diff --git a/litellm/llms/codestral/completion/handler.py b/litellm/llms/codestral/completion/handler.py index b149ae46ee91..6a91601e6fc5 100644 --- a/litellm/llms/codestral/completion/handler.py +++ b/litellm/llms/codestral/completion/handler.py @@ -42,12 +42,8 @@ def __init__( if response is not None: self.response = response else: - self.response = httpx.Response( - status_code=status_code, request=self.request - ) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + self.response = httpx.Response(status_code=status_code, request=self.request) + super().__init__(self.message) # Call the base class constructor with the parameters it needs async def make_call( @@ -62,9 +58,7 @@ async def make_call( response = await client.post(api_base, headers=headers, data=data, stream=True) if response.status_code != 200: - raise TextCompletionCodestralError( - status_code=response.status_code, message=response.text - ) + raise TextCompletionCodestralError(status_code=response.status_code, message=response.text) completion_stream = response.aiter_lines() # LOGGING @@ -88,9 +82,7 @@ def _validate_environment( user_headers: dict, ) -> dict: if api_key is None: - raise ValueError( - "Missing CODESTRAL_API_Key - Please add CODESTRAL_API_Key to your environment variables" - ) + raise ValueError("Missing CODESTRAL_API_Key - Please add CODESTRAL_API_Key to your environment variables") headers = { "content-type": "application/json", "Authorization": "Bearer {}".format(api_key), @@ -215,9 +207,7 @@ def completion( if optional_params.pop("custom_endpoint", None) is True: completion_url = api_base else: - completion_url = ( - api_base or "https://codestral.mistral.ai/v1/fim/completions" - ) + completion_url = api_base or "https://codestral.mistral.ai/v1/fim/completions" if model in custom_prompt_dict: # check if the model has a registered custom prompt @@ -358,9 +348,7 @@ async def async_completion( params={"timeout": timeout}, ) try: - response = await async_handler.post( - api_base, headers=headers, data=json.dumps(data) - ) + response = await async_handler.post(api_base, headers=headers, data=json.dumps(data)) except httpx.HTTPStatusError as e: raise TextCompletionCodestralError( status_code=e.response.status_code, diff --git a/litellm/llms/codestral/completion/transformation.py b/litellm/llms/codestral/completion/transformation.py index 31d6652f48a8..d4299ee2ebd1 100644 --- a/litellm/llms/codestral/completion/transformation.py +++ b/litellm/llms/codestral/completion/transformation.py @@ -83,9 +83,7 @@ def _chunk_parser(self, chunk_data: str) -> GenericStreamingChunk: finish_reason = None logprobs = None - chunk_data = ( - litellm.CustomStreamWrapper._strip_sse_data_from_chunk(chunk_data) or "" - ) + chunk_data = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(chunk_data) or "" chunk_data = chunk_data.strip() if len(chunk_data) == 0 or chunk_data == "[DONE]": return { diff --git a/litellm/llms/cohere/chat/transformation.py b/litellm/llms/cohere/chat/transformation.py index 5dd44aca80a9..10eea9493901 100644 --- a/litellm/llms/cohere/chat/transformation.py +++ b/litellm/llms/cohere/chat/transformation.py @@ -232,9 +232,7 @@ def transform_response( raw_response_json = raw_response.json() model_response.choices[0].message.content = raw_response_json["text"] # type: ignore except Exception: - raise CohereError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise CohereError(message=raw_response.text, status_code=raw_response.status_code) ## ADD CITATIONS if "citations" in raw_response_json: @@ -338,14 +336,8 @@ def _translate_openai_tool_to_cohere( "parameter_definitions": {}, } - for param_name, param_def in openai_tool["function"]["parameters"][ - "properties" - ].items(): - required_params = ( - openai_tool.get("function", {}) - .get("parameters", {}) - .get("required", []) - ) + for param_name, param_def in openai_tool["function"]["parameters"]["properties"].items(): + required_params = openai_tool.get("function", {}).get("parameters", {}).get("required", []) cohere_param_def = { "description": param_def.get("description", ""), "type": param_def.get("type", ""), diff --git a/litellm/llms/cohere/chat/v2_transformation.py b/litellm/llms/cohere/chat/v2_transformation.py index 9aa8c114907b..909130077e46 100644 --- a/litellm/llms/cohere/chat/v2_transformation.py +++ b/litellm/llms/cohere/chat/v2_transformation.py @@ -144,10 +144,7 @@ def map_openai_params( optional_params["stream"] = value if param == "temperature": optional_params["temperature"] = value - if ( - param == "max_tokens" - and "max_completion_tokens" not in non_default_params - ): + if param == "max_tokens" and "max_completion_tokens" not in non_default_params: optional_params["max_tokens"] = value if param == "max_completion_tokens": optional_params["max_tokens"] = value @@ -178,9 +175,7 @@ def transform_request( """ Cohere v2 chat api is in openai format, so we can use the openai transform request function to transform the request. """ - data = super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + data = super().transform_request(model, messages, optional_params, litellm_params, headers) return data @@ -201,9 +196,7 @@ def transform_response( try: raw_response_json = raw_response.json() except Exception: - raise CohereError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise CohereError(message=raw_response.text, status_code=raw_response.status_code) try: cohere_v2_chat_response = CohereV2ChatResponse(**raw_response_json) # type: ignore @@ -213,21 +206,14 @@ def transform_response( cohere_content = cohere_v2_chat_response["message"].get("content", None) if cohere_content is not None: model_response.choices[0].message.content = "".join( # type: ignore - [ - content.get("text", "") - for content in cohere_content - if content is not None - ] + [content.get("text", "") for content in cohere_content if content is not None] ) ## ADD CITATIONS AS ANNOTATIONS annotations: Optional[List[ChatCompletionAnnotation]] = None citations = None - if ( - "message" in cohere_v2_chat_response - and "citations" in cohere_v2_chat_response["message"] - ): + if "message" in cohere_v2_chat_response and "citations" in cohere_v2_chat_response["message"]: citations = cohere_v2_chat_response["message"]["citations"] if citations: @@ -304,9 +290,7 @@ def get_error_class( ) -> BaseLLMException: return CohereError(status_code=status_code, message=error_message) - def _translate_citations_to_openai_annotations( - self, citations: List[dict] - ) -> List[ChatCompletionAnnotation]: + def _translate_citations_to_openai_annotations(self, citations: List[dict]) -> List[ChatCompletionAnnotation]: """ Transform Cohere citations to OpenAI annotations format. diff --git a/litellm/llms/cohere/common_utils.py b/litellm/llms/cohere/common_utils.py index 05e3cec54446..c03061ba18f8 100644 --- a/litellm/llms/cohere/common_utils.py +++ b/litellm/llms/cohere/common_utils.py @@ -27,9 +27,7 @@ def get_provider_info( """ return None - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: """ Returns a list of models supported by this provider. """ @@ -118,9 +116,7 @@ def validate_environment( class ModelResponseIterator: - def __init__( - self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False - ): + def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False): self.streaming_response = streaming_response self.response_iterator = self.streaming_response self.content_blocks: List = [] @@ -221,9 +217,7 @@ async def __anext__(self): class CohereV2ModelResponseIterator: """V2-specific response iterator for Cohere streaming""" - def __init__( - self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False - ): + def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False): self.streaming_response = streaming_response self.response_iterator = self.streaming_response self.content_blocks: List = [] @@ -241,9 +235,7 @@ def _parse_content_delta(self, chunk: dict) -> str: return content return "" - def _parse_tool_call_delta( - self, chunk: dict - ) -> Optional[ChatCompletionToolCallChunk]: + def _parse_tool_call_delta(self, chunk: dict) -> Optional[ChatCompletionToolCallChunk]: """Parse tool-call-delta chunks to extract tool calls.""" delta = chunk.get("delta", {}) tool_calls = delta.get("tool_calls", []) @@ -285,9 +277,7 @@ def _parse_citation_start(self, chunk: dict) -> Optional[dict]: return {"citations": [citation_data]} return None - def _parse_message_end( - self, chunk: dict - ) -> Tuple[bool, str, Optional[ChatCompletionUsageBlock]]: + def _parse_message_end(self, chunk: dict) -> Tuple[bool, str, Optional[ChatCompletionUsageBlock]]: """Parse message-end events to extract finish info and usage.""" data = chunk.get("data", {}) delta = data.get("delta", {}) @@ -301,8 +291,7 @@ def _parse_message_end( usage = ChatCompletionUsageBlock( prompt_tokens=tokens_data.get("input_tokens", 0), completion_tokens=tokens_data.get("output_tokens", 0), - total_tokens=tokens_data.get("input_tokens", 0) - + tokens_data.get("output_tokens", 0), + total_tokens=tokens_data.get("input_tokens", 0) + tokens_data.get("output_tokens", 0), ) return is_finished, finish_reason, usage diff --git a/litellm/llms/cohere/embed/handler.py b/litellm/llms/cohere/embed/handler.py index 81b6a1c7aec8..bd2859fa3dcf 100644 --- a/litellm/llms/cohere/embed/handler.py +++ b/litellm/llms/cohere/embed/handler.py @@ -41,13 +41,9 @@ class CohereError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.cohere.ai/v1/generate" - ) + self.request = httpx.Request(method="POST", url="https://api.cohere.ai/v1/generate") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs async def async_embedding( @@ -153,11 +149,7 @@ def embedding( api_key=api_key, headers=headers, encoding=encoding, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), ) ## LOGGING diff --git a/litellm/llms/cohere/embed/transformation.py b/litellm/llms/cohere/embed/transformation.py index b5b350a952c9..3325e6be578b 100644 --- a/litellm/llms/cohere/embed/transformation.py +++ b/litellm/llms/cohere/embed/transformation.py @@ -122,9 +122,7 @@ def transform_embedding_request( optional_params: dict, headers: dict, ) -> dict: - if isinstance(input, list) and ( - isinstance(input[0], list) or isinstance(input[0], int) - ): + if isinstance(input, list) and (isinstance(input[0], list) or isinstance(input[0], int)): raise ValueError("Input must be a list of strings") return cast( dict, @@ -197,9 +195,7 @@ def _transform_response( output_data = [] for k, embedding_list in embeddings.items(): for idx, embedding in enumerate(embedding_list): - output_data.append( - {"object": "embedding", "index": idx, "embedding": embedding} - ) + output_data.append({"object": "embedding", "index": idx, "embedding": embedding}) model_response.object = "list" model_response.data = output_data model_response.model = model diff --git a/litellm/llms/cohere/embed/v1_transformation.py b/litellm/llms/cohere/embed/v1_transformation.py index 82c901e7eca6..3f0fcfc03ad3 100644 --- a/litellm/llms/cohere/embed/v1_transformation.py +++ b/litellm/llms/cohere/embed/v1_transformation.py @@ -27,9 +27,7 @@ def __init__(self) -> None: def get_supported_openai_params(self) -> List[str]: return ["encoding_format"] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: for k, v in non_default_params.items(): if k == "encoding_format": optional_params["embedding_types"] = v @@ -143,9 +141,7 @@ def _populate_embedding_response( """ embeddings = response_json["embeddings"] output_data = [] - is_embeddings_by_type = ( - response_json.get("response_type") == "embeddings_by_type" - ) + is_embeddings_by_type = response_json.get("response_type") == "embeddings_by_type" if isinstance(embeddings, dict): is_embeddings_by_type = True @@ -163,9 +159,7 @@ def _populate_embedding_response( ) else: for idx, embedding in enumerate(embeddings): - output_data.append( - {"object": "embedding", "index": idx, "embedding": embedding} - ) + output_data.append({"object": "embedding", "index": idx, "embedding": embedding}) model_response.object = "list" model_response.data = output_data model_response.model = model diff --git a/litellm/llms/cohere/rerank/guardrail_translation/handler.py b/litellm/llms/cohere/rerank/guardrail_translation/handler.py index 0824e1cca41c..36ca3895d4ac 100644 --- a/litellm/llms/cohere/rerank/guardrail_translation/handler.py +++ b/litellm/llms/cohere/rerank/guardrail_translation/handler.py @@ -58,15 +58,9 @@ async def process_input_messages( """ # Collect every scannable text field in a stable order so the # guardrailed results can be written back to the right key by index. - fields_to_scan = [ - (key, data[key]) - for key in self._SCANNED_FIELDS - if isinstance(data.get(key), str) - ] + fields_to_scan = [(key, data[key]) for key in self._SCANNED_FIELDS if isinstance(data.get(key), str)] if not fields_to_scan: - verbose_proxy_logger.debug( - "Rerank: No query/instruction to process or not strings" - ) + verbose_proxy_logger.debug("Rerank: No query/instruction to process or not strings") return data inputs = GenericGuardrailAPIInputs(texts=[value for _, value in fields_to_scan]) @@ -88,8 +82,7 @@ async def process_input_messages( if idx < len(guardrailed_texts): data[key] = guardrailed_texts[idx] verbose_proxy_logger.debug( - "Rerank: Applied guardrail to %s. " - "Original length: %d, New length: %d", + "Rerank: Applied guardrail to %s. Original length: %d, New length: %d", key, len(original), len(data[key]), @@ -122,7 +115,6 @@ async def process_output_response( Unmodified response (rankings don't need text guardrails) """ verbose_proxy_logger.debug( - "Rerank: Output processing not applicable " - "(output contains relevance scores, not text)" + "Rerank: Output processing not applicable (output contains relevance scores, not text)" ) return response diff --git a/litellm/llms/cohere/rerank/transformation.py b/litellm/llms/cohere/rerank/transformation.py index dd3f0f1a4462..e494e89fbf23 100644 --- a/litellm/llms/cohere/rerank/transformation.py +++ b/litellm/llms/cohere/rerank/transformation.py @@ -83,11 +83,7 @@ def validate_environment( optional_params: dict | None = None, ) -> dict: if api_key is None: - api_key = ( - get_secret_str("COHERE_API_KEY") - or get_secret_str("CO_API_KEY") - or litellm.cohere_key - ) + api_key = get_secret_str("COHERE_API_KEY") or get_secret_str("CO_API_KEY") or litellm.cohere_key if api_key is None: raise ValueError( @@ -148,9 +144,7 @@ def transform_rerank_response( try: raw_response_json = raw_response.json() except Exception: - raise CohereError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise CohereError(message=raw_response.text, status_code=raw_response.status_code) return RerankResponse(**raw_response_json) diff --git a/litellm/llms/cometapi/chat/transformation.py b/litellm/llms/cometapi/chat/transformation.py index 1e15ee188c61..1a0a3e88547f 100644 --- a/litellm/llms/cometapi/chat/transformation.py +++ b/litellm/llms/cometapi/chat/transformation.py @@ -36,9 +36,7 @@ def map_openai_params( """ Map OpenAI format parameters to CometAPI format """ - mapped_openai_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_openai_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) # CometAPI-specific parameters (if any) extra_body: dict[str, Any] = {} @@ -63,9 +61,7 @@ def remove_cache_control_flag_from_messages_and_tools( Remove cache control flags from messages and tools if not supported """ # For CometAPI, use default behavior (remove cache control) - return super().remove_cache_control_flag_from_messages_and_tools( - model, messages, tools - ) + return super().remove_cache_control_flag_from_messages_and_tools(model, messages, tools) def transform_request( self, @@ -82,9 +78,7 @@ def transform_request( dict: The transformed request. Sent as the body of the API call. """ extra_body = optional_params.pop("extra_body", {}) - response = super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + response = super().transform_request(model, messages, optional_params, litellm_params, headers) response.update(extra_body) return response @@ -169,9 +163,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: # Handle error in chunk if "error" in chunk: error_chunk = chunk["error"] - error_message = "CometAPI Error: {}".format( - error_chunk.get("message", "Unknown error") - ) + error_message = "CometAPI Error: {}".format(error_chunk.get("message", "Unknown error")) raise CometAPIException( message=error_message, status_code=error_chunk.get("code", 400), @@ -183,9 +175,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: for choice in chunk["choices"]: # Handle reasoning content if present if "delta" in choice and "reasoning" in choice["delta"]: - choice["delta"]["reasoning_content"] = choice["delta"].get( - "reasoning" - ) + choice["delta"]["reasoning_content"] = choice["delta"].get("reasoning") new_choices.append(choice) return ModelResponseStream( diff --git a/litellm/llms/cometapi/embed/transformation.py b/litellm/llms/cometapi/embed/transformation.py index d1972def8b78..2d481eb1bcb9 100644 --- a/litellm/llms/cometapi/embed/transformation.py +++ b/litellm/llms/cometapi/embed/transformation.py @@ -39,9 +39,7 @@ def get_complete_url( """ Get the complete URL for the CometAPI embedding endpoint. """ - api_base = ( - "https://api.cometapi.com/v1" if api_base is None else api_base.rstrip("/") - ) + api_base = "https://api.cometapi.com/v1" if api_base is None else api_base.rstrip("/") complete_url = f"{api_base}/embeddings" return complete_url @@ -152,6 +150,4 @@ def get_error_class( """ Get the appropriate error class for CometAPI exceptions. """ - return CometAPIException( - message=error_message, status_code=status_code, headers=headers - ) + return CometAPIException(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/cometapi/image_generation/cost_calculator.py b/litellm/llms/cometapi/image_generation/cost_calculator.py index 987e79e18dad..b10c9d090871 100644 --- a/litellm/llms/cometapi/image_generation/cost_calculator.py +++ b/litellm/llms/cometapi/image_generation/cost_calculator.py @@ -22,6 +22,4 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") diff --git a/litellm/llms/cometapi/image_generation/transformation.py b/litellm/llms/cometapi/image_generation/transformation.py index bc6bd3f3ecc1..e78b50b2fabe 100644 --- a/litellm/llms/cometapi/image_generation/transformation.py +++ b/litellm/llms/cometapi/image_generation/transformation.py @@ -24,9 +24,7 @@ class CometAPIImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://api.cometapi.com" IMAGE_GENERATION_ENDPOINT: str = "v1/images/generations" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ https://api.cometapi.com/v1/images/generations """ @@ -94,11 +92,7 @@ def validate_environment( api_key: Optional[str] = None, api_base: Optional[str] = None, ) -> dict: - final_api_key: Optional[str] = ( - api_key - or get_secret_str("COMETAPI_KEY") - or get_secret_str("COMETAPI_API_KEY") - ) + final_api_key: Optional[str] = api_key or get_secret_str("COMETAPI_KEY") or get_secret_str("COMETAPI_API_KEY") if not final_api_key: raise ValueError("COMETAPI_KEY or COMETAPI_API_KEY is not set") diff --git a/litellm/llms/compactifai/chat/transformation.py b/litellm/llms/compactifai/chat/transformation.py index d4b9c5a83aee..2dc1ade2f4ec 100644 --- a/litellm/llms/compactifai/chat/transformation.py +++ b/litellm/llms/compactifai/chat/transformation.py @@ -76,9 +76,7 @@ def transform_response( # Convert tool calls to content for JSON mode tool_calls = message.get("tool_calls", []) if len(tool_calls) == 1: - message["content"] = tool_calls[0]["function"].get( - "arguments", "" - ) + message["content"] = tool_calls[0]["function"].get("arguments", "") message["tool_calls"] = None returned_response = ModelResponse(**response_json) diff --git a/litellm/llms/custom_httpx/aiohttp_handler.py b/litellm/llms/custom_httpx/aiohttp_handler.py index 93b6c563dc1e..9726314409b3 100644 --- a/litellm/llms/custom_httpx/aiohttp_handler.py +++ b/litellm/llms/custom_httpx/aiohttp_handler.py @@ -40,19 +40,13 @@ def __init__( connector: Optional[aiohttp.BaseConnector] = None, ): self.client_session = client_session - self._owns_session = ( - client_session is None - ) # Track if we own the session for cleanup + self._owns_session = client_session is None # Track if we own the session for cleanup self.transport = transport - self._owns_transport = ( - transport is None - ) # Track if we own the transport for cleanup + self._owns_transport = transport is None # Track if we own the transport for cleanup self.connector = connector - self._owns_connector = ( - connector is None - ) # Track if we own the connector for cleanup + self._owns_connector = connector is None # Track if we own the connector for cleanup def _get_or_create_transport(self) -> Optional[LiteLLMAiohttpTransport]: """Get existing transport or create a new one if needed.""" @@ -99,9 +93,7 @@ def _create_client_session_with_transport(self) -> ClientSession: session = aiohttp.ClientSession() return session - def _get_async_client_session( - self, dynamic_client_session: Optional[ClientSession] = None - ) -> ClientSession: + def _get_async_client_session(self, dynamic_client_session: Optional[ClientSession] = None) -> ClientSession: if dynamic_client_session: return dynamic_client_session elif self.client_session: @@ -115,19 +107,11 @@ def _get_async_client_session( async def close(self): """Close the aiohttp client session and transport if we own them.""" # Close client session if we own it - if ( - self.client_session - and not self.client_session.closed - and self._owns_session - ): + if self.client_session and not self.client_session.closed and self._owns_session: await self.client_session.close() # Close transport if we own it - if ( - self.transport - and self._owns_transport - and hasattr(self.transport, "aclose") - ): + if self.transport and self._owns_transport and hasattr(self.transport, "aclose"): try: await self.transport.aclose() except Exception: @@ -141,11 +125,7 @@ def __del__(self): Provides defense-in-depth for issue #12443 - ensures cleanup happens even if atexit handler doesn't run (abnormal termination). """ - if ( - self.client_session is not None - and not self.client_session.closed - and self._owns_session - ): + if self.client_session is not None and not self.client_session.closed and self._owns_session: try: import asyncio @@ -182,14 +162,10 @@ async def _make_common_async_call( stream: bool = False, ) -> aiohttp.ClientResponse: """Common implementation across stream + non-stream calls. Meant to ensure consistent error-handling.""" - max_retry_on_unprocessable_entity_error = ( - provider_config.max_retry_on_unprocessable_entity_error - ) + max_retry_on_unprocessable_entity_error = provider_config.max_retry_on_unprocessable_entity_error response: Optional[aiohttp.ClientResponse] = None - async_client_session = self._get_async_client_session( - dynamic_client_session=async_client_session - ) + async_client_session = self._get_async_client_session(dynamic_client_session=async_client_session) for i in range(max(max_retry_on_unprocessable_entity_error, 1)): try: @@ -231,9 +207,7 @@ def _make_common_sync_call( content: Any = None, params: Optional[dict] = None, ) -> httpx.Response: - max_retry_on_unprocessable_entity_error = ( - provider_config.max_retry_on_unprocessable_entity_error - ) + max_retry_on_unprocessable_entity_error = provider_config.max_retry_on_unprocessable_entity_error response: Optional[httpx.Response] = None @@ -255,11 +229,7 @@ def _make_common_sync_call( e=e, litellm_params=litellm_params ) if should_retry and not hit_max_retry: - data = ( - provider_config.transform_request_on_unprocessable_entity_error( - e=e, request_data=data - ) - ) + data = provider_config.transform_request_on_unprocessable_entity_error(e=e, request_data=data) continue else: raise self._handle_error(e=e, provider_config=provider_config) @@ -341,9 +311,7 @@ def completion( model=model, provider=litellm.LlmProviders(custom_llm_provider) ) if provider_config is None: - raise ValueError( - f"Provider config not found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"Provider config not found for model: {model} and provider: {custom_llm_provider}") # get config from model, custom llm provider headers = provider_config.validate_environment( api_key=api_key, @@ -399,11 +367,7 @@ def completion( optional_params=optional_params, litellm_params=litellm_params, encoding=encoding, - client=( - client - if client is not None and isinstance(client, ClientSession) - else None - ), + client=(client if client is not None and isinstance(client, ClientSession) else None), ) if stream is True: @@ -419,11 +383,7 @@ def completion( logging_obj=logging_obj, timeout=timeout, fake_stream=fake_stream, - client=( - client - if client is not None and isinstance(client, HTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, HTTPHandler) else None), litellm_params=litellm_params, ) return CustomStreamWrapper( @@ -602,9 +562,7 @@ def image_variations( ) if provider_config is None: - raise ValueError( - f"image variation provider not found: {custom_llm_provider}." - ) + raise ValueError(f"image variation provider not found: {custom_llm_provider}.") api_base = provider_config.get_complete_url( api_base=api_base, diff --git a/litellm/llms/custom_httpx/aiohttp_transport.py b/litellm/llms/custom_httpx/aiohttp_transport.py index b97a59a93a6d..3172d3667e19 100644 --- a/litellm/llms/custom_httpx/aiohttp_transport.py +++ b/litellm/llms/custom_httpx/aiohttp_transport.py @@ -83,9 +83,7 @@ def __init__(self, aiohttp_response: ClientResponse) -> None: async def __aiter__(self) -> typing.AsyncIterator[bytes]: try: - async for chunk in self._aiohttp_response.content.iter_chunked( - self.CHUNK_SIZE - ): + async for chunk in self._aiohttp_response.content.iter_chunked(self.CHUNK_SIZE): yield chunk except ( aiohttp.ClientPayloadError, @@ -103,9 +101,7 @@ async def __aiter__(self) -> typing.AsyncIterator[bytes]: # with message "Connection closed.". Treat this as a graceful # end-of-stream so downstream consumers don't error. if "Connection closed" in str(e): - verbose_logger.debug( - "Upstream closed streaming connection; ending iterator gracefully" - ) + verbose_logger.debug("Upstream closed streaming connection; ending iterator gracefully") return raise except aiohttp.http_exceptions.TransferEncodingError as e: @@ -205,11 +201,7 @@ def _get_valid_client_session(self) -> ClientSession: current_loop = asyncio.get_running_loop() # If session is from a different or closed loop, recreate it - if ( - session_loop is None - or session_loop != current_loop - or session_loop.is_closed() - ): + if session_loop is None or session_loop != current_loop or session_loop.is_closed(): # Close old session to prevent leaks old_session = self.client try: @@ -218,9 +210,7 @@ def _get_valid_client_session(self) -> ClientSession: asyncio.create_task(old_session.close()) except RuntimeError: # Different event loop - can't schedule task, rely on GC - verbose_logger.debug( - "Old session from different loop, relying on GC" - ) + verbose_logger.debug("Old session from different loop, relying on GC") except Exception as e: verbose_logger.debug(f"Error closing old session: {e}") @@ -328,9 +318,7 @@ async def handle_async_request( except RuntimeError as e: # Handle the case where session was closed between our check and actual use if "Session is closed" in str(e): - verbose_logger.debug( - f"Session closed during request, retrying with new session: {e}" - ) + verbose_logger.debug(f"Session closed during request, retrying with new session: {e}") # Force creation of a new session if hasattr(self, "_client_factory") and callable(self._client_factory): self.client = self._client_factory() @@ -361,10 +349,7 @@ async def handle_async_request( async def _get_proxy_settings(self, request: httpx.Request): proxy = None - if not ( - litellm.disable_aiohttp_trust_env - or str_to_bool(os.getenv("DISABLE_AIOHTTP_TRUST_ENV", "False")) - ): + if not (litellm.disable_aiohttp_trust_env or str_to_bool(os.getenv("DISABLE_AIOHTTP_TRUST_ENV", "False"))): try: proxy = self._proxy_from_env(request.url) except Exception as e: # pragma: no cover - best effort diff --git a/litellm/llms/custom_httpx/async_client_cleanup.py b/litellm/llms/custom_httpx/async_client_cleanup.py index 9c1f6af7e9c5..8d1ddb960537 100644 --- a/litellm/llms/custom_httpx/async_client_cleanup.py +++ b/litellm/llms/custom_httpx/async_client_cleanup.py @@ -58,9 +58,7 @@ async def close_litellm_async_clients(): # This is used by Gemini and other providers that use aiohttp if hasattr(litellm, "base_llm_aiohttp_handler"): base_handler = getattr(litellm, "base_llm_aiohttp_handler", None) - if isinstance(base_handler, BaseLLMAIOHTTPHandler) and hasattr( - base_handler, "close" - ): + if isinstance(base_handler, BaseLLMAIOHTTPHandler) and hasattr(base_handler, "close"): try: await base_handler.close() except Exception: diff --git a/litellm/llms/custom_httpx/container_handler.py b/litellm/llms/custom_httpx/container_handler.py index 501390d840b2..7d6a25bc0903 100644 --- a/litellm/llms/custom_httpx/container_handler.py +++ b/litellm/llms/custom_httpx/container_handler.py @@ -209,9 +209,7 @@ def _sync_handle( # Get HTTP client if client is None or not isinstance(client, HTTPHandler): - http_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + http_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: http_client = client @@ -229,15 +227,11 @@ def _sync_handle( ) # Build URL with path params - path_params = { - p: kwargs.get(p, "") for p in endpoint_config.get("path_params", []) - } + path_params = {p: kwargs.get(p, "") for p in endpoint_config.get("path_params", [])} url = _build_url(api_base, endpoint_config["path"], path_params) # Build query params - query_params = _build_query_params( - endpoint_config.get("query_params", []), kwargs - ) + query_params = _build_query_params(endpoint_config.get("query_params", []), kwargs) if extra_query: query_params.update(extra_query) @@ -264,25 +258,15 @@ def _sync_handle( try: if method == "GET": - response = http_client.get( - url=url, headers=headers, params=effective_params - ) + response = http_client.get(url=url, headers=headers, params=effective_params) elif method == "DELETE": - response = http_client.delete( - url=url, headers=headers, params=effective_params - ) + response = http_client.delete(url=url, headers=headers, params=effective_params) elif method == "POST": if is_multipart and "file" in kwargs: - files, headers = _prepare_multipart_file_upload( - kwargs["file"], headers - ) - response = http_client.post( - url=url, headers=headers, params=effective_params, files=files - ) + files, headers = _prepare_multipart_file_upload(kwargs["file"], headers) + response = http_client.post(url=url, headers=headers, params=effective_params, files=files) else: - response = http_client.post( - url=url, headers=headers, params=effective_params - ) + response = http_client.post(url=url, headers=headers, params=effective_params) else: raise ValueError(f"Unsupported HTTP method: {method}") @@ -295,9 +279,7 @@ def _sync_handle( if "error" in response_json: from litellm.llms.base_llm.chat.transformation import BaseLLMException - error_msg = response_json.get("error", {}).get( - "message", str(response_json) - ) + error_msg = response_json.get("error", {}).get("message", str(response_json)) raise BaseLLMException( status_code=response.status_code, message=error_msg, @@ -353,15 +335,11 @@ async def _async_handle( ) # Build URL with path params - path_params = { - p: kwargs.get(p, "") for p in endpoint_config.get("path_params", []) - } + path_params = {p: kwargs.get(p, "") for p in endpoint_config.get("path_params", [])} url = _build_url(api_base, endpoint_config["path"], path_params) # Build query params - query_params = _build_query_params( - endpoint_config.get("query_params", []), kwargs - ) + query_params = _build_query_params(endpoint_config.get("query_params", []), kwargs) if extra_query: query_params.update(extra_query) @@ -388,25 +366,15 @@ async def _async_handle( try: if method == "GET": - response = await http_client.get( - url=url, headers=headers, params=effective_params - ) + response = await http_client.get(url=url, headers=headers, params=effective_params) elif method == "DELETE": - response = await http_client.delete( - url=url, headers=headers, params=effective_params - ) + response = await http_client.delete(url=url, headers=headers, params=effective_params) elif method == "POST": if is_multipart and "file" in kwargs: - files, headers = _prepare_multipart_file_upload( - kwargs["file"], headers - ) - response = await http_client.post( - url=url, headers=headers, params=effective_params, files=files - ) + files, headers = _prepare_multipart_file_upload(kwargs["file"], headers) + response = await http_client.post(url=url, headers=headers, params=effective_params, files=files) else: - response = await http_client.post( - url=url, headers=headers, params=effective_params - ) + response = await http_client.post(url=url, headers=headers, params=effective_params) else: raise ValueError(f"Unsupported HTTP method: {method}") @@ -419,9 +387,7 @@ async def _async_handle( if "error" in response_json: from litellm.llms.base_llm.chat.transformation import BaseLLMException - error_msg = response_json.get("error", {}).get( - "message", str(response_json) - ) + error_msg = response_json.get("error", {}).get("message", str(response_json)) raise BaseLLMException( status_code=response.status_code, message=error_msg, diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index 33601b476099..5cec763bb5d6 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -67,14 +67,10 @@ # aiohttp 3.10+ exposes a `socket_factory` kwarg on TCPConnector. Older # versions don't — detect once and skip the keep-alive wiring there. # https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.TCPConnector -_AIOHTTP_SUPPORTS_SOCKET_FACTORY = ( - "socket_factory" in inspect.signature(TCPConnector.__init__).parameters -) +_AIOHTTP_SUPPORTS_SOCKET_FACTORY = "socket_factory" in inspect.signature(TCPConnector.__init__).parameters -def _build_aiohttp_keepalive_socket_factory() -> Optional[ - Callable[[Tuple[Any, ...]], socket.socket] -]: +def _build_aiohttp_keepalive_socket_factory() -> Optional[Callable[[Tuple[Any, ...]], socket.socket]]: """ Build a socket_factory that enables SO_KEEPALIVE on aiohttp TCP sockets. @@ -97,17 +93,11 @@ def factory(addr_info: Tuple[Any, ...]) -> socket.socket: # Linux: TCP_KEEPIDLE is idle-before-first-probe. # macOS/Darwin: TCP_KEEPALIVE is the equivalent. if hasattr(socket, "TCP_KEEPIDLE"): - sock.setsockopt( - socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, AIOHTTP_TCP_KEEPIDLE - ) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, AIOHTTP_TCP_KEEPIDLE) elif hasattr(socket, "TCP_KEEPALIVE"): - sock.setsockopt( - socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, AIOHTTP_TCP_KEEPIDLE - ) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPALIVE, AIOHTTP_TCP_KEEPIDLE) if hasattr(socket, "TCP_KEEPINTVL"): - sock.setsockopt( - socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, AIOHTTP_TCP_KEEPINTVL - ) + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, AIOHTTP_TCP_KEEPINTVL) if hasattr(socket, "TCP_KEEPCNT"): sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, AIOHTTP_TCP_KEEPCNT) return sock @@ -144,9 +134,7 @@ def _default_cached_client_timeout() -> httpx.Timeout: configured = get_configured_request_timeout() if configured is None: return _DEFAULT_TIMEOUT - return httpx.Timeout( - timeout=configured, connect=HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS - ) + return httpx.Timeout(timeout=configured, connect=HTTP_HANDLER_CONNECT_TIMEOUT_SECONDS) _STREAMING_ERROR_BODY_READ_TIMEOUT_SECONDS = 5.0 @@ -199,9 +187,7 @@ def _prepare_request_data_and_content( # Cache for SSL contexts to avoid creating duplicate contexts with the same configuration # Key: tuple of (cafile, ssl_security_level, ssl_ecdh_curve) # Value: ssl.SSLContext -_ssl_context_cache: Dict[ - Tuple[Optional[str], Optional[str], Optional[str]], ssl.SSLContext -] = {} +_ssl_context_cache: Dict[Tuple[Optional[str], Optional[str], Optional[str]], ssl.SSLContext] = {} def _create_ssl_context( @@ -388,11 +374,7 @@ def mask_sensitive_info(error_message): masked_message = error_message[: key_index + 4] + "[REDACTED_API_KEY]" else: # Replace the key with redacted value, keeping other parameters - masked_message = ( - error_message[: key_index + 4] - + "[REDACTED_API_KEY]" - + error_message[next_param:] - ) + masked_message = error_message[: key_index + 4] + "[REDACTED_API_KEY]" + error_message[next_param:] return masked_message @@ -407,9 +389,7 @@ def _safe_get_response_text(response: httpx.Response) -> str: return "" -async def _safe_aread_response( - response: httpx.Response, timeout: Optional[float] = None -) -> bytes: +async def _safe_aread_response(response: httpx.Response, timeout: Optional[float] = None) -> bytes: """Safely read async response body, falling back to empty bytes on errors.""" try: if timeout is not None: @@ -419,9 +399,7 @@ async def _safe_aread_response( return b"" -def _safe_read_response( - response: httpx.Response, timeout: Optional[float] = None -) -> bytes: +def _safe_read_response(response: httpx.Response, timeout: Optional[float] = None) -> bytes: """Safely read sync response body, falling back to empty bytes on errors.""" try: if timeout is not None: @@ -477,9 +455,7 @@ async def _raise_masked_async_error(e: httpx.HTTPStatusError, stream: bool) -> N class MaskedHTTPStatusError(httpx.HTTPStatusError): - def __init__( - self, original_error, message: Optional[str] = None, text: Optional[str] = None - ): + def __init__(self, original_error, message: Optional[str] = None, text: Optional[str] = None): # Create a new error with the masked URL masked_url = mask_sensitive_info(str(original_error.request.url)) # Mask the original exception message too (it contains the full URL) @@ -607,9 +583,7 @@ async def get( timeout: Optional[Union[float, httpx.Timeout]] = None, ): # Set follow_redirects to UseClientDefault if None - _follow_redirects = ( - follow_redirects if follow_redirects is not None else USE_CLIENT_DEFAULT - ) + _follow_redirects = follow_redirects if follow_redirects is not None else USE_CLIENT_DEFAULT params = params or {} params.update(HTTPHandler.extract_query_params(url)) @@ -643,9 +617,7 @@ async def post( timeout = self.timeout # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) req = self.client.build_request( "POST", @@ -663,9 +635,7 @@ async def post( return response except (httpx.RemoteProtocolError, httpx.ConnectError): # Retry the request with a new session if there is a connection error - new_client = self.create_client( - timeout=timeout, event_hooks=self.event_hooks - ) + new_client = self.create_client(timeout=timeout, event_hooks=self.event_hooks) try: return await self.single_connection_post_request( url=url, @@ -714,9 +684,7 @@ async def put( timeout = self.timeout # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) req = self.client.build_request( "PUT", @@ -733,9 +701,7 @@ async def put( return response except (httpx.RemoteProtocolError, httpx.ConnectError): # Retry the request with a new session if there is a connection error - new_client = self.create_client( - timeout=timeout, event_hooks=self.event_hooks - ) + new_client = self.create_client(timeout=timeout, event_hooks=self.event_hooks) try: return await self.single_connection_post_request( url=url, @@ -782,9 +748,7 @@ async def patch( timeout = self.timeout # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) req = self.client.build_request( "PATCH", @@ -801,9 +765,7 @@ async def patch( return response except (httpx.RemoteProtocolError, httpx.ConnectError): # Retry the request with a new session if there is a connection error - new_client = self.create_client( - timeout=timeout, event_hooks=self.event_hooks - ) + new_client = self.create_client(timeout=timeout, event_hooks=self.event_hooks) try: return await self.single_connection_post_request( url=url, @@ -850,9 +812,7 @@ async def delete( timeout = self.timeout # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) req = self.client.build_request( "DELETE", @@ -869,9 +829,7 @@ async def delete( return response except (httpx.RemoteProtocolError, httpx.ConnectError): # Retry the request with a new session if there is a connection error - new_client = self.create_client( - timeout=timeout, event_hooks=self.event_hooks - ) + new_client = self.create_client(timeout=timeout, event_hooks=self.event_hooks) try: return await self.single_connection_post_request( url=url, @@ -1034,9 +992,7 @@ def _create_aiohttp_transport( from litellm.llms.custom_httpx.aiohttp_transport import LiteLLMAiohttpTransport from litellm.secret_managers.main import str_to_bool - connector_kwargs = AsyncHTTPHandler._get_ssl_connector_kwargs( - ssl_verify=ssl_verify, ssl_context=ssl_context - ) + connector_kwargs = AsyncHTTPHandler._get_ssl_connector_kwargs(ssl_verify=ssl_verify, ssl_context=ssl_context) ######################################################### # Check if user enabled aiohttp trust env # use for HTTP_PROXY, HTTPS_PROXY, etc. @@ -1059,9 +1015,7 @@ def _create_aiohttp_transport( # Use shared session if provided and valid if shared_session is not None and not shared_session.closed: - verbose_logger.debug( - f"SHARED SESSION: Reusing existing ClientSession (ID: {id(shared_session)})" - ) + verbose_logger.debug(f"SHARED SESSION: Reusing existing ClientSession (ID: {id(shared_session)})") return LiteLLMAiohttpTransport( client=shared_session, ssl_verify=ssl_for_transport, @@ -1069,9 +1023,7 @@ def _create_aiohttp_transport( ) # Create new session only if none provided or existing one is invalid - verbose_logger.debug( - "NEW SESSION: Creating new ClientSession (no shared session provided)" - ) + verbose_logger.debug("NEW SESSION: Creating new ClientSession (no shared session provided)") transport_connector_kwargs = { "keepalive_timeout": AIOHTTP_KEEPALIVE_TIMEOUT, "ttl_dns_cache": AIOHTTP_TTL_DNS_CACHE, @@ -1082,9 +1034,7 @@ def _create_aiohttp_transport( if AIOHTTP_CONNECTOR_LIMIT > 0: transport_connector_kwargs["limit"] = AIOHTTP_CONNECTOR_LIMIT if AIOHTTP_CONNECTOR_LIMIT_PER_HOST > 0: - transport_connector_kwargs["limit_per_host"] = ( - AIOHTTP_CONNECTOR_LIMIT_PER_HOST - ) + transport_connector_kwargs["limit_per_host"] = AIOHTTP_CONNECTOR_LIMIT_PER_HOST # Returns None when SO_KEEPALIVE is disabled or aiohttp is too old to # accept socket_factory — version detection lives inside the builder. socket_factory = _build_aiohttp_keepalive_socket_factory() @@ -1165,9 +1115,7 @@ def get( timeout: Optional[Union[float, httpx.Timeout]] = None, ): # Set follow_redirects to UseClientDefault if None - _follow_redirects = ( - follow_redirects if follow_redirects is not None else USE_CLIENT_DEFAULT - ) + _follow_redirects = follow_redirects if follow_redirects is not None else USE_CLIENT_DEFAULT params = params or {} params.update(self.extract_query_params(url)) @@ -1209,9 +1157,7 @@ def post( ): try: # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) if timeout is not None: req = self.client.build_request( @@ -1263,9 +1209,7 @@ def patch( ): try: # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) if timeout is not None: req = self.client.build_request( @@ -1315,9 +1259,7 @@ def put( ): try: # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) if timeout is not None: req = self.client.build_request( @@ -1366,9 +1308,7 @@ def delete( ): try: # Prepare data/content parameters to prevent httpx DeprecationWarning (memory leak fix) - request_data, request_content = _prepare_request_data_and_content( - data, content - ) + request_data, request_content = _prepare_request_data_and_content(data, content) if timeout is not None: req = self.client.build_request( @@ -1460,9 +1400,7 @@ def get_async_httpx_client( if params is not None: # Filter out params that are only used for cache key, not for AsyncHTTPHandler.__init__ - handler_params = { - k: v for k, v in params.items() if k != "disable_aiohttp_transport" - } + handler_params = {k: v for k, v in params.items() if k != "disable_aiohttp_transport"} handler_params["shared_session"] = shared_session _new_client = AsyncHTTPHandler(**handler_params) else: @@ -1511,9 +1449,7 @@ def _get_httpx_client(params: Optional[dict] = None) -> HTTPHandler: if params is not None: # Filter out params that are only used for cache key, not for HTTPHandler.__init__ - handler_params = { - k: v for k, v in params.items() if k != "disable_aiohttp_transport" - } + handler_params = {k: v for k, v in params.items() if k != "disable_aiohttp_transport"} _new_client = HTTPHandler(**handler_params) else: _new_client = HTTPHandler(timeout=_default_cached_client_timeout()) diff --git a/litellm/llms/custom_httpx/httpx_handler.py b/litellm/llms/custom_httpx/httpx_handler.py index 6e9f29151cd2..a66d30c9007d 100644 --- a/litellm/llms/custom_httpx/httpx_handler.py +++ b/litellm/llms/custom_httpx/httpx_handler.py @@ -39,9 +39,7 @@ async def close(self): # Close the client when you're done with it await self.client.aclose() - async def get( - self, url: str, params: Optional[dict] = None, headers: Optional[dict] = None - ): + async def get(self, url: str, params: Optional[dict] = None, headers: Optional[dict] = None): response = await self.client.get(url, params=params, headers=headers) return response diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index d33ec295e94c..d8f4856b4ad7 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -177,9 +177,7 @@ def _google_genai_streaming_hidden_params( """Pre-stream metadata for proxy response headers (mirrors CustomStreamWrapper._hidden_params).""" from litellm.litellm_core_utils.core_helpers import process_response_headers - _model_info: Dict[str, Any] = dict( - getattr(litellm_params, "model_info", None) or {} - ) + _model_info: Dict[str, Any] = dict(getattr(litellm_params, "model_info", None) or {}) _raw_id = _model_info.get("id") or logging_obj.get_router_model_id() or "" _model_id = _raw_id if isinstance(_raw_id, str) else str(_raw_id) return { @@ -225,9 +223,7 @@ def _has_pre_call_deployment_hook(logging_obj: Any) -> bool: base_func = CustomLogger.async_pre_call_deployment_hook for cb in _custom_logger_callbacks(logging_obj): cb_func = getattr(type(cb), "async_pre_call_deployment_hook", base_func) - if getattr(cb_func, "__func__", cb_func) is not getattr( - base_func, "__func__", base_func - ): + if getattr(cb_func, "__func__", cb_func) is not getattr(base_func, "__func__", base_func): return True return False @@ -247,9 +243,7 @@ async def _make_common_async_call( signed_json_body: Optional[bytes] = None, ) -> httpx.Response: """Common implementation across stream + non-stream calls. Meant to ensure consistent error-handling.""" - max_retry_on_unprocessable_entity_error = ( - provider_config.max_retry_on_unprocessable_entity_error - ) + max_retry_on_unprocessable_entity_error = provider_config.max_retry_on_unprocessable_entity_error response: Optional[httpx.Response] = None for i in range(max(max_retry_on_unprocessable_entity_error, 1)): @@ -257,11 +251,7 @@ async def _make_common_async_call( response = await async_httpx_client.post( url=api_base, headers=headers, - data=( - signed_json_body - if signed_json_body is not None - else json.dumps(data) - ), + data=(signed_json_body if signed_json_body is not None else json.dumps(data)), timeout=timeout, stream=stream, logging_obj=logging_obj, @@ -272,11 +262,7 @@ async def _make_common_async_call( e=e, litellm_params=litellm_params ) if should_retry and not hit_max_retry: - data = ( - provider_config.transform_request_on_unprocessable_entity_error( - e=e, request_data=data - ) - ) + data = provider_config.transform_request_on_unprocessable_entity_error(e=e, request_data=data) continue else: raise self._handle_error(e=e, provider_config=provider_config) @@ -306,9 +292,7 @@ def _make_common_sync_call( stream: bool = False, signed_json_body: Optional[bytes] = None, ) -> httpx.Response: - max_retry_on_unprocessable_entity_error = ( - provider_config.max_retry_on_unprocessable_entity_error - ) + max_retry_on_unprocessable_entity_error = provider_config.max_retry_on_unprocessable_entity_error response: Optional[httpx.Response] = None @@ -317,11 +301,7 @@ def _make_common_sync_call( response = sync_httpx_client.post( url=api_base, headers=headers, - data=( - signed_json_body - if signed_json_body is not None - else json.dumps(data) - ), + data=(signed_json_body if signed_json_body is not None else json.dumps(data)), timeout=timeout, stream=stream, logging_obj=logging_obj, @@ -332,11 +312,7 @@ def _make_common_sync_call( e=e, litellm_params=litellm_params ) if should_retry and not hit_max_retry: - data = ( - provider_config.transform_request_on_unprocessable_entity_error( - e=e, request_data=data - ) - ) + data = provider_config.transform_request_on_unprocessable_entity_error(e=e, request_data=data) continue else: raise self._handle_error(e=e, provider_config=provider_config) @@ -450,23 +426,16 @@ def completion( json_mode: bool = optional_params.pop("json_mode", False) extra_body: Optional[dict] = optional_params.pop("extra_body", None) - provider_config = ( - provider_config - or ProviderConfigManager.get_provider_chat_config( - model=model, provider=litellm.LlmProviders(custom_llm_provider) - ) + provider_config = provider_config or ProviderConfigManager.get_provider_chat_config( + model=model, provider=litellm.LlmProviders(custom_llm_provider) ) if provider_config is None: - raise ValueError( - f"Provider config not found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"Provider config not found for model: {model} and provider: {custom_llm_provider}") fake_stream = ( fake_stream or optional_params.pop("fake_stream", False) - or provider_config.should_fake_stream( - model=model, custom_llm_provider=custom_llm_provider, stream=stream - ) + or provider_config.should_fake_stream(model=model, custom_llm_provider=custom_llm_provider, stream=stream) ) # get config from model, custom llm provider @@ -525,9 +494,7 @@ def completion( # Check if stream was converted for WebSearch interception # This is set by the async_pre_request_hook in WebSearchInterceptionLogger if litellm_params.get("_websearch_interception_converted_stream", False): - logging_obj.model_call_details[ - "websearch_interception_converted_stream" - ] = True + logging_obj.model_call_details["websearch_interception_converted_stream"] = True if acompletion is True: if stream is True: @@ -547,11 +514,7 @@ def completion( logging_obj=logging_obj, data=data, fake_stream=fake_stream, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), litellm_params=litellm_params, json_mode=json_mode, optional_params=optional_params, @@ -574,11 +537,7 @@ def completion( optional_params=optional_params, litellm_params=litellm_params, encoding=encoding, - client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), json_mode=json_mode, signed_json_body=signed_json_body, shared_session=shared_session, @@ -615,11 +574,7 @@ def completion( logging_obj=logging_obj, timeout=timeout, fake_stream=fake_stream, - client=( - client - if client is not None and isinstance(client, HTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, HTTPHandler) else None), litellm_params=litellm_params, json_mode=json_mode, optional_params=optional_params, @@ -720,9 +675,7 @@ def make_sync_call( json_mode=json_mode, ) - completion_stream: Any = MockResponseIterator( - model_response=model_response, json_mode=json_mode - ) + completion_stream: Any = MockResponseIterator(model_response=model_response, json_mode=json_mode) else: completion_stream = provider_config.get_model_response_iterator( streaming_response=response.iter_lines(), @@ -858,9 +811,7 @@ async def make_async_call_stream_helper( json_mode=json_mode, ) - completion_stream: Any = MockResponseIterator( - model_response=model_response, json_mode=json_mode - ) + completion_stream: Any = MockResponseIterator(model_response=model_response, json_mode=json_mode) else: completion_stream = provider_config.get_model_response_iterator( streaming_response=response.aiter_lines(), sync_stream=False @@ -916,9 +867,7 @@ def embedding( model=model, provider=litellm.LlmProviders(custom_llm_provider) ) if provider_config is None: - raise ValueError( - f"Provider {custom_llm_provider} does not support embedding" - ) + raise ValueError(f"Provider {custom_llm_provider} does not support embedding") # get config from model, custom llm provider headers = provider_config.validate_environment( api_key=api_key, @@ -986,9 +935,7 @@ def embedding( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -1183,9 +1130,7 @@ async def arerank( client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, ) -> RerankResponse: if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=litellm.LlmProviders(custom_llm_provider) - ) + async_httpx_client = get_async_httpx_client(llm_provider=litellm.LlmProviders(custom_llm_provider)) else: async_httpx_client = client try: @@ -1255,9 +1200,7 @@ def _prepare_audio_transcription_request( # All providers now return AudioTranscriptionRequestData if not isinstance(transformed_result, AudioTranscriptionRequestData): - raise ValueError( - f"Provider {provider_config.__class__.__name__} must return AudioTranscriptionRequestData" - ) + raise ValueError(f"Provider {provider_config.__class__.__name__} must return AudioTranscriptionRequestData") data = transformed_result.data files = transformed_result.files @@ -1312,9 +1255,7 @@ def audio_transcriptions( shared_session: Optional["ClientSession"] = None, ) -> Union[TranscriptionResponse, Coroutine[Any, Any, TranscriptionResponse]]: if provider_config is None: - raise ValueError( - f"No provider config found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"No provider config found for model: {model} and provider: {custom_llm_provider}") if atranscription is True: return self.async_audio_transcriptions( # type: ignore @@ -1400,9 +1341,7 @@ async def async_audio_transcriptions( shared_session: Optional["ClientSession"] = None, ) -> TranscriptionResponse: if provider_config is None: - raise ValueError( - f"No provider config found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"No provider config found for model: {model} and provider: {custom_llm_provider}") # Prepare the request ( @@ -1501,15 +1440,11 @@ def _prepare_ocr_request( # All providers return OCRRequestData if not isinstance(transformed_result, OCRRequestData): - raise ValueError( - f"Provider {provider_config.__class__.__name__} must return OCRRequestData" - ) + raise ValueError(f"Provider {provider_config.__class__.__name__} must return OCRRequestData") # Data is always a dict for Mistral OCR format if not isinstance(transformed_result.data, dict): - raise ValueError( - f"Expected dict data for OCR request, got {type(transformed_result.data)}" - ) + raise ValueError(f"Expected dict data for OCR request, got {type(transformed_result.data)}") data = transformed_result.data @@ -1571,15 +1506,11 @@ async def _async_prepare_ocr_request( # All providers return OCRRequestData if not isinstance(transformed_result, OCRRequestData): - raise ValueError( - f"Provider {provider_config.__class__.__name__} must return OCRRequestData" - ) + raise ValueError(f"Provider {provider_config.__class__.__name__} must return OCRRequestData") # Data is always a dict for Mistral OCR format if not isinstance(transformed_result.data, dict): - raise ValueError( - f"Expected dict data for OCR request, got {type(transformed_result.data)}" - ) + raise ValueError(f"Expected dict data for OCR request, got {type(transformed_result.data)}") data = transformed_result.data @@ -1630,9 +1561,7 @@ def ocr( Sync OCR handler. """ if provider_config is None: - raise ValueError( - f"No provider config found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"No provider config found for model: {model} and provider: {custom_llm_provider}") if litellm_params is None: litellm_params = {} @@ -1706,9 +1635,7 @@ async def async_ocr( Async OCR handler. """ if provider_config is None: - raise ValueError( - f"No provider config found for model: {model} and provider: {custom_llm_provider}" - ) + raise ValueError(f"No provider config found for model: {model} and provider: {custom_llm_provider}") if litellm_params is None: litellm_params = {} @@ -1769,9 +1696,7 @@ def search( Sync Search handler. """ if provider_config is None: - raise ValueError( - f"No provider config found for provider: {custom_llm_provider}" - ) + raise ValueError(f"No provider config found for provider: {custom_llm_provider}") if asearch is True: return self.async_search( @@ -1866,9 +1791,7 @@ async def async_search( Async Search handler. """ if provider_config is None: - raise ValueError( - f"No provider config found for provider: {custom_llm_provider}" - ) + raise ValueError(f"No provider config found for provider: {custom_llm_provider}") # Validate environment and get headers headers = provider_config.validate_environment( @@ -1909,9 +1832,7 @@ async def async_search( # For search providers, use special Search provider type from litellm.types.llms.custom_http import httpxSpecialProvider - async_httpx_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.Search - ) + async_httpx_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Search) else: async_httpx_client = client @@ -1958,9 +1879,7 @@ async def _async_post_anthropic_messages_with_http_error_retry( api_key: Optional[str], model: str, ) -> httpx.Response: - max_attempts = max( - provider_config.max_retry_on_anthropic_messages_http_error, 1 - ) + max_attempts = max(provider_config.max_retry_on_anthropic_messages_http_error, 1) litellm_params_dict = dict(litellm_params) optional_params_dict = dict(litellm_params) for attempt_idx in range(max_attempts): @@ -1976,10 +1895,8 @@ async def _async_post_anthropic_messages_with_http_error_retry( return response except httpx.HTTPStatusError as e: hit_max_attempt = attempt_idx + 1 == max_attempts - should_retry = ( - provider_config.should_retry_anthropic_messages_on_http_error( - e=e, litellm_params=litellm_params_dict - ) + should_retry = provider_config.should_retry_anthropic_messages_on_http_error( + e=e, litellm_params=litellm_params_dict ) if should_retry and not hit_max_attempt: verbose_logger.debug( @@ -1988,9 +1905,7 @@ async def _async_post_anthropic_messages_with_http_error_retry( attempt_idx + 2, max_attempts, ) - provider_config.transform_anthropic_messages_request_on_http_error( - e=e, request_data=request_body - ) + provider_config.transform_anthropic_messages_request_on_http_error(e=e, request_data=request_body) headers, signed_json_body = provider_config.sign_request( headers=headers, optional_params=optional_params_dict, @@ -2007,9 +1922,7 @@ async def _async_post_anthropic_messages_with_http_error_retry( except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) - raise RuntimeError( - "unreachable: anthropic messages HTTP retry loop exited without return" - ) + raise RuntimeError("unreachable: anthropic messages HTTP retry loop exited without return") async def async_anthropic_messages_handler( self, @@ -2032,9 +1945,7 @@ async def async_anthropic_messages_handler( ) if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=litellm.LlmProviders.ANTHROPIC - ) + async_httpx_client = get_async_httpx_client(llm_provider=litellm.LlmProviders.ANTHROPIC) else: async_httpx_client = client @@ -2044,11 +1955,9 @@ async def async_anthropic_messages_handler( Optional[litellm.types.utils.ProviderSpecificHeader], kwargs.get("provider_specific_header", None), ) - provider_specific_headers = ( - ProviderSpecificHeaderUtils.get_provider_specific_headers( - provider_specific_header=provider_specific_header, - custom_llm_provider=custom_llm_provider, - ) + provider_specific_headers = ProviderSpecificHeaderUtils.get_provider_specific_headers( + provider_specific_header=provider_specific_header, + custom_llm_provider=custom_llm_provider, ) forwarded_headers = kwargs.get("headers", None) # Also check for extra_headers in kwargs (from config or direct calls) @@ -2074,9 +1983,7 @@ async def async_anthropic_messages_handler( api_base=api_base, ) - headers = update_headers_with_filtered_beta( - headers=headers, provider=custom_llm_provider - ) + headers = update_headers_with_filtered_beta(headers=headers, provider=custom_llm_provider) logging_obj.update_from_kwargs( kwargs=kwargs, @@ -2130,9 +2037,7 @@ async def async_anthropic_messages_handler( headers, signed_json_body = anthropic_messages_provider_config.sign_request( headers=headers, - optional_params=dict( - litellm_params - ), # dynamic aws_* params are passed under litellm_params + optional_params=dict(litellm_params), # dynamic aws_* params are passed under litellm_params request_data=request_body, api_base=request_url, api_key=api_key, @@ -2165,9 +2070,7 @@ async def async_anthropic_messages_handler( async_httpx_client=async_httpx_client, request_url=request_url, headers=headers, - signed_json_body=( - signed_json_body if signed_json_body is not None else request_body_json - ), + signed_json_body=(signed_json_body if signed_json_body is not None else request_body_json), request_body=request_body, stream=stream or False, logging_obj=logging_obj, @@ -2233,7 +2136,11 @@ async def async_anthropic_messages_handler( kwargs=kwargs, ) - return final_response if final_response is not None else initial_response + return self._maybe_wrap_in_fake_stream( + final_response if final_response is not None else initial_response, + logging_obj, + "anthropic_messages", + ) def anthropic_messages_handler( self, @@ -2323,11 +2230,7 @@ def _run_sync_responses_pre_call_deployment_hook( optional_param_names = _responses_api_optional_request_param_names() updated_response_params = { **response_api_optional_request_params, - **{ - key: value - for key, value in modified_kwargs.items() - if key in optional_param_names - }, + **{key: value for key, value in modified_kwargs.items() if key in optional_param_names}, } updated_litellm_params = GenericLiteLLMParams( **{ @@ -2335,8 +2238,7 @@ def _run_sync_responses_pre_call_deployment_hook( **{ key: value for key, value in modified_kwargs.items() - if key not in optional_param_names - and key not in {"model", "input", "custom_llm_provider"} + if key not in optional_param_names and key not in {"model", "input", "custom_llm_provider"} }, } ) @@ -2375,9 +2277,7 @@ def response_api_handler( ) -> Union[ ResponsesAPIResponse, BaseResponsesAPIStreamingIterator, - Coroutine[ - Any, Any, Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator] - ], + Coroutine[Any, Any, Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator]], ]: """ Handles responses API requests. @@ -2423,9 +2323,7 @@ def response_api_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -2492,9 +2390,7 @@ def response_api_handler( stream=stream, fake_stream=fake_stream, ) - body_kwargs: Dict[str, Any] = ( - {"data": signed_body} if signed_body is not None else {"json": data} - ) + body_kwargs: Dict[str, Any] = {"data": signed_body} if signed_body is not None else {"json": data} ## LOGGING logging_obj.pre_call( @@ -2512,8 +2408,7 @@ def response_api_handler( response = sync_httpx_client.post( url=api_base, headers=headers, - timeout=timeout - or float(response_api_optional_request_params.get("timeout", 0)), + timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), stream=stream, **body_kwargs, ) @@ -2543,8 +2438,7 @@ def response_api_handler( response = sync_httpx_client.post( url=api_base, headers=headers, - timeout=timeout - or float(response_api_optional_request_params.get("timeout", 0)), + timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), **body_kwargs, ) except Exception as e: @@ -2553,12 +2447,10 @@ def response_api_handler( provider_config=responses_api_provider_config, ) - initial_response = ( - responses_api_provider_config.transform_response_api_response( - model=model, - raw_response=response, - logging_obj=logging_obj, - ) + initial_response = responses_api_provider_config.transform_response_api_response( + model=model, + raw_response=response, + logging_obj=logging_obj, ) if self._has_agentic_completion_hook(logging_obj): @@ -2566,11 +2458,7 @@ def response_api_handler( self._call_agentic_completion_hooks, response=initial_response, model=model, - messages=( - input - if isinstance(input, list) - else [{"role": "user", "content": input}] - ), + messages=(input if isinstance(input, list) else [{"role": "user", "content": input}]), anthropic_messages_provider_config=responses_api_provider_config, anthropic_messages_optional_request_params=response_api_optional_request_params, logging_obj=logging_obj, @@ -2676,9 +2564,7 @@ async def async_response_api_handler( stream=stream, fake_stream=fake_stream, ) - body_kwargs: Dict[str, Any] = ( - {"data": signed_body} if signed_body is not None else {"json": data} - ) + body_kwargs: Dict[str, Any] = {"data": signed_body} if signed_body is not None else {"json": data} ## LOGGING logging_obj.pre_call( @@ -2696,8 +2582,7 @@ async def async_response_api_handler( response = await async_httpx_client.post( url=api_base, headers=headers, - timeout=timeout - or float(response_api_optional_request_params.get("timeout", 0)), + timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), stream=stream, **body_kwargs, ) @@ -2729,8 +2614,7 @@ async def async_response_api_handler( response = await async_httpx_client.post( url=api_base, headers=headers, - timeout=timeout - or float(response_api_optional_request_params.get("timeout", 0)), + timeout=timeout or float(response_api_optional_request_params.get("timeout", 0)), **body_kwargs, ) @@ -2740,22 +2624,16 @@ async def async_response_api_handler( provider_config=responses_api_provider_config, ) - initial_response = ( - responses_api_provider_config.transform_response_api_response( - model=model, - raw_response=response, - logging_obj=logging_obj, - ) + initial_response = responses_api_provider_config.transform_response_api_response( + model=model, + raw_response=response, + logging_obj=logging_obj, ) final_response = await self._call_agentic_completion_hooks( response=initial_response, model=model, - messages=( - input - if isinstance(input, list) - else [{"role": "user", "content": input}] - ), + messages=(input if isinstance(input, list) else [{"role": "user", "content": input}]), anthropic_messages_provider_config=responses_api_provider_config, anthropic_messages_optional_request_params=response_api_optional_request_params, logging_obj=logging_obj, @@ -2766,9 +2644,9 @@ async def async_response_api_handler( ) result = final_response if final_response is not None else initial_response - if litellm_params.get( - "_code_interpreter_interception_converted_stream" - ) and not litellm_params.get("_agentic_loop_depth"): + if litellm_params.get("_code_interpreter_interception_converted_stream") and not litellm_params.get( + "_agentic_loop_depth" + ): return self._wrap_responses_response_as_fake_stream( result=result, model=model, @@ -2894,9 +2772,7 @@ def delete_response_api_handler( shared_session=shared_session, ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -2987,9 +2863,7 @@ def get_responses( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -3095,9 +2969,7 @@ async def async_get_responses( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=data - ) + response = await async_httpx_client.get(url=url, headers=headers, params=data) except Exception as e: verbose_logger.exception(f"Error retrieving response: {e}") @@ -3151,9 +3023,7 @@ def list_responses_input_items( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -3265,9 +3135,7 @@ async def async_list_responses_input_items( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=responses_api_provider_config) @@ -3370,10 +3238,7 @@ def create_file( else: sync_httpx_client = client - if ( - isinstance(transformed_request, dict) - and "initial_request" in transformed_request - ): + if isinstance(transformed_request, dict) and "initial_request" in transformed_request: # Handle two-step uploads (TwoStepFileUploadConfig) # Used by providers like Manus, Google Cloud Storage try: @@ -3394,21 +3259,15 @@ def create_file( initial_response_data, ) = self._extract_upload_url_from_response( response=initial_response, - upload_url_location=transformed_request.get( - "upload_url_location", "headers" - ), - upload_url_key=transformed_request.get( - "upload_url_key", "upload_url" - ), + upload_url_location=transformed_request.get("upload_url_location", "headers"), + upload_url_key=transformed_request.get("upload_url_key", "upload_url"), ) if not upload_url: raise ValueError("Failed to get upload URL from initial request") # Step 2: Upload the actual file - upload_method = ( - transformed_request["upload_request"].get("method", "POST").lower() - ) + upload_method = transformed_request["upload_request"].get("method", "POST").lower() upload_response = getattr(sync_httpx_client, upload_method)( url=upload_url, headers=transformed_request["upload_request"]["headers"], @@ -3432,34 +3291,25 @@ def create_file( # Handle pre-signed requests (e.g., from Bedrock S3 uploads) # Type narrowing: this is a plain dict, not TwoStepFileUploadConfig presigned_request = cast(Dict[str, Any], transformed_request) - upload_response = getattr( - sync_httpx_client, presigned_request["method"].lower() - )( + upload_response = getattr(sync_httpx_client, presigned_request["method"].lower())( url=presigned_request["url"], headers=presigned_request["headers"], data=presigned_request["data"], timeout=timeout, ) - elif ( - isinstance(transformed_request, dict) - and "resumable_chunked_upload" in transformed_request - ): + elif isinstance(transformed_request, dict) and "resumable_chunked_upload" in transformed_request: try: upload_response = self._resumable_chunked_upload( client=sync_httpx_client, initiate_url=api_base, base_headers=headers, - config=cast(Dict[str, Any], transformed_request)[ - "resumable_chunked_upload" - ], + config=cast(Dict[str, Any], transformed_request)["resumable_chunked_upload"], timeout=timeout, ) except Exception as e: verbose_logger.exception(f"Error creating file: {e}") raise self._handle_error(e=e, provider_config=provider_config) - elif isinstance(transformed_request, str) or isinstance( - transformed_request, bytes - ): + elif isinstance(transformed_request, str) or isinstance(transformed_request, bytes): # Handle traditional file uploads # Ensure transformed_request is a string for httpx compatibility if isinstance(transformed_request, bytes): @@ -3492,9 +3342,7 @@ def create_file( timeout=timeout, ) else: - raise ValueError( - f"Unsupported transformed_request type: {type(transformed_request)}" - ) + raise ValueError(f"Unsupported transformed_request type: {type(transformed_request)}") # Store the upload URL in litellm_params for the transformation method # Honour the URL already set by transform_create_file_request (e.g. Bedrock pre-signed S3 uploads), @@ -3525,9 +3373,7 @@ async def async_create_file( Creates a file using Gemini's two-step upload process """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -3543,8 +3389,7 @@ async def async_create_file( # a placeholder instead of re-materializing the payload. "complete_input_dict": ( "" - if isinstance(transformed_request, dict) - and "resumable_chunked_upload" in transformed_request + if isinstance(transformed_request, dict) and "resumable_chunked_upload" in transformed_request else transformed_request ), "api_base": api_base, @@ -3552,10 +3397,7 @@ async def async_create_file( }, ) - if ( - isinstance(transformed_request, dict) - and "initial_request" in transformed_request - ): + if isinstance(transformed_request, dict) and "initial_request" in transformed_request: # Handle two-step uploads (TwoStepFileUploadConfig) # Used by providers like Manus, Google Cloud Storage try: @@ -3576,21 +3418,15 @@ async def async_create_file( initial_response_data, ) = self._extract_upload_url_from_response( response=initial_response, - upload_url_location=transformed_request.get( - "upload_url_location", "headers" - ), - upload_url_key=transformed_request.get( - "upload_url_key", "upload_url" - ), + upload_url_location=transformed_request.get("upload_url_location", "headers"), + upload_url_key=transformed_request.get("upload_url_key", "upload_url"), ) if not upload_url: raise ValueError("Failed to get upload URL from initial request") # Step 2: Upload the actual file - upload_method = ( - transformed_request["upload_request"].get("method", "POST").lower() - ) + upload_method = transformed_request["upload_request"].get("method", "POST").lower() upload_response = await getattr(async_httpx_client, upload_method)( url=upload_url, headers=transformed_request["upload_request"]["headers"], @@ -3615,34 +3451,25 @@ async def async_create_file( # Handle pre-signed requests (e.g., from Bedrock S3 uploads) # Type narrowing: this is a plain dict, not TwoStepFileUploadConfig presigned_request = cast(Dict[str, Any], transformed_request) - upload_response = await getattr( - async_httpx_client, presigned_request["method"].lower() - )( + upload_response = await getattr(async_httpx_client, presigned_request["method"].lower())( url=presigned_request["url"], headers=presigned_request["headers"], data=presigned_request["data"], timeout=timeout, ) - elif ( - isinstance(transformed_request, dict) - and "resumable_chunked_upload" in transformed_request - ): + elif isinstance(transformed_request, dict) and "resumable_chunked_upload" in transformed_request: try: upload_response = await self._aresumable_chunked_upload( client=async_httpx_client, initiate_url=api_base, base_headers=headers, - config=cast(Dict[str, Any], transformed_request)[ - "resumable_chunked_upload" - ], + config=cast(Dict[str, Any], transformed_request)["resumable_chunked_upload"], timeout=timeout, ) except Exception as e: verbose_logger.exception(f"Error creating file: {e}") raise self._handle_error(e=e, provider_config=provider_config) - elif isinstance(transformed_request, str) or isinstance( - transformed_request, bytes - ): + elif isinstance(transformed_request, str) or isinstance(transformed_request, bytes): # Handle traditional file uploads # Note: transformed_request can be bytes (for binary files like PDFs) # or str (for text files like JSONL). httpx handles both correctly. @@ -3672,9 +3499,7 @@ async def async_create_file( timeout=timeout, ) else: - raise ValueError( - f"Unsupported transformed_request type: {type(transformed_request)}" - ) + raise ValueError(f"Unsupported transformed_request type: {type(transformed_request)}") return provider_config.transform_create_file_response( model=None, @@ -3687,9 +3512,7 @@ async def async_create_file( _RESUMABLE_CHUNK_SIZE = 8 * 1024 * 1024 @staticmethod - def _iter_resumable_chunks( - byte_iter: Iterator[bytes], chunk_size: int - ) -> Iterator[bytes]: + def _iter_resumable_chunks(byte_iter: Iterator[bytes], chunk_size: int) -> Iterator[bytes]: """Regroup a byte stream into ``chunk_size`` pieces, yielding a final partial piece only when it is non-empty. Every full piece is exactly ``chunk_size`` bytes (kept a 256 KiB multiple for GCS) and never more than @@ -3755,9 +3578,7 @@ def _resumable_chunked_upload( init_resp.raise_for_status() session_url = init_resp.headers.get(session_url_header) if not session_url: - raise ValueError( - f"resumable upload: no session URL in '{session_url_header}' header" - ) + raise ValueError(f"resumable upload: no session URL in '{session_url_header}' header") offset = 0 pending: Optional[bytes] = None @@ -3799,9 +3620,7 @@ def _send_resumable_chunk( **base_headers, "Content-Range": self._resumable_content_range(offset, len(data), is_final), } - req = httpx_client.build_request( - "PUT", url, **self._resumable_request_kwargs(headers, data, timeout) - ) + req = httpx_client.build_request("PUT", url, **self._resumable_request_kwargs(headers, data, timeout)) resp = httpx_client.send(req, follow_redirects=False) resp.read() if resp.status_code not in ((200, 201) if is_final else (308,)): @@ -3837,9 +3656,7 @@ async def _aresumable_chunked_upload( init_resp.raise_for_status() session_url = init_resp.headers.get(session_url_header) if not session_url: - raise ValueError( - f"resumable upload: no session URL in '{session_url_header}' header" - ) + raise ValueError(f"resumable upload: no session URL in '{session_url_header}' header") offset = 0 pending: Optional[bytes] = None @@ -3889,9 +3706,7 @@ async def _asend_resumable_chunk( **base_headers, "Content-Range": self._resumable_content_range(offset, len(data), is_final), } - req = httpx_client.build_request( - "PUT", url, **self._resumable_request_kwargs(headers, data, timeout) - ) + req = httpx_client.build_request("PUT", url, **self._resumable_request_kwargs(headers, data, timeout)) resp = await httpx_client.send(req, follow_redirects=False) await resp.aread() if resp.status_code not in ((200, 201) if is_final else (308,)): @@ -3969,14 +3784,9 @@ def create_batch( sync_httpx_client = client try: - if ( - isinstance(transformed_request, dict) - and "method" in transformed_request - ): + if isinstance(transformed_request, dict) and "method" in transformed_request: # Handle pre-signed requests (e.g., from Bedrock with AWS auth) - batch_response = getattr( - sync_httpx_client, transformed_request["method"].lower() - )( + batch_response = getattr(sync_httpx_client, transformed_request["method"].lower())( url=transformed_request["url"], headers=transformed_request["headers"], data=transformed_request["data"], @@ -4062,10 +3872,7 @@ def retrieve_batch( sync_httpx_client = client try: - if ( - isinstance(transformed_request, dict) - and "method" in transformed_request - ): + if isinstance(transformed_request, dict) and "method" in transformed_request: # Handle pre-signed requests (e.g., from Bedrock with AWS auth) method = transformed_request["method"].lower() request_kwargs = { @@ -4124,9 +3931,7 @@ async def async_create_batch( Async version of create_batch """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -4144,14 +3949,9 @@ async def async_create_batch( ) try: - if ( - isinstance(transformed_request, dict) - and "method" in transformed_request - ): + if isinstance(transformed_request, dict) and "method" in transformed_request: # Handle pre-signed requests (e.g., from Bedrock with AWS auth) - batch_response = await getattr( - async_httpx_client, transformed_request["method"].lower() - )( + batch_response = await getattr(async_httpx_client, transformed_request["method"].lower())( url=transformed_request["url"], headers=transformed_request["headers"], data=transformed_request["data"], @@ -4210,9 +4010,7 @@ async def async_retrieve_batch( Async version of retrieve_batch """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -4231,10 +4029,7 @@ async def async_retrieve_batch( ) try: - if ( - isinstance(transformed_request, dict) - and "method" in transformed_request - ): + if isinstance(transformed_request, dict) and "method" in transformed_request: # Handle pre-signed requests (e.g., from Bedrock with AWS auth) method = transformed_request["method"].lower() request_kwargs = { @@ -4246,9 +4041,7 @@ async def async_retrieve_batch( if method != "get" and transformed_request.get("data") is not None: request_kwargs["data"] = transformed_request["data"] - batch_response = await getattr(async_httpx_client, method)( - **request_kwargs - ) + batch_response = await getattr(async_httpx_client, method)(**request_kwargs) elif isinstance(transformed_request, dict) and api_base: # For other providers that use JSON requests batch_response = await async_httpx_client.get( @@ -4310,9 +4103,7 @@ def cancel_response_api_handler( shared_session=shared_session, ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -4347,9 +4138,7 @@ def cancel_response_api_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=data, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=data, timeout=timeout) except Exception as e: raise self._handle_error( @@ -4423,9 +4212,7 @@ async def async_cancel_response_api_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=data, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=data, timeout=timeout) except Exception as e: raise self._handle_error( @@ -4473,9 +4260,7 @@ def compact_response_api_handler( shared_session=shared_session, ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -4512,9 +4297,7 @@ def compact_response_api_handler( api_key=litellm_params.api_key, model=model, ) - body_kwargs: Dict[str, Any] = ( - {"data": signed_body} if signed_body is not None else {"json": data} - ) + body_kwargs: Dict[str, Any] = {"data": signed_body} if signed_body is not None else {"json": data} ## LOGGING logging_obj.pre_call( @@ -4528,9 +4311,7 @@ def compact_response_api_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, timeout=timeout, **body_kwargs - ) + response = sync_httpx_client.post(url=url, headers=headers, timeout=timeout, **body_kwargs) except Exception as e: raise self._handle_error( @@ -4607,9 +4388,7 @@ async def async_compact_response_api_handler( api_key=litellm_params.api_key, model=model, ) - body_kwargs: Dict[str, Any] = ( - {"data": signed_body} if signed_body is not None else {"json": data} - ) + body_kwargs: Dict[str, Any] = {"data": signed_body} if signed_body is not None else {"json": data} ## LOGGING logging_obj.pre_call( @@ -4623,9 +4402,7 @@ async def async_compact_response_api_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, timeout=timeout, **body_kwargs - ) + response = await async_httpx_client.post(url=url, headers=headers, timeout=timeout, **body_kwargs) except Exception as e: raise self._handle_error( @@ -4720,9 +4497,7 @@ async def async_retrieve_file( Async retrieve file metadata by ID """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -4754,9 +4529,7 @@ async def async_retrieve_file( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -4848,9 +4621,7 @@ async def async_delete_file( Async delete a file by ID """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -4882,9 +4653,7 @@ async def async_delete_file( ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, params=params, timeout=timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, params=params, timeout=timeout) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -4976,9 +4745,7 @@ async def async_list_files( Async list all files """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -5010,9 +4777,7 @@ async def async_list_files( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -5032,9 +4797,7 @@ def retrieve_file_content( _is_async: bool = False, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, timeout: Optional[Union[float, httpx.Timeout]] = None, - ) -> Union[ - "HttpxBinaryResponseContent", Coroutine[Any, Any, "HttpxBinaryResponseContent"] - ]: + ) -> Union["HttpxBinaryResponseContent", Coroutine[Any, Any, "HttpxBinaryResponseContent"]]: """ Retrieve file content by ID """ @@ -5106,9 +4869,7 @@ async def async_retrieve_file_content( Async retrieve file content by ID """ if client is None or not isinstance(client, AsyncHTTPHandler): - async_httpx_client = get_async_httpx_client( - llm_provider=provider_config.custom_llm_provider - ) + async_httpx_client = get_async_httpx_client(llm_provider=provider_config.custom_llm_provider) else: async_httpx_client = client @@ -5140,9 +4901,7 @@ async def async_retrieve_file_content( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=provider_config) @@ -5200,9 +4959,7 @@ def _has_agentic_completion_hook(logging_obj: Any) -> bool: base_func = CustomLogger.async_should_run_agentic_loop for cb in _custom_logger_callbacks(logging_obj): cb_func = getattr(type(cb), "async_should_run_agentic_loop", base_func) - if getattr(cb_func, "__func__", cb_func) is not getattr( - base_func, "__func__", base_func - ): + if getattr(cb_func, "__func__", cb_func) is not getattr(base_func, "__func__", base_func): return True return False @@ -5225,13 +4982,9 @@ def _check_agentic_loop_safety( """ fingerprint = BaseLLMHTTPHandler._fingerprint_agentic_tools(tool_calls) if fingerprint in fingerprints: - raise ValueError( - "Agentic loop detected repeated tool-call fingerprint; aborting rerun" - ) + raise ValueError("Agentic loop detected repeated tool-call fingerprint; aborting rerun") if depth >= max_loops: - raise ValueError( - f"Exceeded max_agentic_loops={max_loops} for model={model}" - ) + raise ValueError(f"Exceeded max_agentic_loops={max_loops} for model={model}") return fingerprint @staticmethod @@ -5264,9 +5017,7 @@ async def _execute_anthropic_agentic_plan( full_model_name = model if logging_obj is not None: - agentic_params = logging_obj.model_call_details.get( - "agentic_loop_params", {} - ) + agentic_params = logging_obj.model_call_details.get("agentic_loop_params", {}) full_model_name = cast(str, agentic_params.get("model", model)) optional_params = dict(anthropic_messages_optional_request_params) @@ -5413,8 +5164,7 @@ async def _run_agentic_loop_cleanup( except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") verbose_logger.exception( - "LiteLLM.AgenticHookError: Exception in " - "async_agentic_loop_cleanup_hook [call_id=%s model=%s]: %s", + "LiteLLM.AgenticHookError: Exception in async_agentic_loop_cleanup_hook [call_id=%s model=%s]: %s", _call_id, model, str(e), @@ -5504,6 +5254,45 @@ async def _execute_chat_completion_agentic_plan( **kwargs_for_followup, ) + def _maybe_wrap_in_fake_stream( + self, + response: Any, + logging_obj: Optional["LiteLLMLoggingObj"], + api_surface: str, + ) -> Any: + """ + If the original request was streaming but converted to non-streaming for + WebSearch interception, wrap the dict response in a FakeAnthropicMessagesStreamIterator. + + The converted-stream flag is only ever set by anthropic-messages websearch + interception, and the wrapper rebuilds an Anthropic SSE stream, so wrapping + is gated on ``api_surface == "anthropic_messages"`` to leave other surfaces + (e.g. the responses API) untouched. + """ + if api_surface != "anthropic_messages": + return response + websearch_converted_stream = ( + logging_obj.model_call_details.get("websearch_interception_converted_stream", False) + if logging_obj is not None + else False + ) + if websearch_converted_stream and isinstance(response, dict): + from typing import cast + + from litellm._logging import verbose_logger + from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import ( + FakeAnthropicMessagesStreamIterator, + ) + from litellm.types.llms.anthropic_messages.anthropic_response import ( + AnthropicMessagesResponse, + ) + + verbose_logger.debug( + "WebSearchInterception: Agentic loop completed, converting non-streaming response to fake stream" + ) + return FakeAnthropicMessagesStreamIterator(response=cast(AnthropicMessagesResponse, response)) + return response + async def _call_agentic_completion_hooks( self, response: Any, @@ -5557,8 +5346,7 @@ async def _call_agentic_completion_hooks( except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") verbose_logger.exception( - "LiteLLM.AgenticHookError: Exception in " - "async_should_run_agentic_loop [call_id=%s model=%s]: %s", + "LiteLLM.AgenticHookError: Exception in async_should_run_agentic_loop [call_id=%s model=%s]: %s", _call_id, model, str(e), @@ -5582,11 +5370,10 @@ async def _call_agentic_completion_hooks( kwargs_with_provider = kwargs.copy() if kwargs else {} kwargs_with_provider["custom_llm_provider"] = custom_llm_provider build_plan_overridden = ( - callback.__class__.async_build_agentic_loop_plan - is not CustomLogger.async_build_agentic_loop_plan + callback.__class__.async_build_agentic_loop_plan is not CustomLogger.async_build_agentic_loop_plan ) if not build_plan_overridden: - return await callback.async_run_agentic_loop( + agentic_result = await callback.async_run_agentic_loop( tools=tool_calls, model=model, messages=messages, @@ -5597,6 +5384,7 @@ async def _call_agentic_completion_hooks( stream=stream, kwargs=kwargs_with_provider, ) + return self._maybe_wrap_in_fake_stream(agentic_result, logging_obj, api_surface) plan = await callback.async_build_agentic_loop_plan( tools=tool_calls, @@ -5611,14 +5399,14 @@ async def _call_agentic_completion_hooks( ) if plan.response_override is not None: - return plan.response_override + return self._maybe_wrap_in_fake_stream(plan.response_override, logging_obj, api_surface) if plan.terminate: verbose_logger.debug( "Agentic loop terminated by callback=%s reason=%s", callback.__class__.__name__, plan.stop_reason, ) - return response + return self._maybe_wrap_in_fake_stream(response, logging_obj, api_surface) if not plan.run_agentic_loop: continue @@ -5636,25 +5424,28 @@ async def _call_agentic_completion_hooks( callback=callback, ) - return await self._execute_anthropic_agentic_plan( - plan=plan, - model=model, - messages=messages, - anthropic_messages_optional_request_params=anthropic_messages_optional_request_params, - logging_obj=logging_obj, - kwargs=kwargs_with_provider, - depth=depth, - max_loops=max_loops, - fingerprints=fingerprints, - fingerprint=fingerprint, - stream=stream, - callback=callback, + return self._maybe_wrap_in_fake_stream( + await self._execute_anthropic_agentic_plan( + plan=plan, + model=model, + messages=messages, + anthropic_messages_optional_request_params=anthropic_messages_optional_request_params, + logging_obj=logging_obj, + kwargs=kwargs_with_provider, + depth=depth, + max_loops=max_loops, + fingerprints=fingerprints, + fingerprint=fingerprint, + stream=stream, + callback=callback, + ), + logging_obj, + api_surface, ) except Exception as e: _call_id = getattr(logging_obj, "litellm_call_id", "unknown") verbose_logger.exception( - "LiteLLM.AgenticHookError: Exception in agentic completion hooks " - "[call_id=%s model=%s]: %s", + "LiteLLM.AgenticHookError: Exception in agentic completion hooks [call_id=%s model=%s]: %s", _call_id, model, str(e), @@ -5665,37 +5456,9 @@ async def _call_agentic_completion_hooks( # 1. Stream was originally True but converted to False for WebSearch interception # 2. No agentic loop ran (LLM didn't use the tool) # 3. We have a non-streaming response that needs to be converted to streaming - websearch_converted_stream = ( - logging_obj.model_call_details.get( - "websearch_interception_converted_stream", False - ) - if logging_obj is not None - else False - ) - - if api_surface == "anthropic_messages" and websearch_converted_stream: - from typing import cast - - from litellm._logging import verbose_logger - from litellm.llms.anthropic.experimental_pass_through.messages.fake_stream_iterator import ( - FakeAnthropicMessagesStreamIterator, - ) - from litellm.types.llms.anthropic_messages.anthropic_response import ( - AnthropicMessagesResponse, - ) - - verbose_logger.debug( - "WebSearchInterception: No tool call made, converting non-streaming response to fake stream" - ) - - # Convert the non-streaming response to a fake stream - # The response should be an AnthropicMessagesResponse (dict) - if isinstance(response, dict): - # Create a fake streaming iterator - fake_stream = FakeAnthropicMessagesStreamIterator( - response=cast(AnthropicMessagesResponse, response) - ) - return fake_stream + result = self._maybe_wrap_in_fake_stream(response, logging_obj, api_surface) + if result is not response: + return result return None @@ -5748,8 +5511,7 @@ async def _call_agentic_chat_completion_hooks( ) except Exception as e: verbose_logger.exception( - "LiteLLM.AgenticHookError: Exception in " - "async_should_run_chat_completion_agentic_loop: %s", + "LiteLLM.AgenticHookError: Exception in async_should_run_chat_completion_agentic_loop: %s", str(e), ) continue @@ -5832,9 +5594,7 @@ async def _call_agentic_chat_completion_hooks( # 2. No agentic loop ran (LLM didn't use the tool) # 3. We have a non-streaming response that needs to be converted to streaming websearch_converted_stream = ( - logging_obj.model_call_details.get( - "websearch_interception_converted_stream", False - ) + logging_obj.model_call_details.get("websearch_interception_converted_stream", False) if logging_obj is not None else False ) @@ -5914,9 +5674,7 @@ def _handle_error( ) @staticmethod - def _append_query_params( - url: str, query_params: Optional[RealtimeQueryParams] - ) -> str: + def _append_query_params(url: str, query_params: Optional[RealtimeQueryParams]) -> str: """Append query_params to url, skipping keys already present in the URL.""" if not query_params: return url @@ -5972,9 +5730,7 @@ async def async_realtime( # (e.g. Gemini/Vertex AI Live needs a `setup` message before any realtime_input) _session_config: Optional[str] = None if provider_config.requires_session_configuration(): - _session_config = provider_config.session_configuration_request( - model - ) + _session_config = provider_config.session_configuration_request(model) if _session_config: await backend_ws.send(_session_config) @@ -5990,9 +5746,7 @@ async def async_realtime( user_api_key_dict=user_api_key_dict, request_data=_request_data, force_transcription_model=( - model - if (query_params or {}).get("intent") == "transcription" - else None + model if (query_params or {}).get("intent") == "transcription" else None ), ) if _session_config: @@ -6015,9 +5769,7 @@ async def async_realtime( realtime_streaming.store_message(synthetic_session_str) await websocket.send_text(synthetic_session_str) realtime_streaming._session_created_sent_to_client = True - verbose_logger.debug( - "Sent synthetic session.created to client to unblock connection" - ) + verbose_logger.debug("Sent synthetic session.created to client to unblock connection") await realtime_streaming.bidirectional_forward() @@ -6027,20 +5779,14 @@ async def async_realtime( except Exception as e: verbose_logger.exception(f"Error connecting to backend: {e}") try: - await websocket.close( - code=1011, reason=_redact_string(f"Internal server error: {str(e)}") - ) + await websocket.close(code=1011, reason=_redact_string(f"Internal server error: {str(e)}")) except RuntimeError as close_error: - if "already completed" in str(close_error) or "websocket.close" in str( - close_error - ): + if "already completed" in str(close_error) or "websocket.close" in str(close_error): # The WebSocket is already closed or the response is completed, so we can ignore this error pass else: # If it's a different RuntimeError, we might want to log it or handle it differently - raise Exception( - f"Unexpected error while closing WebSocket: {close_error}" - ) + raise Exception(f"Unexpected error while closing WebSocket: {close_error}") async def async_realtime_client_secret_handler( self, @@ -6137,9 +5883,7 @@ async def _async_realtime_session_post( api_base=api_base, model=model or "", api_version=api_version ) else: - url = provider_config.get_complete_url( - api_base=api_base, model=model or "", api_version=api_version - ) + url = provider_config.get_complete_url(api_base=api_base, model=model or "", api_version=api_version) headers: Dict[str, Any] = provider_config.validate_environment( headers={}, model=model or "", api_key=api_key ) @@ -6210,12 +5954,8 @@ async def async_realtime_calls_handler( async_httpx_client = client if provider_config is not None: - url = provider_config.get_realtime_calls_url( - api_base=api_base, model=model or "", api_version=api_version - ) - headers: Dict[str, Any] = provider_config.get_realtime_calls_headers( - ephemeral_key=openai_ephemeral_key - ) + url = provider_config.get_realtime_calls_url(api_base=api_base, model=model or "", api_version=api_version) + headers: Dict[str, Any] = provider_config.get_realtime_calls_headers(ephemeral_key=openai_ephemeral_key) else: url = f"{api_base.rstrip('/')}/v1/realtime/calls" headers = { @@ -6290,10 +6030,7 @@ async def async_responses_websocket( - Uses ManagedResponsesWebSocketHandler which makes HTTP streaming calls - Forwards events over the websocket connection """ - if ( - responses_api_provider_config is None - or not responses_api_provider_config.supports_native_websocket() - ): + if responses_api_provider_config is None or not responses_api_provider_config.supports_native_websocket(): from litellm.responses.streaming_iterator import ( ManagedResponsesWebSocketHandler, ) @@ -6342,9 +6079,7 @@ async def async_responses_websocket( _qs = parse_qs(_parsed.query) if "model" not in _qs: _qs["model"] = [model] - ws_url = urlunparse( - _parsed._replace(query=urlencode({k: v[0] for k, v in _qs.items()})) - ) + ws_url = urlunparse(_parsed._replace(query=urlencode({k: v[0] for k, v in _qs.items()}))) try: ssl_context = get_shared_realtime_ssl_context() @@ -6385,9 +6120,7 @@ async def async_responses_websocket( cb for cb in _litellm.callbacks if callable(getattr(cb, "check_pii", None)) - and callable( - getattr(cb, "get_presidio_settings_from_request_data", None) - ) + and callable(getattr(cb, "get_presidio_settings_from_request_data", None)) and callable(getattr(cb, "_unmask_pii_text", None)) and getattr(cb, "output_parse_pii", False) ] @@ -6395,9 +6128,7 @@ async def async_responses_websocket( cb for cb in _litellm.callbacks if callable(getattr(cb, "check_pii", None)) - and callable( - getattr(cb, "get_presidio_settings_from_request_data", None) - ) + and callable(getattr(cb, "get_presidio_settings_from_request_data", None)) and getattr(cb, "apply_to_output", False) ] except Exception as _guardrail_exc: @@ -6426,18 +6157,12 @@ async def async_responses_websocket( except Exception as e: verbose_logger.exception(f"Error in responses WS: {e}") try: - await websocket.close( - code=1011, reason=_redact_string(f"Internal server error: {str(e)}") - ) + await websocket.close(code=1011, reason=_redact_string(f"Internal server error: {str(e)}")) except RuntimeError as close_error: - if "already completed" in str(close_error) or "websocket.close" in str( - close_error - ): + if "already completed" in str(close_error) or "websocket.close" in str(close_error): pass else: - raise Exception( - f"Unexpected error while closing WebSocket: {close_error}" - ) + raise Exception(f"Unexpected error while closing WebSocket: {close_error}") def image_edit_handler( self, @@ -6485,9 +6210,7 @@ def image_edit_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -6516,9 +6239,7 @@ def image_edit_handler( litellm_params=litellm_params, headers=headers, ) - data = image_edit_provider_config.finalize_image_edit_request_data( - data, api_base - ) + data = image_edit_provider_config.finalize_image_edit_request_data(data, api_base) ## LOGGING logging_obj.pre_call( @@ -6617,9 +6338,7 @@ async def async_image_edit_handler( litellm_params=litellm_params, headers=headers, ) - data = image_edit_provider_config.finalize_image_edit_request_data( - data, api_base - ) + data = image_edit_provider_config.finalize_image_edit_request_data(data, api_base) ## LOGGING logging_obj.pre_call( @@ -6709,16 +6428,13 @@ def image_generation_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client headers = image_generation_provider_config.validate_environment( api_key=api_key, - headers=image_generation_optional_request_params.get("extra_headers", {}) - or {}, + headers=image_generation_optional_request_params.get("extra_headers", {}) or {}, model=model, messages=[], optional_params=image_generation_optional_request_params, @@ -6781,17 +6497,15 @@ def image_generation_handler( provider_config=image_generation_provider_config, ) - model_response: ImageResponse = ( - image_generation_provider_config.transform_image_generation_response( - model=model, - raw_response=response, - model_response=litellm.ImageResponse(), - logging_obj=logging_obj, - request_data=data, - optional_params=image_generation_optional_request_params, - litellm_params=dict(litellm_params), - encoding=None, - ) + model_response: ImageResponse = image_generation_provider_config.transform_image_generation_response( + model=model, + raw_response=response, + model_response=litellm.ImageResponse(), + logging_obj=logging_obj, + request_data=data, + optional_params=image_generation_optional_request_params, + litellm_params=dict(litellm_params), + encoding=None, ) return model_response @@ -6827,8 +6541,7 @@ async def async_image_generation_handler( headers = image_generation_provider_config.validate_environment( api_key=api_key, - headers=image_generation_optional_request_params.get("extra_headers", {}) - or {}, + headers=image_generation_optional_request_params.get("extra_headers", {}) or {}, model=model, messages=[], optional_params=image_generation_optional_request_params, @@ -6891,17 +6604,15 @@ async def async_image_generation_handler( provider_config=image_generation_provider_config, ) - model_response: ImageResponse = ( - image_generation_provider_config.transform_image_generation_response( - model=model, - raw_response=response, - model_response=litellm.ImageResponse(), - logging_obj=logging_obj, - request_data=data, - optional_params=image_generation_optional_request_params, - litellm_params=dict(litellm_params), - encoding=None, - ) + model_response: ImageResponse = image_generation_provider_config.transform_image_generation_response( + model=model, + raw_response=response, + model_response=litellm.ImageResponse(), + logging_obj=logging_obj, + request_data=data, + optional_params=image_generation_optional_request_params, + litellm_params=dict(litellm_params), + encoding=None, ) return model_response @@ -6952,16 +6663,13 @@ def video_generation_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client headers = video_generation_provider_config.validate_environment( api_key=api_key or litellm_params.get("api_key", None), - headers=video_generation_optional_request_params.get("extra_headers", {}) - or {}, + headers=video_generation_optional_request_params.get("extra_headers", {}) or {}, model=model, litellm_params=litellm_params, ) @@ -7065,8 +6773,7 @@ async def async_video_generation_handler( headers = video_generation_provider_config.validate_environment( api_key=api_key or litellm_params.get("api_key", None), - headers=video_generation_optional_request_params.get("extra_headers", {}) - or {}, + headers=video_generation_optional_request_params.get("extra_headers", {}) or {}, model=model, litellm_params=litellm_params, ) @@ -7169,9 +6876,7 @@ def video_content_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -7344,9 +7049,7 @@ def video_remix_handler( # For sync calls, use sync HTTP client directly (like video_generation does) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -7520,9 +7223,7 @@ def video_create_character_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -7676,9 +7377,7 @@ def video_get_character_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -7769,9 +7468,7 @@ async def async_video_get_character_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) response.raise_for_status() return video_provider_config.transform_video_get_character_response( raw_response=response, @@ -7811,9 +7508,7 @@ def video_edit_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -8020,9 +7715,7 @@ def video_extension_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -8401,9 +8094,7 @@ def video_status_handler( # For sync calls, use sync HTTP client directly (like video_generation does) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -8461,12 +8152,10 @@ def video_status_handler( headers=headers, ) - return ( - video_status_provider_config.transform_video_status_retrieve_response( - raw_response=response, - logging_obj=logging_obj, - custom_llm_provider=custom_llm_provider, - ) + return video_status_provider_config.transform_video_status_retrieve_response( + raw_response=response, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, ) except Exception as e: @@ -8552,12 +8241,10 @@ async def async_video_status_handler( url=url, headers=headers, ) - return ( - video_status_provider_config.transform_video_status_retrieve_response( - raw_response=response, - logging_obj=logging_obj, - custom_llm_provider=custom_llm_provider, - ) + return video_status_provider_config.transform_video_status_retrieve_response( + raw_response=response, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, ) except Exception as e: @@ -8594,9 +8281,7 @@ def container_create_handler( # For sync calls, use sync HTTP client if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -8763,9 +8448,7 @@ def container_list_handler( # For sync calls, use sync HTTP client if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -8928,9 +8611,7 @@ def container_retrieve_handler( # For sync calls, use sync HTTP client if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -9095,9 +8776,7 @@ def container_delete_handler( # For sync calls, use sync HTTP client if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -9249,9 +8928,7 @@ def container_file_list_handler( timeout: Union[float, httpx.Timeout] = 600, _is_async: bool = False, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, - ) -> Union[ - "ContainerFileListResponse", Coroutine[Any, Any, "ContainerFileListResponse"] - ]: + ) -> Union["ContainerFileListResponse", Coroutine[Any, Any, "ContainerFileListResponse"]]: if _is_async: return self.async_container_file_list_handler( container_id=container_id, @@ -9269,9 +8946,7 @@ def container_file_list_handler( # For sync calls, use sync HTTP client if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -9436,9 +9111,7 @@ def container_file_content_handler( # For sync calls, use sync HTTP client if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -9611,9 +9284,7 @@ async def async_vector_store_search_handler( ) # Check if provider has async transform method - if hasattr( - vector_store_provider_config, "atransform_search_vector_store_request" - ): + if hasattr(vector_store_provider_config, "atransform_search_vector_store_request"): ( url, request_body, @@ -9658,9 +9329,7 @@ async def async_vector_store_search_handler( }, ) - request_data = ( - json.dumps(request_body) if signed_json_body is None else signed_json_body - ) + request_data = json.dumps(request_body) if signed_json_body is None else signed_json_body try: response = await async_httpx_client.post( @@ -9691,9 +9360,7 @@ def vector_store_search_handler( timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, _is_async: bool = False, - ) -> Union[ - VectorStoreSearchResponse, Coroutine[Any, Any, VectorStoreSearchResponse] - ]: + ) -> Union[VectorStoreSearchResponse, Coroutine[Any, Any, VectorStoreSearchResponse]]: if _is_async: return self.async_vector_store_search_handler( vector_store_id=vector_store_id, @@ -9710,9 +9377,7 @@ def vector_store_search_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -9761,9 +9426,7 @@ def vector_store_search_handler( }, ) - request_data = ( - json.dumps(request_body) if signed_json_body is None else signed_json_body - ) + request_data = json.dumps(request_body) if signed_json_body is None else signed_json_body try: response = sync_httpx_client.post( @@ -9831,9 +9494,7 @@ async def async_vector_store_create_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error(e=e, provider_config=vector_store_provider_config) @@ -9853,9 +9514,7 @@ def vector_store_create_handler( timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, _is_async: bool = False, - ) -> Union[ - VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse] - ]: + ) -> Union[VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse]]: if _is_async: return self.async_vector_store_create_handler( vector_store_create_optional_params=vector_store_create_optional_params, @@ -9870,9 +9529,7 @@ def vector_store_create_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -9907,9 +9564,7 @@ def vector_store_create_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body) except Exception as e: raise self._handle_error(e=e, provider_config=vector_store_provider_config) @@ -9949,9 +9604,7 @@ async def async_vector_store_retrieve_handler( litellm_params=dict(litellm_params), ) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}" logging_obj.pre_call( @@ -9984,9 +9637,7 @@ def vector_store_retrieve_handler( timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, _is_async: bool = False, - ) -> Union[ - VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse] - ]: + ) -> Union[VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse]]: if _is_async: return self.async_vector_store_retrieve_handler( vector_store_id=vector_store_id, @@ -10001,9 +9652,7 @@ def vector_store_retrieve_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10019,9 +9668,7 @@ def vector_store_retrieve_handler( litellm_params=dict(litellm_params), ) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}" logging_obj.pre_call( @@ -10100,9 +9747,7 @@ async def async_vector_store_list_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=params) except Exception as e: raise self._handle_error(e=e, provider_config=vector_store_provider_config) @@ -10141,9 +9786,7 @@ def vector_store_list_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10221,9 +9864,7 @@ async def async_vector_store_update_handler( litellm_params=dict(litellm_params), ) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}" request_body: Dict[str, Any] = dict(vector_store_update_optional_params) @@ -10248,9 +9889,7 @@ async def async_vector_store_update_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error(e=e, provider_config=vector_store_provider_config) @@ -10271,9 +9910,7 @@ def vector_store_update_handler( timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, _is_async: bool = False, - ) -> Union[ - VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse] - ]: + ) -> Union[VectorStoreCreateResponse, Coroutine[Any, Any, VectorStoreCreateResponse]]: if _is_async: return self.async_vector_store_update_handler( vector_store_id=vector_store_id, @@ -10289,9 +9926,7 @@ def vector_store_update_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10307,9 +9942,7 @@ def vector_store_update_handler( litellm_params=dict(litellm_params), ) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}" request_body: Dict[str, Any] = dict(vector_store_update_optional_params) @@ -10334,9 +9967,7 @@ def vector_store_update_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body) except Exception as e: raise self._handle_error(e=e, provider_config=vector_store_provider_config) @@ -10376,9 +10007,7 @@ async def async_vector_store_delete_handler( litellm_params=dict(litellm_params), ) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}" logging_obj.pre_call( @@ -10391,9 +10020,7 @@ async def async_vector_store_delete_handler( ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error(e=e, provider_config=vector_store_provider_config) @@ -10426,9 +10053,7 @@ def vector_store_delete_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10444,9 +10069,7 @@ def vector_store_delete_handler( litellm_params=dict(litellm_params), ) - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}" logging_obj.pre_call( @@ -10527,17 +10150,11 @@ async def async_vector_store_file_create_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_create_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_create_vector_store_file_response(response=response) def vector_store_file_create_handler( self, @@ -10569,9 +10186,7 @@ def vector_store_file_create_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10612,17 +10227,11 @@ def vector_store_file_create_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_create_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_create_vector_store_file_response(response=response) async def async_vector_store_file_list_handler( self, @@ -10682,17 +10291,11 @@ async def async_vector_store_file_list_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=request_params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=request_params) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_list_vector_store_files_response( - response=response - ) + return vector_store_files_provider_config.transform_list_vector_store_files_response(response=response) def vector_store_file_list_handler( self, @@ -10708,9 +10311,7 @@ def vector_store_file_list_handler( timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, _is_async: bool = False, - ) -> Union[ - VectorStoreFileListResponse, Coroutine[Any, Any, VectorStoreFileListResponse] - ]: + ) -> Union[VectorStoreFileListResponse, Coroutine[Any, Any, VectorStoreFileListResponse]]: if _is_async: return self.async_vector_store_file_list_handler( vector_store_id=vector_store_id, @@ -10726,9 +10327,7 @@ def vector_store_file_list_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10768,17 +10367,11 @@ def vector_store_file_list_handler( ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=request_params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=request_params) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_list_vector_store_files_response( - response=response - ) + return vector_store_files_provider_config.transform_list_vector_store_files_response(response=response) async def async_vector_store_file_retrieve_handler( self, @@ -10833,17 +10426,11 @@ async def async_vector_store_file_retrieve_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=request_params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=request_params) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_retrieve_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_retrieve_vector_store_file_response(response=response) def vector_store_file_retrieve_handler( self, @@ -10873,9 +10460,7 @@ def vector_store_file_retrieve_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -10911,17 +10496,11 @@ def vector_store_file_retrieve_handler( ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=request_params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=request_params) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_retrieve_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_retrieve_vector_store_file_response(response=response) async def async_vector_store_file_content_handler( self, @@ -10976,13 +10555,9 @@ async def async_vector_store_file_content_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=request_params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=request_params) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) return vector_store_files_provider_config.transform_retrieve_vector_store_file_content_response( response=response @@ -11019,9 +10594,7 @@ def vector_store_file_content_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -11057,13 +10630,9 @@ def vector_store_file_content_handler( ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=request_params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=request_params) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) return vector_store_files_provider_config.transform_retrieve_vector_store_file_content_response( response=response @@ -11129,17 +10698,11 @@ async def async_vector_store_file_update_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_update_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_update_vector_store_file_response(response=response) def vector_store_file_update_handler( self, @@ -11173,9 +10736,7 @@ def vector_store_file_update_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -11216,17 +10777,11 @@ def vector_store_file_update_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_update_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_update_vector_store_file_response(response=response) async def async_vector_store_file_delete_handler( self, @@ -11281,17 +10836,11 @@ async def async_vector_store_file_delete_handler( ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, params=request_params, timeout=timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, params=request_params, timeout=timeout) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_delete_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_delete_vector_store_file_response(response=response) def vector_store_file_delete_handler( self, @@ -11324,9 +10873,7 @@ def vector_store_file_delete_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -11362,17 +10909,11 @@ def vector_store_file_delete_handler( ) try: - response = sync_httpx_client.delete( - url=url, headers=headers, params=request_params, timeout=timeout - ) + response = sync_httpx_client.delete(url=url, headers=headers, params=request_params, timeout=timeout) except Exception as e: - raise self._handle_error( - e=e, provider_config=vector_store_files_provider_config - ) + raise self._handle_error(e=e, provider_config=vector_store_files_provider_config) - return vector_store_files_provider_config.transform_delete_vector_store_file_response( - response=response - ) + return vector_store_files_provider_config.transform_delete_vector_store_file_response(response=response) ##################################################################### ################ Google GenAI GENERATE CONTENT HANDLER ########################### @@ -11424,9 +10965,7 @@ def generate_content_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -11667,9 +11206,7 @@ def text_to_speech_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -11911,9 +11448,7 @@ def create_skill_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -11931,19 +11466,13 @@ def create_skill_handler( try: # Check if files are present - use multipart/form-data - data, files = self._prepare_skill_multipart_request( - request_body=request_body, headers=headers - ) + data, files = self._prepare_skill_multipart_request(request_body=request_body, headers=headers) if files is not None: - response = sync_httpx_client.post( - url=url, headers=headers, data=data, files=files, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, data=data, files=files, timeout=timeout) else: # No files - send as JSON - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -11991,9 +11520,7 @@ async def async_create_skill_handler( try: # Check if files are present - use multipart/form-data - data, files = self._prepare_skill_multipart_request( - request_body=request_body, headers=headers - ) + data, files = self._prepare_skill_multipart_request(request_body=request_body, headers=headers) if files is not None: response = await async_httpx_client.post( @@ -12001,9 +11528,7 @@ async def async_create_skill_handler( ) else: # No files - send as JSON - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12045,9 +11570,7 @@ def list_skills_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12064,9 +11587,7 @@ def list_skills_handler( ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=query_params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=query_params) except Exception as e: raise self._handle_error( e=e, @@ -12113,9 +11634,7 @@ async def async_list_skills_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=query_params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=query_params) except Exception as e: raise self._handle_error( e=e, @@ -12155,9 +11674,7 @@ def get_skill_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12258,9 +11775,7 @@ def delete_skill_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12276,9 +11791,7 @@ def delete_skill_handler( ) try: - response = sync_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = sync_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12323,9 +11836,7 @@ async def async_delete_skill_handler( ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12371,9 +11882,7 @@ def create_eval_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12390,9 +11899,7 @@ def create_eval_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12439,9 +11946,7 @@ async def async_create_eval_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12483,9 +11988,7 @@ def list_evals_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12502,9 +12005,7 @@ def list_evals_handler( ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=query_params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=query_params) except Exception as e: raise self._handle_error( e=e, @@ -12551,9 +12052,7 @@ async def async_list_evals_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=query_params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=query_params) except Exception as e: raise self._handle_error( e=e, @@ -12593,9 +12092,7 @@ def get_eval_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12698,9 +12195,7 @@ def update_eval_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12717,9 +12212,7 @@ def update_eval_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12766,9 +12259,7 @@ async def async_update_eval_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12808,9 +12299,7 @@ def delete_eval_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12826,9 +12315,7 @@ def delete_eval_handler( ) try: - response = sync_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = sync_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12873,9 +12360,7 @@ async def async_delete_eval_handler( ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12915,9 +12400,7 @@ def cancel_eval_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -12933,9 +12416,7 @@ def cancel_eval_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json={}, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json={}, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -12980,9 +12461,7 @@ async def async_cancel_eval_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json={}, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json={}, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -13028,9 +12507,7 @@ def create_run_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -13047,9 +12524,7 @@ def create_run_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -13096,9 +12571,7 @@ async def async_create_run_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -13140,9 +12613,7 @@ def list_runs_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -13159,9 +12630,7 @@ def list_runs_handler( ) try: - response = sync_httpx_client.get( - url=url, headers=headers, params=query_params - ) + response = sync_httpx_client.get(url=url, headers=headers, params=query_params) except Exception as e: raise self._handle_error( e=e, @@ -13208,9 +12677,7 @@ async def async_list_runs_handler( ) try: - response = await async_httpx_client.get( - url=url, headers=headers, params=query_params - ) + response = await async_httpx_client.get(url=url, headers=headers, params=query_params) except Exception as e: raise self._handle_error( e=e, @@ -13250,9 +12717,7 @@ def get_run_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -13353,9 +12818,7 @@ def cancel_run_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -13371,9 +12834,7 @@ def cancel_run_handler( ) try: - response = sync_httpx_client.post( - url=url, headers=headers, json={}, timeout=timeout - ) + response = sync_httpx_client.post(url=url, headers=headers, json={}, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -13418,9 +12879,7 @@ async def async_cancel_run_handler( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json={}, timeout=timeout - ) + response = await async_httpx_client.post(url=url, headers=headers, json={}, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -13460,9 +12919,7 @@ def delete_run_handler( ) if client is None or not isinstance(client, HTTPHandler): - sync_httpx_client = _get_httpx_client( - params={"ssl_verify": litellm_params.get("ssl_verify", None)} - ) + sync_httpx_client = _get_httpx_client(params={"ssl_verify": litellm_params.get("ssl_verify", None)}) else: sync_httpx_client = client @@ -13478,9 +12935,7 @@ def delete_run_handler( ) try: - response = sync_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = sync_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error( e=e, @@ -13525,9 +12980,7 @@ async def async_delete_run_handler( ) try: - response = await async_httpx_client.delete( - url=url, headers=headers, timeout=timeout - ) + response = await async_httpx_client.delete(url=url, headers=headers, timeout=timeout) except Exception as e: raise self._handle_error( e=e, diff --git a/litellm/llms/custom_llm.py b/litellm/llms/custom_llm.py index a820ac7f3455..e0af3986465b 100644 --- a/litellm/llms/custom_llm.py +++ b/litellm/llms/custom_llm.py @@ -39,9 +39,7 @@ def __init__( ): self.status_code = status_code self.message = message - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class CustomLLM(BaseLLM): @@ -154,12 +152,8 @@ async def aimage_generation( model: str, prompt: str, model_response: ImageResponse, - api_key: Optional[ - str - ], # dynamically set api_key - https://docs.litellm.ai/docs/set_keys#api_key - api_base: Optional[ - str - ], # dynamically set api_base - https://docs.litellm.ai/docs/set_keys#api_base + api_key: Optional[str], # dynamically set api_key - https://docs.litellm.ai/docs/set_keys#api_key + api_base: Optional[str], # dynamically set api_base - https://docs.litellm.ai/docs/set_keys#api_base optional_params: dict, logging_obj: Any, timeout: Optional[Union[float, httpx.Timeout]] = None, @@ -228,9 +222,7 @@ async def aimage_edit( raise CustomLLMError(status_code=500, message="Not implemented yet!") -def custom_chat_llm_router( - async_fn: bool, stream: Optional[bool], custom_llm: CustomLLM -): +def custom_chat_llm_router(async_fn: bool, stream: Optional[bool], custom_llm: CustomLLM): """ Routes call to CustomLLM completion/acompletion/streaming/astreaming functions, based on call type diff --git a/litellm/llms/dashscope/chat/transformation.py b/litellm/llms/dashscope/chat/transformation.py index ccb4d370c957..743bf494d92c 100644 --- a/litellm/llms/dashscope/chat/transformation.py +++ b/litellm/llms/dashscope/chat/transformation.py @@ -42,21 +42,15 @@ def _transform_messages( self, messages: List[AllMessageValues], model: str, is_async: bool = False ) -> Union[List[AllMessageValues], Coroutine[Any, Any, List[AllMessageValues]]]: if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: api_base = ( - api_base - or get_secret_str("DASHSCOPE_API_BASE") - or "https://dashscope.aliyuncs.com/compatible-mode/v1" + api_base or get_secret_str("DASHSCOPE_API_BASE") or "https://dashscope.aliyuncs.com/compatible-mode/v1" ) # type: ignore dynamic_api_key = api_key or get_secret_str("DASHSCOPE_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/dashscope/cost_calculator.py b/litellm/llms/dashscope/cost_calculator.py index 8bb7f605b82b..2f710d781269 100644 --- a/litellm/llms/dashscope/cost_calculator.py +++ b/litellm/llms/dashscope/cost_calculator.py @@ -24,9 +24,7 @@ class TokenBreakdown: def _extract_token_breakdown(usage: Usage) -> TokenBreakdown: """Extract token counts from usage, handling cached and reasoning tokens.""" cached_tokens = 0 - if usage.prompt_tokens_details and hasattr( - usage.prompt_tokens_details, "cached_tokens" - ): + if usage.prompt_tokens_details and hasattr(usage.prompt_tokens_details, "cached_tokens"): cached_tokens = usage.prompt_tokens_details.cached_tokens or 0 text_tokens = usage.prompt_tokens - cached_tokens @@ -41,9 +39,7 @@ def _extract_token_breakdown(usage: Usage) -> TokenBreakdown: completion_tokens = (usage.completion_tokens or 0) - reasoning_tokens - return TokenBreakdown( - text_tokens, cached_tokens, completion_tokens, reasoning_tokens - ) + return TokenBreakdown(text_tokens, cached_tokens, completion_tokens, reasoning_tokens) def _calculate_tiered_cost( @@ -181,9 +177,7 @@ def _calculate_completion_cost( else: reasoning_cost = float(reasoning_cost_val) - return (breakdown.completion_tokens * output_cost) + ( - breakdown.reasoning_tokens * reasoning_cost - ) + return (breakdown.completion_tokens * output_cost) + (breakdown.reasoning_tokens * reasoning_cost) def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: @@ -201,15 +195,9 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: """ model_info = get_model_info(model=model, custom_llm_provider="dashscope") breakdown = _extract_token_breakdown(usage) - tiered_pricing = ( - model_info.get("tiered_pricing") - if isinstance(model_info.get("tiered_pricing"), list) - else None - ) + tiered_pricing = model_info.get("tiered_pricing") if isinstance(model_info.get("tiered_pricing"), list) else None - prompt_cost = _calculate_prompt_cost( - breakdown=breakdown, model_info=model_info, tiered_pricing=tiered_pricing - ) + prompt_cost = _calculate_prompt_cost(breakdown=breakdown, model_info=model_info, tiered_pricing=tiered_pricing) completion_cost = _calculate_completion_cost( breakdown=breakdown, model_info=model_info, tiered_pricing=tiered_pricing ) diff --git a/litellm/llms/dashscope/embed/transformation.py b/litellm/llms/dashscope/embed/transformation.py index 5bc0e5ca817c..070e2f576678 100644 --- a/litellm/llms/dashscope/embed/transformation.py +++ b/litellm/llms/dashscope/embed/transformation.py @@ -144,11 +144,7 @@ def transform_embedding_response( if "error" in response_json: error = response_json["error"] - message = ( - error.get("message", str(error)) - if isinstance(error, dict) - else str(error) - ) + message = error.get("message", str(error)) if isinstance(error, dict) else str(error) raise DashScopeError( status_code=raw_response.status_code, message=message, diff --git a/litellm/llms/dashscope/image_generation/transformation.py b/litellm/llms/dashscope/image_generation/transformation.py index 77676b11d513..094e06d12692 100644 --- a/litellm/llms/dashscope/image_generation/transformation.py +++ b/litellm/llms/dashscope/image_generation/transformation.py @@ -62,9 +62,7 @@ class DashScopeImageGenerationConfig(BaseImageGenerationConfig): Configuration for DashScope image generation (qwen-image-2.0, qwen-image-2.0-pro). """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return ["n", "size"] def map_openai_params( @@ -97,9 +95,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - return ( - api_base or get_secret_str("DASHSCOPE_API_BASE_IMAGE") or DEFAULT_API_BASE - ) + return api_base or get_secret_str("DASHSCOPE_API_BASE_IMAGE") or DEFAULT_API_BASE def validate_environment( self, diff --git a/litellm/llms/databricks/chat/transformation.py b/litellm/llms/databricks/chat/transformation.py index 09c782a4755e..a2c1d41022be 100644 --- a/litellm/llms/databricks/chat/transformation.py +++ b/litellm/llms/databricks/chat/transformation.py @@ -84,11 +84,7 @@ def _sanitize_empty_content(message_dict: dict[str, Any]) -> None: filtered = [ block for block in content - if not ( - isinstance(block, dict) - and block.get("type") == "text" - and not (block.get("text") or "").strip() - ) + if not (isinstance(block, dict) and block.get("type") == "text" and not (block.get("text") or "").strip()) ] if not filtered: message_dict.pop("content") @@ -241,12 +237,9 @@ def _map_openai_to_dbrx_tool(self, model: str, tools: List) -> List[DatabricksTo return tools # if claude, convert to anthropic tool and then to databricks tool - anthropic_tools, _ = self._map_tools( - tools=tools - ) # unclear how mcp tool calling on databricks works + anthropic_tools, _ = self._map_tools(tools=tools) # unclear how mcp tool calling on databricks works databricks_tools = [ - cast(DatabricksTool, self.convert_anthropic_tool_to_databricks_tool(tool)) - for tool in anthropic_tools + cast(DatabricksTool, self.convert_anthropic_tool_to_databricks_tool(tool)) for tool in anthropic_tools ] return databricks_tools @@ -260,9 +253,7 @@ def map_response_format_to_databricks_tool( if value is None: return None - tool = self.map_response_format_to_anthropic_tool( - value, optional_params, is_thinking_enabled - ) + tool = self.map_response_format_to_anthropic_tool(value, optional_params, is_thinking_enabled) databricks_tool = self.convert_anthropic_tool_to_databricks_tool(tool) return databricks_tool @@ -291,17 +282,10 @@ def map_openai_params( replace_max_completion_tokens_with_max_tokens: bool = True, ) -> dict: is_thinking_enabled = self.is_thinking_enabled(non_default_params) - mapped_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) if "tools" in mapped_params: - mapped_params["tools"] = self._map_openai_to_dbrx_tool( - model=model, tools=mapped_params["tools"] - ) - if ( - "max_completion_tokens" in non_default_params - and replace_max_completion_tokens_with_max_tokens - ): + mapped_params["tools"] = self._map_openai_to_dbrx_tool(model=model, tools=mapped_params["tools"]) + if "max_completion_tokens" in non_default_params and replace_max_completion_tokens_with_max_tokens: mapped_params["max_tokens"] = non_default_params[ "max_completion_tokens" ] # most openai-compatible providers support 'max_tokens' not 'max_completion_tokens' @@ -316,16 +300,12 @@ def map_openai_params( ) if _tool is not None: - self._add_tools_to_optional_params( - optional_params=optional_params, tools=[_tool] - ) + self._add_tools_to_optional_params(optional_params=optional_params, tools=[_tool]) optional_params["json_mode"] = True if not is_thinking_enabled: _tool_choice = ChatCompletionToolChoiceObjectParam( type="function", - function=ChatCompletionToolChoiceFunctionParam( - name=RESPONSE_FORMAT_TOOL_NAME - ), + function=ChatCompletionToolChoiceFunctionParam(name=RESPONSE_FORMAT_TOOL_NAME), ) optional_params["tool_choice"] = _tool_choice optional_params.pop( @@ -347,9 +327,7 @@ def map_openai_params( if AnthropicConfig._is_adaptive_thinking_model(model): mapped_effort: Optional[str] = None if isinstance(reasoning_effort_value, str): - mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get( - reasoning_effort_value - ) + mapped_effort = REASONING_EFFORT_TO_OUTPUT_CONFIG_EFFORT.get(reasoning_effort_value) if mapped_effort is None: AnthropicConfig._raise_invalid_reasoning_effort( model=model, @@ -408,17 +386,11 @@ def _transform_messages( new_messages.append(_message) if is_async: - return super()._transform_messages( - messages=new_messages, model=model, is_async=cast(Literal[True], True) - ) + return super()._transform_messages(messages=new_messages, model=model, is_async=cast(Literal[True], True)) else: - return super()._transform_messages( - messages=new_messages, model=model, is_async=cast(Literal[False], False) - ) + return super()._transform_messages(messages=new_messages, model=model, is_async=cast(Literal[False], False)) - def _move_cache_control_into_string_content_block( - self, message: AllMessageValues - ) -> AllMessageValues: + def _move_cache_control_into_string_content_block(self, message: AllMessageValues) -> AllMessageValues: """ Moves message-level cache_control into a content block when content is a string. @@ -466,22 +438,14 @@ def extract_reasoning_content( content: Optional[AllDatabricksContentValues], ) -> Tuple[ Optional[str], - Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ], + Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]], ]: """ Extract and return the reasoning content and thinking blocks """ if content is None: return None, None - thinking_blocks: Optional[ - List[ - Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock] - ] - ] = None + thinking_blocks: Optional[List[Union[ChatCompletionThinkingBlock, ChatCompletionRedactedThinkingBlock]]] = None reasoning_content: Optional[str] = None if isinstance(content, list): for item in content: @@ -513,12 +477,7 @@ def extract_citations( for item in content: text = item.get("text", None) if citations_item := item.get("citations"): - citations.append( - [ - {**citation, "supported_text": text} - for citation in citations_item - ] - ) + citations.append([{**citation, "supported_text": text} for citation in citations_item]) return citations or None def _transform_dbrx_choices( @@ -534,9 +493,7 @@ def _transform_dbrx_choices( for _tc in tool_calls: _openai_tc = ChatCompletionMessageToolCall(**_tc) # type: ignore _openai_tool_calls.append(_openai_tc) - fixed_tool_calls = _handle_invalid_parallel_tool_calls( - _openai_tool_calls - ) + fixed_tool_calls = _handle_invalid_parallel_tool_calls(_openai_tool_calls) if fixed_tool_calls is not None: tool_calls = fixed_tool_calls @@ -548,30 +505,22 @@ def _transform_dbrx_choices( convert_tool_call_to_json_mode=json_mode, ): # to support response_format on claude models - json_mode_content_str: Optional[str] = ( - str(tool_calls[0]["function"].get("arguments", "")) or None - ) + json_mode_content_str: Optional[str] = str(tool_calls[0]["function"].get("arguments", "")) or None if json_mode_content_str is not None: translated_message = Message(content=json_mode_content_str) finish_reason = "stop" if translated_message is None: ## get the content str - content_str = DatabricksConfig.extract_content_str( - choice["message"]["content"] - ) + content_str = DatabricksConfig.extract_content_str(choice["message"]["content"]) ## get the reasoning content ( reasoning_content, thinking_blocks, - ) = DatabricksConfig.extract_reasoning_content( - choice["message"].get("content") - ) + ) = DatabricksConfig.extract_reasoning_content(choice["message"].get("content")) - citations = DatabricksConfig.extract_citations( - choice["message"].get("content") - ) + citations = DatabricksConfig.extract_citations(choice["message"].get("content")) translated_message = Message( role="assistant", @@ -579,9 +528,7 @@ def _transform_dbrx_choices( reasoning_content=reasoning_content, thinking_blocks=thinking_blocks, tool_calls=choice["message"].get("tool_calls"), - provider_specific_fields=( - {"citations": citations} if citations is not None else None - ), + provider_specific_fields=({"citations": citations} if citations is not None else None), ) if finish_reason is None: @@ -630,9 +577,7 @@ def transform_response( except Exception as e: response_headers = getattr(raw_response, "headers", None) raise DatabricksException( - message="Unable to get json response - {}, Original Response: {}".format( - str(e), raw_response.text - ), + message="Unable to get json response - {}, Original Response: {}".format(str(e), raw_response.text), status_code=raw_response.status_code, headers=response_headers, ) @@ -715,29 +660,21 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: for _tc in tool_calls: if _tc.get("function", {}).get("arguments") == "{}": _tc["function"]["arguments"] = "" # avoid invalid json - if isinstance(choice["delta"].get("content"), list) and ( - content := choice["delta"]["content"] - ): + if isinstance(choice["delta"].get("content"), list) and (content := choice["delta"]["content"]): if citations := content[0].get("citations"): # TODO: Databricks delta does not include supported text or chunk type. # Add either here once Databricks supports it to enable citation linkage. - choice["delta"].setdefault("provider_specific_fields", {})[ - "citation" - ] = citations[ + choice["delta"].setdefault("provider_specific_fields", {})["citation"] = citations[ 0 ] # Databricks Content item always has citation as a list of list # extract the content str - content_str = DatabricksConfig.extract_content_str( - choice["delta"].get("content") - ) + content_str = DatabricksConfig.extract_content_str(choice["delta"].get("content")) # extract the reasoning content ( reasoning_content, thinking_blocks, - ) = DatabricksConfig.extract_reasoning_content( - choice["delta"].get("content") - ) + ) = DatabricksConfig.extract_reasoning_content(choice["delta"].get("content")) choice["delta"]["content"] = content_str choice["delta"]["reasoning_content"] = reasoning_content diff --git a/litellm/llms/databricks/common_utils.py b/litellm/llms/databricks/common_utils.py index d39d52d2d593..908aa56a4d6e 100644 --- a/litellm/llms/databricks/common_utils.py +++ b/litellm/llms/databricks/common_utils.py @@ -170,10 +170,7 @@ def _build_user_agent(custom_user_agent: Optional[str] = None) -> str: partner_name = custom_user_agent # Validate partner name: alphanumeric, underscore, hyphen only - if ( - partner_name - and partner_name.replace("_", "").replace("-", "").isalnum() - ): + if partner_name and partner_name.replace("_", "").replace("-", "").isalnum(): return f"{partner_name}_litellm/{version}" # Default: just litellm @@ -289,9 +286,7 @@ def _get_databricks_credentials( api_base = api_base or f"{databricks_client.config.host}/serving-endpoints" if api_key is None: - databricks_auth_headers: dict[str, str] = ( - databricks_client.config.authenticate() - ) + databricks_auth_headers: dict[str, str] = databricks_client.config.authenticate() headers = {**databricks_auth_headers, **headers} return api_base, headers @@ -391,9 +386,7 @@ def databricks_validate_environment( headers["User-Agent"] = self._build_user_agent(custom_user_agent) # Debug logging with redaction (never log actual tokens) - verbose_logger.debug( - f"Databricks request headers: {self.redact_headers_for_logging(headers)}" - ) + verbose_logger.debug(f"Databricks request headers: {self.redact_headers_for_logging(headers)}") if endpoint_type == "chat_completions" and custom_endpoint is not True: api_base = "{}/chat/completions".format(api_base) diff --git a/litellm/llms/databricks/cost_calculator.py b/litellm/llms/databricks/cost_calculator.py index 5558e133b4d1..9db151538b59 100644 --- a/litellm/llms/databricks/cost_calculator.py +++ b/litellm/llms/databricks/cost_calculator.py @@ -21,37 +21,23 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd """ base_model = model - if model.startswith("databricks/dbrx-instruct") or model.startswith( - "dbrx-instruct" - ): + if model.startswith("databricks/dbrx-instruct") or model.startswith("dbrx-instruct"): base_model = "databricks-dbrx-instruct" - elif model.startswith("databricks/meta-llama-3.1-70b-instruct") or model.startswith( - "meta-llama-3.1-70b-instruct" - ): + elif model.startswith("databricks/meta-llama-3.1-70b-instruct") or model.startswith("meta-llama-3.1-70b-instruct"): base_model = "databricks-meta-llama-3-1-70b-instruct" - elif model.startswith( - "databricks/meta-llama-3.1-405b-instruct" - ) or model.startswith("meta-llama-3.1-405b-instruct"): - base_model = "databricks-meta-llama-3-1-405b-instruct" - elif model.startswith("databricks/mixtral-8x7b-instruct-v0.1") or model.startswith( - "mixtral-8x7b-instruct-v0.1" + elif model.startswith("databricks/meta-llama-3.1-405b-instruct") or model.startswith( + "meta-llama-3.1-405b-instruct" ): + base_model = "databricks-meta-llama-3-1-405b-instruct" + elif model.startswith("databricks/mixtral-8x7b-instruct-v0.1") or model.startswith("mixtral-8x7b-instruct-v0.1"): base_model = "databricks-mixtral-8x7b-instruct" - elif model.startswith("databricks/mixtral-8x7b-instruct-v0.1") or model.startswith( - "mixtral-8x7b-instruct-v0.1" - ): + elif model.startswith("databricks/mixtral-8x7b-instruct-v0.1") or model.startswith("mixtral-8x7b-instruct-v0.1"): base_model = "databricks-mixtral-8x7b-instruct" - elif model.startswith("databricks/bge-large-en") or model.startswith( - "bge-large-en" - ): + elif model.startswith("databricks/bge-large-en") or model.startswith("bge-large-en"): base_model = "databricks-bge-large-en" - elif model.startswith("databricks/gte-large-en") or model.startswith( - "gte-large-en" - ): + elif model.startswith("databricks/gte-large-en") or model.startswith("gte-large-en"): base_model = "databricks-gte-large-en" - elif model.startswith("databricks/llama-2-70b-chat") or model.startswith( - "llama-2-70b-chat" - ): + elif model.startswith("databricks/llama-2-70b-chat") or model.startswith("llama-2-70b-chat"): base_model = "databricks-llama-2-70b-chat" ## GET MODEL INFO model_info = get_model_info(model=base_model, custom_llm_provider="databricks") diff --git a/litellm/llms/databricks/streaming_utils.py b/litellm/llms/databricks/streaming_utils.py index 7a7330227d6d..a6a45719fe66 100644 --- a/litellm/llms/databricks/streaming_utils.py +++ b/litellm/llms/databricks/streaming_utils.py @@ -127,9 +127,7 @@ def __next__(self): except StopIteration: raise StopIteration except ValueError as e: - verbose_logger.debug( - f"Error parsing chunk: {e},\nReceived chunk: {chunk}. Defaulting to empty chunk here." - ) + verbose_logger.debug(f"Error parsing chunk: {e},\nReceived chunk: {chunk}. Defaulting to empty chunk here.") return GenericStreamingChunk( text="", is_finished=False, @@ -174,9 +172,7 @@ async def __anext__(self): except StopAsyncIteration: raise StopAsyncIteration except ValueError as e: - verbose_logger.debug( - f"Error parsing chunk: {e},\nReceived chunk: {chunk}. Defaulting to empty chunk here." - ) + verbose_logger.debug(f"Error parsing chunk: {e},\nReceived chunk: {chunk}. Defaulting to empty chunk here.") return GenericStreamingChunk( text="", is_finished=False, diff --git a/litellm/llms/dataforseo/search/transformation.py b/litellm/llms/dataforseo/search/transformation.py index 701db586b72a..97a2539b3df7 100644 --- a/litellm/llms/dataforseo/search/transformation.py +++ b/litellm/llms/dataforseo/search/transformation.py @@ -26,9 +26,7 @@ class DataForSEOSearchConfig(BaseSearchConfig): API endpoint: https://api.dataforseo.com/v3/serp/google/organic/live/advanced """ - DATAFORSEO_API_BASE = ( - "https://api.dataforseo.com/v3/serp/google/organic/live/advanced" - ) + DATAFORSEO_API_BASE = "https://api.dataforseo.com/v3/serp/google/organic/live/advanced" @staticmethod def ui_friendly_name() -> str: @@ -103,11 +101,7 @@ def get_complete_url( DataForSEO uses POST requests, so no query parameters in URL. """ - return ( - api_base - or get_secret_str("DATAFORSEO_API_BASE") - or self.DATAFORSEO_API_BASE - ) + return api_base or get_secret_str("DATAFORSEO_API_BASE") or self.DATAFORSEO_API_BASE def transform_search_request( self, @@ -152,10 +146,7 @@ def transform_search_request( # For simplicity, we'll use location_name which accepts country names task["location_name"] = optional_params["country"] - if ( - "search_domain_filter" in optional_params - and optional_params["search_domain_filter"] - ): + if "search_domain_filter" in optional_params and optional_params["search_domain_filter"]: # DataForSEO uses 'domain' parameter to filter by domain task["domain"] = optional_params["search_domain_filter"] @@ -169,10 +160,7 @@ def transform_search_request( # Pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in task - ): + if param not in self.get_supported_perplexity_optional_params() and param not in task: task[param] = value # DataForSEO API expects an array of tasks diff --git a/litellm/llms/datarobot/chat/transformation.py b/litellm/llms/datarobot/chat/transformation.py index f81e2420930c..75bbfc19b699 100644 --- a/litellm/llms/datarobot/chat/transformation.py +++ b/litellm/llms/datarobot/chat/transformation.py @@ -42,9 +42,7 @@ def _resolve_api_base(api_base: Optional[str] = None) -> Optional[str]: path += f"/api/v2/{LLMGW_PATH}" elif "api/v2/deployments" in path: # Dedicated deployment, leave it pass - elif ( - "api/v2" in path and LLMGW_PATH not in path - ): # Standard ENDPOINT path, add LLMGW + elif "api/v2" in path and LLMGW_PATH not in path: # Standard ENDPOINT path, add LLMGW path += LLMGW_PATH # Ensure the url ends with a trailing slash diff --git a/litellm/llms/deepgram/audio_transcription/transformation.py b/litellm/llms/deepgram/audio_transcription/transformation.py index 6a540d727784..b05fba3b5ca8 100644 --- a/litellm/llms/deepgram/audio_transcription/transformation.py +++ b/litellm/llms/deepgram/audio_transcription/transformation.py @@ -24,9 +24,7 @@ class DeepgramAudioTranscriptionConfig(BaseAudioTranscriptionConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: return ["language"] def map_openai_params( @@ -42,12 +40,8 @@ def map_openai_params( optional_params[k] = v return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return DeepgramException( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return DeepgramException(message=error_message, status_code=status_code, headers=headers) def transform_audio_transcription_request( self, @@ -72,9 +66,7 @@ def transform_audio_transcription_request( # Return structured data with binary content and no files # For Deepgram, we send binary data directly as request body - return AudioTranscriptionRequestData( - data=processed_audio.file_content, files=None - ) + return AudioTranscriptionRequestData(data=processed_audio.file_content, files=None) def transform_audio_transcription_response( self, @@ -131,9 +123,7 @@ def transform_audio_transcription_response( return response except Exception as e: - raise ValueError( - f"Error transforming Deepgram response: {str(e)}\nResponse: {raw_response.text}" - ) + raise ValueError(f"Error transforming Deepgram response: {str(e)}\nResponse: {raw_response.text}") def _reconstruct_diarized_transcript(self, words: list) -> str: """ @@ -160,9 +150,7 @@ def _reconstruct_diarized_transcript(self, words: list) -> str: if speaker != current_speaker: # New speaker: save previous segment and start new one if current_words: - segments.append( - f"Speaker {current_speaker}: {' '.join(current_words)}" - ) + segments.append(f"Speaker {current_speaker}: {' '.join(current_words)}") current_speaker = speaker current_words = [word_text] else: @@ -185,9 +173,7 @@ def get_complete_url( stream: Optional[bool] = None, ) -> str: if api_base is None: - api_base = ( - get_secret_str("DEEPGRAM_API_BASE") or "https://api.deepgram.com/v1" - ) + api_base = get_secret_str("DEEPGRAM_API_BASE") or "https://api.deepgram.com/v1" api_base = api_base.rstrip("/") # Remove trailing slash if present # Build query parameters including the model diff --git a/litellm/llms/deepinfra/chat/transformation.py b/litellm/llms/deepinfra/chat/transformation.py index a6bd8b4934f4..494c53354f74 100644 --- a/litellm/llms/deepinfra/chat/transformation.py +++ b/litellm/llms/deepinfra/chat/transformation.py @@ -94,15 +94,11 @@ def map_openai_params( supported_openai_params = self.get_supported_openai_params(model=model) for param, value in non_default_params.items(): if ( - param == "temperature" - and value == 0 - and model == "mistralai/Mistral-7B-Instruct-v0.1" + param == "temperature" and value == 0 and model == "mistralai/Mistral-7B-Instruct-v0.1" ): # this model does no support temperature == 0 value = MIN_NON_ZERO_TEMPERATURE # close to 0 if param == "tool_choice": - if ( - value != "auto" and value != "none" - ): # https://deepinfra.com/docs/advanced/function_calling + if value != "auto" and value != "none": # https://deepinfra.com/docs/advanced/function_calling ## UNSUPPORTED TOOL CHOICE VALUE if litellm.drop_params is True or drop_params is True: value = None @@ -120,9 +116,7 @@ def map_openai_params( optional_params[param] = value return optional_params - def _transform_tool_message_content( - self, messages: List[AllMessageValues] - ) -> List[AllMessageValues]: + def _transform_tool_message_content(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: """ Transform tool message content from array to string format for DeepInfra compatibility. @@ -201,10 +195,6 @@ def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: # deepinfra is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.endpoints.anyscale.com/v1 - api_base = ( - api_base - or get_secret_str("DEEPINFRA_API_BASE") - or "https://api.deepinfra.com/v1/openai" - ) + api_base = api_base or get_secret_str("DEEPINFRA_API_BASE") or "https://api.deepinfra.com/v1/openai" dynamic_api_key = api_key or get_secret_str("DEEPINFRA_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/deepinfra/rerank/transformation.py b/litellm/llms/deepinfra/rerank/transformation.py index 385aa051d007..82069e4e195e 100644 --- a/litellm/llms/deepinfra/rerank/transformation.py +++ b/litellm/llms/deepinfra/rerank/transformation.py @@ -53,9 +53,7 @@ def get_complete_url( ) # Remove 'openai' from the base if present - api_base_clean = ( - api_base.replace("openai", "") if "openai" in api_base else api_base - ) + api_base_clean = api_base.replace("openai", "") if "openai" in api_base else api_base # Remove any trailing slashes for consistency, then add one api_base_clean = api_base_clean.rstrip("/") + "/" @@ -74,9 +72,7 @@ def validate_environment( api_key = get_secret_str("DEEPINFRA_API_KEY") if api_key is None: - raise ValueError( - "Deepinfra API key is required. Please set 'DEEPINFRA_API_KEY' environment variable" - ) + raise ValueError("Deepinfra API key is required. Please set 'DEEPINFRA_API_KEY' environment variable") default_headers = { "Authorization": f"Bearer {api_key}", @@ -171,9 +167,7 @@ def transform_rerank_response( # Create RerankResponse results = [] for i, score in enumerate(scores): - results.append( - RerankResponseResult(index=i, relevance_score=float(score)) - ) + results.append(RerankResponseResult(index=i, relevance_score=float(score))) # Create metadata for the response tokens = RerankTokens( @@ -183,9 +177,7 @@ def transform_rerank_response( billed_units = RerankBilledUnits(total_tokens=input_tokens) meta = RerankResponseMeta(tokens=tokens, billed_units=billed_units) - rerank_response = RerankResponse( - id=request_id or str(uuid.uuid4()), results=results, meta=meta - ) + rerank_response = RerankResponse(id=request_id or str(uuid.uuid4()), results=results, meta=meta) # Store additional information in hidden params rerank_response._hidden_params = { diff --git a/litellm/llms/deepseek/chat/transformation.py b/litellm/llms/deepseek/chat/transformation.py index b90b1e1aa21e..7a548136f2aa 100644 --- a/litellm/llms/deepseek/chat/transformation.py +++ b/litellm/llms/deepseek/chat/transformation.py @@ -40,9 +40,7 @@ def map_openai_params( Reference: https://api-docs.deepseek.com/guides/thinking_mode """ # Let parent handle standard params first - optional_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + optional_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) # Pop thinking/reasoning_effort from optional_params first (parent may have added them) # Then re-add only if valid for DeepSeek @@ -51,10 +49,7 @@ def map_openai_params( # Handle thinking parameter - only accept {"type": "enabled"} if thinking_value is not None: - if ( - isinstance(thinking_value, dict) - and thinking_value.get("type") == "enabled" - ): + if isinstance(thinking_value, dict) and thinking_value.get("type") == "enabled": # DeepSeek only accepts {"type": "enabled"}, ignore budget_tokens optional_params["thinking"] = {"type": "enabled"} @@ -64,9 +59,7 @@ def map_openai_params( return optional_params - def _fill_reasoning_content( - self, messages: List[AllMessageValues] - ) -> List[AllMessageValues]: + def _fill_reasoning_content(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: """ DeepSeek thinking mode requires `reasoning_content` to be passed back on every assistant message in multi-turn conversations. If it is missing, @@ -127,13 +120,9 @@ def _transform_messages( """ messages = handle_messages_with_content_list_to_str_conversion(messages) if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _thinking_mode_active(self, model: str, optional_params: dict) -> bool: """ @@ -177,9 +166,7 @@ def _get_function_tool_name(tool: object) -> str | None: name = function.get("name") return name if isinstance(name, str) else None - def _tool_choice_matches_function_tool( - tool_choice: object, function_tool_names: set[str] - ) -> bool: + def _tool_choice_matches_function_tool(tool_choice: object, function_tool_names: set[str]) -> bool: if not isinstance(tool_choice, dict): return True if tool_choice.get("type") != "function": @@ -210,21 +197,12 @@ def _tool_choice_matches_function_tool( cleaned = {k: v for k, v in optional_params.items() if k != "tools"} if function_tools: function_tool_names = { - name - for tool in function_tools - for name in (_get_function_tool_name(tool),) - if name is not None + name for tool in function_tools for name in (_get_function_tool_name(tool),) if name is not None } - if not _tool_choice_matches_function_tool( - cleaned.get("tool_choice"), function_tool_names - ): + if not _tool_choice_matches_function_tool(cleaned.get("tool_choice"), function_tool_names): cleaned = {k: v for k, v in cleaned.items() if k != "tool_choice"} return {**cleaned, "tools": function_tools} - return { - k: v - for k, v in cleaned.items() - if k not in ("tool_choice", "parallel_tool_calls") - } + return {k: v for k, v in cleaned.items() if k not in ("tool_choice", "parallel_tool_calls")} def transform_request( self, @@ -280,11 +258,7 @@ async def async_transform_request( def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( - api_base - or get_secret_str("DEEPSEEK_API_BASE") - or "https://api.deepseek.com/beta" - ) # type: ignore + api_base = api_base or get_secret_str("DEEPSEEK_API_BASE") or "https://api.deepseek.com/beta" # type: ignore dynamic_api_key = api_key or get_secret_str("DEEPSEEK_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/deepseek/cost_calculator.py b/litellm/llms/deepseek/cost_calculator.py index e652ebeac541..312bd5bdeab6 100644 --- a/litellm/llms/deepseek/cost_calculator.py +++ b/litellm/llms/deepseek/cost_calculator.py @@ -16,6 +16,4 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: Follows the same logic as Anthropic's cost per token calculation. """ - return generic_cost_per_token( - model=model, usage=usage, custom_llm_provider="deepseek" - ) + return generic_cost_per_token(model=model, usage=usage, custom_llm_provider="deepseek") diff --git a/litellm/llms/deepseek/messages/transformation.py b/litellm/llms/deepseek/messages/transformation.py index 63b736ffd1d9..ddbbe7c21074 100644 --- a/litellm/llms/deepseek/messages/transformation.py +++ b/litellm/llms/deepseek/messages/transformation.py @@ -54,11 +54,7 @@ def validate_anthropic_messages_environment( ) -> Tuple[dict, Optional[str]]: dynamic_api_key = self.get_api_key(api_key=api_key) - if ( - "x-api-key" not in headers - and "authorization" not in headers - and dynamic_api_key is not None - ): + if "x-api-key" not in headers and "authorization" not in headers and dynamic_api_key is not None: headers["x-api-key"] = dynamic_api_key if "anthropic-version" not in headers: @@ -130,7 +126,5 @@ def transform_anthropic_messages_request( headers=headers, ) if "tools" in anthropic_messages_request: - anthropic_messages_request["tools"] = self._sanitize_tools_for_deepseek( - anthropic_messages_request["tools"] - ) + anthropic_messages_request["tools"] = self._sanitize_tools_for_deepseek(anthropic_messages_request["tools"]) return anthropic_messages_request diff --git a/litellm/llms/deprecated_providers/aleph_alpha.py b/litellm/llms/deprecated_providers/aleph_alpha.py index 81ad13464141..f58297997b6a 100644 --- a/litellm/llms/deprecated_providers/aleph_alpha.py +++ b/litellm/llms/deprecated_providers/aleph_alpha.py @@ -13,13 +13,9 @@ class AlephAlphaError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.aleph-alpha.com/complete" - ) + self.request = httpx.Request(method="POST", url="https://api.aleph-alpha.com/complete") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class AlephAlphaConfig: @@ -77,9 +73,7 @@ class AlephAlphaConfig: - `control_log_additive` (boolean; default value: true): Method of applying control to attention scores. """ - maximum_tokens: Optional[int] = ( - litellm.max_tokens - ) # aleph alpha requires max tokens + maximum_tokens: Optional[int] = litellm.max_tokens # aleph alpha requires max tokens minimum_tokens: Optional[int] = None echo: Optional[bool] = None temperature: Optional[int] = None @@ -209,9 +203,7 @@ def completion( if "control" in model: # follow the ###Instruction / ###Response format for idx, message in enumerate(messages): if "role" in message: - if ( - idx == 0 - ): # set first message as instruction (required), let later user messages be input + if idx == 0: # set first message as instruction (required), let later user messages be input prompt += f"###Instruction: {message['content']}" else: if message["role"] == "system": diff --git a/litellm/llms/deprecated_providers/palm.py b/litellm/llms/deprecated_providers/palm.py index 657a6fdb229c..a8523ecfa0ee 100644 --- a/litellm/llms/deprecated_providers/palm.py +++ b/litellm/llms/deprecated_providers/palm.py @@ -19,9 +19,7 @@ def __init__(self, status_code, message): url="https://developers.generativeai.google/api/python/google/generativeai/chat", ) self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class PalmConfig: @@ -102,9 +100,7 @@ def completion( try: import google.generativeai as palm # type: ignore except Exception: - raise Exception( - "Importing google.generativeai failed, please run 'pip install -q google-generativeai" - ) + raise Exception("Importing google.generativeai failed, please run 'pip install -q google-generativeai") palm.configure(api_key=api_key) model = model @@ -167,9 +163,7 @@ def completion( choices_list.append(choice_obj) model_response.choices = choices_list # type: ignore except Exception: - raise PalmError( - message=traceback.format_exc(), status_code=response.status_code - ) + raise PalmError(message=traceback.format_exc(), status_code=response.status_code) try: completion_response = model_response["choices"][0]["message"].get("content") @@ -181,9 +175,7 @@ def completion( ## CALCULATING USAGE - baseten charges on time, not tokens - have some mapping of cost here. prompt_tokens = len(encoding.encode(prompt)) - completion_tokens = len( - encoding.encode(model_response["choices"][0]["message"].get("content", "")) - ) + completion_tokens = len(encoding.encode(model_response["choices"][0]["message"].get("content", ""))) model_response.created = int(time.time()) model_response.model = "palm/" + model diff --git a/litellm/llms/docker_model_runner/chat/transformation.py b/litellm/llms/docker_model_runner/chat/transformation.py index dc03c80f1544..137a39e0984e 100644 --- a/litellm/llms/docker_model_runner/chat/transformation.py +++ b/litellm/llms/docker_model_runner/chat/transformation.py @@ -44,13 +44,9 @@ def _transform_messages( """ messages = handle_messages_with_content_list_to_str_conversion(messages) if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] @@ -62,14 +58,10 @@ def _get_openai_compatible_provider_info( The engine path should be included in the api_base. """ api_base = ( - api_base - or get_secret_str("DOCKER_MODEL_RUNNER_API_BASE") - or "http://localhost:22088/engines/llama.cpp" + api_base or get_secret_str("DOCKER_MODEL_RUNNER_API_BASE") or "http://localhost:22088/engines/llama.cpp" ) # type: ignore # Docker Model Runner may not require authentication for local instances - dynamic_api_key = ( - api_key or get_secret_str("DOCKER_MODEL_RUNNER_API_KEY") or "dummy-key" - ) + dynamic_api_key = api_key or get_secret_str("DOCKER_MODEL_RUNNER_API_KEY") or "dummy-key" return api_base, dynamic_api_key def get_complete_url( diff --git a/litellm/llms/duckduckgo/search/transformation.py b/litellm/llms/duckduckgo/search/transformation.py index e8eda3a37ab3..0ef21222a29b 100644 --- a/litellm/llms/duckduckgo/search/transformation.py +++ b/litellm/llms/duckduckgo/search/transformation.py @@ -80,11 +80,7 @@ def get_complete_url( Get complete URL for Search endpoint. DuckDuckGo uses query parameters, so we construct the URL with the query. """ - api_base = ( - api_base - or get_secret_str("DUCKDUCKGO_API_BASE") - or self.DUCKDUCKGO_API_BASE - ) + api_base = api_base or get_secret_str("DUCKDUCKGO_API_BASE") or self.DUCKDUCKGO_API_BASE # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_duckduckgo_params" in data: diff --git a/litellm/llms/e2b/sandbox/transformation.py b/litellm/llms/e2b/sandbox/transformation.py index ecfc1642c979..a78f1d8541e9 100644 --- a/litellm/llms/e2b/sandbox/transformation.py +++ b/litellm/llms/e2b/sandbox/transformation.py @@ -63,9 +63,7 @@ async def acreate_sandbox( "templateID": template or E2B_DEFAULT_TEMPLATE, "timeout": timeout if timeout is not None else DEFAULT_SANDBOX_TIMEOUT, "secure": True, - "allow_internet_access": ( - True if allow_internet_access is None else allow_internet_access - ), + "allow_internet_access": (True if allow_internet_access is None else allow_internet_access), } if metadata: body["metadata"] = metadata @@ -141,11 +139,7 @@ async def adelete_sandbox( **kwargs, ) -> bool: handle = self._as_handle(container) - key = ( - api_key - or handle._hidden_params.get("api_key") - or self.validate_environment() - ) + key = api_key or handle._hidden_params.get("api_key") or self.validate_environment() base = api_base or handle._hidden_params.get("api_base") or E2B_API_BASE try: response = cast( @@ -165,9 +159,7 @@ async def adelete_sandbox( def _as_handle(container: Union[ContainerHandle, str]) -> ContainerHandle: if isinstance(container, ContainerHandle): return container - handle = ContainerHandle( - id=str(container), provider="e2b", domain=E2B_DEFAULT_DOMAIN - ) + handle = ContainerHandle(id=str(container), provider="e2b", domain=E2B_DEFAULT_DOMAIN) handle._hidden_params = {} return handle @@ -180,20 +172,14 @@ def _try_parse(stripped: str): return None messages = tuple( - parsed - for line in lines - if (stripped := line.strip()) - if (parsed := _try_parse(stripped)) is not None + parsed for line in lines if (stripped := line.strip()) if (parsed := _try_parse(stripped)) is not None ) def of_type(message_type: str): return (m for m in messages if m.get("type") == message_type) error = next( - ( - {key: m.get(key) for key in ("name", "value", "traceback")} - for m in of_type("error") - ), + ({key: m.get(key) for key in ("name", "value", "traceback")} for m in of_type("error")), None, ) execution_count = next( @@ -204,9 +190,7 @@ def of_type(message_type: str): return CodeExecutionResult( stdout="".join(m.get("text", "") for m in of_type("stdout")), stderr="".join(m.get("text", "") for m in of_type("stderr")), - results=[ - {k: v for k, v in m.items() if k != "type"} for m in of_type("result") - ], + results=[{k: v for k, v in m.items() if k != "type"} for m in of_type("result")], error=error, execution_count=execution_count, ) diff --git a/litellm/llms/elevenlabs/audio_transcription/transformation.py b/litellm/llms/elevenlabs/audio_transcription/transformation.py index 8746e92d9f6e..68d1b5e16ddf 100644 --- a/litellm/llms/elevenlabs/audio_transcription/transformation.py +++ b/litellm/llms/elevenlabs/audio_transcription/transformation.py @@ -28,9 +28,7 @@ class ElevenLabsAudioTranscriptionConfig(BaseAudioTranscriptionConfig): def custom_llm_provider(self) -> str: return litellm.LlmProviders.ELEVENLABS.value - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: return ["language", "temperature"] def map_openai_params( @@ -50,12 +48,8 @@ def map_openai_params( optional_params[k] = v return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return ElevenLabsException( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return ElevenLabsException(message=error_message, status_code=status_code, headers=headers) def transform_audio_transcription_request( self, @@ -152,9 +146,7 @@ def transform_audio_transcription_response( return response except Exception as e: - raise ValueError( - f"Error transforming ElevenLabs response: {str(e)}\nResponse: {raw_response.text}" - ) + raise ValueError(f"Error transforming ElevenLabs response: {str(e)}\nResponse: {raw_response.text}") def get_complete_url( self, @@ -166,9 +158,7 @@ def get_complete_url( stream: Optional[bool] = None, ) -> str: if api_base is None: - api_base = ( - get_secret_str("ELEVENLABS_API_BASE") or "https://api.elevenlabs.io" - ) + api_base = get_secret_str("ELEVENLABS_API_BASE") or "https://api.elevenlabs.io" api_base = api_base.rstrip("/") # Remove trailing slash if present # ElevenLabs speech-to-text endpoint @@ -188,9 +178,7 @@ def validate_environment( ) -> dict: api_key = api_key or get_secret_str("ELEVENLABS_API_KEY") if api_key is None: - raise ValueError( - "ElevenLabs API key is required. Set ELEVENLABS_API_KEY environment variable." - ) + raise ValueError("ElevenLabs API key is required. Set ELEVENLABS_API_KEY environment variable.") auth_header = { "xi-api-key": api_key, diff --git a/litellm/llms/elevenlabs/text_to_speech/transformation.py b/litellm/llms/elevenlabs/text_to_speech/transformation.py index 612fc687ef90..b5b7799a3e9f 100644 --- a/litellm/llms/elevenlabs/text_to_speech/transformation.py +++ b/litellm/llms/elevenlabs/text_to_speech/transformation.py @@ -105,9 +105,7 @@ def _resolve_voice_id( mapped_voice = self._extract_voice_id(voice_override) if mapped_voice is None: - raise ValueError( - "ElevenLabs voice_id is required. Pass `voice` when calling `litellm.speech()`." - ) + raise ValueError("ElevenLabs voice_id is required. Pass `voice` when calling `litellm.speech()`.") return mapped_voice @@ -175,17 +173,10 @@ def validate_environment( """ Validate Azure environment and set up authentication headers """ - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("ELEVENLABS_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("ELEVENLABS_API_KEY") if api_key is None: - raise ValueError( - "ElevenLabs API key is required. Set ELEVENLABS_API_KEY environment variable." - ) + raise ValueError("ElevenLabs API key is required. Set ELEVENLABS_API_KEY environment variable.") headers.update( { @@ -196,12 +187,8 @@ def validate_environment( return headers - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return ElevenLabsException( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return ElevenLabsException(message=error_message, status_code=status_code, headers=headers) def transform_text_to_speech_request( self, @@ -310,16 +297,12 @@ def get_complete_url( """ Construct the ElevenLabs endpoint URL, including path voice_id and query params. """ - base_url = ( - api_base or get_secret_str("ELEVENLABS_API_BASE") or self.TTS_BASE_URL - ) + base_url = api_base or get_secret_str("ELEVENLABS_API_BASE") or self.TTS_BASE_URL base_url = base_url.rstrip("/") voice_id = litellm_params.get(self.ELEVENLABS_VOICE_ID_KEY) if not isinstance(voice_id, str) or not voice_id.strip(): - raise ValueError( - "ElevenLabs voice_id is required. Pass `voice` when calling `litellm.speech()`." - ) + raise ValueError("ElevenLabs voice_id is required. Pass `voice` when calling `litellm.speech()`.") encoded_voice_id = encode_url_path_segment(voice_id, field_name="voice_id") url = f"{base_url}{self.TTS_ENDPOINT_PATH}/{encoded_voice_id}" diff --git a/litellm/llms/exa_ai/search/transformation.py b/litellm/llms/exa_ai/search/transformation.py index 5cfd14aeaa9b..93fbdeff9901 100644 --- a/litellm/llms/exa_ai/search/transformation.py +++ b/litellm/llms/exa_ai/search/transformation.py @@ -40,9 +40,7 @@ class ExaAISearchRequest(_ExaAISearchRequestRequired, total=False): startPublishedDate: str # Optional - published date filter (ISO 8601 format) endPublishedDate: str # Optional - published date filter (ISO 8601 format) includeText: List[str] # Optional - strings that must be present in webpage text - excludeText: List[ - str - ] # Optional - strings that must not be present in webpage text + excludeText: List[str] # Optional - strings that must not be present in webpage text context: Union[bool, dict] # Optional - format results for LLMs moderation: bool # Optional - enable content moderation, default false contents: dict # Optional - content retrieval options @@ -73,9 +71,7 @@ def validate_environment( default_api_base=self.EXA_AI_API_BASE, ) if not api_key: - raise ValueError( - "EXA_API_KEY is not set. Set `EXA_API_KEY` environment variable." - ) + raise ValueError("EXA_API_KEY is not set. Set `EXA_API_KEY` environment variable.") headers["x-api-key"] = api_key headers["Content-Type"] = "application/json" return headers @@ -146,10 +142,7 @@ def transform_search_request( # pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # By default, request text content if not explicitly specified diff --git a/litellm/llms/fal_ai/cost_calculator.py b/litellm/llms/fal_ai/cost_calculator.py index 9cdd0cd485b9..6e32141afd44 100644 --- a/litellm/llms/fal_ai/cost_calculator.py +++ b/litellm/llms/fal_ai/cost_calculator.py @@ -22,6 +22,4 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") diff --git a/litellm/llms/fal_ai/image_generation/__init__.py b/litellm/llms/fal_ai/image_generation/__init__.py index 7f3358934a76..d31524510b84 100644 --- a/litellm/llms/fal_ai/image_generation/__init__.py +++ b/litellm/llms/fal_ai/image_generation/__init__.py @@ -59,11 +59,7 @@ def get_fal_ai_image_generation_config(model: str) -> BaseImageGenerationConfig: if "ultra" in model_lower: return FalAIFluxProV11UltraConfig() return FalAIFluxProV11Config() - elif ( - "flux/schnell" in model_lower - or "flux-schnell" in model_lower - or "schnell" in model_lower - ): + elif "flux/schnell" in model_lower or "flux-schnell" in model_lower or "schnell" in model_lower: return FalAIFluxSchnellConfig() elif "bytedance/seedream" in model_lower: return FalAIBytedanceSeedreamV3Config() diff --git a/litellm/llms/fal_ai/image_generation/bria_transformation.py b/litellm/llms/fal_ai/image_generation/bria_transformation.py index dd6e737324e0..7bdfa860c5d5 100644 --- a/litellm/llms/fal_ai/image_generation/bria_transformation.py +++ b/litellm/llms/fal_ai/image_generation/bria_transformation.py @@ -28,9 +28,7 @@ class FalAIBriaConfig(FalAIBaseConfig): IMAGE_GENERATION_ENDPOINT: str = "bria/text-to-image/3.2" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for Bria 3.2. """ diff --git a/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py b/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py index fef292d33115..fb980905a288 100644 --- a/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py +++ b/litellm/llms/fal_ai/image_generation/flux_pro_v11_ultra_transformation.py @@ -28,9 +28,7 @@ class FalAIFluxProV11UltraConfig(FalAIBaseConfig): IMAGE_GENERATION_ENDPOINT: str = "fal-ai/flux-pro/v1.1-ultra" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for Flux Pro v1.1-ultra. """ @@ -256,8 +254,6 @@ def transform_image_generation_response( if "timings" in response_data: model_response._hidden_params["timings"] = response_data["timings"] if "has_nsfw_concepts" in response_data: - model_response._hidden_params["has_nsfw_concepts"] = response_data[ - "has_nsfw_concepts" - ] + model_response._hidden_params["has_nsfw_concepts"] = response_data["has_nsfw_concepts"] return model_response diff --git a/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py b/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py index 14e136d5d6f7..500a4b20ef2c 100644 --- a/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py +++ b/litellm/llms/fal_ai/image_generation/ideogram_v3_transformation.py @@ -38,9 +38,7 @@ class FalAIIdeogramV3Config(FalAIBaseConfig): "1024x1536": "portrait_16_9", } - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Ideogram v3 accepts the core OpenAI image parameters. """ diff --git a/litellm/llms/fal_ai/image_generation/imagen4_transformation.py b/litellm/llms/fal_ai/image_generation/imagen4_transformation.py index ea6e7c1f3c9f..1b111c989872 100644 --- a/litellm/llms/fal_ai/image_generation/imagen4_transformation.py +++ b/litellm/llms/fal_ai/image_generation/imagen4_transformation.py @@ -31,9 +31,7 @@ class FalAIImagen4Config(FalAIBaseConfig): IMAGE_GENERATION_ENDPOINT: str = "fal-ai/imagen4/preview" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for Imagen4. """ diff --git a/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py b/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py index dd4758055ac5..0a8ba3699bbd 100644 --- a/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py +++ b/litellm/llms/fal_ai/image_generation/nano_banana_transformation.py @@ -40,15 +40,11 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - base_url: str = ( - api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL - ).rstrip("/") + base_url: str = (api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL).rstrip("/") endpoint = model if model.startswith("fal-ai/") else f"fal-ai/{model}" return f"{base_url}/{endpoint}" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return ["n", "response_format", "size"] def map_openai_params( diff --git a/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py b/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py index 72ee165b51a8..2ce36d9c1ea0 100644 --- a/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py +++ b/litellm/llms/fal_ai/image_generation/recraft_v3_transformation.py @@ -28,9 +28,7 @@ class FalAIRecraftV3Config(FalAIBaseConfig): IMAGE_GENERATION_ENDPOINT: str = "fal-ai/recraft/v3/text-to-image" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for Recraft v3. """ diff --git a/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py b/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py index f0077c6a6745..bc7a3839bd38 100644 --- a/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py +++ b/litellm/llms/fal_ai/image_generation/stable_diffusion_transformation.py @@ -46,9 +46,7 @@ def get_complete_url( """ from litellm.secret_managers.main import get_secret_str - complete_url: str = ( - api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") @@ -65,9 +63,7 @@ def get_complete_url( complete_url = f"{complete_url}/{endpoint}" return complete_url - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for Stable Diffusion models. """ @@ -272,8 +268,6 @@ def transform_image_generation_response( if "timings" in response_data: model_response._hidden_params["timings"] = response_data["timings"] if "has_nsfw_concepts" in response_data: - model_response._hidden_params["has_nsfw_concepts"] = response_data[ - "has_nsfw_concepts" - ] + model_response._hidden_params["has_nsfw_concepts"] = response_data["has_nsfw_concepts"] return model_response diff --git a/litellm/llms/fal_ai/image_generation/transformation.py b/litellm/llms/fal_ai/image_generation/transformation.py index 4a0dea48a10e..07eb2cc4cc4b 100644 --- a/litellm/llms/fal_ai/image_generation/transformation.py +++ b/litellm/llms/fal_ai/image_generation/transformation.py @@ -43,9 +43,7 @@ def get_complete_url( Some providers need `model` in `api_base` """ - complete_url: str = ( - api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("FAL_AI_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") if self.IMAGE_GENERATION_ENDPOINT: @@ -124,9 +122,7 @@ class FalAIImageGenerationConfig(FalAIBaseConfig): Default Fal AI image generation configuration for generic models. """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for fal.ai image generation """ diff --git a/litellm/llms/fastcrw/search/transformation.py b/litellm/llms/fastcrw/search/transformation.py index b571a659cace..6de9ef642fbc 100644 --- a/litellm/llms/fastcrw/search/transformation.py +++ b/litellm/llms/fastcrw/search/transformation.py @@ -34,9 +34,7 @@ class FastCRWSearchRequest(_FastCRWSearchRequestRequired, total=False): """ limit: int # Optional - maximum number of results to return - sources: list[ - str - ] # Optional - sources to search ('web', 'images'), default ['web'] + sources: list[str] # Optional - sources to search ('web', 'images'), default ['web'] scrapeOptions: dict # Optional - options for scraping search results @@ -65,9 +63,7 @@ def validate_environment( default_api_base=self.FASTCRW_API_BASE, ) if not api_key: - raise ValueError( - "CRW_API_KEY is not set. Set `CRW_API_KEY` environment variable." - ) + raise ValueError("CRW_API_KEY is not set. Set `CRW_API_KEY` environment variable.") headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -129,10 +125,7 @@ def transform_search_request( # pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # By default, request markdown content if not explicitly specified diff --git a/litellm/llms/featherless_ai/chat/transformation.py b/litellm/llms/featherless_ai/chat/transformation.py index e62108624d3f..cf11c72c3261 100644 --- a/litellm/llms/featherless_ai/chat/transformation.py +++ b/litellm/llms/featherless_ai/chat/transformation.py @@ -107,11 +107,7 @@ def _get_openai_compatible_provider_info( or get_secret_str("FEATHERLESS_API_BASE") or "https://api.featherless.ai/v1" ) - dynamic_api_key = ( - api_key - or get_secret_str("FEATHERLESS_AI_API_KEY") - or get_secret_str("FEATHERLESS_API_KEY") - ) + dynamic_api_key = api_key or get_secret_str("FEATHERLESS_AI_API_KEY") or get_secret_str("FEATHERLESS_API_KEY") return api_base, dynamic_api_key def validate_environment( diff --git a/litellm/llms/firecrawl/search/transformation.py b/litellm/llms/firecrawl/search/transformation.py index 7e01ba58706e..7aac6d7e7dd6 100644 --- a/litellm/llms/firecrawl/search/transformation.py +++ b/litellm/llms/firecrawl/search/transformation.py @@ -30,12 +30,8 @@ class FirecrawlSearchRequest(_FirecrawlSearchRequestRequired, total=False): """ limit: int # Optional - maximum number of results to return (default 5, max 100) - sources: List[ - str - ] # Optional - sources to search ('web', 'images', 'news'), default ['web'] - categories: List[ - Dict[str, str] - ] # Optional - categories to filter by (github, research, pdf) + sources: List[str] # Optional - sources to search ('web', 'images', 'news'), default ['web'] + categories: List[Dict[str, str]] # Optional - categories to filter by (github, research, pdf) tbs: str # Optional - time-based search parameter location: str # Optional - location parameter for geo-targeting country: str # Optional - ISO country code (default 'US') @@ -69,9 +65,7 @@ def validate_environment( default_api_base=self.FIRECRAWL_API_BASE, ) if not api_key: - raise ValueError( - "FIRECRAWL_API_KEY is not set. Set `FIRECRAWL_API_KEY` environment variable." - ) + raise ValueError("FIRECRAWL_API_KEY is not set. Set `FIRECRAWL_API_KEY` environment variable.") headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -86,9 +80,7 @@ def get_complete_url( """ Get complete URL for Search endpoint. """ - api_base = ( - api_base or get_secret_str("FIRECRAWL_API_BASE") or self.FIRECRAWL_API_BASE - ) + api_base = api_base or get_secret_str("FIRECRAWL_API_BASE") or self.FIRECRAWL_API_BASE # Append "/search" to the api base if it's not already there if not api_base.endswith("/search"): @@ -141,10 +133,7 @@ def transform_search_request( # pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # By default, request markdown content if not explicitly specified diff --git a/litellm/llms/fireworks_ai/chat/transformation.py b/litellm/llms/fireworks_ai/chat/transformation.py index 3c93677d6d4e..d4258557fe78 100644 --- a/litellm/llms/fireworks_ai/chat/transformation.py +++ b/litellm/llms/fireworks_ai/chat/transformation.py @@ -60,9 +60,7 @@ def _extract_fireworks_hidden_params(payload: dict) -> dict: """ choices = [c for c in (payload.get("choices") or []) if isinstance(c, dict)] top_level = { - f"fireworks_{field}": payload[field] - for field in ("perf_metrics", "prompt_token_ids") - if field in payload + f"fireworks_{field}": payload[field] for field in ("perf_metrics", "prompt_token_ids") if field in payload } per_choice = { f"fireworks_{dest}": [c[field] for c in choices if field in c] @@ -204,14 +202,8 @@ def map_openai_params( drop_params: bool, ) -> dict: supported_openai_params = self.get_supported_openai_params(model=model) - is_tools_set = any( - param == "tools" and value is not None - for param, value in non_default_params.items() - ) - if ( - non_default_params.get("thinking") is not None - and non_default_params.get("reasoning_effort") is not None - ): + is_tools_set = any(param == "tools" and value is not None for param, value in non_default_params.items()) + if non_default_params.get("thinking") is not None and non_default_params.get("reasoning_effort") is not None: raise litellm.BadRequestError( message=( "Fireworks AI chat completions does not support specifying both " @@ -230,9 +222,7 @@ def map_openai_params( # pass through the value of tool choice optional_params["tool_choice"] = value elif param == "response_format": - if ( - is_tools_set - ): # fireworks ai doesn't support tools and response_format together + if is_tools_set: # fireworks ai doesn't support tools and response_format together optional_params = self._add_response_format_to_tools( optional_params=optional_params, value=value, @@ -256,9 +246,7 @@ def map_openai_params( return optional_params - def _transform_tools( - self, tools: List[OpenAIChatCompletionToolParam] - ) -> List[OpenAIChatCompletionToolParam]: + def _transform_tools(self, tools: List[OpenAIChatCompletionToolParam]) -> List[OpenAIChatCompletionToolParam]: for tool in tools: if tool.get("type") != "function": continue @@ -279,9 +267,7 @@ def _transform_messages_helper( filter_value_from_dict, ) - supports_vision_value = self._get_model_cost_capability_exact( - model=model, capability="supports_vision" - ) + supports_vision_value = self._get_model_cost_capability_exact(model=model, capability="supports_vision") for message in messages: if message["role"] == "user": _message_content = message.get("content") @@ -301,10 +287,7 @@ def _transform_messages_helper( model=model, llm_provider="fireworks_ai", ) - if ( - content.get("type") == "image_url" - and supports_vision_value is False - ): + if content.get("type") == "image_url" and supports_vision_value is False: raise litellm.BadRequestError( message=( f"Fireworks AI model {model} does not support " @@ -338,11 +321,7 @@ def _get_fireworks_index(cls) -> List[Tuple[str, dict]]: model_cost = litellm.model_cost signature = (id(model_cost), get_model_cost_mutation_generation()) cached = cls._fireworks_index_cache - if ( - cached is not None - and cached[0] == signature[0] - and cached[1] == signature[1] - ): + if cached is not None and cached[0] == signature[0] and cached[1] == signature[1]: return cached[2] index: List[Tuple[str, dict]] = [] @@ -384,9 +363,7 @@ def _short_model_name(model: str) -> str: short_name = short_name[len("accounts/fireworks/models/") :] return short_name - def _get_model_cost_capability_exact( - self, model: str, capability: str - ) -> Optional[bool]: + def _get_model_cost_capability_exact(self, model: str, capability: str) -> Optional[bool]: short_name = self._short_model_name(model) candidate_keys = ( model, @@ -400,9 +377,7 @@ def _get_model_cost_capability_exact( return None def _get_model_cost_capability(self, model: str, capability: str) -> Optional[bool]: - exact = self._get_model_cost_capability_exact( - model=model, capability=capability - ) + exact = self._get_model_cost_capability_exact(model=model, capability=capability) if exact is not None: return exact @@ -418,8 +393,7 @@ def _get_model_cost_capability(self, model: str, capability: str) -> Optional[bo matches = [ (key_short, cast(Optional[bool], model_info.get(capability))) for key_short, model_info in self._get_fireworks_index() - if model_info.get(capability) is not None - and self._matches_on_hyphen_boundary(short_name, key_short) + if model_info.get(capability) is not None and self._matches_on_hyphen_boundary(short_name, key_short) ] if not matches: return None @@ -429,15 +403,9 @@ def get_provider_info(self, model: str) -> ProviderSpecificModelInfo: supports_function_calling_value = self._get_model_cost_capability( model=model, capability="supports_function_calling" ) - supports_reasoning_value = self._get_model_cost_capability( - model=model, capability="supports_reasoning" - ) - supports_vision_value = self._get_model_cost_capability( - model=model, capability="supports_vision" - ) - supports_pdf_input_value = self._get_model_cost_capability( - model=model, capability="supports_pdf_input" - ) + supports_reasoning_value = self._get_model_cost_capability(model=model, capability="supports_reasoning") + supports_vision_value = self._get_model_cost_capability(model=model, capability="supports_vision") + supports_pdf_input_value = self._get_model_cost_capability(model=model, capability="supports_pdf_input") provider_specific_model_info: ProviderSpecificModelInfo = { "supports_function_calling": True, @@ -445,23 +413,17 @@ def get_provider_info(self, model: str) -> ProviderSpecificModelInfo: } if supports_function_calling_value is not None: - provider_specific_model_info["supports_function_calling"] = ( - supports_function_calling_value - ) + provider_specific_model_info["supports_function_calling"] = supports_function_calling_value # Only include supports_reasoning if True if supports_reasoning_value: - provider_specific_model_info["supports_reasoning"] = ( - supports_reasoning_value - ) + provider_specific_model_info["supports_reasoning"] = supports_reasoning_value if supports_vision_value is not None: provider_specific_model_info["supports_vision"] = supports_vision_value if supports_pdf_input_value is not None: - provider_specific_model_info["supports_pdf_input"] = ( - supports_pdf_input_value - ) + provider_specific_model_info["supports_pdf_input"] = supports_pdf_input_value return provider_specific_model_info @@ -478,9 +440,7 @@ def transform_request( model = f"accounts/fireworks/routers/{model}" else: model = f"accounts/fireworks/models/{model}" - messages = self._transform_messages_helper( - messages=messages, model=model, litellm_params=litellm_params - ) + messages = self._transform_messages_helper(messages=messages, model=model, litellm_params=litellm_params) if "tools" in optional_params and optional_params["tools"] is not None: tools = self._transform_tools(tools=optional_params["tools"]) optional_params["tools"] = tools @@ -511,19 +471,13 @@ def _handle_message_content_with_tool_calls( Relevant Issue: https://github.com/BerriAI/litellm/issues/7209#issuecomment-2813208780 """ - if ( - tool_calls is not None - and message.content is not None - and message.tool_calls is None - ): + if tool_calls is not None and message.content is not None and message.tool_calls is None: try: function = Function(**json.loads(message.content)) if function.name != RESPONSE_FORMAT_TOOL_NAME and function.name in [ tool["function"]["name"] for tool in tool_calls ]: - tool_call = ChatCompletionMessageToolCall( - function=function, id=str(uuid.uuid4()), type="function" - ) + tool_call = ChatCompletionMessageToolCall(function=function, id=str(uuid.uuid4()), type="function") message.tool_calls = [tool_call] message.content = None @@ -560,9 +514,7 @@ def transform_response( except Exception as e: response_headers = getattr(raw_response, "headers", None) raise FireworksAIException( - message="Unable to get json response - {}, Original Response: {}".format( - str(e), raw_response.text - ), + message="Unable to get json response - {}, Original Response: {}".format(str(e), raw_response.text), status_code=raw_response.status_code, headers=response_headers, ) @@ -578,9 +530,7 @@ def transform_response( ## FIREWORKS AI sends tool calls in the content field instead of tool_calls for choice in response.choices: - cast( - Choices, choice - ).message = self._handle_message_content_with_tool_calls( + cast(Choices, choice).message = self._handle_message_content_with_tool_calls( message=cast(Choices, choice).message, tool_calls=optional_params.get("tools", None), ) @@ -607,11 +557,7 @@ def get_model_response_iterator( def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( - api_base - or get_secret_str("FIREWORKS_API_BASE") - or "https://api.fireworks.ai/inference/v1" - ) # type: ignore + api_base = api_base or get_secret_str("FIREWORKS_API_BASE") or "https://api.fireworks.ai/inference/v1" # type: ignore dynamic_api_key = api_key or ( get_secret_str("FIREWORKS_API_KEY") or get_secret_str("FIREWORKS_AI_API_KEY") @@ -621,9 +567,7 @@ def _get_openai_compatible_provider_info( return api_base, dynamic_api_key def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None): - api_base, api_key = self._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + api_base, api_key = self._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) if api_base is None or api_key is None: raise ValueError( "FIREWORKS_API_BASE or FIREWORKS_API_KEY is not set. Please set the environment variable, to query Fireworks AI's `/models` endpoint." diff --git a/litellm/llms/fireworks_ai/common_utils.py b/litellm/llms/fireworks_ai/common_utils.py index 17aa67b525b7..a1b6309d1e02 100644 --- a/litellm/llms/fireworks_ai/common_utils.py +++ b/litellm/llms/fireworks_ai/common_utils.py @@ -17,9 +17,7 @@ class FireworksAIMixin: Common Base Config functions across Fireworks AI Endpoints """ - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: return FireworksAIException( status_code=status_code, message=error_message, diff --git a/litellm/llms/fireworks_ai/cost_calculator.py b/litellm/llms/fireworks_ai/cost_calculator.py index 46026f266d66..ed936f6233a9 100644 --- a/litellm/llms/fireworks_ai/cost_calculator.py +++ b/litellm/llms/fireworks_ai/cost_calculator.py @@ -72,9 +72,7 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: base_model = get_base_model_for_pricing(model_name=model) ## GET MODEL INFO - model_info = get_model_info( - model=base_model, custom_llm_provider="fireworks_ai" - ) + model_info = get_model_info(model=base_model, custom_llm_provider="fireworks_ai") ## CALCULATE INPUT COST diff --git a/litellm/llms/fireworks_ai/embed/fireworks_ai_transformation.py b/litellm/llms/fireworks_ai/embed/fireworks_ai_transformation.py index 80906443984b..414c4dcef68b 100644 --- a/litellm/llms/fireworks_ai/embed/fireworks_ai_transformation.py +++ b/litellm/llms/fireworks_ai/embed/fireworks_ai_transformation.py @@ -17,9 +17,7 @@ def get_supported_openai_params(self, model: str): return ["dimensions"] return [] - def map_openai_params( - self, non_default_params: dict, optional_params: dict, model: str - ): + def map_openai_params(self, non_default_params: dict, optional_params: dict, model: str): """ No transformation is applied - fireworks ai is openai compatible """ diff --git a/litellm/llms/fireworks_ai/rerank/transformation.py b/litellm/llms/fireworks_ai/rerank/transformation.py index 400d511a02f7..393a6c5a8e54 100644 --- a/litellm/llms/fireworks_ai/rerank/transformation.py +++ b/litellm/llms/fireworks_ai/rerank/transformation.py @@ -154,19 +154,11 @@ def transform_rerank_request( "documents": optional_rerank_params["documents"], } - if ( - "top_n" in optional_rerank_params - and optional_rerank_params["top_n"] is not None - ): + if "top_n" in optional_rerank_params and optional_rerank_params["top_n"] is not None: request_data["top_n"] = optional_rerank_params["top_n"] - if ( - "return_documents" in optional_rerank_params - and optional_rerank_params["return_documents"] is not None - ): - request_data["return_documents"] = optional_rerank_params[ - "return_documents" - ] + if "return_documents" in optional_rerank_params and optional_rerank_params["return_documents"] is not None: + request_data["return_documents"] = optional_rerank_params["return_documents"] return request_data @@ -221,9 +213,7 @@ def transform_rerank_response( rerank_meta = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens) # Extract results - Fireworks AI uses "data" instead of "results" - _results: List[dict] | None = raw_response_json.get( - "data" - ) or raw_response_json.get("results") + _results: List[dict] | None = raw_response_json.get("data") or raw_response_json.get("results") if _results is None: raise ValueError(f"No results found in the response={raw_response_json}") @@ -261,11 +251,7 @@ def transform_rerank_response( rerank_results.append(rerank_result) # Use model name as id if no id is provided - response_id = ( - raw_response_json.get("id") - or raw_response_json.get("model") - or str(uuid.uuid4()) - ) + response_id = raw_response_json.get("id") or raw_response_json.get("model") or str(uuid.uuid4()) return RerankResponse( id=response_id, diff --git a/litellm/llms/gemini/agents/transformation.py b/litellm/llms/gemini/agents/transformation.py index f6e0b95cf28b..9e1f6935da47 100644 --- a/litellm/llms/gemini/agents/transformation.py +++ b/litellm/llms/gemini/agents/transformation.py @@ -113,10 +113,7 @@ def validate_environment( ) api_key = GeminiModelInfo.get_api_key(explicit_api_key) if not api_key: - raise ValueError( - "Google API key is required. " - "Set GOOGLE_API_KEY or GEMINI_API_KEY, or pass api_key." - ) + raise ValueError("Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY, or pass api_key.") headers["x-goog-api-key"] = api_key return headers @@ -289,9 +286,7 @@ def transform_list_versions_response( data = raw_response.json() except Exception: data = {} - verbose_logger.debug( - "GeminiAgentsConfig list_versions response for '%s': %s", name, data - ) + verbose_logger.debug("GeminiAgentsConfig list_versions response for '%s': %s", name, data) return AgentVersionsResponse( agent_versions=data.get("agentVersions", []), next_page_token=data.get("nextPageToken"), diff --git a/litellm/llms/gemini/chat/transformation.py b/litellm/llms/gemini/chat/transformation.py index 4e9764446c99..94130ac4a6ea 100644 --- a/litellm/llms/gemini/chat/transformation.py +++ b/litellm/llms/gemini/chat/transformation.py @@ -130,14 +130,8 @@ def _transform_messages( else: _image_url = img_element.get("image_url") # type: ignore if _image_url and "https://" in _image_url: - image_obj = convert_to_anthropic_image_obj( - _image_url, format=format - ) - converted_image_url = ( - convert_generic_image_chunk_to_openai_image_obj( - image_obj - ) - ) + image_obj = convert_to_anthropic_image_obj(_image_url, format=format) + converted_image_url = convert_generic_image_chunk_to_openai_image_obj(image_obj) if detail is not None: img_element["image_url"] = { # type: ignore "url": converted_image_url, diff --git a/litellm/llms/gemini/common_utils.py b/litellm/llms/gemini/common_utils.py index 4cca2e2b850f..f02e25c57358 100644 --- a/litellm/llms/gemini/common_utils.py +++ b/litellm/llms/gemini/common_utils.py @@ -95,17 +95,13 @@ } -def map_openai_size_to_gemini_image_config( - size: str, model: str -) -> Optional[Dict[str, str]]: +def map_openai_size_to_gemini_image_config(size: str, model: str) -> Optional[Dict[str, str]]: dimensions = _parse_openai_image_size(size) if dimensions is None: return None width, height = dimensions - image_config = { - "aspectRatio": _map_dimensions_to_gemini_aspect_ratio(width, height) - } + image_config = {"aspectRatio": _map_dimensions_to_gemini_aspect_ratio(width, height)} image_size = _map_dimensions_to_gemini_image_size(width, height) if is_gemini_image_model(model): if supports_gemini_image_size(model): @@ -139,9 +135,7 @@ def map_openai_image_params_to_gemini( parse_image_config_string: bool = False, ) -> Dict[str, Any]: optional_params = optional_params or {} - filtered_params = { - key: value for key, value in params.items() if key in supported_params - } + filtered_params = {key: value for key, value in params.items() if key in supported_params} mapped_params: Dict[str, Any] = {} @@ -174,10 +168,7 @@ def map_openai_image_params_to_gemini( mapped_params["imageConfig"] = image_config_param for key, value in filtered_params.items(): - if ( - key not in ("n", "size", "imageConfig", "tools", "web_search_options") - and key not in optional_params - ): + if key not in ("n", "size", "imageConfig", "tools", "web_search_options") and key not in optional_params: mapped_params[key] = value return mapped_params @@ -217,10 +208,7 @@ def _has_gemini_search_tool(tools: List[Any]) -> bool: ) search_tool_keys = VertexGeminiConfig._search_tool_keys() - return any( - isinstance(tool, dict) and any(key in tool for key in search_tool_keys) - for tool in tools - ) + return any(isinstance(tool, dict) and any(key in tool for key in search_tool_keys) for tool in tools) def map_gemini_image_tools_params( @@ -237,9 +225,7 @@ def map_gemini_image_tools_params( tools_value = non_default_params.get("tools") if isinstance(tools_value, list) and tools_value: - mapped_tools = gemini_config._map_function( - value=tools_value, optional_params=result - ) + mapped_tools = gemini_config._map_function(value=tools_value, optional_params=result) result = gemini_config._add_tools_to_optional_params(result, mapped_tools) web_search_options = non_default_params.get("web_search_options") @@ -335,9 +321,7 @@ def _map_dimensions_to_gemini_aspect_ratio(width: int, height: int) -> str: requested_ratio = width / height return min( GEMINI_IMAGE_ASPECT_RATIOS, - key=lambda aspect_ratio: abs( - math.log(GEMINI_IMAGE_ASPECT_RATIOS[aspect_ratio] / requested_ratio) - ), + key=lambda aspect_ratio: abs(math.log(GEMINI_IMAGE_ASPECT_RATIOS[aspect_ratio] / requested_ratio)), ) @@ -376,19 +360,11 @@ def api_version(self) -> str: @staticmethod def get_api_base(api_base: Optional[str] = None) -> Optional[str]: - return ( - api_base - or get_secret_str("GEMINI_API_BASE") - or "https://generativelanguage.googleapis.com" - ) + return api_base or get_secret_str("GEMINI_API_BASE") or "https://generativelanguage.googleapis.com" @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: - return ( - api_key - or (get_secret_str("GOOGLE_API_KEY")) - or (get_secret_str("GEMINI_API_KEY")) - ) + return api_key or (get_secret_str("GOOGLE_API_KEY")) or (get_secret_str("GEMINI_API_KEY")) @staticmethod def get_base_model(model: str) -> Optional[str]: @@ -402,9 +378,7 @@ def process_model_name(self, models: List[Dict[str, str]]) -> List[str]: litellm_model_names.append(litellm_model_name) return litellm_model_names - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: api_base = GeminiModelInfo.get_api_base(api_base) api_key = GeminiModelInfo.get_api_key(api_key) endpoint = f"/{self.api_version}/models" @@ -431,9 +405,7 @@ def get_models( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return GeminiError( - status_code=status_code, message=error_message, headers=headers - ) + return GeminiError(status_code=status_code, message=error_message, headers=headers) def get_token_counter(self) -> Optional[BaseTokenCounter]: """ @@ -446,9 +418,7 @@ def get_token_counter(self) -> Optional[BaseTokenCounter]: return GoogleAIStudioTokenCounter() -def encode_unserializable_types( - data: Dict[str, object], depth: int = 0 -) -> Dict[str, object]: +def encode_unserializable_types(data: Dict[str, object], depth: int = 0) -> Dict[str, object]: """Converts unserializable types in dict to json.dumps() compatible types. This function is called in models.py after calling convert_to_dict(). The @@ -476,15 +446,11 @@ def encode_unserializable_types( processed_data[key] = encode_unserializable_types(value, depth + 1) elif isinstance(value, list): if all(isinstance(v, bytes) for v in value): - processed_data[key] = [ - base64.urlsafe_b64encode(v).decode("ascii") for v in value - ] + processed_data[key] = [base64.urlsafe_b64encode(v).decode("ascii") for v in value] if all(isinstance(v, datetime.datetime) for v in value): processed_data[key] = [v.isoformat() for v in value] else: - processed_data[key] = [ - encode_unserializable_types(v, depth + 1) for v in value - ] + processed_data[key] = [encode_unserializable_types(v, depth + 1) for v in value] else: processed_data[key] = value return processed_data @@ -520,9 +486,7 @@ async def count_tokens( from litellm.llms.gemini.count_tokens.handler import GoogleAIStudioTokenCounter deployment = deployment or {} - count_tokens_params_request = copy.deepcopy( - deployment.get("litellm_params", {}) - ) + count_tokens_params_request = copy.deepcopy(deployment.get("litellm_params", {})) count_tokens_params = { "model": model_to_use, "contents": contents, diff --git a/litellm/llms/gemini/cost_calculator.py b/litellm/llms/gemini/cost_calculator.py index 7b9bd7486a59..f69cfe032706 100644 --- a/litellm/llms/gemini/cost_calculator.py +++ b/litellm/llms/gemini/cost_calculator.py @@ -10,9 +10,7 @@ from litellm.types.utils import ModelInfo, Usage -def cost_per_token( - model: str, usage: "Usage", service_tier: Optional[str] = None -) -> Tuple[float, float]: +def cost_per_token(model: str, usage: "Usage", service_tier: Optional[str] = None) -> Tuple[float, float]: """ Calculates the cost per token for a given model, prompt tokens, and completion tokens. diff --git a/litellm/llms/gemini/count_tokens/handler.py b/litellm/llms/gemini/count_tokens/handler.py index fdb77452d4c8..27df584d476e 100644 --- a/litellm/llms/gemini/count_tokens/handler.py +++ b/litellm/llms/gemini/count_tokens/handler.py @@ -43,9 +43,7 @@ def _clean_contents_for_gemini_api(self, contents: Any) -> Any: function_response_data = part["functionResponse"] function_response_part = FunctionResponse(**function_response_data) function_response_part.id = None - part["functionResponse"] = function_response_part.model_dump( - exclude_none=True - ) + part["functionResponse"] = function_response_part.model_dump(exclude_none=True) return cleaned_contents @@ -139,9 +137,7 @@ async def acount_tokens( ) try: - response = await async_httpx_client.post( - url=url, headers=headers, json=request_body - ) + response = await async_httpx_client.post(url=url, headers=headers, json=request_body) # Check for HTTP errors response.raise_for_status() @@ -160,9 +156,7 @@ async def acount_tokens( ) from e except httpx.RequestError as e: error_msg = f"Request to Google Gen AI Studio failed: {str(e)}" - raise litellm.APIConnectionError( - message=error_msg, llm_provider="gemini", model=model - ) from e + raise litellm.APIConnectionError(message=error_msg, llm_provider="gemini", model=model) from e except Exception as e: error_msg = f"Unexpected error during token counting: {str(e)}" raise Exception(error_msg) from e diff --git a/litellm/llms/gemini/files/transformation.py b/litellm/llms/gemini/files/transformation.py index 63a383ebd3da..a18dc152cb6c 100644 --- a/litellm/llms/gemini/files/transformation.py +++ b/litellm/llms/gemini/files/transformation.py @@ -55,9 +55,7 @@ def validate_environment( """ resolved_api_key = self.get_api_key(api_key) if not resolved_api_key: - raise ValueError( - "GEMINI_API_KEY is required for Google AI Studio file operations" - ) + raise ValueError("GEMINI_API_KEY is required for Google AI Studio file operations") headers["x-goog-api-key"] = resolved_api_key return headers @@ -91,9 +89,7 @@ def get_complete_url( url = "{}/{}".format(api_base, endpoint) return url - def get_supported_openai_params( - self, model: str - ) -> List[OpenAICreateFileRequestOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAICreateFileRequestOptionalParams]: return [] def map_openai_params( @@ -140,11 +136,7 @@ def transform_create_file_request( headers.update(extracted_data["headers"]) # Add any custom headers # Initial metadata request body - initial_data = { - "file": { - "display_name": extracted_data["filename"] or str(int(time.time())) - } - } + initial_data = {"file": {"display_name": extracted_data["filename"] or str(int(time.time()))}} # Step 2: Actual file upload data upload_headers = { @@ -182,9 +174,7 @@ def transform_create_file_response( return OpenAIFileObject( id=response_object["uri"], # Gemini uses URI as identifier - bytes=int( - response_object["sizeBytes"] - ), # Gemini doesn't return file size + bytes=int(response_object["sizeBytes"]), # Gemini doesn't return file size created_at=int( time.mktime( time.strptime( @@ -227,10 +217,7 @@ def transform_retrieve_file_request( file_part = self._normalize_gemini_file_id(file_id) - api_base = ( - self.get_api_base(litellm_params.get("api_base")) - or "https://generativelanguage.googleapis.com" - ) + api_base = self.get_api_base(litellm_params.get("api_base")) or "https://generativelanguage.googleapis.com" api_base = api_base.rstrip("/") url = f"{api_base}/v1beta/{file_part}" @@ -262,9 +249,7 @@ def _normalize_gemini_file_id(self, file_id: str) -> str: if normalized_file_id.startswith("files/"): normalized_file_id = normalized_file_id.removeprefix("files/") - encoded_file_id = encode_url_path_segment( - normalized_file_id, field_name="file_id" - ) + encoded_file_id = encode_url_path_segment(normalized_file_id, field_name="file_id") return f"files/{encoded_file_id}" @@ -306,11 +291,7 @@ def transform_retrieve_file_response( object="file", purpose="user_data", status=status, - status_details=( - str(response_json.get("error", "")) - if gemini_state == "FAILED" - else None - ), + status_details=(str(response_json.get("error", "")) if gemini_state == "FAILED" else None), ) except Exception as e: verbose_logger.exception(f"Error parsing file retrieve response: {str(e)}") @@ -390,9 +371,7 @@ def transform_list_files_request( optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - raise NotImplementedError( - "GoogleAIStudioFilesHandler does not support file listing" - ) + raise NotImplementedError("GoogleAIStudioFilesHandler does not support file listing") def transform_list_files_response( self, @@ -400,9 +379,7 @@ def transform_list_files_response( logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> List[OpenAIFileObject]: - raise NotImplementedError( - "GoogleAIStudioFilesHandler does not support file listing" - ) + raise NotImplementedError("GoogleAIStudioFilesHandler does not support file listing") def transform_file_content_request( self, @@ -410,9 +387,7 @@ def transform_file_content_request( optional_params: dict, litellm_params: dict, ) -> tuple[str, dict]: - raise NotImplementedError( - "GoogleAIStudioFilesHandler does not support file content retrieval" - ) + raise NotImplementedError("GoogleAIStudioFilesHandler does not support file content retrieval") def transform_file_content_response( self, @@ -420,6 +395,4 @@ def transform_file_content_response( logging_obj: LiteLLMLoggingObj, litellm_params: dict, ) -> HttpxBinaryResponseContent: - raise NotImplementedError( - "GoogleAIStudioFilesHandler does not support file content retrieval" - ) + raise NotImplementedError("GoogleAIStudioFilesHandler does not support file content retrieval") diff --git a/litellm/llms/gemini/google_genai/transformation.py b/litellm/llms/gemini/google_genai/transformation.py index ee201af7e1a4..68f303086218 100644 --- a/litellm/llms/gemini/google_genai/transformation.py +++ b/litellm/llms/gemini/google_genai/transformation.py @@ -118,17 +118,11 @@ def map_generate_content_optional_params( ) _generate_content_config_dict: Dict[str, Any] = {} - supported_google_genai_params = ( - self.get_supported_generate_content_optional_params(model) - ) + supported_google_genai_params = self.get_supported_generate_content_optional_params(model) # Create a set with both camelCase and snake_case versions for faster lookup supported_params_set = set(supported_google_genai_params) - supported_params_set.update( - _snake_to_camel(p) for p in supported_google_genai_params - ) - supported_params_set.update( - _camel_to_snake(p) for p in supported_google_genai_params if "_" not in p - ) + supported_params_set.update(_snake_to_camel(p) for p in supported_google_genai_params) + supported_params_set.update(_camel_to_snake(p) for p in supported_google_genai_params if "_" not in p) for param, value in generate_content_config_dict.items(): # Google GenAI API expects camelCase, so we'll always output in camelCase @@ -160,9 +154,7 @@ def validate_environment( "Content-Type": "application/json", } # Use the passed api_key first, then fall back to litellm_params and environment - gemini_api_key = api_key or self._get_google_ai_studio_api_key( - dict(litellm_params or {}) - ) + gemini_api_key = api_key or self._get_google_ai_studio_api_key(dict(litellm_params or {})) if isinstance(gemini_api_key, dict): default_headers.update(gemini_api_key) elif gemini_api_key is not None: @@ -308,23 +300,13 @@ async def get_auth_token_and_url( ) @staticmethod - def _normalize_response_schema( - generate_content_config_dict: Dict, model: str - ) -> None: + def _normalize_response_schema(generate_content_config_dict: Dict, model: str) -> None: schema_key = next( - ( - k - for k in ("responseSchema", "response_schema") - if k in generate_content_config_dict - ), + (k for k in ("responseSchema", "response_schema") if k in generate_content_config_dict), None, ) json_schema_key = next( - ( - k - for k in ("responseJsonSchema", "response_json_schema") - if k in generate_content_config_dict - ), + (k for k in ("responseJsonSchema", "response_json_schema") if k in generate_content_config_dict), None, ) @@ -340,11 +322,7 @@ def _normalize_response_schema( generate_content_config_dict.pop(schema_key) return generate_content_config_dict.pop(schema_key) - new_json_schema_key = ( - "response_json_schema" - if schema_key == "response_schema" - else "responseJsonSchema" - ) + new_json_schema_key = "response_json_schema" if schema_key == "response_schema" else "responseJsonSchema" generate_content_config_dict[new_json_schema_key] = value else: if json_schema_key is not None: @@ -420,13 +398,9 @@ def convert_citation_sources_to_citations(self, response: Dict) -> Dict: """ if "candidates" in response: for candidate in response["candidates"]: - if "citationMetadata" in candidate and isinstance( - candidate["citationMetadata"], dict - ): + if "citationMetadata" in candidate and isinstance(candidate["citationMetadata"], dict): citation_metadata = candidate["citationMetadata"] # Transform citationSources to citations to match expected schema if "citationSources" in citation_metadata: - citation_metadata["citations"] = citation_metadata.pop( - "citationSources" - ) + citation_metadata["citations"] = citation_metadata.pop("citationSources") return response diff --git a/litellm/llms/gemini/image_edit/transformation.py b/litellm/llms/gemini/image_edit/transformation.py index 2316361d6e7f..78d682395bb9 100644 --- a/litellm/llms/gemini/image_edit/transformation.py +++ b/litellm/llms/gemini/image_edit/transformation.py @@ -78,9 +78,7 @@ def get_complete_url( api_base: Optional[str], litellm_params: dict, ) -> str: - base_url = ( - api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL - ) + base_url = api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL base_url = base_url.rstrip("/") return f"{base_url}/models/{model}:generateContent" @@ -152,14 +150,10 @@ def transform_image_edit_response( model_response.data = cast(List[OpenAIImage], data_list) if "usageMetadata" in response_json: - model_response.usage = transform_gemini_image_usage( - response_json["usageMetadata"] - ) + model_response.usage = transform_gemini_image_usage(response_json["usageMetadata"]) return model_response - def _prepare_inline_image_parts( - self, image: Union[FileTypes, List[FileTypes]] - ) -> List[Dict[str, Any]]: + def _prepare_inline_image_parts(self, image: Union[FileTypes, List[FileTypes]]) -> List[Dict[str, Any]]: images: List[FileTypes] if isinstance(image, list): images = image diff --git a/litellm/llms/gemini/image_generation/cost_calculator.py b/litellm/llms/gemini/image_generation/cost_calculator.py index 380e2c21e9ec..40e234a0b71d 100644 --- a/litellm/llms/gemini/image_generation/cost_calculator.py +++ b/litellm/llms/gemini/image_generation/cost_calculator.py @@ -25,9 +25,7 @@ def cost_calculator( ) if not isinstance(image_response, ImageResponse): - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") web_search_cost = calculate_image_response_web_search_cost( image_response=image_response, diff --git a/litellm/llms/gemini/image_generation/transformation.py b/litellm/llms/gemini/image_generation/transformation.py index ebfb0d68830b..dcdec46edca8 100644 --- a/litellm/llms/gemini/image_generation/transformation.py +++ b/litellm/llms/gemini/image_generation/transformation.py @@ -34,9 +34,7 @@ class GoogleImageGenConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://generativelanguage.googleapis.com/v1beta" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Google AI Imagen API supported parameters https://ai.google.dev/gemini-api/docs/imagen @@ -60,9 +58,7 @@ def map_openai_params( optional_params=optional_params, ) if is_gemini_image_model(model): - mapped_params = map_gemini_image_tools_params( - non_default_params, mapped_params - ) + mapped_params = map_gemini_image_tools_params(non_default_params, mapped_params) return mapped_params def get_complete_url( @@ -80,9 +76,7 @@ def get_complete_url( Gemini 2.5 Flash Image Preview: :generateContent Other Imagen models: :predict """ - complete_url: str = ( - api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("GEMINI_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") @@ -159,11 +153,9 @@ def transform_image_generation_request( GeminiImageGenerationParameters, ) - request_body_obj: GeminiImageGenerationRequest = ( - GeminiImageGenerationRequest( - instances=[GeminiImageGenerationInstance(prompt=prompt)], - parameters=GeminiImageGenerationParameters(**optional_params), - ) + request_body_obj: GeminiImageGenerationRequest = GeminiImageGenerationRequest( + instances=[GeminiImageGenerationInstance(prompt=prompt)], + parameters=GeminiImageGenerationParameters(**optional_params), ) return request_body_obj.model_dump(exclude_none=True) @@ -216,23 +208,17 @@ def transform_image_generation_response( b64_json=inline_data["data"], url=None, provider_specific_fields=( - {"thought_signature": thought_sig} - if thought_sig - else None + {"thought_signature": thought_sig} if thought_sig else None ), ) ) # Extract usage metadata for Gemini models if "usageMetadata" in response_data: - model_response.usage = transform_gemini_image_usage( - response_data["usageMetadata"] - ) + model_response.usage = transform_gemini_image_usage(response_data["usageMetadata"]) web_search_requests = get_gemini_image_web_search_requests(response_data) if web_search_requests and model_response.usage is not None: - setattr( - model_response.usage, "web_search_requests", web_search_requests - ) + setattr(model_response.usage, "web_search_requests", web_search_requests) else: # Original Imagen format - predictions with generated images predictions = response_data.get("predictions", []) diff --git a/litellm/llms/gemini/image_usage_transformation.py b/litellm/llms/gemini/image_usage_transformation.py index 5a55bdeffb1c..a4626907f22a 100644 --- a/litellm/llms/gemini/image_usage_transformation.py +++ b/litellm/llms/gemini/image_usage_transformation.py @@ -16,9 +16,7 @@ def _get_modality_token_details(usage_metadata: dict, *details_keys: str) -> lis return [] -def _sum_modality_token_details( - usage_metadata: dict, *details_keys: str -) -> ImageUsageInputTokensDetails: +def _sum_modality_token_details(usage_metadata: dict, *details_keys: str) -> ImageUsageInputTokensDetails: tokens_details = ImageUsageInputTokensDetails( image_tokens=0, text_tokens=0, @@ -40,22 +38,16 @@ def transform_gemini_image_usage(usage_metadata: dict) -> ImageUsage: """ Transform Gemini usageMetadata to ImageUsage format. """ - input_tokens_details = _sum_modality_token_details( - usage_metadata, "promptTokensDetails", "prompt_tokens_details" - ) + input_tokens_details = _sum_modality_token_details(usage_metadata, "promptTokensDetails", "prompt_tokens_details") output_tokens = usage_metadata.get("candidatesTokenCount", 0) output_tokens_details = _sum_modality_token_details( usage_metadata, "candidatesTokensDetails", "candidates_tokens_details" ) - if not _get_modality_token_details( - usage_metadata, "candidatesTokensDetails", "candidates_tokens_details" - ): + if not _get_modality_token_details(usage_metadata, "candidatesTokensDetails", "candidates_tokens_details"): output_tokens_details.image_tokens = output_tokens else: - known_output_tokens = ( - output_tokens_details.text_tokens + output_tokens_details.image_tokens - ) + known_output_tokens = output_tokens_details.text_tokens + output_tokens_details.image_tokens if output_tokens > known_output_tokens: output_tokens_details.text_tokens += output_tokens - known_output_tokens diff --git a/litellm/llms/gemini/interactions/transformation.py b/litellm/llms/gemini/interactions/transformation.py index b18b6a28ce48..7443720f4969 100644 --- a/litellm/llms/gemini/interactions/transformation.py +++ b/litellm/llms/gemini/interactions/transformation.py @@ -114,9 +114,7 @@ def get_complete_url( api_key = GeminiModelInfo.get_api_key(litellm_params.get("api_key")) if not api_key: - raise ValueError( - "Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable." - ) + raise ValueError("Google API key is required. Set GOOGLE_API_KEY or GEMINI_API_KEY environment variable.") if stream: return f"{api_base}/{self.api_version}/interactions?alt=sse" @@ -189,10 +187,7 @@ def transform_request( if ( response_mime_type and not isinstance(response_format, list) - and ( - not isinstance(response_format, dict) - or "mime_type" not in response_format - ) + and (not isinstance(response_format, dict) or "mime_type" not in response_format) ): # Wrap the legacy schema into the new polymorphic format. new_rf: Dict[str, Any] = { @@ -207,15 +202,11 @@ def transform_request( request_body["response_format"] = response_format # image_config moves out of generation_config into response_format. - generation_config: Optional[Dict[str, Any]] = optional_params.get( - "generation_config" - ) + generation_config: Optional[Dict[str, Any]] = optional_params.get("generation_config") if generation_config is not None: image_config = None if isinstance(generation_config, dict): - generation_config = dict( - generation_config - ) # avoid mutating the caller's dict + generation_config = dict(generation_config) # avoid mutating the caller's dict image_config = generation_config.pop("image_config", None) if not generation_config: generation_config = None @@ -261,9 +252,7 @@ def transform_response( response = InteractionsAPIResponse(**raw_json) response._hidden_params["headers"] = dict(raw_response.headers) - response._hidden_params["additional_headers"] = process_response_headers( - dict(raw_response.headers) - ) + response._hidden_params["additional_headers"] = process_response_headers(dict(raw_response.headers)) return response @@ -290,9 +279,7 @@ def transform_get_interaction_request( resolved_api_base = GeminiModelInfo.get_api_base(api_base) if not GeminiModelInfo.get_api_key(litellm_params.api_key): raise ValueError("Google API key is required") - encoded_interaction_id = encode_url_path_segment( - interaction_id, field_name="interaction_id" - ) + encoded_interaction_id = encode_url_path_segment(interaction_id, field_name="interaction_id") return ( f"{resolved_api_base}/{self.api_version}/interactions/{encoded_interaction_id}", {}, @@ -326,9 +313,7 @@ def transform_delete_interaction_request( resolved_api_base = GeminiModelInfo.get_api_base(api_base) if not GeminiModelInfo.get_api_key(litellm_params.api_key): raise ValueError("Google API key is required") - encoded_interaction_id = encode_url_path_segment( - interaction_id, field_name="interaction_id" - ) + encoded_interaction_id = encode_url_path_segment(interaction_id, field_name="interaction_id") return ( f"{resolved_api_base}/{self.api_version}/interactions/{encoded_interaction_id}", {}, @@ -359,9 +344,7 @@ def transform_cancel_interaction_request( resolved_api_base = GeminiModelInfo.get_api_base(api_base) if not GeminiModelInfo.get_api_key(litellm_params.api_key): raise ValueError("Google API key is required") - encoded_interaction_id = encode_url_path_segment( - interaction_id, field_name="interaction_id" - ) + encoded_interaction_id = encode_url_path_segment(interaction_id, field_name="interaction_id") return ( f"{resolved_api_base}/{self.api_version}/interactions/{encoded_interaction_id}:cancel", {}, diff --git a/litellm/llms/gemini/realtime/transformation.py b/litellm/llms/gemini/realtime/transformation.py index 9c0a4a30efb8..0ff4190a6d3f 100644 --- a/litellm/llms/gemini/realtime/transformation.py +++ b/litellm/llms/gemini/realtime/transformation.py @@ -60,9 +60,7 @@ from ..common_utils import encode_unserializable_types, get_api_key_from_env -MAP_GEMINI_FIELD_TO_OPENAI_EVENT: Dict[ - str, Union[OpenAIRealtimeEventTypes, ResponsesAPIStreamEvents] -] = { +MAP_GEMINI_FIELD_TO_OPENAI_EVENT: Dict[str, Union[OpenAIRealtimeEventTypes, ResponsesAPIStreamEvents]] = { "setupComplete": OpenAIRealtimeEventTypes.SESSION_CREATED, "serverContent.generationComplete": OpenAIRealtimeEventTypes.RESPONSE_TEXT_DONE, "serverContent.turnComplete": OpenAIRealtimeEventTypes.RESPONSE_DONE, @@ -71,9 +69,7 @@ } # Keys the main transform loop handles; siblings like ``usageMetadata`` are skipped. -_KNOWN_GEMINI_TOP_LEVEL_KEYS: set = { - map_key.split(".", 1)[0] for map_key in MAP_GEMINI_FIELD_TO_OPENAI_EVENT -} +_KNOWN_GEMINI_TOP_LEVEL_KEYS: set = {map_key.split(".", 1)[0] for map_key in MAP_GEMINI_FIELD_TO_OPENAI_EVENT} class GeminiRealtimeConfig(BaseRealtimeConfig): @@ -90,9 +86,7 @@ def is_setup_message(self, msg_obj: dict) -> bool: return "setup" in msg_obj def is_content_message(self, msg_obj: dict) -> bool: - return any( - k in msg_obj for k in ("realtimeInput", "clientContent", "toolResponse") - ) + return any(k in msg_obj for k in ("realtimeInput", "clientContent", "toolResponse")) def _include_function_response_id(self) -> bool: """Google AI Studio Gemini 3.5+ accepts ``id`` on functionResponses; Vertex AI rejects it.""" @@ -125,14 +119,10 @@ def _add_pipecat_usage_detail_aliases(usage_dict: Dict[str, Any]) -> Dict[str, A ) return usage_dict - def validate_environment( - self, headers: dict, model: str, api_key: Optional[str] = None - ) -> dict: + def validate_environment(self, headers: dict, model: str, api_key: Optional[str] = None) -> dict: return headers - def get_complete_url( - self, api_base: Optional[str], model: str, api_key: Optional[str] = None - ) -> str: + def get_complete_url(self, api_base: Optional[str], model: str, api_key: Optional[str] = None) -> str: """ Example output: "BACKEND_WS_URL = "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent""; @@ -151,9 +141,7 @@ def get_complete_url( # already covers the main leak vector. return f"{api_base}/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent?key={api_key}" - def map_model_turn_event( - self, model_turn: HttpxContentType - ) -> OpenAIRealtimeEventTypes: + def map_model_turn_event(self, model_turn: HttpxContentType) -> OpenAIRealtimeEventTypes: """ Map the model turn event to the OpenAI realtime events. @@ -166,9 +154,7 @@ def map_model_turn_event( if "parts" in model_turn: parts = model_turn["parts"] if len(parts) != 1: - verbose_logger.warning( - f"Realtime: Expected 1 part, got {len(parts)} for Gemini model turn event." - ) + verbose_logger.warning(f"Realtime: Expected 1 part, got {len(parts)} for Gemini model turn event.") part = parts[0] if "text" in part: return OpenAIRealtimeEventTypes.RESPONSE_TEXT_DELTA @@ -178,9 +164,7 @@ def map_model_turn_event( raise ValueError(f"Unexpected part type: {part}") raise ValueError(f"Unexpected model turn event, no 'parts' key: {model_turn}") - def map_generation_complete_event( - self, delta_type: Optional[ALL_DELTA_TYPES] - ) -> OpenAIRealtimeEventTypes: + def map_generation_complete_event(self, delta_type: Optional[ALL_DELTA_TYPES]) -> OpenAIRealtimeEventTypes: if delta_type == "text": return OpenAIRealtimeEventTypes.RESPONSE_TEXT_DONE elif delta_type == "audio": @@ -197,55 +181,36 @@ def get_audio_mime_type(self, input_audio_format: str = "pcm16"): return mime_types.get(input_audio_format, "application/octet-stream") - def _manual_turn_detection_enabled( - self, session_configuration_request: Optional[str] - ) -> bool: + def _manual_turn_detection_enabled(self, session_configuration_request: Optional[str]) -> bool: if not session_configuration_request: return False try: setup = json.loads(session_configuration_request).get("setup", {}) - automatic_detection = setup.get("realtimeInputConfig", {}).get( - "automaticActivityDetection", {} - ) - return ( - isinstance(automatic_detection, dict) - and automatic_detection.get("disabled") is True - ) + automatic_detection = setup.get("realtimeInputConfig", {}).get("automaticActivityDetection", {}) + return isinstance(automatic_detection, dict) and automatic_detection.get("disabled") is True except (json.JSONDecodeError, TypeError, AttributeError): return False - def _handle_input_audio_buffer_commit_or_end( - self, session_configuration_request: Optional[str] - ) -> List[str]: + def _handle_input_audio_buffer_commit_or_end(self, session_configuration_request: Optional[str]) -> List[str]: """Map OpenAI buffer commit/end to Gemini Live turn-boundary signals.""" if self._manual_turn_detection_enabled(session_configuration_request): realtime_input_dict: BidiGenerateContentRealtimeInput = { "activityEnd": True, } - verbose_logger.debug( - "Gemini Realtime: Sending activityEnd realtimeInput to backend" - ) + verbose_logger.debug("Gemini Realtime: Sending activityEnd realtimeInput to backend") else: realtime_input_dict = {"audioStreamEnd": True} - verbose_logger.debug( - "Gemini Realtime: Sending audioStreamEnd realtimeInput to backend" - ) + verbose_logger.debug("Gemini Realtime: Sending audioStreamEnd realtimeInput to backend") return [json.dumps({"realtimeInput": realtime_input_dict})] - def map_automatic_turn_detection( - self, value: OpenAIRealtimeTurnDetection - ) -> AutomaticActivityDetection: + def map_automatic_turn_detection(self, value: OpenAIRealtimeTurnDetection) -> AutomaticActivityDetection: """Map OpenAI ``server_vad`` to Gemini ``automaticActivityDetection``. OpenAI ``semantic_vad`` has no Gemini Live equivalent — return an empty dict so callers omit ``realtimeInputConfig`` (mapping it with ``disabled: true`` breaks native-audio sessions). """ - if ( - isinstance(value, dict) - and value.get("type") == "semantic_vad" - and "create_response" not in value - ): + if isinstance(value, dict) and value.get("type") == "semantic_vad" and "create_response" not in value: return AutomaticActivityDetection() automatic_activity_dection = AutomaticActivityDetection() @@ -258,12 +223,8 @@ def map_automatic_turn_detection( automatic_activity_dection["disabled"] = True if "prefix_padding_ms" in value and isinstance(value["prefix_padding_ms"], int): automatic_activity_dection["prefixPaddingMs"] = value["prefix_padding_ms"] - if "silence_duration_ms" in value and isinstance( - value["silence_duration_ms"], int - ): - automatic_activity_dection["silenceDurationMs"] = value[ - "silence_duration_ms" - ] + if "silence_duration_ms" in value and isinstance(value["silence_duration_ms"], int): + automatic_activity_dection["silenceDurationMs"] = value["silence_duration_ms"] return automatic_activity_dection def get_supported_openai_params(self, model: str) -> List[str]: @@ -278,16 +239,12 @@ def get_supported_openai_params(self, model: str) -> List[str]: "voice", ] - def map_openai_params( - self, optional_params: dict, non_default_params: dict - ) -> dict: + def map_openai_params(self, optional_params: dict, non_default_params: dict) -> dict: if "generationConfig" not in optional_params: optional_params["generationConfig"] = {} for key, value in non_default_params.items(): if key == "instructions": - optional_params["systemInstruction"] = HttpxContentType( - role="user", parts=[{"text": value}] - ) + optional_params["systemInstruction"] = HttpxContentType(role="user", parts=[{"text": value}]) elif key == "temperature": optional_params["generationConfig"]["temperature"] = value elif key == "max_response_output_tokens": @@ -319,14 +276,10 @@ def map_openai_params( # Only skip when there is no create_response override so that # a guardrail-injected create_response:false is not dropped. continue - transformed_audio_activity_config = self.map_automatic_turn_detection( - value_typed - ) + transformed_audio_activity_config = self.map_automatic_turn_detection(value_typed) if transformed_audio_activity_config: - optional_params["realtimeInputConfig"] = ( - BidiGenerateContentRealtimeInputConfig( - automaticActivityDetection=transformed_audio_activity_config - ) + optional_params["realtimeInputConfig"] = BidiGenerateContentRealtimeInputConfig( + automaticActivityDetection=transformed_audio_activity_config ) elif key == "voice": from litellm.llms.vertex_ai.gemini.vertex_and_google_ai_studio_gemini import ( @@ -387,21 +340,14 @@ def _normalize_session_payload_for_mapping(session: dict) -> dict: if isinstance(audio, dict): input_cfg = audio.get("input") if isinstance(input_cfg, dict): - if ( - "input_audio_transcription" not in normalized - and "transcription" in input_cfg - ): + if "input_audio_transcription" not in normalized and "transcription" in input_cfg: normalized["input_audio_transcription"] = input_cfg["transcription"] output_cfg = audio.get("output") if isinstance(output_cfg, dict) and output_cfg.get("voice"): normalized["voice"] = output_cfg["voice"] - extracted_turn_detection = GeminiRealtimeConfig._extract_turn_detection( - normalized - ) - if extracted_turn_detection is not None and not isinstance( - normalized.get("turn_detection"), dict - ): + extracted_turn_detection = GeminiRealtimeConfig._extract_turn_detection(normalized) + if extracted_turn_detection is not None and not isinstance(normalized.get("turn_detection"), dict): normalized["turn_detection"] = extracted_turn_detection return normalized @@ -411,30 +357,23 @@ def _model_cost_entry(model: str) -> dict: entry = litellm.model_cost.get(model) if entry is None: stripped = model.split("/", 1)[-1] - entry = litellm.model_cost.get(stripped) or litellm.model_cost.get( - f"gemini/{stripped}" - ) + entry = litellm.model_cost.get(stripped) or litellm.model_cost.get(f"gemini/{stripped}") return entry or {} @staticmethod def _is_audio_only_live_model(model: str) -> bool: entry = GeminiRealtimeConfig._model_cost_entry(model) - return bool( - entry.get("gemini_native_audio") or entry.get("gemini_audio_only_live") - ) + return bool(entry.get("gemini_native_audio") or entry.get("gemini_audio_only_live")) @staticmethod def _is_native_audio_model(model: str) -> bool: - return bool( - GeminiRealtimeConfig._model_cost_entry(model).get("gemini_native_audio") - ) + return bool(GeminiRealtimeConfig._model_cost_entry(model).get("gemini_native_audio")) @staticmethod def _coerce_response_modalities(model: str, modalities: list[Any]) -> list[str]: """Map unsupported TEXT responseModalities to AUDIO for audio-only Live models.""" normalized = [ - modality.upper() if isinstance(modality, str) else str(modality).upper() - for modality in modalities + modality.upper() if isinstance(modality, str) else str(modality).upper() for modality in modalities ] if not GeminiRealtimeConfig._is_audio_only_live_model(model): return normalized @@ -444,16 +383,14 @@ def _coerce_response_modalities(model: str, modalities: list[Any]) -> list[str]: return without_text if without_text else ["AUDIO"] @staticmethod - def _finalize_gemini_live_setup( - model: str, setup: Dict[str, Any] - ) -> Dict[str, Any]: + def _finalize_gemini_live_setup(model: str, setup: Dict[str, Any]) -> Dict[str, Any]: """Drop fields Gemini Live native-audio rejects on ``setup``.""" generation_config = setup.get("generationConfig") if isinstance(generation_config, dict): modalities = generation_config.get("responseModalities") if isinstance(modalities, list): - generation_config["responseModalities"] = ( - GeminiRealtimeConfig._coerce_response_modalities(model, modalities) + generation_config["responseModalities"] = GeminiRealtimeConfig._coerce_response_modalities( + model, modalities ) if GeminiRealtimeConfig._is_native_audio_model(model): generation_config.pop("speechConfig", None) @@ -490,28 +427,18 @@ def _handle_session_update( # would be silently dropped because ``map_openai_params`` only # recognises the flat OpenAI-beta key names. session_payload = self._normalize_session_payload_for_mapping(session_payload) - new_overrides = self.map_openai_params( - optional_params={}, non_default_params=session_payload - ) + new_overrides = self.map_openai_params(optional_params={}, non_default_params=session_payload) if session_configuration_request is None: generation_config = new_overrides.setdefault("generationConfig", {}) generation_config.setdefault("responseModalities", ["AUDIO"]) new_overrides.setdefault("inputAudioTranscription", {}) new_overrides["model"] = f"models/{model}" - verbose_logger.debug( - "Gemini Realtime: Sending initial setup with tools to backend" - ) - return [ - json.dumps( - {"setup": self._finalize_gemini_live_setup(model, new_overrides)} - ) - ] + verbose_logger.debug("Gemini Realtime: Sending initial setup with tools to backend") + return [json.dumps({"setup": self._finalize_gemini_live_setup(model, new_overrides)})] if not new_overrides: - verbose_logger.debug( - "Gemini Realtime: Ignoring session.update (no mappable fields)" - ) + verbose_logger.debug("Gemini Realtime: Ignoring session.update (no mappable fields)") return [] try: @@ -534,18 +461,14 @@ def _handle_session_update( } original_generation_config = original_setup.get("generationConfig") new_generation_config = new_overrides.get("generationConfig") - if isinstance(original_generation_config, dict) and isinstance( - new_generation_config, dict - ): + if isinstance(original_generation_config, dict) and isinstance(new_generation_config, dict): follow_up_setup["generationConfig"] = { **original_generation_config, **new_generation_config, } original_realtime_input_config = original_setup.get("realtimeInputConfig") new_realtime_input_config = new_overrides.get("realtimeInputConfig") - if isinstance(original_realtime_input_config, dict) and isinstance( - new_realtime_input_config, dict - ): + if isinstance(original_realtime_input_config, dict) and isinstance(new_realtime_input_config, dict): merged_realtime_input_config = { **original_realtime_input_config, **new_realtime_input_config, @@ -555,12 +478,8 @@ def _handle_session_update( # ``create_response: False``) does not silently drop unrelated # knobs like ``silenceDurationMs`` / ``prefixPaddingMs`` from # the original setup. - original_automatic_activity_detection = original_realtime_input_config.get( - "automaticActivityDetection" - ) - new_automatic_activity_detection = new_realtime_input_config.get( - "automaticActivityDetection" - ) + original_automatic_activity_detection = original_realtime_input_config.get("automaticActivityDetection") + new_automatic_activity_detection = new_realtime_input_config.get("automaticActivityDetection") if isinstance(original_automatic_activity_detection, dict) and isinstance( new_automatic_activity_detection, dict ): @@ -572,21 +491,15 @@ def _handle_session_update( BidiGenerateContentRealtimeInputConfig, merged_realtime_input_config, ) - finalized_follow_up = self._finalize_gemini_live_setup( - model, cast(dict[str, Any], follow_up_setup) - ) + finalized_follow_up = self._finalize_gemini_live_setup(model, cast(dict[str, Any], follow_up_setup)) # Skip if the follow-up setup is identical to the one already sent. # The final session.update from Pipecat's _create_response (after history # items) matches the pre-history session.update we intentionally sent # before content; sending a duplicate at that point would risk a 1007. if finalized_follow_up == original_setup: - verbose_logger.debug( - "Gemini Realtime: Skipping duplicate follow-up session.update (no changes)" - ) + verbose_logger.debug("Gemini Realtime: Skipping duplicate follow-up session.update (no changes)") return [] - verbose_logger.debug( - "Gemini Realtime: Forwarding session.update as follow-up setup" - ) + verbose_logger.debug("Gemini Realtime: Forwarding session.update as follow-up setup") return [json.dumps({"setup": finalized_follow_up})] def _handle_conversation_item(self, json_message: dict) -> List[str]: @@ -608,20 +521,14 @@ def _handle_function_call_output(self, item: dict) -> List[str]: call_id = item.get("call_id", "") output = item.get("output", "{}") - verbose_logger.debug( - f"Gemini Realtime: Transforming function_call_output for call_id={call_id}" - ) + verbose_logger.debug(f"Gemini Realtime: Transforming function_call_output for call_id={call_id}") # Gemini functionResponses[].response must be a dict; wrap non-dicts. try: parsed_output = json.loads(output) if isinstance(output, str) else output except json.JSONDecodeError: parsed_output = output - output_dict = ( - parsed_output - if isinstance(parsed_output, dict) - else {"result": parsed_output} - ) + output_dict = parsed_output if isinstance(parsed_output, dict) else {"result": parsed_output} # Keep the entry (don't delete) so retried tool responses still find the name. function_name = self._tool_call_id_to_name.get(call_id) @@ -639,20 +546,14 @@ def _handle_function_call_output(self, item: dict) -> List[str]: if function_name: function_response["name"] = function_name - tool_response_message = { - "toolResponse": {"functionResponses": [function_response]} - } + tool_response_message = {"toolResponse": {"functionResponses": [function_response]}} return [json.dumps(tool_response_message)] def _handle_user_text_content(self, item: dict) -> List[str]: """Transform user text content to Gemini clientContent format.""" content_list = item.get("content", []) - text_parts = [ - c.get("text", "") - for c in content_list - if isinstance(c, dict) and c.get("type") == "input_text" - ] + text_parts = [c.get("text", "") for c in content_list if isinstance(c, dict) and c.get("type") == "input_text"] text = " ".join(filter(None, text_parts)) if not text: return [] @@ -686,9 +587,7 @@ def transform_realtime_request( msg_type = json_message.get("type") if msg_type == "session.update": - return self._handle_session_update( - json_message, model, session_configuration_request - ) + return self._handle_session_update(json_message, model, session_configuration_request) if msg_type == "response.create": return [] # Gemini responds automatically; nothing to forward @@ -703,22 +602,16 @@ def transform_realtime_request( realtime_input_dict = cast( BidiGenerateContentRealtimeInput, - encode_unserializable_types( - cast(Dict[str, object], realtime_input_dict) - ), + encode_unserializable_types(cast(Dict[str, object], realtime_input_dict)), ) gemini_msg = json.dumps({"realtimeInput": realtime_input_dict}) - verbose_logger.debug( - "Gemini Realtime: Sending audio realtimeInput to backend" - ) + verbose_logger.debug("Gemini Realtime: Sending audio realtimeInput to backend") messages.append(gemini_msg) return messages if msg_type in ("input_audio_buffer.commit", "input_audio_buffer.end"): - return self._handle_input_audio_buffer_commit_or_end( - session_configuration_request - ) + return self._handle_input_audio_buffer_commit_or_end(session_configuration_request) if msg_type == "input_audio_buffer.clear": return [] # local buffer op, nothing to forward @@ -739,16 +632,10 @@ def transform_session_created_event( session_configuration_request_dict = {} _model = session_configuration_request_dict.get("model") or model - generation_config = ( - session_configuration_request_dict.get("generationConfig", {}) or {} - ) + generation_config = session_configuration_request_dict.get("generationConfig", {}) or {} gemini_modalities = generation_config.get("responseModalities", ["AUDIO"]) - _modalities = [ - modality.lower() for modality in cast(List[str], gemini_modalities) - ] - _system_instruction = session_configuration_request_dict.get( - "systemInstruction" - ) + _modalities = [modality.lower() for modality in cast(List[str], gemini_modalities)] + _system_instruction = session_configuration_request_dict.get("systemInstruction") session = OpenAIRealtimeStreamSession( id=logging_session_id, modalities=_modalities, @@ -776,9 +663,7 @@ def _is_new_content_delta( ) -> bool: if previous_messages is None or len(previous_messages) == 0: return True - if "type" in previous_messages[-1] and previous_messages[-1]["type"].endswith( - "delta" - ): + if "type" in previous_messages[-1] and previous_messages[-1]["type"].endswith("delta"): return False return True @@ -793,18 +678,12 @@ def return_new_content_delta_events( session_configuration_request_dict: BidiGenerateContentSetup = {} if session_configuration_request is not None: try: - session_configuration_request_dict = json.loads( - session_configuration_request - ).get("setup", {}) + session_configuration_request_dict = json.loads(session_configuration_request).get("setup", {}) except json.JSONDecodeError: session_configuration_request_dict = {} - generation_config = session_configuration_request_dict.get( - "generationConfig", {} - ) + generation_config = session_configuration_request_dict.get("generationConfig", {}) gemini_modalities = generation_config.get("responseModalities", ["AUDIO"]) - _modalities = [ - modality.lower() for modality in cast(List[str], gemini_modalities) - ] + _modalities = [modality.lower() for modality in cast(List[str], gemini_modalities)] _temperature = generation_config.get("temperature") _max_output_tokens = generation_config.get("maxOutputTokens") @@ -904,16 +783,10 @@ def transform_content_delta_events( elif "inlineData" in part: delta += part["inlineData"].get("data", "") except Exception as e: - raise ValueError( - f"Error transforming content delta events: {e}, got message: {message}" - ) + raise ValueError(f"Error transforming content delta events: {e}, got message: {message}") return OpenAIRealtimeResponseDelta( - type=( - "response.output_text.delta" - if delta_type == "text" - else "response.output_audio.delta" - ), + type=("response.output_text.delta" if delta_type == "text" else "response.output_audio.delta"), content_index=0, event_id="event_{}".format(uuid.uuid4()), item_id=output_item_id, @@ -961,9 +834,7 @@ def return_additional_content_done_events( self, current_output_item_id: Optional[str], current_response_id: Optional[str], - delta_done_event: Union[ - OpenAIRealtimeResponseTextDone, OpenAIRealtimeResponseAudioDone - ], + delta_done_event: Union[OpenAIRealtimeResponseTextDone, OpenAIRealtimeResponseAudioDone], delta_type: ALL_DELTA_TYPES, ) -> List[OpenAIRealtimeEvents]: """ @@ -1046,9 +917,7 @@ def transform_tool_call_events( resolved_response_id = response_id or f"resp_{uuid.uuid4()}" resolved_output_item_id = output_item_id or f"item_{uuid.uuid4()}" - verbose_logger.debug( - f"Gemini Realtime: Transforming {len(function_calls)} tool call(s) to OpenAI format" - ) + verbose_logger.debug(f"Gemini Realtime: Transforming {len(function_calls)} tool call(s) to OpenAI format") events: List[OpenAIRealtimeFunctionCallArgumentsDone] = [] for idx, fc in enumerate(function_calls): @@ -1098,9 +967,7 @@ def update_current_delta_chunks( any_delta_chunk = False for event in transformed_message: if event["type"] == "response.output_text.delta": - current_delta_chunks.append( - cast(OpenAIRealtimeResponseDelta, event) - ) + current_delta_chunks.append(cast(OpenAIRealtimeResponseDelta, event)) any_delta_chunk = True if not any_delta_chunk: current_delta_chunks = None @@ -1110,9 +977,7 @@ def update_current_delta_chunks( ): # audio deltas are not accumulated (memory) if current_delta_chunks is None: current_delta_chunks = [] - current_delta_chunks.append( - cast(OpenAIRealtimeResponseDelta, transformed_message) - ) + current_delta_chunks.append(cast(OpenAIRealtimeResponseDelta, transformed_message)) else: current_delta_chunks = None return current_delta_chunks @@ -1132,9 +997,7 @@ def update_current_item_chunks( any_item_chunk = False for event in transformed_message: if event["type"] == "response.output_item.done": - current_item_chunks.append( - cast(OpenAIRealtimeOutputItemDone, event) - ) + current_item_chunks.append(cast(OpenAIRealtimeOutputItemDone, event)) any_item_chunk = True if not any_item_chunk: current_item_chunks = None @@ -1142,16 +1005,12 @@ def update_current_item_chunks( if transformed_message["type"] == "response.output_item.done": if current_item_chunks is None: current_item_chunks = [] - current_item_chunks.append( - cast(OpenAIRealtimeOutputItemDone, transformed_message) - ) + current_item_chunks.append(cast(OpenAIRealtimeOutputItemDone, transformed_message)) else: current_item_chunks = None return current_item_chunks except Exception as e: - raise ValueError( - f"Error updating current item chunks: {e}, got transformed_message: {transformed_message}" - ) + raise ValueError(f"Error updating current item chunks: {e}, got transformed_message: {transformed_message}") def transform_response_done_event( self, @@ -1173,18 +1032,12 @@ def transform_response_done_event( else: session_configuration_request_dict = {} - generation_config = session_configuration_request_dict.get( - "generationConfig", {} - ) + generation_config = session_configuration_request_dict.get("generationConfig", {}) temperature = generation_config.get("temperature") max_output_tokens = generation_config.get("maxOutputTokens") gemini_modalities = generation_config.get("responseModalities", ["AUDIO"]) - _modalities = [ - modality.lower() for modality in cast(List[str], gemini_modalities) - ] - resolved_usage_metadata = self._consume_usage_metadata_for_response_done( - cast(dict, message) - ) + _modalities = [modality.lower() for modality in cast(List[str], gemini_modalities)] + resolved_usage_metadata = self._consume_usage_metadata_for_response_done(cast(dict, message)) if resolved_usage_metadata is not None: _chat_completion_usage = VertexGeminiConfig._calculate_usage( completion_response=cast( @@ -1208,11 +1061,7 @@ def transform_response_done_event( id=current_response_id, status="completed", status_details=None, # type: ignore[typeddict-item] - output=( - [output_item["item"] for output_item in output_items] - if output_items - else [] - ), + output=([output_item["item"] for output_item in output_items] if output_items else []), conversation_id=current_conversation_id, modalities=_modalities, usage=_usage_dict, @@ -1221,9 +1070,7 @@ def transform_response_done_event( if temperature is not None: response_done_event["response"]["temperature"] = temperature if max_output_tokens is not None: - response_done_event["response"]["max_output_tokens"] = cast( - int, max_output_tokens - ) + response_done_event["response"]["max_output_tokens"] = cast(int, max_output_tokens) return response_done_event @@ -1234,17 +1081,11 @@ def handle_openai_modality_event( realtime_response_transform_input: RealtimeResponseTransformInput, delta_type: ALL_DELTA_TYPES, ) -> RealtimeModalityResponseTransformOutput: - current_output_item_id = realtime_response_transform_input[ - "current_output_item_id" - ] + current_output_item_id = realtime_response_transform_input["current_output_item_id"] current_response_id = realtime_response_transform_input["current_response_id"] - current_conversation_id = realtime_response_transform_input[ - "current_conversation_id" - ] + current_conversation_id = realtime_response_transform_input["current_conversation_id"] current_delta_chunks = realtime_response_transform_input["current_delta_chunks"] - session_configuration_request = realtime_response_transform_input[ - "session_configuration_request" - ] + session_configuration_request = realtime_response_transform_input["session_configuration_request"] returned_message: List[OpenAIRealtimeEvents] = [] if ( @@ -1255,9 +1096,7 @@ def handle_openai_modality_event( if not current_output_item_id: # send the list of standard 'new' content.delta events current_output_item_id = "item_{}".format(uuid.uuid4()) - current_conversation_id = current_conversation_id or "conv_{}".format( - uuid.uuid4() - ) + current_conversation_id = current_conversation_id or "conv_{}".format(uuid.uuid4()) returned_message = self.return_new_content_delta_events( session_configuration_request=session_configuration_request, response_id=current_response_id, @@ -1288,12 +1127,8 @@ def handle_openai_modality_event( # Use IDs from the done event — transform_content_done_event may have # generated UUID fallbacks when the originals were None. - resolved_item_id = ( - transformed_content_done_event.get("item_id") or current_output_item_id - ) - resolved_response_id = ( - transformed_content_done_event.get("response_id") or current_response_id - ) + resolved_item_id = transformed_content_done_event.get("item_id") or current_output_item_id + resolved_response_id = transformed_content_done_event.get("response_id") or current_response_id additional_items = self.return_additional_content_done_events( current_output_item_id=resolved_item_id, @@ -1324,15 +1159,11 @@ def map_openai_event( else: model_turn_event = None generation_complete_event = None - openai_event: Optional[ - Union[OpenAIRealtimeEventTypes, ResponsesAPIStreamEvents] - ] = None + openai_event: Optional[Union[OpenAIRealtimeEventTypes, ResponsesAPIStreamEvents]] = None if model_turn_event: # check if model turn event openai_event = self.map_model_turn_event(model_turn_event) elif generation_complete_event: - openai_event = self.map_generation_complete_event( - delta_type=current_delta_type - ) + openai_event = self.map_generation_complete_event(delta_type=current_delta_type) else: # Check if this key or any nested key matches our mapping. Use a # distinct loop variable so we don't shadow ``openai_event`` and @@ -1350,8 +1181,7 @@ def map_openai_event( if ( prefix == key and isinstance(value, dict) - and GeminiRealtimeConfig.get_nested_value(value, nested_path) - is not None + and GeminiRealtimeConfig.get_nested_value(value, nested_path) is not None ): openai_event = candidate_event break @@ -1380,30 +1210,18 @@ def transform_realtime_response( verbose_logger.debug( "Realtime Response Transform: Gemini frame keys=%s", - ( - sorted(json_message.keys()) - if isinstance(json_message, dict) - else type(json_message).__name__ - ), + (sorted(json_message.keys()) if isinstance(json_message, dict) else type(json_message).__name__), ) logging_session_id = logging_obj.litellm_trace_id - current_output_item_id = realtime_response_transform_input[ - "current_output_item_id" - ] + current_output_item_id = realtime_response_transform_input["current_output_item_id"] current_response_id = realtime_response_transform_input["current_response_id"] - current_conversation_id = realtime_response_transform_input[ - "current_conversation_id" - ] + current_conversation_id = realtime_response_transform_input["current_conversation_id"] current_delta_chunks = realtime_response_transform_input["current_delta_chunks"] - session_configuration_request = realtime_response_transform_input[ - "session_configuration_request" - ] + session_configuration_request = realtime_response_transform_input["session_configuration_request"] current_item_chunks = realtime_response_transform_input["current_item_chunks"] - current_delta_type: Optional[ALL_DELTA_TYPES] = ( - realtime_response_transform_input["current_delta_type"] - ) + current_delta_type: Optional[ALL_DELTA_TYPES] = realtime_response_transform_input["current_delta_type"] returned_message: List[OpenAIRealtimeEvents] = [] server_content = json_message.get("serverContent") @@ -1429,9 +1247,7 @@ def transform_realtime_response( current_response_id = "resp_{}".format(uuid.uuid4()) if current_output_item_id is None: current_output_item_id = "item_{}".format(uuid.uuid4()) - current_conversation_id = ( - current_conversation_id or "conv_{}".format(uuid.uuid4()) - ) + current_conversation_id = current_conversation_id or "conv_{}".format(uuid.uuid4()) returned_message.extend( self.return_new_content_delta_events( session_configuration_request=session_configuration_request, @@ -1465,16 +1281,12 @@ def transform_realtime_response( "interrupted", "generationComplete", } - server_content_handled = not any( - k in server_content for k in _model_content_keys - ) + server_content_handled = not any(k in server_content for k in _model_content_keys) else: server_content_handled = False tool_call_handled = False - for key, value in list( - json_message.items() - ): # snapshot: handlers may mutate json_message + for key, value in list(json_message.items()): # snapshot: handlers may mutate json_message # Skip sibling metadata keys (e.g. ``usageMetadata``) that can # accompany a primary payload like ``toolCall`` or ``serverContent``. # ``map_openai_event`` raises ValueError on unknown keys, which @@ -1512,21 +1324,15 @@ def transform_realtime_response( session_setup: BidiGenerateContentSetup = {} if session_configuration_request is not None: try: - session_setup = json.loads(session_configuration_request).get( - "setup", {} - ) + session_setup = json.loads(session_configuration_request).get("setup", {}) except (json.JSONDecodeError, TypeError): session_setup = {} - tool_call_generation_config = ( - session_setup.get("generationConfig", {}) or {} - ) + tool_call_generation_config = session_setup.get("generationConfig", {}) or {} tool_call_modalities = [ modality.lower() for modality in cast( List[str], - tool_call_generation_config.get( - "responseModalities", ["AUDIO"] - ), + tool_call_generation_config.get("responseModalities", ["AUDIO"]), ) ] @@ -1545,12 +1351,8 @@ def transform_realtime_response( "output": [], "conversation_id": current_conversation_id, "modalities": tool_call_modalities, - "temperature": tool_call_generation_config.get( - "temperature" - ), - "max_output_tokens": tool_call_generation_config.get( - "maxOutputTokens" - ), + "temperature": tool_call_generation_config.get("temperature"), + "max_output_tokens": tool_call_generation_config.get("maxOutputTokens"), }, } ) @@ -1630,25 +1432,23 @@ def transform_realtime_response( ) ) - resolved_tool_call_usage_metadata = ( - self._consume_usage_metadata_for_response_done(json_message) - ) + resolved_tool_call_usage_metadata = self._consume_usage_metadata_for_response_done(json_message) if resolved_tool_call_usage_metadata is not None: - _tool_call_chat_completion_usage = ( - VertexGeminiConfig._calculate_usage( - completion_response=cast( - BidiGenerateContentServerMessage, - { - **json_message, - "usageMetadata": resolved_tool_call_usage_metadata, - }, - ), - ) + _tool_call_chat_completion_usage = VertexGeminiConfig._calculate_usage( + completion_response=cast( + BidiGenerateContentServerMessage, + { + **json_message, + "usageMetadata": resolved_tool_call_usage_metadata, + }, + ), ) else: _tool_call_chat_completion_usage = get_empty_usage() - tool_call_responses_api_usage = LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage( - _tool_call_chat_completion_usage, + tool_call_responses_api_usage = ( + LiteLLMCompletionResponsesConfig._transform_chat_completion_usage_to_responses_usage( + _tool_call_chat_completion_usage, + ) ) _tool_usage_dict = tool_call_responses_api_usage.model_dump() self._add_pipecat_usage_detail_aliases(_tool_usage_dict) @@ -1679,23 +1479,16 @@ def transform_realtime_response( ) tool_call_temperature = tool_call_generation_config.get("temperature") if tool_call_temperature is not None: - tool_call_done_event["response"]["temperature"] = ( - tool_call_temperature - ) - tool_call_max_output_tokens = tool_call_generation_config.get( - "maxOutputTokens" - ) + tool_call_done_event["response"]["temperature"] = tool_call_temperature + tool_call_max_output_tokens = tool_call_generation_config.get("maxOutputTokens") if tool_call_max_output_tokens is not None: - tool_call_done_event["response"]["max_output_tokens"] = cast( - int, tool_call_max_output_tokens - ) + tool_call_done_event["response"]["max_output_tokens"] = cast(int, tool_call_max_output_tokens) returned_message.append(tool_call_done_event) current_output_item_id = None current_response_id = None elif openai_event == OpenAIRealtimeEventTypes.RESPONSE_DONE: _has_pending_function_call = current_item_chunks and any( - chunk.get("item", {}).get("type") == "function_call" - for chunk in current_item_chunks + chunk.get("item", {}).get("type") == "function_call" for chunk in current_item_chunks ) if current_response_id is None and _has_pending_function_call: # Trailing bare turnComplete after a toolCall (Vertex emits ~5 @@ -1787,9 +1580,7 @@ def transform_realtime_response( for msg in returned_message: event_type = msg.get("type") if isinstance(msg, dict) else "unknown" - verbose_logger.debug( - "Realtime Response Transform: OpenAI event=%s", event_type - ) + verbose_logger.debug("Realtime Response Transform: OpenAI event=%s", event_type) return { "response": returned_message, diff --git a/litellm/llms/gemini/vector_stores/transformation.py b/litellm/llms/gemini/vector_stores/transformation.py index 35d83bd2adc6..f98cb0e5b0c1 100644 --- a/litellm/llms/gemini/vector_stores/transformation.py +++ b/litellm/llms/gemini/vector_stores/transformation.py @@ -45,9 +45,7 @@ def __init__(self) -> None: self.model_info = GeminiModelInfo() self._cached_api_key: Optional[str] = None - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: """Gemini uses x-goog-api-key header for authentication.""" return {} @@ -63,15 +61,11 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [("POST", "/fileSearchStores")], } - def get_supported_openai_params( - self, model: str - ) -> List[VECTOR_STORE_OPENAI_PARAMS]: + def get_supported_openai_params(self, model: str) -> List[VECTOR_STORE_OPENAI_PARAMS]: """Supported parameters for Gemini File Search.""" return ["max_num_results", "filters"] - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """Validate and set up headers for Gemini API.""" headers = headers or {} headers.setdefault("Content-Type", "application/json") @@ -100,9 +94,7 @@ def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str api_version = "v1beta" return f"{api_base}/{api_version}" - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] - ) -> GeminiError: + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]) -> GeminiError: """Return Gemini-specific error class.""" return GeminiError( status_code=status_code, @@ -141,9 +133,7 @@ def transform_search_vector_store_request( url = f"{api_base}/models/{model}:generateContent" # Build file_search tool configuration (using snake_case as per Gemini docs) - file_search_config: Dict[str, Any] = { - "file_search_store_names": [vector_store_id] - } + file_search_config: Dict[str, Any] = {"file_search_store_names": [vector_store_id]} # Add metadata filter if provided metadata_filter = vector_store_search_optional_params.get("filters") @@ -214,9 +204,7 @@ def transform_search_vector_store_response( results.append( VectorStoreSearchResult( score=None, # Gemini doesn't provide explicit scores - content=[ - VectorStoreResultContent(text=text, type="text") - ], + content=[VectorStoreResultContent(text=text, type="text")], file_id=file_id, filename=title if title else None, attributes={ @@ -251,9 +239,7 @@ def transform_search_vector_store_response( results.append( VectorStoreSearchResult( score=score, - content=[ - VectorStoreResultContent(text=text, type="text") - ], + content=[VectorStoreResultContent(text=text, type="text")], attributes={ "grounding_chunk_indices": grounding_chunk_indices, }, @@ -296,9 +282,7 @@ def transform_create_vector_store_request( return url, request_body - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: """ Transform Gemini's fileSearchStore response to standard format. """ @@ -316,9 +300,7 @@ def transform_create_vector_store_response( created_at = None if create_time: try: - dt = datetime.datetime.fromisoformat( - create_time.replace("Z", "+00:00") - ) + dt = datetime.datetime.fromisoformat(create_time.replace("Z", "+00:00")) created_at = int(dt.timestamp()) except Exception: created_at = None diff --git a/litellm/llms/gemini/videos/transformation.py b/litellm/llms/gemini/videos/transformation.py index 644e96a7dd17..4a9b3830ec57 100644 --- a/litellm/llms/gemini/videos/transformation.py +++ b/litellm/llms/gemini/videos/transformation.py @@ -115,11 +115,7 @@ def map_openai_params( # Get supported OpenAI params (exclude "model" and "prompt" which are handled separately) supported_openai_params = self.get_supported_openai_params(model) - openai_params_to_map = { - param - for param in supported_openai_params - if param not in {"model", "prompt"} - } + openai_params_to_map = {param for param in supported_openai_params if param not in {"model", "prompt"}} # Map input_reference to image if "input_reference" in video_create_optional_params: @@ -203,12 +199,7 @@ def validate_environment( if litellm_params and litellm_params.api_key: api_key = api_key or litellm_params.api_key - api_key = ( - api_key - or litellm.api_key - or get_secret_str("GOOGLE_API_KEY") - or get_secret_str("GEMINI_API_KEY") - ) + api_key = api_key or litellm.api_key or get_secret_str("GOOGLE_API_KEY") or get_secret_str("GEMINI_API_KEY") if not api_key: raise ValueError( @@ -236,10 +227,7 @@ def get_complete_url( For status/delete: returns base URL only """ if api_base is None: - api_base = ( - get_secret_str("GEMINI_API_BASE") - or "https://generativelanguage.googleapis.com" - ) + api_base = get_secret_str("GEMINI_API_BASE") or "https://generativelanguage.googleapis.com" if not model or model == "": return api_base.rstrip("/") @@ -294,9 +282,7 @@ def transform_video_create_request( parameters = GeminiVideoGenerationParameters(**params_copy) - request_body_obj = GeminiVideoGenerationRequest( - instances=[instance], parameters=parameters - ) + request_body_obj = GeminiVideoGenerationRequest(instances=[instance], parameters=parameters) request_data = request_body_obj.model_dump(exclude_none=True) @@ -339,9 +325,7 @@ def transform_video_create_response( raise ValueError(f"No operation name in Veo response: {response_data}") if custom_llm_provider: - video_id = encode_video_id_with_provider( - operation_name, custom_llm_provider, model - ) + video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, model) else: video_id = operation_name @@ -355,10 +339,7 @@ def transform_video_create_response( usage_data: Dict[str, Any] = {} if request_data: parameters = request_data.get("parameters", {}) - duration = ( - parameters.get("durationSeconds") - or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS - ) + duration = parameters.get("durationSeconds") or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS if duration is not None: try: usage_data["duration_seconds"] = float(duration) @@ -430,9 +411,7 @@ def transform_video_status_retrieve_response( is_done = operation_response.done if custom_llm_provider: - video_id = encode_video_id_with_provider( - operation_name, custom_llm_provider, None - ) + video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, None) else: video_id = operation_name @@ -470,16 +449,13 @@ def transform_video_content_request( if not operation_response.done: raise ValueError( - "Video generation is not complete yet. " - "Please check status with video_status() before downloading." + "Video generation is not complete yet. Please check status with video_status() before downloading." ) if not operation_response.response: raise ValueError("No response data in completed operation") - generated_samples = ( - operation_response.response.generateVideoResponse.generatedSamples - ) + generated_samples = operation_response.response.generateVideoResponse.generatedSamples download_url = generated_samples[0].video.uri params: Dict[str, Any] = {} @@ -510,8 +486,7 @@ def transform_video_remix_request( Video remix is not supported by Veo API. """ raise NotImplementedError( - "Video remix is not supported by Google Veo. " - "Please use video_generation() to create new videos." + "Video remix is not supported by Google Veo. Please use video_generation() to create new videos." ) def transform_video_remix_response( @@ -561,8 +536,7 @@ def transform_video_delete_request( Video delete is not supported by Veo API. """ raise NotImplementedError( - "Video delete is not supported by Google Veo. " - "Videos are automatically cleaned up by Google." + "Video delete is not supported by Google Veo. Videos are automatically cleaned up by Google." ) def transform_video_delete_response( @@ -573,17 +547,13 @@ def transform_video_delete_response( """Video delete is not supported.""" raise NotImplementedError("Video delete is not supported by Google Veo.") - def transform_video_create_character_request( - self, name, video, api_base, litellm_params, headers - ): + def transform_video_create_character_request(self, name, video, api_base, litellm_params, headers): raise NotImplementedError("video create character is not supported for Gemini") def transform_video_create_character_response(self, raw_response, logging_obj): raise NotImplementedError("video create character is not supported for Gemini") - def transform_video_get_character_request( - self, character_id, api_base, litellm_params, headers - ): + def transform_video_get_character_request(self, character_id, api_base, litellm_params, headers): raise NotImplementedError("video get character is not supported for Gemini") def transform_video_get_character_response(self, raw_response, logging_obj): @@ -622,9 +592,7 @@ def transform_video_extension_request( ): raise NotImplementedError("video extension is not supported for Gemini") - def transform_video_extension_response( - self, raw_response, logging_obj, custom_llm_provider=None - ): + def transform_video_extension_response(self, raw_response, logging_obj, custom_llm_provider=None): raise NotImplementedError("video extension is not supported for Gemini") def get_error_class( diff --git a/litellm/llms/gigachat/authenticator.py b/litellm/llms/gigachat/authenticator.py index 59942a9c0382..e61015a4a210 100644 --- a/litellm/llms/gigachat/authenticator.py +++ b/litellm/llms/gigachat/authenticator.py @@ -104,9 +104,7 @@ def get_access_token( token, expires_at = _request_token_sync(credentials, scope, auth_url) # Cache token - ttl_seconds = max( - 0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000 - ) + ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000) if ttl_seconds > 0: _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds) @@ -142,9 +140,7 @@ async def get_access_token_async( token, expires_at = await _request_token_async(credentials, scope, auth_url) # Cache token - ttl_seconds = max( - 0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000 - ) + ttl_seconds = max(0, (expires_at - TOKEN_EXPIRY_BUFFER_MS - time.time() * 1000) / 1000) if ttl_seconds > 0: _token_cache.set_cache(cache_key, (token, expires_at), ttl=ttl_seconds) diff --git a/litellm/llms/gigachat/chat/transformation.py b/litellm/llms/gigachat/chat/transformation.py index cef807687622..dbf04fd015df 100644 --- a/litellm/llms/gigachat/chat/transformation.py +++ b/litellm/llms/gigachat/chat/transformation.py @@ -111,11 +111,7 @@ def validate_environment( Set up headers with OAuth token. """ # Get access token - credentials = ( - api_key - or get_secret_str("GIGACHAT_CREDENTIALS") - or get_secret_str("GIGACHAT_API_KEY") - ) + credentials = api_key or get_secret_str("GIGACHAT_CREDENTIALS") or get_secret_str("GIGACHAT_API_KEY") access_token = get_access_token(credentials=credentials) # Store credentials for image uploads @@ -216,9 +212,7 @@ def _convert_tools_to_functions(self, tools: List[dict]) -> List[dict]: ) return functions - def _map_tool_choice( - self, tool_choice: Union[str, dict] - ) -> Optional[Union[str, dict]]: + def _map_tool_choice(self, tool_choice: Union[str, dict]) -> Optional[Union[str, dict]]: """ Map OpenAI tool_choice to GigaChat function_call format. diff --git a/litellm/llms/github_copilot/authenticator.py b/litellm/llms/github_copilot/authenticator.py index 3785f9c46573..9fefc5df0c51 100644 --- a/litellm/llms/github_copilot/authenticator.py +++ b/litellm/llms/github_copilot/authenticator.py @@ -36,9 +36,7 @@ def __init__(self) -> None: self.token_dir, os.getenv("GITHUB_COPILOT_ACCESS_TOKEN_FILE", "access-token"), ) - self.api_key_file = os.path.join( - self.token_dir, os.getenv("GITHUB_COPILOT_API_KEY_FILE", "api-key.json") - ) + self.api_key_file = os.path.join(self.token_dir, os.getenv("GITHUB_COPILOT_API_KEY_FILE", "api-key.json")) self._ensure_token_dir() def get_access_token(self) -> str: @@ -57,9 +55,7 @@ def get_access_token(self) -> str: if access_token: return access_token except IOError: - verbose_logger.warning( - "No existing access token found or error reading file" - ) + verbose_logger.warning("No existing access token found or error reading file") for attempt in range(3): verbose_logger.debug(f"Access token acquisition attempt {attempt + 1}/3") @@ -161,9 +157,7 @@ def _refresh_api_key(self) -> Dict[str, Any]: """ access_token = self.get_access_token() headers = self._get_github_headers(access_token) - api_key_url = os.getenv( - "GITHUB_COPILOT_API_KEY_URL", DEFAULT_GITHUB_API_KEY_URL - ) + api_key_url = os.getenv("GITHUB_COPILOT_API_KEY_URL", DEFAULT_GITHUB_API_KEY_URL) max_retries = 3 for attempt in range(max_retries): @@ -177,13 +171,9 @@ def _refresh_api_key(self) -> Dict[str, Any]: if "token" in response_json: return response_json else: - verbose_logger.warning( - f"API key response missing token: {response_json}" - ) + verbose_logger.warning(f"API key response missing token: {response_json}") except httpx.HTTPStatusError as e: - verbose_logger.error( - f"HTTP error refreshing API key (attempt {attempt + 1}/{max_retries}): {str(e)}" - ) + verbose_logger.error(f"HTTP error refreshing API key (attempt {attempt + 1}/{max_retries}): {str(e)}") except Exception as e: verbose_logger.error(f"Unexpected error refreshing API key: {str(e)}") @@ -235,9 +225,7 @@ def _get_device_code(self) -> Dict[str, str]: """ try: sync_client = _get_httpx_client() - device_code_url = os.getenv( - "GITHUB_COPILOT_DEVICE_CODE_URL", DEFAULT_GITHUB_DEVICE_CODE_URL - ) + device_code_url = os.getenv("GITHUB_COPILOT_DEVICE_CODE_URL", DEFAULT_GITHUB_DEVICE_CODE_URL) client_id = os.getenv("GITHUB_COPILOT_CLIENT_ID", DEFAULT_GITHUB_CLIENT_ID) resp = sync_client.post( device_code_url, @@ -291,9 +279,7 @@ def _poll_for_access_token(self, device_code: str) -> str: sync_client = _get_httpx_client() max_attempts = 12 # 1 minute (12 * 5 seconds) - access_token_url = os.getenv( - "GITHUB_COPILOT_ACCESS_TOKEN_URL", DEFAULT_GITHUB_ACCESS_TOKEN_URL - ) + access_token_url = os.getenv("GITHUB_COPILOT_ACCESS_TOKEN_URL", DEFAULT_GITHUB_ACCESS_TOKEN_URL) client_id = os.getenv("GITHUB_COPILOT_CLIENT_ID", DEFAULT_GITHUB_CLIENT_ID) for attempt in range(max_attempts): @@ -313,13 +299,8 @@ def _poll_for_access_token(self, device_code: str) -> str: if "access_token" in resp_json: verbose_logger.info("Authentication successful!") return resp_json["access_token"] - elif ( - "error" in resp_json - and resp_json.get("error") == "authorization_pending" - ): - verbose_logger.debug( - f"Authorization pending (attempt {attempt + 1}/{max_attempts})" - ) + elif "error" in resp_json and resp_json.get("error") == "authorization_pending": + verbose_logger.debug(f"Authorization pending (attempt {attempt + 1}/{max_attempts})") else: verbose_logger.warning(f"Unexpected response: {resp_json}") except httpx.HTTPStatusError as e: @@ -335,9 +316,7 @@ def _poll_for_access_token(self, device_code: str) -> str: status_code=400, ) except Exception as e: - verbose_logger.error( - f"Unexpected error polling for access token: {str(e)}" - ) + verbose_logger.error(f"Unexpected error polling for access token: {str(e)}") raise GetAccessTokenError( message=f"Failed to get access token: {str(e)}", status_code=400, diff --git a/litellm/llms/github_copilot/chat/transformation.py b/litellm/llms/github_copilot/chat/transformation.py index 54cbf69a4ace..2cc052279488 100644 --- a/litellm/llms/github_copilot/chat/transformation.py +++ b/litellm/llms/github_copilot/chat/transformation.py @@ -189,9 +189,7 @@ def _parse_anthropic_native_content( _web_search_results, _tool_results, _compaction_blocks, - ) = AnthropicConfig().extract_response_content( - completion_response={"content": content_blocks} - ) + ) = AnthropicConfig().extract_response_content(completion_response={"content": content_blocks}) return text_content, tool_calls, thinking_blocks @staticmethod @@ -202,9 +200,7 @@ def _normalize_anthropic_usage(usage: dict) -> dict: if "output_tokens" in usage and "completion_tokens" not in usage: normalized["completion_tokens"] = usage["output_tokens"] if "total_tokens" not in normalized: - normalized["total_tokens"] = normalized.get( - "prompt_tokens", 0 - ) + normalized.get("completion_tokens", 0) + normalized["total_tokens"] = normalized.get("prompt_tokens", 0) + normalized.get("completion_tokens", 0) return normalized @classmethod @@ -227,9 +223,7 @@ def _synthesize_choices_for_anthropic_native(cls, response_json: dict) -> dict: thinking_blocks: List[Any] | None = None raw_content = response_json.get("content") if isinstance(raw_content, list): - content, tool_calls, thinking_blocks = cls._parse_anthropic_native_content( - raw_content - ) + content, tool_calls, thinking_blocks = cls._parse_anthropic_native_content(raw_content) elif isinstance(raw_content, str): content = raw_content @@ -260,9 +254,7 @@ def _synthesize_choices_for_anthropic_native(cls, response_json: dict) -> dict: synthesized = { **response_json, - "choices": [ - {"index": 0, "message": message, "finish_reason": finish_reason} - ], + "choices": [{"index": 0, "message": message, "finish_reason": finish_reason}], } usage = response_json.get("usage") if isinstance(usage, dict): diff --git a/litellm/llms/github_copilot/embedding/transformation.py b/litellm/llms/github_copilot/embedding/transformation.py index da2dc339d6e7..d4014ec62425 100644 --- a/litellm/llms/github_copilot/embedding/transformation.py +++ b/litellm/llms/github_copilot/embedding/transformation.py @@ -76,9 +76,7 @@ def validate_environment( # Merge with existing headers (user's extra_headers take priority) merged_headers = {**default_headers, **headers} - verbose_logger.debug( - f"GitHub Copilot Embedding API: Successfully configured headers for model {model}" - ) + verbose_logger.debug(f"GitHub Copilot Embedding API: Successfully configured headers for model {model}") return merged_headers @@ -185,11 +183,7 @@ def map_openai_params( optional_params[param] = value return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Any - ) -> Any: + def get_error_class(self, error_message: str, status_code: int, headers: Any) -> Any: from litellm.llms.openai.openai import OpenAIConfig - return OpenAIConfig().get_error_class( - error_message=error_message, status_code=status_code, headers=headers - ) + return OpenAIConfig().get_error_class(error_message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/github_copilot/responses/transformation.py b/litellm/llms/github_copilot/responses/transformation.py index d9f759e0a058..0393d6a9d641 100644 --- a/litellm/llms/github_copilot/responses/transformation.py +++ b/litellm/llms/github_copilot/responses/transformation.py @@ -53,9 +53,7 @@ def github_copilot_supports_responses_api(model: str) -> bool: register_model, which also clears the cache used here). """ try: - info = _cached_get_model_info_helper( - model=model, custom_llm_provider="github_copilot" - ) + info = _cached_get_model_info_helper(model=model, custom_llm_provider="github_copilot") except Exception as e: verbose_logger.debug( "github_copilot_supports_responses_api: get_model_info failed for %s: %s", @@ -74,9 +72,7 @@ def github_copilot_supports_responses_api(model: str) -> bool: # model_cost entry via the resolved key. key = info.get("key") raw_info = litellm.model_cost.get(key) if isinstance(key, str) else None - endpoints = ( - raw_info.get("supported_endpoints") if isinstance(raw_info, dict) else None - ) + endpoints = raw_info.get("supported_endpoints") if isinstance(raw_info, dict) else None return isinstance(endpoints, list) and "/v1/responses" in endpoints @@ -227,20 +223,14 @@ def validate_environment( if input_param is not None: initiator = self._get_initiator(input_param) merged_headers["X-Initiator"] = initiator - verbose_logger.debug( - f"GitHub Copilot Responses API: Set X-Initiator={initiator}" - ) + verbose_logger.debug(f"GitHub Copilot Responses API: Set X-Initiator={initiator}") # Add vision header if input contains images if self._has_vision_input(input_param): merged_headers["copilot-vision-request"] = "true" - verbose_logger.debug( - "GitHub Copilot Responses API: Enabled vision request" - ) + verbose_logger.debug("GitHub Copilot Responses API: Enabled vision request") - verbose_logger.debug( - f"GitHub Copilot Responses API: Successfully configured headers for model {model}" - ) + verbose_logger.debug(f"GitHub Copilot Responses API: Successfully configured headers for model {model}") return merged_headers @@ -384,9 +374,7 @@ def _has_vision_input(self, input_param: Union[str, ResponseInputParam]) -> bool """ return self._contains_vision_content(input_param) - def _contains_vision_content( - self, value: Any, depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH - ) -> bool: + def _contains_vision_content(self, value: Any, depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> bool: """ Recursively check if a value contains vision content. @@ -403,12 +391,7 @@ def _contains_vision_content( # Check arrays if isinstance(value, list): - return any( - self._contains_vision_content( - item, depth=depth + 1, max_depth=max_depth - ) - for item in value - ) + return any(self._contains_vision_content(item, depth=depth + 1, max_depth=max_depth) for item in value) # Only check dict/object types if not isinstance(value, dict): @@ -422,10 +405,7 @@ def _contains_vision_content( # Check content field recursively if "content" in value and isinstance(value["content"], list): return any( - self._contains_vision_content( - item, depth=depth + 1, max_depth=max_depth - ) - for item in value["content"] + self._contains_vision_content(item, depth=depth + 1, max_depth=max_depth) for item in value["content"] ) return False diff --git a/litellm/llms/google_pse/search/transformation.py b/litellm/llms/google_pse/search/transformation.py index 5cd3f2085a8c..52d4baba955c 100644 --- a/litellm/llms/google_pse/search/transformation.py +++ b/litellm/llms/google_pse/search/transformation.py @@ -43,14 +43,10 @@ class GooglePSESearchRequest(_GooglePSESearchRequestRequired, total=False): hq: str # Optional - append query terms to query imgSize: str # Optional - returns images of specified size imgType: str # Optional - returns images of specified type - linkSite: ( - str # Optional - specifies all search results should contain a link to a URL - ) + linkSite: str # Optional - specifies all search results should contain a link to a URL lr: str # Optional - language restrict (e.g., 'lang_en', 'lang_es') orTerms: str # Optional - provides additional search terms - relatedSite: ( - str # Optional - specifies all search results should be pages related to URL - ) + relatedSite: str # Optional - specifies all search results should be pages related to URL rights: str # Optional - filters based on licensing safe: str # Optional - search safety level ('active', 'off') searchType: str # Optional - specifies search type ('image') @@ -93,14 +89,10 @@ def validate_environment( default_api_base=self.GOOGLE_PSE_API_BASE, ) if not api_key: - raise ValueError( - "GOOGLE_PSE_API_KEY is not set. Set `GOOGLE_PSE_API_KEY` environment variable." - ) + raise ValueError("GOOGLE_PSE_API_KEY is not set. Set `GOOGLE_PSE_API_KEY` environment variable.") # Also check for search engine ID - search_engine_id = kwargs.get("search_engine_id") or get_secret_str( - "GOOGLE_PSE_ENGINE_ID" - ) + search_engine_id = kwargs.get("search_engine_id") or get_secret_str("GOOGLE_PSE_ENGINE_ID") if not search_engine_id: raise ValueError( "GOOGLE_PSE_ENGINE_ID is not set. Set `GOOGLE_PSE_ENGINE_ID` environment variable or pass `search_engine_id` parameter." @@ -124,11 +116,7 @@ def get_complete_url( """ from urllib.parse import urlencode - api_base = ( - api_base - or get_secret_str("GOOGLE_PSE_API_BASE") - or self.GOOGLE_PSE_API_BASE - ) + api_base = api_base or get_secret_str("GOOGLE_PSE_API_BASE") or self.GOOGLE_PSE_API_BASE # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_google_pse_params" in data: @@ -220,10 +208,7 @@ def transform_search_request( # Pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # Store params in special key for URL building (Google PSE uses GET not POST) diff --git a/litellm/llms/gradient_ai/chat/transformation.py b/litellm/llms/gradient_ai/chat/transformation.py index 1bc5e8896b11..e81c09d5cf3c 100644 --- a/litellm/llms/gradient_ai/chat/transformation.py +++ b/litellm/llms/gradient_ai/chat/transformation.py @@ -20,9 +20,7 @@ class GradientAIConfig(OpenAILikeChatConfig): include_retrieval_info: Optional[bool] = None include_guardrails_info: Optional[bool] = None provide_citations: Optional[bool] = None - retrieval_method: Optional[ - Literal["rewrite", "step_back", "sub_queries", "none"] - ] = None + retrieval_method: Optional[Literal["rewrite", "step_back", "sub_queries", "none"]] = None def __init__( self, @@ -110,10 +108,7 @@ def get_complete_url( if api_base and api_base != GRADIENT_AI_SERVERLESS_ENDPOINT: complete_url = f"{api_base}/api/v1/chat/completions" - elif ( - gradient_ai_endpoint - and gradient_ai_endpoint != GRADIENT_AI_SERVERLESS_ENDPOINT - ): + elif gradient_ai_endpoint and gradient_ai_endpoint != GRADIENT_AI_SERVERLESS_ENDPOINT: complete_url = f"{gradient_ai_endpoint}/api/v1/chat/completions" return complete_url diff --git a/litellm/llms/groq/chat/handler.py b/litellm/llms/groq/chat/handler.py index dc4c3222b120..2553af6df778 100644 --- a/litellm/llms/groq/chat/handler.py +++ b/litellm/llms/groq/chat/handler.py @@ -43,9 +43,7 @@ def completion( streaming_decoder: Optional[CustomStreamingDecoder] = None, fake_stream: bool = False, ): - messages = GroqChatConfig()._transform_messages( - messages=cast(List[AllMessageValues], messages), model=model - ) + messages = GroqChatConfig()._transform_messages(messages=cast(List[AllMessageValues], messages), model=model) if optional_params.get("stream") is True: fake_stream = GroqChatConfig()._should_fake_stream(optional_params) diff --git a/litellm/llms/groq/chat/transformation.py b/litellm/llms/groq/chat/transformation.py index d07da006f2dd..089c0cac62c8 100644 --- a/litellm/llms/groq/chat/transformation.py +++ b/litellm/llms/groq/chat/transformation.py @@ -104,9 +104,7 @@ def get_supported_openai_params(self, model: str) -> list: pass try: - if litellm.supports_reasoning( - model=model, custom_llm_provider=self.custom_llm_provider - ): + if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider): base_params.append("reasoning_effort") except Exception as e: verbose_logger.debug(f"Error checking if model supports reasoning: {e}") @@ -146,23 +144,15 @@ def _transform_messages( messages[idx] = new_message if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: # groq is openai compatible, we just need to set this to custom_openai and have the api_base be https://api.groq.com/openai/v1 - api_base = ( - api_base - or get_secret_str("GROQ_API_BASE") - or "https://api.groq.com/openai/v1" - ) # type: ignore + api_base = api_base or get_secret_str("GROQ_API_BASE") or "https://api.groq.com/openai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("GROQ_API_KEY") return api_base, dynamic_api_key @@ -226,9 +216,7 @@ def map_openai_params( """ if json_schema is not None: # Check if model supports native response_schema - if not litellm.supports_response_schema( - model=model, custom_llm_provider="groq" - ): + if not litellm.supports_response_schema(model=model, custom_llm_provider="groq"): # Check if user is also passing tools - this combination won't work # See: https://console.groq.com/docs/structured-outputs # "Streaming and tool use are not currently supported with Structured Outputs" @@ -258,9 +246,7 @@ def map_openai_params( "response_format", None ) # only remove if it's a json_schema - handled via using groq's tool calling params. # else: model supports native json_schema, let response_format pass through - optional_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + optional_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) return optional_params @@ -292,17 +278,13 @@ def transform_response( json_mode=json_mode, ) - mapped_service_tier: Literal["auto", "default", "flex"] = ( - self._map_groq_service_tier( - original_service_tier=getattr(model_response, "service_tier") - ) + mapped_service_tier: Literal["auto", "default", "flex"] = self._map_groq_service_tier( + original_service_tier=getattr(model_response, "service_tier") ) setattr(model_response, "service_tier", mapped_service_tier) return model_response - def _map_groq_service_tier( - self, original_service_tier: Optional[str] - ) -> Literal["auto", "default", "flex"]: + def _map_groq_service_tier(self, original_service_tier: Optional[str]) -> Literal["auto", "default", "flex"]: """ Ensure groq service tier is OpenAI compatible. """ @@ -318,9 +300,7 @@ class GroqChatCompletionStreamingHandler(OpenAIChatCompletionStreamingHandler): def chunk_parser(self, chunk: dict) -> ModelResponseStream: error = chunk.get("error") if error: - raise OpenAIError( - status_code=error.get("code"), message=error.get("message"), body=error - ) + raise OpenAIError(status_code=error.get("code"), message=error.get("message"), body=error) # Map Groq's 'reasoning' field to LiteLLM's 'reasoning_content' field # Groq returns delta.reasoning, but LiteLLM expects delta.reasoning_content diff --git a/litellm/llms/heroku/chat/transformation.py b/litellm/llms/heroku/chat/transformation.py index fb4cc3611893..2efa9fe673fc 100644 --- a/litellm/llms/heroku/chat/transformation.py +++ b/litellm/llms/heroku/chat/transformation.py @@ -42,13 +42,9 @@ def _transform_messages( """ messages = handle_messages_with_content_list_to_str_conversion(messages) if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] diff --git a/litellm/llms/hosted_vllm/chat/transformation.py b/litellm/llms/hosted_vllm/chat/transformation.py index 7c42e6a9a002..db98749eae0a 100644 --- a/litellm/llms/hosted_vllm/chat/transformation.py +++ b/litellm/llms/hosted_vllm/chat/transformation.py @@ -20,6 +20,9 @@ _get_image_mime_type_from_url, ) from litellm.litellm_core_utils.prompt_templates.factory import _parse_mime_type +from litellm.litellm_core_utils.reasoning_effort_utils import ( + reasoning_effort_from_thinking_budget, +) from litellm.secret_managers.main import get_secret_str from litellm.types.llms.openai import ( AllMessageValues, @@ -35,9 +38,7 @@ class HostedVLLMChatConfig(OpenAIGPTConfig): - def _convert_custom_tools_to_function_tools( - self, tools: List[Dict[str, Any]] - ) -> List[Dict[str, Any]]: + def _convert_custom_tools_to_function_tools(self, tools: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ vLLM chat completions currently accepts only OpenAI function tools. Convert custom tools into function tools so request validation does not fail. @@ -56,13 +57,9 @@ def _convert_custom_tools_to_function_tools( if not isinstance(custom_tool, dict): custom_tool = {} - tool_name = ( - custom_tool.get("name") or tool.get("name") or f"custom_tool_{idx}" - ) + tool_name = custom_tool.get("name") or tool.get("name") or f"custom_tool_{idx}" tool_description = custom_tool.get("description") or tool.get("description") - tool_parameters = custom_tool.get("input_schema") or tool.get( - "input_schema" - ) + tool_parameters = custom_tool.get("input_schema") or tool.get("input_schema") if not isinstance(tool_parameters, dict): tool_parameters = { @@ -115,27 +112,17 @@ def map_openai_params( if thinking is not None and isinstance(thinking, dict): if thinking.get("type") == "enabled": if "reasoning_effort" not in non_default_params: - budget_tokens = thinking.get("budget_tokens", 0) - if budget_tokens >= 10000: - non_default_params["reasoning_effort"] = "high" - elif budget_tokens >= 5000: - non_default_params["reasoning_effort"] = "medium" - elif budget_tokens >= 2000: - non_default_params["reasoning_effort"] = "low" - else: - non_default_params["reasoning_effort"] = "minimal" + non_default_params["reasoning_effort"] = reasoning_effort_from_thinking_budget( + thinking.get("budget_tokens", 0) + ) - return super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + return super().map_openai_params(non_default_params, optional_params, model, drop_params) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: api_base = api_base or get_secret_str("HOSTED_VLLM_API_BASE") - dynamic_api_key = ( - api_key or get_secret_str("HOSTED_VLLM_API_KEY") or "fake-api-key" - ) + dynamic_api_key = api_key or get_secret_str("HOSTED_VLLM_API_KEY") or "fake-api-key" return api_base, dynamic_api_key def _is_video_file(self, content_item: ChatCompletionFileObject) -> bool: @@ -157,21 +144,15 @@ def _is_video_file(self, content_item: ChatCompletionFileObject) -> bool: return True return False - def _convert_file_to_video_url( - self, content_item: ChatCompletionFileObject - ) -> ChatCompletionVideoObject: + def _convert_file_to_video_url(self, content_item: ChatCompletionFileObject) -> ChatCompletionVideoObject: file = content_item.get("file", {}) file_id = file.get("file_id") file_data = file.get("file_data") if file_id: - return ChatCompletionVideoObject( - type="video_url", video_url=ChatCompletionVideoUrlObject(url=file_id) - ) + return ChatCompletionVideoObject(type="video_url", video_url=ChatCompletionVideoUrlObject(url=file_id)) elif file_data: - return ChatCompletionVideoObject( - type="video_url", video_url=ChatCompletionVideoUrlObject(url=file_data) - ) + return ChatCompletionVideoObject(type="video_url", video_url=ChatCompletionVideoUrlObject(url=file_data)) raise ValueError("file_id or file_data is required") @overload @@ -237,8 +218,7 @@ def _transform_messages( existing_tool_call_ids = { tool_call.get("id") for tool_call in existing_tool_calls - if isinstance(tool_call, dict) - and tool_call.get("id") is not None + if isinstance(tool_call, dict) and tool_call.get("id") is not None } new_tool_calls = [ tool_call @@ -246,37 +226,25 @@ def _transform_messages( if tool_call.get("id") not in existing_tool_call_ids ] if new_tool_calls: - message["tool_calls"] = ( - existing_tool_calls + new_tool_calls - ) + message["tool_calls"] = existing_tool_calls + new_tool_calls else: message["tool_calls"] = tool_calls content_str = "\n".join(text_parts) - new_content = ( - content_blocks if has_structured_content else content_str - ) + new_content = content_blocks if has_structured_content else content_str message["content"] = new_content # type: ignore[typeddict-item] elif message["role"] == "user": message_content = message.get("content") if message_content and isinstance(message_content, list): - replaced_content_items: List[ - Tuple[int, ChatCompletionFileObject] - ] = [] + replaced_content_items: List[Tuple[int, ChatCompletionFileObject]] = [] for idx, content_item in enumerate(message_content): if content_item.get("type") == "file": content_item = cast(ChatCompletionFileObject, content_item) if self._is_video_file(content_item): replaced_content_items.append((idx, content_item)) for idx, content_item in replaced_content_items: - message_content[idx] = self._convert_file_to_video_url( - content_item - ) + message_content[idx] = self._convert_file_to_video_url(content_item) if is_async: - return super()._transform_messages( - messages, model, is_async=cast(Literal[True], True) - ) + return super()._transform_messages(messages, model, is_async=cast(Literal[True], True)) else: - return super()._transform_messages( - messages, model, is_async=cast(Literal[False], False) - ) + return super()._transform_messages(messages, model, is_async=cast(Literal[False], False)) diff --git a/litellm/llms/hosted_vllm/rerank/transformation.py b/litellm/llms/hosted_vllm/rerank/transformation.py index 474953504600..77504eba04a1 100644 --- a/litellm/llms/hosted_vllm/rerank/transformation.py +++ b/litellm/llms/hosted_vllm/rerank/transformation.py @@ -164,25 +164,19 @@ def transform_rerank_response( try: raw_response_json = raw_response.json() except Exception: - raise ValueError( - f"Error parsing response: {raw_response.text}, status_code={raw_response.status_code}" - ) + raise ValueError(f"Error parsing response: {raw_response.text}, status_code={raw_response.status_code}") return self._transform_response(raw_response_json) def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return HostedVLLMRerankError( - message=error_message, status_code=status_code, headers=headers - ) + return HostedVLLMRerankError(message=error_message, status_code=status_code, headers=headers) def _transform_response(self, response: dict) -> RerankResponse: # Extract usage information usage_data = response.get("usage", {}) - _billed_units = RerankBilledUnits( - total_tokens=usage_data.get("total_tokens", 0) - ) + _billed_units = RerankBilledUnits(total_tokens=usage_data.get("total_tokens", 0)) _tokens = RerankTokens(input_tokens=usage_data.get("total_tokens", 0)) rerank_meta = RerankResponseMeta(billed_units=_billed_units, tokens=_tokens) @@ -201,11 +195,7 @@ def _transform_response(self, response: dict) -> RerankResponse: # Get document data if it exists document_data = result.get("document", {}) - document = ( - RerankResponseDocument(text=str(document_data.get("text", ""))) - if document_data - else None - ) + document = RerankResponseDocument(text=str(document_data.get("text", ""))) if document_data else None # Create typed result rerank_result = RerankResponseResult( diff --git a/litellm/llms/hosted_vllm/responses/transformation.py b/litellm/llms/hosted_vllm/responses/transformation.py index 4d44eeda9f9a..d79690292aa8 100644 --- a/litellm/llms/hosted_vllm/responses/transformation.py +++ b/litellm/llms/hosted_vllm/responses/transformation.py @@ -36,9 +36,7 @@ def validate_environment( ) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() api_key = ( - litellm_params.api_key - or get_secret_str("HOSTED_VLLM_API_KEY") - or "fake-api-key" + litellm_params.api_key or get_secret_str("HOSTED_VLLM_API_KEY") or "fake-api-key" ) # vllm does not require an api key headers.update( { diff --git a/litellm/llms/huggingface/chat/transformation.py b/litellm/llms/huggingface/chat/transformation.py index 557aa48550b0..353d3abac6bb 100644 --- a/litellm/llms/huggingface/chat/transformation.py +++ b/litellm/llms/huggingface/chat/transformation.py @@ -66,9 +66,7 @@ def validate_environment( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return HuggingFaceError( - status_code=status_code, message=error_message, headers=headers - ) + return HuggingFaceError(status_code=status_code, message=error_message, headers=headers) def get_base_url(self, model: str, base_url: Optional[str]) -> Optional[str]: """ @@ -100,9 +98,7 @@ def get_complete_url( complete_url = api_base complete_url = _build_chat_completion_url(complete_url) elif os.getenv("HF_API_BASE") or os.getenv("HUGGINGFACE_API_BASE"): - complete_url = str(os.getenv("HF_API_BASE")) or str( - os.getenv("HUGGINGFACE_API_BASE") - ) + complete_url = str(os.getenv("HF_API_BASE")) or str(os.getenv("HUGGINGFACE_API_BASE")) elif model.startswith(("http://", "https://")): complete_url = model complete_url = _build_chat_completion_url(complete_url) @@ -135,9 +131,7 @@ def transform_request( headers: dict, ) -> dict: if litellm_params.get("api_base"): - return dict( - ChatCompletionRequest(model=model, messages=messages, **optional_params) - ) + return dict(ChatCompletionRequest(model=model, messages=messages, **optional_params)) if "max_retries" in optional_params: logger.warning("`max_retries` is not supported. It will be ignored.") optional_params.pop("max_retries", None) @@ -161,8 +155,4 @@ def transform_request( mapped_model = provider_mapping["providerId"] messages = self._transform_messages(messages=messages, model=mapped_model) - return dict( - ChatCompletionRequest( - model=mapped_model, messages=messages, **optional_params - ) - ) + return dict(ChatCompletionRequest(model=mapped_model, messages=messages, **optional_params)) diff --git a/litellm/llms/huggingface/embedding/handler.py b/litellm/llms/huggingface/embedding/handler.py index 6be885b1f91b..39eb430db74c 100644 --- a/litellm/llms/huggingface/embedding/handler.py +++ b/litellm/llms/huggingface/embedding/handler.py @@ -21,23 +21,19 @@ HF_HUB_URL = "https://huggingface.co" -hf_tasks_embeddings = Literal[ # pipeline tags + hf tei endpoints - https://huggingface.github.io/text-embeddings-inference/#/ - "sentence-similarity", "feature-extraction", "rerank", "embed", "similarity" -] +hf_tasks_embeddings = ( + Literal[ # pipeline tags + hf tei endpoints - https://huggingface.github.io/text-embeddings-inference/#/ + "sentence-similarity", "feature-extraction", "rerank", "embed", "similarity" + ] +) -def get_hf_task_embedding_for_model( - model: str, task_type: Optional[str], api_base: str -) -> Optional[str]: +def get_hf_task_embedding_for_model(model: str, task_type: Optional[str], api_base: str) -> Optional[str]: if task_type is not None: if task_type in get_args(hf_tasks_embeddings): return task_type else: - raise Exception( - "Invalid task_type={}. Expected one of={}".format( - task_type, hf_tasks_embeddings - ) - ) + raise Exception("Invalid task_type={}. Expected one of={}".format(task_type, hf_tasks_embeddings)) http_client = HTTPHandler(concurrent_limit=1) model_info = http_client.get(url=f"{api_base}/api/models/{model}") @@ -49,18 +45,12 @@ def get_hf_task_embedding_for_model( return pipeline_tag -async def async_get_hf_task_embedding_for_model( - model: str, task_type: Optional[str], api_base: str -) -> Optional[str]: +async def async_get_hf_task_embedding_for_model(model: str, task_type: Optional[str], api_base: str) -> Optional[str]: if task_type is not None: if task_type in get_args(hf_tasks_embeddings): return task_type else: - raise Exception( - "Invalid task_type={}. Expected one of={}".format( - task_type, hf_tasks_embeddings - ) - ) + raise Exception("Invalid task_type={}. Expected one of={}".format(task_type, hf_tasks_embeddings)) http_client = get_async_httpx_client( llm_provider=litellm.LlmProviders.HUGGINGFACE, ) @@ -81,9 +71,7 @@ class HuggingFaceEmbedding(BaseLLM): def __init__(self) -> None: super().__init__() - def _transform_input_on_pipeline_tag( - self, input: List, pipeline_tag: Optional[str] - ) -> dict: + def _transform_input_on_pipeline_tag(self, input: List, pipeline_tag: Optional[str]) -> dict: if pipeline_tag is None: return {"inputs": input} if pipeline_tag == "sentence-similarity" or pipeline_tag == "similarity": @@ -110,9 +98,7 @@ async def _async_transform_input( input: List, optional_params: dict, ) -> dict: - hf_task = await async_get_hf_task_embedding_for_model( - model=model, task_type=task_type, api_base=HF_HUB_URL - ) + hf_task = await async_get_hf_task_embedding_for_model(model=model, task_type=task_type, api_base=HF_HUB_URL) data = self._transform_input_on_pipeline_tag(input=input, pipeline_tag=hf_task) @@ -169,22 +155,14 @@ def _transform_input( task_type = optional_params.pop("input_type", None) if call_type == "sync": - hf_task = get_hf_task_embedding_for_model( - model=model, task_type=task_type, api_base=HF_HUB_URL - ) + hf_task = get_hf_task_embedding_for_model(model=model, task_type=task_type, api_base=HF_HUB_URL) elif call_type == "async": - return self._async_transform_input( - model=model, task_type=task_type, embed_url=embed_url, input=input - ) # type: ignore + return self._async_transform_input(model=model, task_type=task_type, embed_url=embed_url, input=input) # type: ignore - data = self._transform_input_on_pipeline_tag( - input=input, pipeline_tag=hf_task - ) + data = self._transform_input_on_pipeline_tag(input=input, pipeline_tag=hf_task) if len(optional_params.keys()) > 0: - data = self._process_optional_params( - data=data, optional_params=optional_params - ) + data = self._process_optional_params(data=data, optional_params=optional_params) return data @@ -229,9 +207,7 @@ def _process_embedding_response( { "object": "embedding", "index": idx, - "embedding": embedding[0][ - 0 - ], # flatten list returned from hf + "embedding": embedding[0][0], # flatten list returned from hf } ) model_response.object = "list" @@ -343,9 +319,7 @@ def embedding( litellm_params=litellm_params, ) task_type = optional_params.get("input_type", None) - task = get_hf_task_embedding_for_model( - model=model, task_type=task_type, api_base=HF_HUB_URL - ) + task = get_hf_task_embedding_for_model(model=model, task_type=task_type, api_base=HF_HUB_URL) # print_verbose(f"{model}, {task}") embed_url = "" if "https" in model: @@ -357,9 +331,7 @@ def embedding( elif "HUGGINGFACE_API_BASE" in os.environ: embed_url = os.getenv("HUGGINGFACE_API_BASE", "") else: - embed_url = ( - f"https://router.huggingface.co/hf-inference/pipeline/{task}/{model}" - ) + embed_url = f"https://router.huggingface.co/hf-inference/pipeline/{task}/{model}" ## ROUTING ## if aembedding is True: diff --git a/litellm/llms/huggingface/embedding/transformation.py b/litellm/llms/huggingface/embedding/transformation.py index 7cddda617a98..13e38ab55603 100644 --- a/litellm/llms/huggingface/embedding/transformation.py +++ b/litellm/llms/huggingface/embedding/transformation.py @@ -48,9 +48,7 @@ class HuggingFaceEmbeddingConfig(BaseConfig): details: Optional[bool] = True # enables returning logprobs + best of max_new_tokens: Optional[int] = None repetition_penalty: Optional[float] = None - return_full_text: Optional[bool] = ( - False # by default don't return the input as part of the output - ) + return_full_text: Optional[bool] = False # by default don't return the input as part of the output seed: Optional[int] = None temperature: Optional[float] = None top_k: Optional[int] = None @@ -120,9 +118,7 @@ def map_openai_params( optional_params["top_p"] = value if param == "n": optional_params["best_of"] = value - optional_params["do_sample"] = ( - True # Need to sample if you want best of for hf inference endpoints - ) + optional_params["do_sample"] = True # Need to sample if you want best of for hf inference endpoints if param == "stream": optional_params["stream"] = value if param == "stop": @@ -212,9 +208,7 @@ def transform_request( task = litellm_params.get("task", None) ## VALIDATE API FORMAT if task is None or not isinstance(task, str) or task not in hf_task_list: - raise Exception( - "Invalid hf task - {}. Valid formats - {}.".format(task, hf_tasks) - ) + raise Exception("Invalid hf task - {}. Valid formats - {}.".format(task, hf_tasks)) ## Load Config config = litellm.HuggingFaceEmbeddingConfig.get_config() @@ -269,12 +263,8 @@ def transform_request( model_prompt_details = litellm.custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles") or {}, - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), - final_prompt_value=model_prompt_details.get( - "final_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), + final_prompt_value=model_prompt_details.get("final_prompt_value", ""), messages=messages, ) else: @@ -298,12 +288,8 @@ def transform_request( model_prompt_details = litellm.custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", {}), - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), - final_prompt_value=model_prompt_details.get( - "final_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), + final_prompt_value=model_prompt_details.get("final_prompt_value", ""), bos_token=model_prompt_details.get("bos_token", ""), eos_token=model_prompt_details.get("eos_token", ""), messages=messages, @@ -373,9 +359,7 @@ def validate_environment( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return HuggingFaceError( - status_code=status_code, message=error_message, headers=headers - ) + return HuggingFaceError(status_code=status_code, message=error_message, headers=headers) def _convert_streamed_response_to_complete_response( self, @@ -439,27 +423,17 @@ def convert_to_model_response_object( completion_response[0]["generated_text"] ) ## GETTING LOGPROBS + FINISH REASON - if ( - "details" in completion_response[0] - and "tokens" in completion_response[0]["details"] - ): - model_response.choices[0].finish_reason = completion_response[0][ - "details" - ]["finish_reason"] + if "details" in completion_response[0] and "tokens" in completion_response[0]["details"]: + model_response.choices[0].finish_reason = completion_response[0]["details"]["finish_reason"] sum_logprob = 0 for token in completion_response[0]["details"]["tokens"]: if token["logprob"] is not None: sum_logprob += token["logprob"] setattr(model_response.choices[0].message, "_logprob", sum_logprob) # type: ignore if "best_of" in optional_params and optional_params["best_of"] > 1: - if ( - "details" in completion_response[0] - and "best_of_sequences" in completion_response[0]["details"] - ): + if "details" in completion_response[0] and "best_of_sequences" in completion_response[0]["details"]: choices_list = [] - for idx, item in enumerate( - completion_response[0]["details"]["best_of_sequences"] - ): + for idx, item in enumerate(completion_response[0]["details"]["best_of_sequences"]): sum_logprob = 0 for token in item["tokens"]: if token["logprob"] is not None: @@ -483,10 +457,7 @@ def convert_to_model_response_object( completion_response ) else: - if ( - isinstance(completion_response, list) - and len(completion_response[0]["generated_text"]) > 0 - ): + if isinstance(completion_response, list) and len(completion_response[0]["generated_text"]) > 0: model_response.choices[0].message.content = output_parser( # type: ignore completion_response[0]["generated_text"] ) @@ -502,9 +473,7 @@ def convert_to_model_response_object( completion_tokens = 0 try: completion_tokens = len( - encoding.encode( - model_response["choices"][0]["message"].get("content", "") - ) + encoding.encode(model_response["choices"][0]["message"].get("content", "")) ) ##[TODO] use the llama2 tokenizer here except Exception: # this should remain non blocking we should not block a response returning if calculating usage fails @@ -540,10 +509,7 @@ def transform_response( ## Some servers might return streaming responses even though stream was not set to true. (e.g. Baseten) task = litellm_params.get("task", None) is_streamed = False - if ( - raw_response.__dict__["headers"].get("Content-Type", "") - == "text/event-stream" - ): + if raw_response.__dict__["headers"].get("Content-Type", "") == "text/event-stream": is_streamed = True # iterate over the complete streamed response, and return the final answer diff --git a/litellm/llms/huggingface/rerank/transformation.py b/litellm/llms/huggingface/rerank/transformation.py index c94fc65acbdc..cdad77a98154 100644 --- a/litellm/llms/huggingface/rerank/transformation.py +++ b/litellm/llms/huggingface/rerank/transformation.py @@ -152,9 +152,7 @@ def transform_rerank_request( if "query" not in optional_rerank_params: raise ValueError("query is required for HuggingFace rerank") if "texts" not in optional_rerank_params: - raise ValueError( - "Cohere 'documents' param is required for HuggingFace rerank" - ) + raise ValueError("Cohere 'documents' param is required for HuggingFace rerank") # Ensure return_text is a boolean value # HuggingFace API expects return_text parameter, corresponding to our return_documents parameter request_body = { @@ -210,25 +208,15 @@ def transform_rerank_response( estimated_input_tokens = token_counter(model=model, text=input_text) except Exception: # Fallback to reasonable estimates if token counting fails - estimated_output_tokens = ( - len(raw_response_json) * 10 if raw_response_json else 10 - ) - estimated_input_tokens = ( - len(input_text) * 4 if "input_text" in locals() else 0 - ) + estimated_output_tokens = len(raw_response_json) * 10 if raw_response_json else 10 + estimated_input_tokens = len(input_text) * 4 if "input_text" in locals() else 0 _billed_units = RerankBilledUnits(search_units=1) - _tokens = RerankTokens( - input_tokens=estimated_input_tokens, output_tokens=estimated_output_tokens - ) - rerank_meta = RerankResponseMeta( - api_version={"version": "1.0"}, billed_units=_billed_units, tokens=_tokens - ) + _tokens = RerankTokens(input_tokens=estimated_input_tokens, output_tokens=estimated_output_tokens) + rerank_meta = RerankResponseMeta(api_version={"version": "1.0"}, billed_units=_billed_units, tokens=_tokens) # Check if documents should be returned based on request parameters - should_return_documents = request_data.get( - "return_text", False - ) or request_data.get("return_documents", False) + should_return_documents = request_data.get("return_text", False) or request_data.get("return_documents", False) original_documents = request_data.get("texts", []) results = [] @@ -252,9 +240,7 @@ def transform_rerank_response( if text_content: result["document"] = RerankResponseDocument(text=text_content) # 2. If no text in API response but original documents are available, use those - elif original_documents and 0 <= item.get("index", -1) < len( - original_documents - ): + elif original_documents and 0 <= item.get("index", -1) < len(original_documents): doc = original_documents[item.get("index")] if isinstance(doc, str): result["document"] = RerankResponseDocument(text=doc) @@ -288,16 +274,11 @@ def get_api_credentials( api_base: API base provided directly to this function, takes precedence over all other sources """ # Get API key from multiple sources - final_api_key = ( - api_key or litellm.huggingface_key or get_secret_str("HUGGINGFACE_API_KEY") - ) + final_api_key = api_key or litellm.huggingface_key or get_secret_str("HUGGINGFACE_API_KEY") # Get API base from multiple sources final_api_base = ( - api_base - or litellm.api_base - or get_secret_str("HF_API_BASE") - or get_secret_str("HUGGINGFACE_API_BASE") + api_base or litellm.api_base or get_secret_str("HF_API_BASE") or get_secret_str("HUGGINGFACE_API_BASE") ) return final_api_key, final_api_base diff --git a/litellm/llms/inception/chat/transformation.py b/litellm/llms/inception/chat/transformation.py index ff87060449b2..4c8af7680476 100644 --- a/litellm/llms/inception/chat/transformation.py +++ b/litellm/llms/inception/chat/transformation.py @@ -45,14 +45,8 @@ def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: passed_api_base = api_base - api_base = ( - api_base - or get_secret_str("INCEPTION_API_BASE") - or "https://api.inceptionlabs.ai/v1" - ) # type: ignore + api_base = api_base or get_secret_str("INCEPTION_API_BASE") or "https://api.inceptionlabs.ai/v1" # type: ignore dynamic_api_key = api_key if passed_api_base is None or api_key: - dynamic_api_key = ( - api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") - ) + dynamic_api_key = api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/infinity/common_utils.py b/litellm/llms/infinity/common_utils.py index 67c54caff982..cf52309ad845 100644 --- a/litellm/llms/infinity/common_utils.py +++ b/litellm/llms/infinity/common_utils.py @@ -5,14 +5,10 @@ class InfinityError(BaseLLMException): - def __init__( - self, status_code: int, message: str, headers: Union[dict, httpx.Headers] = {} - ): + def __init__(self, status_code: int, message: str, headers: Union[dict, httpx.Headers] = {}): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://github.com/michaelfeil/infinity" - ) + self.request = httpx.Request(method="POST", url="https://github.com/michaelfeil/infinity") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( status_code=status_code, diff --git a/litellm/llms/infinity/embedding/transformation.py b/litellm/llms/infinity/embedding/transformation.py index 824dcd38da33..fd75887baa3d 100644 --- a/litellm/llms/infinity/embedding/transformation.py +++ b/litellm/llms/infinity/embedding/transformation.py @@ -117,9 +117,7 @@ def transform_embedding_response( try: raw_response_json = raw_response.json() except Exception: - raise InfinityError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise InfinityError(message=raw_response.text, status_code=raw_response.status_code) # model_response.usage model_response.model = raw_response_json.get("model") @@ -136,6 +134,4 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return InfinityError( - message=error_message, status_code=status_code, headers=headers - ) + return InfinityError(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/infinity/rerank/transformation.py b/litellm/llms/infinity/rerank/transformation.py index b9804605454c..94746da46096 100644 --- a/litellm/llms/infinity/rerank/transformation.py +++ b/litellm/llms/infinity/rerank/transformation.py @@ -48,11 +48,7 @@ def validate_environment( optional_params: Optional[dict] = None, ) -> dict: if api_key is None: - api_key = ( - get_secret_str("INFINITY_API_KEY") - or get_secret_str("INFINITY_API_KEY") - or litellm.infinity_key - ) + api_key = get_secret_str("INFINITY_API_KEY") or get_secret_str("INFINITY_API_KEY") or litellm.infinity_key default_headers = { "Authorization": f"Bearer {api_key}", @@ -86,9 +82,7 @@ def transform_rerank_response( try: raw_response_json = raw_response.json() except Exception: - raise InfinityError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise InfinityError(message=raw_response.text, status_code=raw_response.status_code) _billed_units = RerankBilledUnits(**raw_response_json.get("usage", {})) _tokens = RerankTokens( @@ -108,9 +102,7 @@ def transform_rerank_response( relevance_score=result.get("relevance_score"), ) if result.get("document"): - _rerank_response["document"] = RerankResponseDocument( - text=result.get("document") - ) + _rerank_response["document"] = RerankResponseDocument(text=result.get("document")) cohere_results.append(_rerank_response) if cohere_results is None: raise ValueError(f"No results found in the response={raw_response_json}") diff --git a/litellm/llms/jina_ai/embedding/transformation.py b/litellm/llms/jina_ai/embedding/transformation.py index 7a6349030056..80927a59a643 100644 --- a/litellm/llms/jina_ai/embedding/transformation.py +++ b/litellm/llms/jina_ai/embedding/transformation.py @@ -80,9 +80,7 @@ def _get_openai_compatible_provider_info( - api_base: str - dynamic_api_key: str """ - api_base = ( - api_base or get_secret_str("JINA_AI_API_BASE") or "https://api.jina.ai/v1" - ) # type: ignore + api_base = api_base or get_secret_str("JINA_AI_API_BASE") or "https://api.jina.ai/v1" # type: ignore dynamic_api_key = api_key or ( get_secret_str("JINA_AI_API_KEY") or get_secret_str("JINA_AI_API_KEY") @@ -100,11 +98,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - return ( - f"{api_base}/embeddings" - if api_base - else "https://api.jina.ai/v1/embeddings" - ) + return f"{api_base}/embeddings" if api_base else "https://api.jina.ai/v1/embeddings" def transform_embedding_request( self, diff --git a/litellm/llms/jina_ai/rerank/transformation.py b/litellm/llms/jina_ai/rerank/transformation.py index cabaf079edc2..7f4c0709bdd0 100644 --- a/litellm/llms/jina_ai/rerank/transformation.py +++ b/litellm/llms/jina_ai/rerank/transformation.py @@ -141,9 +141,7 @@ def validate_environment( optional_params: dict | None = None, ) -> Dict: if api_key is None: - raise ValueError( - "api_key is required. Set via `api_key` parameter or `JINA_API_KEY` environment variable." - ) + raise ValueError("api_key is required. Set via `api_key` parameter or `JINA_API_KEY` environment variable.") return { "accept": "application/json", "content-type": "application/json", diff --git a/litellm/llms/lambda_ai/chat/transformation.py b/litellm/llms/lambda_ai/chat/transformation.py index 262a189428db..96d1dad1416a 100644 --- a/litellm/llms/lambda_ai/chat/transformation.py +++ b/litellm/llms/lambda_ai/chat/transformation.py @@ -23,9 +23,7 @@ def _get_openai_compatible_provider_info( ) -> Tuple[Optional[str], Optional[str]]: # Lambda AI is openai compatible, we just need to set the api_base api_base = ( - api_base - or get_secret_str("LAMBDA_API_BASE") - or "https://api.lambda.ai/v1" # Default Lambda API base URL + api_base or get_secret_str("LAMBDA_API_BASE") or "https://api.lambda.ai/v1" # Default Lambda API base URL ) # type: ignore dynamic_api_key = api_key or get_secret_str("LAMBDA_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/langflow/chat/transformation.py b/litellm/llms/langflow/chat/transformation.py index f898163ad028..73fa49f492b4 100644 --- a/litellm/llms/langflow/chat/transformation.py +++ b/litellm/llms/langflow/chat/transformation.py @@ -50,9 +50,7 @@ def _get_openai_compatible_provider_info( ) -> Tuple[Optional[str], Optional[str]]: from litellm.secret_managers.main import get_secret_str - api_base = ( - api_base or get_secret_str("LANGFLOW_API_BASE") or "http://localhost:7860" - ) + api_base = api_base or get_secret_str("LANGFLOW_API_BASE") or "http://localhost:7860" api_key = api_key or get_secret_str("LANGFLOW_API_KEY") return api_base, api_key @@ -78,10 +76,7 @@ def _get_flow_id(self, model: str, optional_params: dict) -> str: if optional_params.get("flow_id") is not None: raise LangFlowError( status_code=400, - message=( - "flow_id cannot be set via request parameters; " - "use model langflow/{flow_id}" - ), + message=("flow_id cannot be set via request parameters; use model langflow/{flow_id}"), ) flow_id = (model.split("/", 1)[1] if "/" in model else model).strip() @@ -264,9 +259,7 @@ def transform_response( from litellm.utils import token_counter prompt_tokens = token_counter(model=model, messages=messages) - completion_tokens = token_counter( - model=model, text=content, count_response_tokens=True - ) + completion_tokens = token_counter(model=model, text=content, count_response_tokens=True) usage = Usage( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, diff --git a/litellm/llms/langgraph/chat/transformation.py b/litellm/llms/langgraph/chat/transformation.py index 9808b665b542..77b5cfbc3fa0 100644 --- a/litellm/llms/langgraph/chat/transformation.py +++ b/litellm/llms/langgraph/chat/transformation.py @@ -65,9 +65,7 @@ def _get_openai_compatible_provider_info( """ from litellm.secret_managers.main import get_secret_str - api_base = ( - api_base or get_secret_str("LANGGRAPH_API_BASE") or "http://localhost:2024" - ) + api_base = api_base or get_secret_str("LANGGRAPH_API_BASE") or "http://localhost:2024" api_key = api_key or get_secret_str("LANGGRAPH_API_KEY") @@ -137,9 +135,7 @@ def _get_assistant_id(self, model: str, optional_params: dict) -> str: return parts[1] return model - def _convert_messages_to_langgraph_format( - self, messages: List[AllMessageValues] - ) -> List[Dict[str, Any]]: + def _convert_messages_to_langgraph_format(self, messages: List[AllMessageValues]) -> List[Dict[str, Any]]: """ Convert OpenAI-format messages to LangGraph format. @@ -265,9 +261,7 @@ def _extract_content_from_response(self, response_json: dict) -> str: return msg.get("content", "") # Fallback: try to serialize the whole response - verbose_logger.warning( - "Could not extract content from LangGraph response, returning raw" - ) + verbose_logger.warning("Could not extract content from LangGraph response, returning raw") return json.dumps(response_json) def get_streaming_response( @@ -317,14 +311,10 @@ def get_sync_custom_stream_wrapper( ) if response.status_code != 200: - raise LangGraphError( - status_code=response.status_code, message=str(response.read()) - ) + raise LangGraphError(status_code=response.status_code, message=str(response.read())) # Create iterator for SSE stream - completion_stream = self.get_streaming_response( - model=model, raw_response=response - ) + completion_stream = self.get_streaming_response(model=model, raw_response=response) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, @@ -366,9 +356,7 @@ async def get_async_custom_stream_wrapper( from litellm.utils import CustomStreamWrapper if client is None or not isinstance(client, AsyncHTTPHandler): - client = get_async_httpx_client( - llm_provider=cast(Any, "langgraph"), params={} - ) + client = get_async_httpx_client(llm_provider=cast(Any, "langgraph"), params={}) verbose_logger.debug(f"Making async streaming request to: {api_base}") @@ -382,14 +370,10 @@ async def get_async_custom_stream_wrapper( ) if response.status_code != 200: - raise LangGraphError( - status_code=response.status_code, message=str(await response.aread()) - ) + raise LangGraphError(status_code=response.status_code, message=str(await response.aread())) # Create iterator for SSE stream - completion_stream = self.get_streaming_response( - model=model, raw_response=response - ) + completion_stream = self.get_streaming_response(model=model, raw_response=response) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, @@ -459,9 +443,7 @@ def transform_response( from litellm.utils import token_counter prompt_tokens = token_counter(model="gpt-3.5-turbo", messages=messages) - completion_tokens = token_counter( - model="gpt-3.5-turbo", text=content, count_response_tokens=True - ) + completion_tokens = token_counter(model="gpt-3.5-turbo", text=content, count_response_tokens=True) total_tokens = prompt_tokens + completion_tokens usage = Usage( diff --git a/litellm/llms/lemonade/chat/transformation.py b/litellm/llms/lemonade/chat/transformation.py index fa546f9e147e..f10dbf49f665 100644 --- a/litellm/llms/lemonade/chat/transformation.py +++ b/litellm/llms/lemonade/chat/transformation.py @@ -78,9 +78,7 @@ def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = No Returns: List of model names prefixed with "lemonade/" """ - api_base, api_key = self._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + api_base, api_key = self._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) if api_base is None: raise ValueError( @@ -173,9 +171,7 @@ def get_model_info( if model.startswith("lemonade/"): model = model.split("/", 1)[1] - api_base, api_key = self._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + api_base, api_key = self._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) encoded_model = quote(model, safe="") try: @@ -211,19 +207,10 @@ def _get_openai_compatible_provider_info( ) -> Tuple[Optional[str], Optional[str]]: # lemonade is openai compatible, we just need to set this to custom_openai and have the api_base be lemonade's endpoint passed_api_base = api_base - api_base = ( - api_base - or get_secret_str("LEMONADE_API_BASE") - or "http://localhost:8000/api/v1" - ) # type: ignore + api_base = api_base or get_secret_str("LEMONADE_API_BASE") or "http://localhost:8000/api/v1" # type: ignore key = self._DEFAULT_API_KEY if passed_api_base is None or api_key: - key = ( - api_key - or litellm.lemonade_key - or get_secret_str("LEMONADE_API_KEY") - or self._DEFAULT_API_KEY - ) + key = api_key or litellm.lemonade_key or get_secret_str("LEMONADE_API_KEY") or self._DEFAULT_API_KEY return api_base, key def _get_auth_headers(self, api_key: Optional[str]) -> dict: diff --git a/litellm/llms/linkup/search/transformation.py b/litellm/llms/linkup/search/transformation.py index d27ae038f9ec..a68231fa867a 100644 --- a/litellm/llms/linkup/search/transformation.py +++ b/litellm/llms/linkup/search/transformation.py @@ -22,9 +22,7 @@ class _LinkupSearchRequestRequired(TypedDict): q: str # Required - The natural language question for which you want to retrieve context depth: Literal["deep", "standard"] # Required - Defines the precision of the search - outputType: Literal[ - "searchResults", "sourcedAnswer", "structured" - ] # Required - The type of output + outputType: Literal["searchResults", "sourcedAnswer", "structured"] # Required - The type of output class LinkupSearchRequest(_LinkupSearchRequestRequired, total=False): @@ -69,9 +67,7 @@ def validate_environment( default_api_base=self.LINKUP_API_BASE, ) if not api_key: - raise ValueError( - "LINKUP_API_KEY is not set. Set `LINKUP_API_KEY` environment variable." - ) + raise ValueError("LINKUP_API_KEY is not set. Set `LINKUP_API_KEY` environment variable.") headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -141,10 +137,7 @@ def transform_search_request( # pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value return result_data diff --git a/litellm/llms/litellm_proxy/chat/transformation.py b/litellm/llms/litellm_proxy/chat/transformation.py index cf6a6ed7a543..eee0ec6fa089 100644 --- a/litellm/llms/litellm_proxy/chat/transformation.py +++ b/litellm/llms/litellm_proxy/chat/transformation.py @@ -42,14 +42,10 @@ def _get_openai_compatible_provider_info( dynamic_api_key = api_key or get_secret_str("LITELLM_PROXY_API_KEY") return api_base, dynamic_api_key - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: api_base, api_key = self._get_openai_compatible_provider_info(api_base, api_key) if api_base is None: - raise ValueError( - "api_base not set for LiteLLM Proxy route. Set in env via `LITELLM_PROXY_API_BASE`" - ) + raise ValueError("api_base not set for LiteLLM Proxy route. Set in env via `LITELLM_PROXY_API_BASE`") models = super().get_models(api_key=api_key, api_base=api_base) return [f"litellm_proxy/{model}" for model in models] @@ -111,9 +107,7 @@ def litellm_proxy_get_custom_llm_provider_info( ( api_base, api_key, - ) = litellm.LiteLLMProxyChatConfig()._get_openai_compatible_provider_info( - api_base=api_base, api_key=api_key - ) + ) = litellm.LiteLLMProxyChatConfig()._get_openai_compatible_provider_info(api_base=api_base, api_key=api_key) return model, custom_llm_provider, api_key, api_base diff --git a/litellm/llms/litellm_proxy/image_edit/transformation.py b/litellm/llms/litellm_proxy/image_edit/transformation.py index 79cd6e15c68d..94825cffeae9 100644 --- a/litellm/llms/litellm_proxy/image_edit/transformation.py +++ b/litellm/llms/litellm_proxy/image_edit/transformation.py @@ -19,13 +19,9 @@ def validate_environment( headers.update({"Authorization": f"Bearer {api_key}"}) return headers - def get_complete_url( - self, model: str, api_base: Optional[str], litellm_params: dict - ) -> str: + def get_complete_url(self, model: str, api_base: Optional[str], litellm_params: dict) -> str: api_base = api_base or get_secret_str("LITELLM_PROXY_API_BASE") if api_base is None: - raise ValueError( - "api_base not set for LiteLLM Proxy route. Set in env via `LITELLM_PROXY_API_BASE`" - ) + raise ValueError("api_base not set for LiteLLM Proxy route. Set in env via `LITELLM_PROXY_API_BASE`") api_base = api_base.rstrip("/") return f"{api_base}/images/edits" diff --git a/litellm/llms/litellm_proxy/image_generation/transformation.py b/litellm/llms/litellm_proxy/image_generation/transformation.py index 3932070e9641..5fad663d1266 100644 --- a/litellm/llms/litellm_proxy/image_generation/transformation.py +++ b/litellm/llms/litellm_proxy/image_generation/transformation.py @@ -34,8 +34,6 @@ def get_complete_url( ) -> str: api_base = api_base or get_secret_str("LITELLM_PROXY_API_BASE") if api_base is None: - raise ValueError( - "api_base not set for LiteLLM Proxy route. Set in env via `LITELLM_PROXY_API_BASE`" - ) + raise ValueError("api_base not set for LiteLLM Proxy route. Set in env via `LITELLM_PROXY_API_BASE`") api_base = api_base.rstrip("/") return f"{api_base}/images/generations" diff --git a/litellm/llms/litellm_proxy/skills/code_execution.py b/litellm/llms/litellm_proxy/skills/code_execution.py index 2b567f037604..4ac3311921d6 100644 --- a/litellm/llms/litellm_proxy/skills/code_execution.py +++ b/litellm/llms/litellm_proxy/skills/code_execution.py @@ -44,9 +44,7 @@ def get_litellm_code_execution_tool() -> Dict[str, Any]: "description": "Execute Python code in a sandboxed environment. Use this to run code that generates files, processes data, or performs computations. Generated files will be returned directly.", "parameters": { "type": "object", - "properties": { - "code": {"type": "string", "description": "Python code to execute"} - }, + "properties": {"code": {"type": "string", "description": "Python code to execute"}}, "required": ["code"], }, }, @@ -65,9 +63,7 @@ def get_litellm_code_execution_tool_anthropic() -> Dict[str, Any]: "description": "Execute Python code in a sandboxed environment. Use this to run code that generates files, processes data, or performs computations. Generated files will be returned directly.", "input_schema": { "type": "object", - "properties": { - "code": {"type": "string", "description": "Python code to execute"} - }, + "properties": {"code": {"type": "string", "description": "Python code to execute"}}, "required": ["code"], }, } @@ -145,9 +141,7 @@ async def execute_with_code_execution( response: Any = None # Initialize to avoid possibly unbound error for iteration in range(self.max_iterations): - verbose_logger.debug( - f"CodeExecutionHandler: Iteration {iteration + 1}/{self.max_iterations}" - ) + verbose_logger.debug(f"CodeExecutionHandler: Iteration {iteration + 1}/{self.max_iterations}") # Make LLM call response = await litellm.acompletion( @@ -181,9 +175,7 @@ async def execute_with_code_execution( # Check if we're done (no tool calls or not tool_calls finish reason) if stop_reason != "tool_calls" or not assistant_message.tool_calls: - verbose_logger.debug( - f"CodeExecutionHandler: Completed after {iteration + 1} iterations" - ) + verbose_logger.debug(f"CodeExecutionHandler: Completed after {iteration + 1} iterations") return { "response": response, "files": generated_files, # Files returned directly with base64 content @@ -201,18 +193,14 @@ async def execute_with_code_execution( args = json.loads(tool_call.function.arguments) code = args.get("code", "") - verbose_logger.debug( - f"CodeExecutionHandler: Executing code ({len(code)} chars)" - ) + verbose_logger.debug(f"CodeExecutionHandler: Executing code ({len(code)} chars)") exec_result = executor.execute( code=code, skill_files=skill_files, ) - verbose_logger.debug( - f"CodeExecutionHandler: Execution result: {exec_result}" - ) + verbose_logger.debug(f"CodeExecutionHandler: Execution result: {exec_result}") execution_results.append( { @@ -241,9 +229,7 @@ async def execute_with_code_execution( "size": len(file_content), } ) - tool_result += ( - f"\n- {f['name']} ({len(file_content)} bytes)" - ) + tool_result += f"\n- {f['name']} ({len(file_content)} bytes)" verbose_logger.debug( f"CodeExecutionHandler: Generated file {f['name']} ({len(file_content)} bytes)" @@ -282,9 +268,7 @@ async def execute_with_code_execution( ) # Max iterations reached - verbose_logger.warning( - f"CodeExecutionHandler: Max iterations ({self.max_iterations}) reached" - ) + verbose_logger.warning(f"CodeExecutionHandler: Max iterations ({self.max_iterations}) reached") return { "response": response, "files": generated_files, diff --git a/litellm/llms/litellm_proxy/skills/handler.py b/litellm/llms/litellm_proxy/skills/handler.py index 9138b9a712f3..6f5ae261d2e0 100644 --- a/litellm/llms/litellm_proxy/skills/handler.py +++ b/litellm/llms/litellm_proxy/skills/handler.py @@ -55,10 +55,7 @@ async def _get_prisma_client(): from litellm.proxy.proxy_server import prisma_client if prisma_client is None: - raise ValueError( - "Prisma client is not initialized. " - "Database connection required for LiteLLM skills." - ) + raise ValueError("Prisma client is not initialized. Database connection required for LiteLLM skills.") return prisma_client @staticmethod @@ -77,9 +74,7 @@ async def create_skill( # Stamping a placeholder would let any two such callers see # each other's skills via the shared owner. ValueError keeps # this module FastAPI-free per the project layering rule. - raise ValueError( - "Unable to record skill ownership: caller has no identity scope." - ) + raise ValueError("Unable to record skill ownership: caller has no identity scope.") skill_data: Dict[str, Any] = { "skill_id": skill_id, @@ -105,9 +100,7 @@ async def create_skill( if data.file_type is not None: skill_data["file_type"] = data.file_type - verbose_logger.debug( - f"LiteLLMSkillsHandler: Creating skill {skill_id} with title={data.display_title}" - ) + verbose_logger.debug(f"LiteLLMSkillsHandler: Creating skill {skill_id} with title={data.display_title}") new_skill = await SkillsRepository(prisma_client).table.create(data=skill_data) return _prisma_skill_to_litellm(new_skill) @@ -120,9 +113,7 @@ async def list_skills( ) -> List[LiteLLM_SkillsTable]: prisma_client = await LiteLLMSkillsHandler._get_prisma_client() - verbose_logger.debug( - f"LiteLLMSkillsHandler: Listing skills with limit={limit}, offset={offset}" - ) + verbose_logger.debug(f"LiteLLMSkillsHandler: Listing skills with limit={limit}, offset={offset}") find_many_kwargs: Dict[str, Any] = { "take": limit, @@ -135,9 +126,7 @@ async def list_skills( return [] find_many_kwargs["where"] = {"created_by": {"in": owner_scopes}} - skills = await SkillsRepository(prisma_client).table.find_many( - **find_many_kwargs - ) + skills = await SkillsRepository(prisma_client).table.find_many(**find_many_kwargs) return [_prisma_skill_to_litellm(s) for s in skills] @staticmethod @@ -152,12 +141,8 @@ async def _load_skill(skill_id: str) -> Optional[Any]: return cached prisma_client = await LiteLLMSkillsHandler._get_prisma_client() - skill = await SkillsRepository(prisma_client).table.find_unique( - where={"skill_id": skill_id} - ) - _SKILL_CACHE.set_cache( - skill_id, skill if skill is not None else _NEGATIVE_SKILL_SENTINEL - ) + skill = await SkillsRepository(prisma_client).table.find_unique(where={"skill_id": skill_id}) + _SKILL_CACHE.set_cache(skill_id, skill if skill is not None else _NEGATIVE_SKILL_SENTINEL) return skill @staticmethod @@ -170,9 +155,7 @@ async def get_skill( skill = await LiteLLMSkillsHandler._load_skill(skill_id) # Same "not found" message for both "missing" and "cross-tenant" # so callers can't enumerate skill IDs they don't own. - if skill is None or not user_can_access_resource_owner( - getattr(skill, "created_by", None), user_api_key_dict - ): + if skill is None or not user_can_access_resource_owner(getattr(skill, "created_by", None), user_api_key_dict): raise ValueError(f"Skill not found: {skill_id}") return _prisma_skill_to_litellm(skill) @@ -186,9 +169,7 @@ async def delete_skill( verbose_logger.debug(f"LiteLLMSkillsHandler: Deleting skill {skill_id}") skill = await LiteLLMSkillsHandler._load_skill(skill_id) - if skill is None or not user_can_access_resource_owner( - getattr(skill, "created_by", None), user_api_key_dict - ): + if skill is None or not user_can_access_resource_owner(getattr(skill, "created_by", None), user_api_key_dict): raise ValueError(f"Skill not found: {skill_id}") await SkillsRepository(prisma_client).table.delete(where={"skill_id": skill_id}) @@ -204,13 +185,9 @@ async def fetch_skill_from_db( """Skills-injection-hook helper: returns None instead of raising on not-found / not-authorized so the hook can silently skip.""" try: - return await LiteLLMSkillsHandler.get_skill( - skill_id, user_api_key_dict=user_api_key_dict - ) + return await LiteLLMSkillsHandler.get_skill(skill_id, user_api_key_dict=user_api_key_dict) except ValueError: return None except Exception as e: - verbose_logger.warning( - f"LiteLLMSkillsHandler: Error fetching skill {skill_id}: {e}" - ) + verbose_logger.warning(f"LiteLLMSkillsHandler: Error fetching skill {skill_id}: {e}") return None diff --git a/litellm/llms/litellm_proxy/skills/prompt_injection.py b/litellm/llms/litellm_proxy/skills/prompt_injection.py index 86b6e2235129..8be6f105845e 100644 --- a/litellm/llms/litellm_proxy/skills/prompt_injection.py +++ b/litellm/llms/litellm_proxy/skills/prompt_injection.py @@ -147,9 +147,7 @@ def inject_skill_content_to_messages( return data # Build the skill injection text - skill_section = "\n\n---\n\n# Available Skills\n\n" + "\n\n---\n\n".join( - skill_contents - ) + skill_section = "\n\n---\n\n# Available Skills\n\n" + "\n\n---\n\n".join(skill_contents) if use_anthropic_format: # Anthropic messages API: use top-level 'system' parameter @@ -243,12 +241,7 @@ def convert_skill_to_tool(self, skill: LiteLLM_SkillsTable) -> Dict[str, Any]: func_name = skill.skill_id.replace("-", "_").replace(" ", "_") # Use instructions as description, fall back to description or title - description = ( - skill.instructions - or skill.description - or skill.display_title - or f"Skill: {skill.skill_id}" - ) + description = skill.instructions or skill.description or skill.display_title or f"Skill: {skill.skill_id}" # Truncate description if too long (OpenAI has limits) max_desc_length = 1024 @@ -276,9 +269,7 @@ def convert_skill_to_tool(self, skill: LiteLLM_SkillsTable) -> Dict[str, Any]: return tool - def convert_skill_to_anthropic_tool( - self, skill: LiteLLM_SkillsTable - ) -> Dict[str, Any]: + def convert_skill_to_anthropic_tool(self, skill: LiteLLM_SkillsTable) -> Dict[str, Any]: """ Convert a LiteLLM skill to an Anthropic-style tool (messages API format). @@ -290,12 +281,7 @@ def convert_skill_to_anthropic_tool( """ func_name = skill.skill_id.replace("-", "_").replace(" ", "_") - description = ( - skill.instructions - or skill.description - or skill.display_title - or f"Skill: {skill.skill_id}" - ) + description = skill.instructions or skill.description or skill.display_title or f"Skill: {skill.skill_id}" max_desc_length = 1024 if len(description) > max_desc_length: diff --git a/litellm/llms/litellm_proxy/skills/sandbox_executor.py b/litellm/llms/litellm_proxy/skills/sandbox_executor.py index 4514512fc59d..5f1f129032c3 100644 --- a/litellm/llms/litellm_proxy/skills/sandbox_executor.py +++ b/litellm/llms/litellm_proxy/skills/sandbox_executor.py @@ -67,10 +67,7 @@ def execute( try: from llm_sandbox import SandboxSession except ImportError: - verbose_logger.error( - "SkillsSandboxExecutor: llm-sandbox not installed. " - "Install `llm-sandbox`." - ) + verbose_logger.error("SkillsSandboxExecutor: llm-sandbox not installed. Install `llm-sandbox`.") return { "success": False, "output": "", @@ -99,9 +96,7 @@ def execute( # Create the file in temp directory local_path = os.path.abspath(os.path.join(tmpdir, path)) if not local_path.startswith(tmpdir_abs + os.sep): - verbose_logger.warning( - f"SkillsSandboxExecutor: Skipping file with invalid path: {path}" - ) + verbose_logger.warning(f"SkillsSandboxExecutor: Skipping file with invalid path: {path}") continue os.makedirs(os.path.dirname(local_path), exist_ok=True) with open(local_path, "wb") as f: @@ -111,9 +106,7 @@ def execute( sandbox_path = f"/sandbox/{path}" session.copy_to_runtime(local_path, sandbox_path) - verbose_logger.debug( - f"SkillsSandboxExecutor: Copied {len(skill_files)} files to sandbox" - ) + verbose_logger.debug(f"SkillsSandboxExecutor: Copied {len(skill_files)} files to sandbox") # 2. Install requirements if present. Let pip parse the # requirements file inside the sandbox so standard syntax like @@ -149,18 +142,14 @@ def execute( """ install_result = session.run(pip_code) if install_result.exit_code != 0: - verbose_logger.debug( - "SkillsSandboxExecutor: Requirements installation failed" - ) + verbose_logger.debug("SkillsSandboxExecutor: Requirements installation failed") return { "success": False, "output": install_result.stdout or "", "error": install_result.stderr or "", "files": [], } - verbose_logger.debug( - "SkillsSandboxExecutor: Installed requirements" - ) + verbose_logger.debug("SkillsSandboxExecutor: Installed requirements") # 3. Execute the code # Wrap code to run from /sandbox directory @@ -179,19 +168,13 @@ def execute( error = result.stderr or "" if success: - verbose_logger.debug( - "SkillsSandboxExecutor: Code execution succeeded" - ) + verbose_logger.debug("SkillsSandboxExecutor: Code execution succeeded") else: verbose_logger.debug( f"SkillsSandboxExecutor: Code execution failed with exit code {result.exit_code}" ) - verbose_logger.debug( - f"SkillsSandboxExecutor: stderr: {error[:500] if error else 'No stderr'}" - ) - verbose_logger.debug( - f"SkillsSandboxExecutor: stdout: {output[:500] if output else 'No stdout'}" - ) + verbose_logger.debug(f"SkillsSandboxExecutor: stderr: {error[:500] if error else 'No stderr'}") + verbose_logger.debug(f"SkillsSandboxExecutor: stdout: {output[:500] if output else 'No stdout'}") # 4. Collect generated files generated_files = self._collect_generated_files(session, skill_files) @@ -287,21 +270,15 @@ def _collect_generated_files( } ) - verbose_logger.debug( - f"SkillsSandboxExecutor: Collected generated file: {rel_path}" - ) + verbose_logger.debug(f"SkillsSandboxExecutor: Collected generated file: {rel_path}") except Exception as e: - verbose_logger.warning( - f"SkillsSandboxExecutor: Error copying file {filepath}: {e}" - ) + verbose_logger.warning(f"SkillsSandboxExecutor: Error copying file {filepath}: {e}") finally: if os.path.exists(tmp_path): os.unlink(tmp_path) except Exception as e: - verbose_logger.warning( - f"SkillsSandboxExecutor: Error collecting generated files: {e}" - ) + verbose_logger.warning(f"SkillsSandboxExecutor: Error collecting generated files: {e}") return generated_files diff --git a/litellm/llms/litellm_proxy/skills/transformation.py b/litellm/llms/litellm_proxy/skills/transformation.py index 199f13191fe3..7fa58ad9df2d 100644 --- a/litellm/llms/litellm_proxy/skills/transformation.py +++ b/litellm/llms/litellm_proxy/skills/transformation.py @@ -87,9 +87,7 @@ def create_skill_handler( if isinstance(first_file, tuple) and len(first_file) >= 2: file_name = first_file[0] file_content = first_file[1] - file_type = ( - first_file[2] if len(first_file) > 2 else "application/zip" - ) + file_type = first_file[2] if len(first_file) > 2 else "application/zip" if _is_async: return self._async_create_skill( diff --git a/litellm/llms/llamafile/chat/transformation.py b/litellm/llms/llamafile/chat/transformation.py index 223f5503c9c2..78cc58708ad9 100644 --- a/litellm/llms/llamafile/chat/transformation.py +++ b/litellm/llms/llamafile/chat/transformation.py @@ -15,9 +15,7 @@ def _resolve_api_key(api_key: Optional[str] = None) -> str: If both are None, a fake API key is returned. """ - return ( - api_key or get_secret_str("LLAMAFILE_API_KEY") or "fake-api-key" - ) # llamafile does not require an API key + return api_key or get_secret_str("LLAMAFILE_API_KEY") or "fake-api-key" # llamafile does not require an API key @staticmethod def _resolve_api_base(api_base: Optional[str] = None) -> Optional[str]: @@ -27,11 +25,7 @@ def _resolve_api_base(api_base: Optional[str] = None) -> Optional[str]: If both are None, a default Llamafile server URL is returned. See: https://github.com/Mozilla-Ocho/llamafile/blob/bd1bbe9aabb1ee12dbdcafa8936db443c571eb9d/README.md#L61 """ - return ( - api_base - or get_secret_str("LLAMAFILE_API_BASE") - or "http://127.0.0.1:8080/v1" - ) # type: ignore + return api_base or get_secret_str("LLAMAFILE_API_BASE") or "http://127.0.0.1:8080/v1" # type: ignore def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] diff --git a/litellm/llms/lm_studio/embed/transformation.py b/litellm/llms/lm_studio/embed/transformation.py index 87f4f6e73d50..f0357b9428c5 100644 --- a/litellm/llms/lm_studio/embed/transformation.py +++ b/litellm/llms/lm_studio/embed/transformation.py @@ -44,7 +44,5 @@ def get_config(cls): def get_supported_openai_params(self) -> List[str]: return [] - def map_openai_params( - self, non_default_params: dict, optional_params: dict - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict) -> dict: return optional_params diff --git a/litellm/llms/manus/files/transformation.py b/litellm/llms/manus/files/transformation.py index 341661613901..4a65fac709b5 100644 --- a/litellm/llms/manus/files/transformation.py +++ b/litellm/llms/manus/files/transformation.py @@ -92,9 +92,7 @@ def validate_environment( ) return headers - def get_supported_openai_params( - self, model: str - ) -> List[OpenAICreateFileRequestOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAICreateFileRequestOptionalParams]: """ Return supported OpenAI file creation parameters for Manus. Manus supports the standard 'purpose' parameter. @@ -129,12 +127,7 @@ def get_complete_url( Returns: str: The full URL for the Manus /v1/files endpoint """ - api_base = ( - api_base - or litellm.api_base - or get_secret_str("MANUS_API_BASE") - or MANUS_API_BASE - ) + api_base = api_base or litellm.api_base or get_secret_str("MANUS_API_BASE") or MANUS_API_BASE # Remove trailing slashes api_base = api_base.rstrip("/") @@ -193,11 +186,7 @@ def transform_create_file_request( ) # Get API key - api_key = ( - litellm_params.get("api_key") - or litellm.api_key - or get_secret_str("MANUS_API_KEY") - ) + api_key = litellm_params.get("api_key") or litellm.api_key or get_secret_str("MANUS_API_KEY") if not api_key: raise ValueError( diff --git a/litellm/llms/manus/responses/transformation.py b/litellm/llms/manus/responses/transformation.py index b3a0073a5c29..0db53f903300 100644 --- a/litellm/llms/manus/responses/transformation.py +++ b/litellm/llms/manus/responses/transformation.py @@ -75,18 +75,14 @@ def _extract_agent_profile(self, model: str) -> str: # If no slash, assume the model name itself is the agent profile return model - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate environment and set up headers for Manus API. Manus uses `API_KEY` header instead of `Authorization: Bearer`. """ litellm_params = litellm_params or GenericLiteLLMParams() - api_key = ( - litellm_params.api_key or litellm.api_key or get_secret_str("MANUS_API_KEY") - ) + api_key = litellm_params.api_key or litellm.api_key or get_secret_str("MANUS_API_KEY") if not api_key: raise ValueError( @@ -114,12 +110,7 @@ def get_complete_url( Returns: str: The full URL for the Manus /v1/responses endpoint """ - api_base = ( - api_base - or litellm.api_base - or get_secret_str("MANUS_API_BASE") - or MANUS_API_BASE - ) + api_base = api_base or litellm.api_base or get_secret_str("MANUS_API_BASE") or MANUS_API_BASE # Remove trailing slashes api_base = api_base.rstrip("/") @@ -166,9 +157,7 @@ def transform_responses_api_request( if extra_body: base_request.update(extra_body) - verbose_logger.debug( - f"Manus: Using agent_profile={agent_profile}, task_mode=agent" - ) + verbose_logger.debug(f"Manus: Using agent_profile={agent_profile}, task_mode=agent") return base_request @@ -191,32 +180,20 @@ def transform_response_api_response( raw_response_json = raw_response.json() # Manus uses camelCase "createdAt" instead of snake_case "created_at" - if ( - "createdAt" in raw_response_json - and "created_at" not in raw_response_json - ): - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["createdAt"] - ) + if "createdAt" in raw_response_json and "created_at" not in raw_response_json: + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["createdAt"]) # Ensure created_at is set if "created_at" in raw_response_json: - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["created_at"] - ) + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["created_at"]) except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) # Ensure reasoning is an empty dict if not present, OpenAI SDK does not allow None - if ( - "reasoning" not in raw_response_json - or raw_response_json.get("reasoning") is None - ): + if "reasoning" not in raw_response_json or raw_response_json.get("reasoning") is None: raw_response_json["reasoning"] = {} if "text" not in raw_response_json or raw_response_json.get("text") is None: @@ -242,9 +219,7 @@ def transform_response_api_response( try: response = ResponsesAPIResponse(**raw_response_json) except Exception: - verbose_logger.debug( - f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" - ) + verbose_logger.debug(f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct") response = ResponsesAPIResponse.model_construct(**raw_response_json) # Store processed headers in additional_headers so they get returned to the client @@ -271,9 +246,7 @@ def transform_get_response_api_request( Reference: https://open.manus.im/docs/openai-compatibility """ - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}" data: Dict = {} return url, data @@ -297,32 +270,20 @@ def transform_get_response_api_response( raw_response_json = raw_response.json() # Manus uses camelCase "createdAt" instead of snake_case "created_at" - if ( - "createdAt" in raw_response_json - and "created_at" not in raw_response_json - ): - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["createdAt"] - ) + if "createdAt" in raw_response_json and "created_at" not in raw_response_json: + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["createdAt"]) # Ensure created_at is set if "created_at" in raw_response_json: - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["created_at"] - ) + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["created_at"]) except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) # Ensure reasoning, text, output, and usage are present with defaults - if ( - "reasoning" not in raw_response_json - or raw_response_json.get("reasoning") is None - ): + if "reasoning" not in raw_response_json or raw_response_json.get("reasoning") is None: raw_response_json["reasoning"] = {} if "text" not in raw_response_json or raw_response_json.get("text") is None: @@ -346,9 +307,7 @@ def transform_get_response_api_response( try: response = ResponsesAPIResponse(**raw_response_json) except Exception: - verbose_logger.debug( - f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" - ) + verbose_logger.debug(f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct") response = ResponsesAPIResponse.model_construct(**raw_response_json) # Store processed headers in additional_headers so they get returned to the client diff --git a/litellm/llms/maritalk.py b/litellm/llms/maritalk.py index 418d13b3448a..4b3a569357f3 100644 --- a/litellm/llms/maritalk.py +++ b/litellm/llms/maritalk.py @@ -57,9 +57,5 @@ def get_supported_openai_params(self, model: str) -> List: "tool_choice", ] - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return MaritalkError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return MaritalkError(status_code=status_code, message=error_message, headers=headers) diff --git a/litellm/llms/meta_llama/chat/transformation.py b/litellm/llms/meta_llama/chat/transformation.py index 6c9b79005f56..d9ffbc46f215 100644 --- a/litellm/llms/meta_llama/chat/transformation.py +++ b/litellm/llms/meta_llama/chat/transformation.py @@ -33,9 +33,7 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - mapped_openai_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_openai_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) # Only json_schema is working for response_format if ( diff --git a/litellm/llms/milvus/vector_stores/transformation.py b/litellm/llms/milvus/vector_stores/transformation.py index 867f6d4b1f57..a53075ba1d69 100644 --- a/litellm/llms/milvus/vector_stores/transformation.py +++ b/litellm/llms/milvus/vector_stores/transformation.py @@ -47,9 +47,7 @@ class MilvusVectorStoreConfig(BaseVectorStoreConfig): def __init__(self): super().__init__() - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: api_key: Optional[str] = None if litellm_params is not None: api_key = litellm_params.api_key or get_secret_str("MILVUS_API_KEY") @@ -63,9 +61,7 @@ def validate_environment( return headers - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: api_key = litellm_params.get("api_key") if not api_key: raise ValueError( @@ -90,9 +86,7 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: ], } - def map_openai_params( - self, non_default_params: dict, optional_params: dict, drop_params: bool - ) -> dict: + def map_openai_params(self, non_default_params: dict, optional_params: dict, drop_params: bool) -> dict: for param, value in non_default_params.items(): if param in MILVUS_OPTIONAL_PARAMS: optional_params[param] = value @@ -218,17 +212,15 @@ def transform_search_vector_store_response( results = response_json.get("data", []) # Try to get text_field from optional_params first, then litellm_params - optional_params = litellm_logging_obj.model_call_details.get( - "optional_params", {} - ) + optional_params = litellm_logging_obj.model_call_details.get("optional_params", {}) text_field = optional_params.get("milvus_text_field", "") # Fallback to litellm_params if not in optional_params if not text_field: - text_field = litellm_logging_obj.model_call_details.get( - "litellm_params", {} - ).get("milvus_text_field", "") + text_field = litellm_logging_obj.model_call_details.get("litellm_params", {}).get( + "milvus_text_field", "" + ) # Transform results to standard format search_results: List[VectorStoreSearchResult] = [] @@ -282,7 +274,5 @@ def transform_create_vector_store_request( ) -> Tuple[str, Dict]: raise NotImplementedError - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: raise NotImplementedError diff --git a/litellm/llms/minimax/chat/transformation.py b/litellm/llms/minimax/chat/transformation.py index 69f228160f65..512c162658cc 100644 --- a/litellm/llms/minimax/chat/transformation.py +++ b/litellm/llms/minimax/chat/transformation.py @@ -39,11 +39,7 @@ def get_api_base( Defaults to international endpoint: https://api.minimax.io/v1 For China, set to: https://api.minimaxi.com/v1 """ - return ( - api_base - or get_secret_str("MINIMAX_API_BASE") - or "https://api.minimax.io/v1" - ) + return api_base or get_secret_str("MINIMAX_API_BASE") or "https://api.minimax.io/v1" def get_complete_url( self, diff --git a/litellm/llms/minimax/messages/transformation.py b/litellm/llms/minimax/messages/transformation.py index 57cfcbf06217..3f46aae1aaa2 100644 --- a/litellm/llms/minimax/messages/transformation.py +++ b/litellm/llms/minimax/messages/transformation.py @@ -47,11 +47,7 @@ def get_api_base( Defaults to international endpoint: https://api.minimax.io/anthropic For China, set to: https://api.minimaxi.com/anthropic """ - return ( - api_base - or get_secret_str("MINIMAX_API_BASE") - or "https://api.minimax.io/anthropic/v1/messages" - ) + return api_base or get_secret_str("MINIMAX_API_BASE") or "https://api.minimax.io/anthropic/v1/messages" def get_complete_url( self, diff --git a/litellm/llms/minimax/text_to_speech/transformation.py b/litellm/llms/minimax/text_to_speech/transformation.py index 2a7d6897edc2..70ce2e71731a 100644 --- a/litellm/llms/minimax/text_to_speech/transformation.py +++ b/litellm/llms/minimax/text_to_speech/transformation.py @@ -202,12 +202,8 @@ def validate_environment( return headers - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return MinimaxException( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return MinimaxException(message=error_message, status_code=status_code, headers=headers) def transform_text_to_speech_request( self, @@ -240,9 +236,7 @@ def transform_text_to_speech_request( # Extract audio settings sample_rate = params.pop("sample_rate", 32000) # 16000, 24000, 32000 - bitrate = params.pop( - "bitrate", 128000 - ) # For MP3: 64000, 128000, 192000, 256000 + bitrate = params.pop("bitrate", 128000) # For MP3: 64000, 128000, 192000, 256000 channel = params.pop("channel", 1) # 1 for mono, 2 for stereo # Output format: 'url' or 'hex' (default is 'hex') diff --git a/litellm/llms/mistral/audio_transcription/transformation.py b/litellm/llms/mistral/audio_transcription/transformation.py index 8c6d604acb4b..53d1428e1f11 100644 --- a/litellm/llms/mistral/audio_transcription/transformation.py +++ b/litellm/llms/mistral/audio_transcription/transformation.py @@ -27,9 +27,7 @@ class MistralAudioTranscriptionException(BaseLLMException): class MistralAudioTranscriptionConfig(BaseAudioTranscriptionConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: return [ "language", "temperature", @@ -59,9 +57,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = ( - "https://api.mistral.ai/v1" if api_base is None else api_base.rstrip("/") - ) + api_base = "https://api.mistral.ai/v1" if api_base is None else api_base.rstrip("/") return f"{api_base}/audio/transcriptions" def get_error_class( @@ -119,9 +115,7 @@ def transform_audio_transcription_request( openai_params=self.get_supported_openai_params(model), ) for key, value in provider_specific_params.items(): - form_fields[key] = ( - str(value).lower() if isinstance(value, bool) else str(value) - ) + form_fields[key] = str(value).lower() if isinstance(value, bool) else str(value) files = { "file": ( diff --git a/litellm/llms/mistral/chat/transformation.py b/litellm/llms/mistral/chat/transformation.py index 8d0cf9938141..0f202a22c964 100644 --- a/litellm/llms/mistral/chat/transformation.py +++ b/litellm/llms/mistral/chat/transformation.py @@ -161,9 +161,7 @@ def map_openai_params( for param, value in non_default_params.items(): if param == "max_tokens": optional_params["max_tokens"] = value - if ( - param == "max_completion_tokens" - ): # max_completion_tokens should take priority + if param == "max_completion_tokens": # max_completion_tokens should take priority optional_params["max_tokens"] = value if param == "tools": # Clean tools to remove problematic schema fields for Mistral API @@ -177,9 +175,7 @@ def map_openai_params( if param == "stop": optional_params["stop"] = value if param == "tool_choice" and isinstance(value, str): - optional_params["tool_choice"] = self._map_tool_choice( - tool_choice=value - ) + optional_params["tool_choice"] = self._map_tool_choice(tool_choice=value) if param == "seed": optional_params["extra_body"] = {"random_seed": value} if param == "response_format": @@ -205,9 +201,7 @@ def _get_openai_compatible_provider_info( ) # type: ignore # if api_base does not end with /v1 we add it - if api_base is not None and not api_base.endswith( - "/v1" - ): # Mistral always needs a /v1 at the end + if api_base is not None and not api_base.endswith("/v1"): # Mistral always needs a /v1 at the end api_base = api_base + "/v1" dynamic_api_key = ( api_key @@ -278,9 +272,7 @@ def _transform_messages( else: return super()._transform_messages(new_messages, model, False) - async def _transform_messages_async( - self, messages: List[AllMessageValues], model: str - ) -> List[AllMessageValues]: + async def _transform_messages_async(self, messages: List[AllMessageValues], model: str) -> List[AllMessageValues]: """ Handle modification of messages for Mistral API in an async context. """ @@ -290,9 +282,7 @@ async def _transform_messages_async( messages = self._handle_message_with_file(messages) return messages - def _transform_messages_sync( - self, messages: List[AllMessageValues], model: str - ) -> List[AllMessageValues]: + def _transform_messages_sync(self, messages: List[AllMessageValues], model: str) -> List[AllMessageValues]: """Handle modification of messages for Mistral API in a sync context.""" # Call parent sync method to handle basic transformations # and then apply Mistral-specific handling for files @@ -301,9 +291,7 @@ def _transform_messages_sync( messages = self._handle_message_with_file(messages) return messages - def _handle_message_with_file( - self, messages: List[AllMessageValues] - ) -> List[AllMessageValues]: + def _handle_message_with_file(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: """ Mistral API supports only 'file_id' in message content with type 'file'. """ @@ -313,9 +301,7 @@ def _handle_message_with_file( if any(c.get("type") == "file" for c in _content_block): # If file content is present, we get file_id from 'file' attribute of content block # then replace 'file' with 'file_id' and assign the value of 'file_id' attribute to it. - file_contents = [ - c for c in _content_block if c.get("type") == "file" - ] + file_contents = [c for c in _content_block if c.get("type") == "file"] for file_content in file_contents: file_id = file_content.get("file", {}).get("file_id") if file_id: @@ -346,21 +332,15 @@ def _add_reasoning_system_prompt_if_needed( # Handle both string and list content, preserving original format if isinstance(existing_content, str): # String content - prepend reasoning prompt - new_content: Union[str, list] = ( - f"{reasoning_prompt}\n\n{existing_content}" - ) + new_content: Union[str, list] = f"{reasoning_prompt}\n\n{existing_content}" elif isinstance(existing_content, list): # List content - prepend reasoning prompt as text block - new_content = [ - {"type": "text", "text": reasoning_prompt + "\n\n"} - ] + existing_content + new_content = [{"type": "text", "text": reasoning_prompt + "\n\n"}] + existing_content else: # Fallback for any other type - convert to string new_content = f"{reasoning_prompt}\n\n{str(existing_content)}" - messages[i] = cast( - AllMessageValues, {**msg, "content": new_content} - ) + messages[i] = cast(AllMessageValues, {**msg, "content": new_content}) break else: # Add new system message with reasoning instructions @@ -405,9 +385,7 @@ def _clean_tool_schema_for_mistral(cls, tools: list) -> list: cleaned_tools = copy.deepcopy(tools) # Apply all cleaning functions with max_depth protection - cleaned_tools = _remove_json_schema_refs( - cleaned_tools, max_depth=DEFAULT_MAX_RECURSE_DEPTH - ) + cleaned_tools = _remove_json_schema_refs(cleaned_tools, max_depth=DEFAULT_MAX_RECURSE_DEPTH) return cleaned_tools @@ -423,11 +401,7 @@ def _strip_output_only_fields(cls, message: AllMessageValues) -> AllMessageValue return message return cast( AllMessageValues, - { - k: v - for k, v in message.items() - if k not in ("reasoning_content", "thinking_blocks") - }, + {k: v for k, v in message.items() if k not in ("reasoning_content", "thinking_blocks")}, ) @classmethod @@ -514,9 +488,7 @@ def _convert_thinking_block_to_reasoning_content( """ Convert Mistral thinking blocks to reasoning content. """ - return "\n".join( - [block.get("text", "") for block in thinking_blocks["thinking"]] - ) + return "\n".join([block.get("text", "") for block in thinking_blocks["thinking"]]) @staticmethod def _handle_content_list_to_str_conversion(response_data: dict) -> dict: @@ -545,9 +517,7 @@ def _handle_content_list_to_str_conversion(response_data: dict) -> dict: thinking_texts = [] for thinking_block in thinking_blocks: if thinking_block.get("type") == "text": - thinking_texts.append( - thinking_block.get("text", "") - ) + thinking_texts.append(thinking_block.get("text", "")) thinking_content = "\n".join(thinking_texts) elif block.get("type") == "text": text_content = block.get("text", "") @@ -575,12 +545,8 @@ def transform_request( dict: The transformed request. Sent as the body of the API call. """ # Add reasoning system prompt if needed (for magistral models) - if "magistral" in model.lower() and optional_params.get( - "_add_reasoning_prompt", False - ): - messages = self._add_reasoning_system_prompt_if_needed( - messages, optional_params - ) + if "magistral" in model.lower() and optional_params.get("_add_reasoning_prompt", False): + messages = self._add_reasoning_system_prompt_if_needed(messages, optional_params) # Call parent transform_request which handles _transform_messages return super().transform_request( @@ -701,7 +667,5 @@ def _normalize_content_blocks( text_segments.append(block.get("text", "")) normalized_text = "".join(text_segments) if text_segments else None - reasoning_content = ( - "\n".join(reasoning_segments) if reasoning_segments else None - ) + reasoning_content = "\n".join(reasoning_segments) if reasoning_segments else None return normalized_text, thinking_blocks, reasoning_content diff --git a/litellm/llms/mistral/ocr/guardrail_translation/handler.py b/litellm/llms/mistral/ocr/guardrail_translation/handler.py index 7d3797a1dbe6..9144c71f70a0 100644 --- a/litellm/llms/mistral/ocr/guardrail_translation/handler.py +++ b/litellm/llms/mistral/ocr/guardrail_translation/handler.py @@ -51,9 +51,7 @@ async def process_input_messages( """ document = data.get("document") if document is None or not isinstance(document, dict): - verbose_proxy_logger.debug( - "OCR guardrail: No valid document found in request data" - ) + verbose_proxy_logger.debug("OCR guardrail: No valid document found in request data") return data # Extract the document URL for guardrail checking @@ -135,9 +133,7 @@ async def process_output_response( # Add user metadata if available if user_api_key_dict is not None: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: # Preserve original behavior: inject metadata into inputs for # third-party guardrail providers that read it from there diff --git a/litellm/llms/modelscope/chat/transformation.py b/litellm/llms/modelscope/chat/transformation.py index 162ef1a236cc..1a54be6e1c81 100644 --- a/litellm/llms/modelscope/chat/transformation.py +++ b/litellm/llms/modelscope/chat/transformation.py @@ -54,20 +54,14 @@ def _transform_messages( message["content"] = "".join(item.get("text") or "" for item in content) if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( - api_base or get_secret_str("MODELSCOPE_API_BASE") or self.DEFAULT_BASE_URL - ) # type: ignore + api_base = api_base or get_secret_str("MODELSCOPE_API_BASE") or self.DEFAULT_BASE_URL # type: ignore dynamic_api_key = api_key or get_secret_str("MODELSCOPE_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/modelscope/image_generation/transformation.py b/litellm/llms/modelscope/image_generation/transformation.py index 0d85f7796fb9..a3d890734d1a 100644 --- a/litellm/llms/modelscope/image_generation/transformation.py +++ b/litellm/llms/modelscope/image_generation/transformation.py @@ -41,9 +41,7 @@ class ModelScopeImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://api-inference.modelscope.cn/v1" - def get_supported_openai_params( - self, model: str - ) -> list[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> list[OpenAIImageGenerationOptionalParams]: """ Return list of OpenAI params supported by ModelScope. @@ -70,9 +68,7 @@ def map_openai_params( """ supported_params = self.get_supported_openai_params(model) if drop_params: - non_default_params = { - k: v for k, v in non_default_params.items() if k in supported_params - } + non_default_params = {k: v for k, v in non_default_params.items() if k in supported_params} optional_params.update(non_default_params) return optional_params @@ -89,9 +85,7 @@ def get_complete_url( """ Get the complete URL for the ModelScope image generation API request. """ - base_url: str = ( - api_base or get_secret_str("MODELSCOPE_API_BASE") or self.DEFAULT_BASE_URL - ) + base_url: str = api_base or get_secret_str("MODELSCOPE_API_BASE") or self.DEFAULT_BASE_URL base_url = base_url.rstrip("/") # Return the images endpoint @@ -115,8 +109,7 @@ def validate_environment( if not final_api_key: raise ValueError( - "MODELSCOPE_API_KEY is not set. " - "Please set it via environment variable or pass api_key parameter." + "MODELSCOPE_API_KEY is not set. Please set it via environment variable or pass api_key parameter." ) default_headers = { @@ -185,9 +178,7 @@ def transform_image_generation_response( # Check for errors in response if "error" in response_data: - error_msg = response_data["error"].get( - "message", str(response_data["error"]) - ) + error_msg = response_data["error"].get("message", str(response_data["error"])) raise self.get_error_class( error_message=f"ModelScope error: {error_msg}", status_code=raw_response.status_code, diff --git a/litellm/llms/moonshot/chat/transformation.py b/litellm/llms/moonshot/chat/transformation.py index a5ac696aae26..07a963e95fdc 100644 --- a/litellm/llms/moonshot/chat/transformation.py +++ b/litellm/llms/moonshot/chat/transformation.py @@ -53,22 +53,14 @@ def _transform_messages( messages = handle_messages_with_content_list_to_str_conversion(messages) if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( - api_base - or get_secret_str("MOONSHOT_API_BASE") - or "https://api.moonshot.ai/v1" - ) # type: ignore + api_base = api_base or get_secret_str("MOONSHOT_API_BASE") or "https://api.moonshot.ai/v1" # type: ignore dynamic_api_key = api_key or get_secret_str("MOONSHOT_API_KEY") return api_base, dynamic_api_key @@ -153,9 +145,7 @@ def map_openai_params( optional_params["temperature"] = 0.3 return optional_params - def fill_reasoning_content( - self, messages: List[AllMessageValues] - ) -> List[AllMessageValues]: + def fill_reasoning_content(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: """ Moonshot reasoning models require `reasoning_content` on every assistant message that contains tool_calls (multi-turn tool-calling flows). diff --git a/litellm/llms/morph/chat/transformation.py b/litellm/llms/morph/chat/transformation.py index 93bd7e16aef7..97ddc12920f3 100644 --- a/litellm/llms/morph/chat/transformation.py +++ b/litellm/llms/morph/chat/transformation.py @@ -25,9 +25,7 @@ def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: api_base = ( - api_base - or get_secret_str("MORPH_API_BASE") - or "https://api.morphllm.com/v1" # default api base + api_base or get_secret_str("MORPH_API_BASE") or "https://api.morphllm.com/v1" # default api base ) dynamic_api_key = api_key or get_secret_str("MORPH_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/nlp_cloud/chat/transformation.py b/litellm/llms/nlp_cloud/chat/transformation.py index 8037a458321e..5aafc4cd45c8 100644 --- a/litellm/llms/nlp_cloud/chat/transformation.py +++ b/litellm/llms/nlp_cloud/chat/transformation.py @@ -146,9 +146,7 @@ def map_openai_params( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return NLPCloudError( - status_code=status_code, message=error_message, headers=headers - ) + return NLPCloudError(status_code=status_code, message=error_message, headers=headers) def transform_request( self, @@ -193,9 +191,7 @@ def transform_response( try: completion_response = raw_response.json() except Exception: - raise NLPCloudError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise NLPCloudError(message=raw_response.text, status_code=raw_response.status_code) if "error" in completion_response: raise NLPCloudError( message=completion_response["error"], diff --git a/litellm/llms/nscale/chat/transformation.py b/litellm/llms/nscale/chat/transformation.py index 6103b8e3c498..1b032fab2acd 100644 --- a/litellm/llms/nscale/chat/transformation.py +++ b/litellm/llms/nscale/chat/transformation.py @@ -23,9 +23,7 @@ def get_api_key(api_key: Optional[str] = None) -> Optional[str]: @staticmethod def get_api_base(api_base: Optional[str] = None) -> Optional[str]: - return ( - api_base or get_secret_str("NSCALE_API_BASE") or NscaleConfig.API_BASE_URL - ) + return api_base or get_secret_str("NSCALE_API_BASE") or NscaleConfig.API_BASE_URL def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] diff --git a/litellm/llms/nvidia_nim/rerank/transformation.py b/litellm/llms/nvidia_nim/rerank/transformation.py index 7ae3f913297f..2d72d52f991b 100644 --- a/litellm/llms/nvidia_nim/rerank/transformation.py +++ b/litellm/llms/nvidia_nim/rerank/transformation.py @@ -156,9 +156,7 @@ def validate_environment( api_key = get_secret_str("NVIDIA_NIM_API_KEY") or litellm.api_key if api_key is None: - raise ValueError( - "Nvidia NIM API key is required. Please set 'NVIDIA_NIM_API_KEY' in your environment" - ) + raise ValueError("Nvidia NIM API key is required. Please set 'NVIDIA_NIM_API_KEY' in your environment") default_headers = { "Authorization": f"Bearer {api_key}", @@ -235,18 +233,12 @@ def transform_rerank_request( } # Add optional top_k parameter if provided (already mapped from top_n in map_cohere_rerank_params) - if ( - "top_k" in optional_rerank_params - and optional_rerank_params.get("top_k") is not None - ): # type: ignore + if "top_k" in optional_rerank_params and optional_rerank_params.get("top_k") is not None: # type: ignore request_data["top_k"] = optional_rerank_params.get("top_k") # type: ignore # Add Nvidia-specific truncate parameter if provided # This is passed through from non_default_params, not in base OptionalRerankParams - if ( - "truncate" in optional_rerank_params - and optional_rerank_params.get("truncate") is not None - ): # type: ignore + if "truncate" in optional_rerank_params and optional_rerank_params.get("truncate") is not None: # type: ignore truncate_value = optional_rerank_params.get("truncate") # type: ignore if truncate_value in ["NONE", "END"]: request_data["truncate"] = truncate_value # type: ignore @@ -305,9 +297,7 @@ def transform_rerank_response( rankings = nvidia_response.get("rankings", []) # Get original documents from request if we need to include them - original_passages: List[NvidiaNimPassageObject] = request_data.get( - "passages", [] - ) + original_passages: List[NvidiaNimPassageObject] = request_data.get("passages", []) for ranking in rankings: result_item: RerankResponseResult = { @@ -327,9 +317,7 @@ def transform_rerank_response( usage = raw_response_json.get("usage", {}) total_tokens = usage.get("total_tokens", 0) - billed_units: RerankBilledUnits = { - "total_tokens": total_tokens if total_tokens > 0 else len(results) - } + billed_units: RerankBilledUnits = {"total_tokens": total_tokens if total_tokens > 0 else len(results)} meta: RerankResponseMeta = {"billed_units": billed_units} diff --git a/litellm/llms/nvidia_riva/audio_transcription/audio_utils.py b/litellm/llms/nvidia_riva/audio_transcription/audio_utils.py index 253d6d2f73f0..7ec679c858d0 100644 --- a/litellm/llms/nvidia_riva/audio_transcription/audio_utils.py +++ b/litellm/llms/nvidia_riva/audio_transcription/audio_utils.py @@ -30,10 +30,7 @@ FloatArray = Any -_INSTALL_HINT = ( - "Install Riva STT extras to enable automatic audio resampling: " - "`pip install 'litellm[stt-nvidia-riva]'`" -) +_INSTALL_HINT = "Install Riva STT extras to enable automatic audio resampling: `pip install 'litellm[stt-nvidia-riva]'`" @dataclass @@ -69,9 +66,7 @@ def resample_to_riva_pcm(file_bytes: bytes) -> ResampledAudio: samples_float = np.asarray(samples_float, dtype=np.float32).ravel() if source_rate != RIVA_TARGET_SAMPLE_RATE_HZ: - samples_float = _resample( - samples_float, source_rate, RIVA_TARGET_SAMPLE_RATE_HZ - ) + samples_float = _resample(samples_float, source_rate, RIVA_TARGET_SAMPLE_RATE_HZ) # Clip + convert float [-1, 1] to int16 little-endian PCM. np.clip(samples_float, -1.0, 1.0, out=samples_float) @@ -167,9 +162,7 @@ def _decode_to_float32(file_bytes: bytes) -> Tuple["FloatArray", int]: pass -def _resample( - samples: "FloatArray", source_rate: int, target_rate: int -) -> "FloatArray": +def _resample(samples: "FloatArray", source_rate: int, target_rate: int) -> "FloatArray": """ Resample mono float32 ``samples`` from ``source_rate`` to ``target_rate``. @@ -189,9 +182,7 @@ def _resample( return cast( "FloatArray", - np.asarray( - soxr.resample(samples, source_rate, target_rate), dtype=np.float32 - ), + np.asarray(soxr.resample(samples, source_rate, target_rate), dtype=np.float32), ) except ImportError: pass @@ -204,18 +195,14 @@ def _resample( g = gcd(int(source_rate), int(target_rate)) up = int(target_rate) // g down = int(source_rate) // g - return cast( - "FloatArray", np.asarray(resample_poly(samples, up, down), dtype=np.float32) - ) + return cast("FloatArray", np.asarray(resample_poly(samples, up, down), dtype=np.float32)) except ImportError: pass return _linear_resample(samples, source_rate, target_rate) -def _linear_resample( - samples: "FloatArray", source_rate: int, target_rate: int -) -> "FloatArray": +def _linear_resample(samples: "FloatArray", source_rate: int, target_rate: int) -> "FloatArray": """Linear-interpolation fallback. See :func:`_resample` for caveats.""" import numpy as np # type: ignore diff --git a/litellm/llms/nvidia_riva/audio_transcription/handler.py b/litellm/llms/nvidia_riva/audio_transcription/handler.py index 9740162ba1cf..eab5abd475bf 100644 --- a/litellm/llms/nvidia_riva/audio_transcription/handler.py +++ b/litellm/llms/nvidia_riva/audio_transcription/handler.py @@ -59,10 +59,7 @@ _DEFAULT_CHUNK_BYTES = _DEFAULT_CHUNK_SAMPLES * 2 # int16 = 2 bytes/sample -_RIVA_INSTALL_HINT = ( - "NVIDIA Riva client is not installed. " - "Install with `pip install 'litellm[stt-nvidia-riva]'`." -) +_RIVA_INSTALL_HINT = "NVIDIA Riva client is not installed. Install with `pip install 'litellm[stt-nvidia-riva]'`." class NvidiaRivaAudioTranscription: @@ -209,9 +206,7 @@ def _run_sync( riva_asr_module=riva_asr_module, recognition_config_dict=recognition_config_dict, ) - streaming_config = riva_asr_module.StreamingRecognitionConfig( - config=recognition_config, interim_results=False - ) + streaming_config = riva_asr_module.StreamingRecognitionConfig(config=recognition_config, interim_results=False) logging_obj.pre_call( input=None, @@ -221,9 +216,7 @@ def _run_sync( "atranscription": atranscription, "complete_input_dict": { "recognition_config": recognition_config_dict, - "nvcf_function_id_set": bool( - optional_params.get("nvcf_function_id") - ), + "nvcf_function_id_set": bool(optional_params.get("nvcf_function_id")), "use_ssl": optional_params.get("use_ssl"), }, }, @@ -239,9 +232,7 @@ def _run_sync( # Forward the deadline so the stream cannot block forever if the # server stalls. Older riva-client versions do not accept a # ``timeout`` kwarg, so pass it only when supported. - if timeout is not None and self._supports_timeout_kwarg( - asr_service.streaming_response_generator - ): + if timeout is not None and self._supports_timeout_kwarg(asr_service.streaming_response_generator): stream_kwargs["timeout"] = float(timeout) stream = asr_service.streaming_response_generator(**stream_kwargs) final_results = self._collect_final_results(stream) @@ -300,11 +291,7 @@ def _construct_auth( """ nvcf_function_id = optional_params.get("nvcf_function_id") use_ssl_override = optional_params.get("use_ssl") - use_ssl = ( - bool(use_ssl_override) - if use_ssl_override is not None - else bool(nvcf_function_id) - ) + use_ssl = bool(use_ssl_override) if use_ssl_override is not None else bool(nvcf_function_id) metadata: List[Tuple[str, str]] = [] if nvcf_function_id: @@ -313,19 +300,13 @@ def _construct_auth( metadata.append(("authorization", f"Bearer {api_key}")) try: - return riva_module.Auth( - uri=api_base, use_ssl=use_ssl, metadata_args=metadata - ) + return riva_module.Auth(uri=api_base, use_ssl=use_ssl, metadata_args=metadata) except TypeError: # Older riva-client signatures used positional-only args. return riva_module.Auth(None, use_ssl, api_base, metadata) - def _build_recognition_config_proto( - self, riva_asr_module: Any, recognition_config_dict: Dict[str, Any] - ): - encoding_name = ( - recognition_config_dict.get("encoding") or "LINEAR_PCM" - ).upper() + def _build_recognition_config_proto(self, riva_asr_module: Any, recognition_config_dict: Dict[str, Any]): + encoding_name = (recognition_config_dict.get("encoding") or "LINEAR_PCM").upper() encoding_enum = getattr( riva_asr_module.AudioEncoding, encoding_name, @@ -337,20 +318,12 @@ def _build_recognition_config_proto( sample_rate_hertz=int(recognition_config_dict["sample_rate_hertz"]), language_code=recognition_config_dict["language_code"], audio_channel_count=int(recognition_config_dict["audio_channel_count"]), - enable_automatic_punctuation=bool( - recognition_config_dict.get("enable_automatic_punctuation", True) - ), - enable_word_time_offsets=bool( - recognition_config_dict.get("enable_word_time_offsets", False) - ), + enable_automatic_punctuation=bool(recognition_config_dict.get("enable_automatic_punctuation", True)), + enable_word_time_offsets=bool(recognition_config_dict.get("enable_word_time_offsets", False)), max_alternatives=int(recognition_config_dict.get("max_alternatives", 1)), model=recognition_config_dict.get("model", "") or "", - verbatim_transcripts=bool( - recognition_config_dict.get("verbatim_transcripts", False) - ), - profanity_filter=bool( - recognition_config_dict.get("profanity_filter", False) - ), + verbatim_transcripts=bool(recognition_config_dict.get("verbatim_transcripts", False)), + profanity_filter=bool(recognition_config_dict.get("profanity_filter", False)), ) endpointing = recognition_config_dict.get("endpointing_config") @@ -437,8 +410,6 @@ def _import_riva(): riva_asr_module = riva_asr_pb2 except ImportError as e: - raise NvidiaRivaException( - status_code=500, message=_RIVA_INSTALL_HINT - ) from e + raise NvidiaRivaException(status_code=500, message=_RIVA_INSTALL_HINT) from e return riva_client, riva_asr_module diff --git a/litellm/llms/nvidia_riva/audio_transcription/transformation.py b/litellm/llms/nvidia_riva/audio_transcription/transformation.py index c2dfc25d945f..43185cb2f7a0 100644 --- a/litellm/llms/nvidia_riva/audio_transcription/transformation.py +++ b/litellm/llms/nvidia_riva/audio_transcription/transformation.py @@ -43,9 +43,7 @@ class NvidiaRivaAudioTranscriptionConfig(BaseAudioTranscriptionConfig): optional TLS via ``use_ssl``). """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: # Riva natively understands language + word timestamps. # `response_format` is honored at response-shaping time in the handler. return ["language", "response_format", "timestamp_granularities"] @@ -79,12 +77,8 @@ def map_openai_params( return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return NvidiaRivaException( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return NvidiaRivaException(message=error_message, status_code=status_code, headers=headers) def transform_audio_transcription_request( self, @@ -141,9 +135,7 @@ def validate_environment( # gRPC auth is constructed in the handler, not via HTTP headers. return headers - def _build_recognition_config_dict( - self, model: str, optional_params: dict - ) -> Dict[str, Any]: + def _build_recognition_config_dict(self, model: str, optional_params: dict) -> Dict[str, Any]: """ Build the Riva ``RecognitionConfig`` shape as a plain dict. @@ -156,28 +148,18 @@ def _build_recognition_config_dict( """ return { "language_code": optional_params.get("language_code", "en-US"), - "sample_rate_hertz": optional_params.get( - "sample_rate_hertz", RIVA_TARGET_SAMPLE_RATE_HZ - ), + "sample_rate_hertz": optional_params.get("sample_rate_hertz", RIVA_TARGET_SAMPLE_RATE_HZ), "encoding": optional_params.get("encoding", RIVA_TARGET_ENCODING), - "audio_channel_count": optional_params.get( - "audio_channel_count", RIVA_TARGET_NUM_CHANNELS - ), - "enable_automatic_punctuation": optional_params.get( - "enable_automatic_punctuation", True - ), - "enable_word_time_offsets": bool( - optional_params.get("enable_word_time_offsets", False) - ), + "audio_channel_count": optional_params.get("audio_channel_count", RIVA_TARGET_NUM_CHANNELS), + "enable_automatic_punctuation": optional_params.get("enable_automatic_punctuation", True), + "enable_word_time_offsets": bool(optional_params.get("enable_word_time_offsets", False)), "max_alternatives": optional_params.get("max_alternatives", 1), "model": optional_params.get("riva_model_name", ""), "verbatim_transcripts": optional_params.get("verbatim_transcripts", False), "profanity_filter": optional_params.get("profanity_filter", False), } - def _build_endpointing_config_dict( - self, optional_params: dict - ) -> Optional[Dict[str, Any]]: + def _build_endpointing_config_dict(self, optional_params: dict) -> Optional[Dict[str, Any]]: """ Translate an OpenAI-style ``chunking_strategy`` into Riva's ``EndpointingConfig`` shape, or pass through an explicit @@ -257,9 +239,7 @@ def build_transcription_response( only ``result.is_final`` entries (empty/non-final chunks are ignored). """ - full_transcript = "".join( - (item.get("transcript") or "") for item in final_results - ).strip() + full_transcript = "".join((item.get("transcript") or "") for item in final_results).strip() response = TranscriptionResponse(text=full_transcript) response["task"] = "transcribe" diff --git a/litellm/llms/nvidia_riva/common_utils.py b/litellm/llms/nvidia_riva/common_utils.py index a3071cf7060e..4206fc91cc63 100644 --- a/litellm/llms/nvidia_riva/common_utils.py +++ b/litellm/llms/nvidia_riva/common_utils.py @@ -84,9 +84,5 @@ def grpc_error_to_litellm_exception(error: Exception) -> NvidiaRivaException: http_status = _GRPC_STATUS_CODE_TO_HTTP.get(status_name or "", 500) detail = _extract_grpc_details(error) or str(error) - message = ( - f"NVIDIA Riva gRPC error ({status_name}): {detail}" - if status_name - else f"NVIDIA Riva error: {detail}" - ) + message = f"NVIDIA Riva gRPC error ({status_name}): {detail}" if status_name else f"NVIDIA Riva error: {detail}" return NvidiaRivaException(status_code=http_status, message=message) diff --git a/litellm/llms/oci/chat/cohere.py b/litellm/llms/oci/chat/cohere.py index de8a09b7a3bf..3661ac908d2b 100644 --- a/litellm/llms/oci/chat/cohere.py +++ b/litellm/llms/oci/chat/cohere.py @@ -54,9 +54,7 @@ def _extract_text_content(content: Any) -> str: return content if isinstance(content, list): return "".join( - item.get("text", "") - for item in content - if isinstance(item, dict) and item.get("type") == "text" + item.get("text", "") for item in content if isinstance(item, dict) and item.get("type") == "text" ) return str(content) @@ -88,9 +86,7 @@ def adapt_messages_to_cohere_standard( tc_id = tc.get("id", "") raw_args: Any = tc.get("function", {}).get("arguments", "{}") try: - params: Dict[str, Any] = ( - json.loads(raw_args) if isinstance(raw_args, str) else raw_args - ) + params: Dict[str, Any] = json.loads(raw_args) if isinstance(raw_args, str) else raw_args except json.JSONDecodeError: params = {} tool_call_lookup[tc_id] = CohereToolCall( @@ -99,17 +95,11 @@ def adapt_messages_to_cohere_standard( ) last_user_index = next( - ( - i - for i in range(len(messages) - 1, -1, -1) - if messages[i].get("role") == "user" - ), + (i for i in range(len(messages) - 1, -1, -1) if messages[i].get("role") == "user"), None, ) history_source = ( - messages - if last_user_index is None - else [m for i, m in enumerate(messages) if i != last_user_index] + messages if last_user_index is None else [m for i, m in enumerate(messages) if i != last_user_index] ) chat_history: List[CohereMessage] = [] @@ -139,14 +129,10 @@ def adapt_messages_to_cohere_standard( if role == "user": chat_history.append(CohereMessage(role="USER", message=content)) elif role == "assistant": - chat_history.append( - CohereMessage(role="CHATBOT", message=content, toolCalls=tool_calls) - ) + chat_history.append(CohereMessage(role="CHATBOT", message=content, toolCalls=tool_calls)) elif role == "tool": tool_call_id = str(msg.get("tool_call_id", "") or "") - cohere_call = tool_call_lookup.get( - tool_call_id, CohereToolCall(name="", parameters={}) - ) + cohere_call = tool_call_lookup.get(tool_call_id, CohereToolCall(name="", parameters={})) tool_result = CohereToolResult( call=cohere_call, outputs=[{"output": content}], @@ -179,9 +165,7 @@ def adapt_tool_definitions_to_cohere_standard( function_def = tool.get("function", {}) raw_params = function_def.get("parameters", {}) - resolved = sanitize_oci_schema( - resolve_oci_schema_anyof(resolve_oci_schema_refs(raw_params)) - ) + resolved = sanitize_oci_schema(resolve_oci_schema_anyof(resolve_oci_schema_refs(raw_params))) properties = resolved.get("properties", {}) required = resolved.get("required", []) @@ -190,9 +174,7 @@ def adapt_tool_definitions_to_cohere_standard( json_type = param_schema.get("type", "string") python_type = OCI_JSON_TO_PYTHON_TYPES.get(json_type, json_type) parameter_definitions[param_name] = CohereParameterDefinition( - description=enrich_cohere_param_description( - param_schema.get("description", ""), param_schema - ), + description=enrich_cohere_param_description(param_schema.get("description", ""), param_schema), type=python_type, isRequired=param_name in required, ) @@ -227,17 +209,13 @@ def handle_cohere_response( model_response.created = int(datetime.datetime.now().timestamp()) response_text = cohere_response.chatResponse.text - finish_reason = _normalize_oci_finish_reason( - cohere_response.chatResponse.finishReason - ) + finish_reason = _normalize_oci_finish_reason(cohere_response.chatResponse.finishReason) tool_calls: Optional[List[Dict[str, Any]]] = None if cohere_response.chatResponse.toolCalls: tool_calls = [ { - "id": _synthesize_oci_tool_call_id( - i, tc.name, json.dumps(tc.parameters, sort_keys=True) - ), + "id": _synthesize_oci_tool_call_id(i, tc.name, json.dumps(tc.parameters, sort_keys=True)), "type": "function", "function": { "name": tc.name, @@ -274,9 +252,7 @@ def handle_cohere_response( total_tokens=usage_info.totalTokens, ) else: - model_response.usage = Usage( - prompt_tokens=0, completion_tokens=0, total_tokens=0 - ) # type: ignore[attr-defined] + model_response.usage = Usage(prompt_tokens=0, completion_tokens=0, total_tokens=0) # type: ignore[attr-defined] return model_response @@ -319,9 +295,7 @@ def handle_cohere_stream_chunk( # already-streamed deltas. We require both signals to be present so that a # future API change which adds `chatHistory` to intermediate chunks (or a # rare early-populated case) doesn't silently drop legitimate token deltas. - is_terminal_consolidation = ( - typed_chunk.chatHistory is not None and typed_chunk.finishReason is not None - ) + is_terminal_consolidation = typed_chunk.chatHistory is not None and typed_chunk.finishReason is not None # On non-terminal text-free chunks (e.g. tool-call-only or keep-alive # chunks) emit ``content=None`` rather than ``content=""`` so downstream # stream-mergers that distinguish "no text in this delta" from "an @@ -331,9 +305,7 @@ def handle_cohere_stream_chunk( # confirmed that text deltas were already emitted earlier — otherwise # (e.g. a degenerate stream that delivers the whole response in a # single SSE event), passing it through is the only chance to surface it. - text: Optional[str] = ( - None if (is_terminal_consolidation and prior_text_emitted) else typed_chunk.text - ) + text: Optional[str] = None if (is_terminal_consolidation and prior_text_emitted) else typed_chunk.text # Tool calls on the terminal consolidation chunk (whether from # `typed_chunk.toolCalls` or from `chatHistory`) typically restate what @@ -343,11 +315,7 @@ def handle_cohere_stream_chunk( # tool calls were already emitted earlier — otherwise (e.g. a short # response that delivers tool calls exclusively on the terminal chunk), # passing them through is the only chance to surface them. - cohere_tool_calls = ( - None - if (is_terminal_consolidation and prior_tool_calls_emitted) - else typed_chunk.toolCalls - ) + cohere_tool_calls = None if (is_terminal_consolidation and prior_tool_calls_emitted) else typed_chunk.toolCalls tool_calls: Optional[List[Dict[str, Any]]] = None if cohere_tool_calls: @@ -357,9 +325,7 @@ def handle_cohere_stream_chunk( # deterministically from the call's content/position. A random # uuid4 per chunk would cause downstream stream-mergers to # treat each chunk as a distinct tool call. - "id": _synthesize_oci_tool_call_id( - i, tc.name, json.dumps(tc.parameters, sort_keys=True) - ), + "id": _synthesize_oci_tool_call_id(i, tc.name, json.dumps(tc.parameters, sort_keys=True)), "type": "function", "function": { "name": tc.name, diff --git a/litellm/llms/oci/chat/generic.py b/litellm/llms/oci/chat/generic.py index 2cc1ac77a40d..02ec762488d9 100644 --- a/litellm/llms/oci/chat/generic.py +++ b/litellm/llms/oci/chat/generic.py @@ -55,9 +55,7 @@ # --------------------------------------------------------------------------- -def adapt_messages_to_generic_oci_standard_content_message( - role: str, content: Union[str, list] -) -> OCIMessage: +def adapt_messages_to_generic_oci_standard_content_message(role: str, content: Union[str, list]) -> OCIMessage: """Convert a plain-text or multipart content message to OCI format.""" new_content: List[OCIContentPartUnion] = [] if isinstance(content, str): @@ -70,9 +68,7 @@ def adapt_messages_to_generic_oci_standard_content_message( for content_item in content: if not isinstance(content_item, dict): - raise OCIError( - status_code=400, message="Each content item must be a dictionary" - ) + raise OCIError(status_code=400, message="Each content item must be a dictionary") item_type = content_item.get("type") if not isinstance(item_type, str): @@ -114,20 +110,14 @@ def adapt_messages_to_generic_oci_standard_content_message( ) -def adapt_messages_to_generic_oci_standard_tool_call( - role: str, tool_calls: list -) -> OCIMessage: +def adapt_messages_to_generic_oci_standard_tool_call(role: str, tool_calls: list) -> OCIMessage: """Convert an assistant tool-call message to OCI format.""" tool_calls_formatted = [] for tool_call in tool_calls: if not isinstance(tool_call, dict): - raise OCIError( - status_code=400, message="Each tool call must be a dictionary" - ) + raise OCIError(status_code=400, message="Each tool call must be a dictionary") if tool_call.get("type") != "function": - raise OCIError( - status_code=400, message="OCI only supports function tool calls" - ) + raise OCIError(status_code=400, message="OCI only supports function tool calls") tool_call_id = tool_call.get("id") if not isinstance(tool_call_id, str): @@ -135,15 +125,11 @@ def adapt_messages_to_generic_oci_standard_tool_call( tool_function = tool_call.get("function") if not isinstance(tool_function, dict): - raise OCIError( - status_code=400, message="Tool call `function` must be a dictionary" - ) + raise OCIError(status_code=400, message="Tool call `function` must be a dictionary") function_name = tool_function.get("name") if not isinstance(function_name, str): - raise OCIError( - status_code=400, message="Tool call `function.name` must be a string" - ) + raise OCIError(status_code=400, message="Tool call `function.name` must be a string") arguments = tool_call["function"].get("arguments", "{}") if not isinstance(arguments, str): @@ -169,9 +155,7 @@ def adapt_messages_to_generic_oci_standard_tool_call( ) -def adapt_messages_to_generic_oci_standard_tool_response( - role: str, tool_call_id: str, content: str -) -> OCIMessage: +def adapt_messages_to_generic_oci_standard_tool_response(role: str, tool_call_id: str, content: str) -> OCIMessage: """Convert a tool-result message to OCI format.""" return OCIMessage( role=open_ai_to_generic_oci_role_map[role], @@ -194,12 +178,8 @@ def adapt_messages_to_generic_oci_standard( if role == "assistant" and tool_calls is not None: if not isinstance(tool_calls, list): - raise OCIError( - status_code=400, message="Message `tool_calls` must be a list" - ) - new_messages.append( - adapt_messages_to_generic_oci_standard_tool_call(role, tool_calls) - ) + raise OCIError(status_code=400, message="Message `tool_calls` must be a list") + new_messages.append(adapt_messages_to_generic_oci_standard_tool_call(role, tool_calls)) elif role in ["system", "user", "assistant"] and content is not None: if not isinstance(content, (str, list)): @@ -207,9 +187,7 @@ def adapt_messages_to_generic_oci_standard( status_code=400, message="Message `content` must be a string or list of content parts", ) - new_messages.append( - adapt_messages_to_generic_oci_standard_content_message(role, content) - ) + new_messages.append(adapt_messages_to_generic_oci_standard_content_message(role, content)) elif role == "tool": if not isinstance(tool_call_id, str): @@ -222,11 +200,7 @@ def adapt_messages_to_generic_oci_standard( status_code=400, message="Tool result message `content` must be a string", ) - new_messages.append( - adapt_messages_to_generic_oci_standard_tool_response( - role, tool_call_id, content - ) - ) + new_messages.append(adapt_messages_to_generic_oci_standard_tool_response(role, tool_call_id, content)) return new_messages @@ -236,9 +210,7 @@ def adapt_messages_to_generic_oci_standard( # --------------------------------------------------------------------------- -def adapt_tool_definition_to_oci_standard( - tools: List[Dict], vendor: OCIVendors -) -> List[OCIToolDefinition]: +def adapt_tool_definition_to_oci_standard(tools: List[Dict], vendor: OCIVendors) -> List[OCIToolDefinition]: """Convert OpenAI-format tool definitions to OCI GENERIC format. Resolves ``$ref``/``$defs`` and ``anyOf`` that the OCI endpoint rejects. @@ -250,14 +222,10 @@ def adapt_tool_definition_to_oci_standard( tool_function = tool.get("function") if not isinstance(tool_function, dict): - raise OCIError( - status_code=400, message="Tool `function` must be a dictionary" - ) + raise OCIError(status_code=400, message="Tool `function` must be a dictionary") raw_params = tool_function.get("parameters", {}) - resolved_params = sanitize_oci_schema( - resolve_oci_schema_anyof(resolve_oci_schema_refs(raw_params)) - ) + resolved_params = sanitize_oci_schema(resolve_oci_schema_anyof(resolve_oci_schema_refs(raw_params))) new_tools.append( OCIToolDefinition( @@ -370,9 +338,7 @@ def handle_generic_response( if text is not None: message.content = text if response_message.toolCalls: - message.tool_calls = adapt_tools_to_openai_standard( - response_message.toolCalls - ) + message.tool_calls = adapt_tools_to_openai_standard(response_message.toolCalls) model_response.choices[0].finish_reason = _normalize_oci_finish_reason( # type: ignore[union-attr,assignment] response_choice.finishReason @@ -380,10 +346,7 @@ def handle_generic_response( oci_usage = completion_response.chatResponse.usage reasoning_tokens: Optional[int] = None - if ( - oci_usage.completionTokensDetails - and oci_usage.completionTokensDetails.reasoningTokens is not None - ): + if oci_usage.completionTokensDetails and oci_usage.completionTokensDetails.reasoningTokens is not None: reasoning_tokens = oci_usage.completionTokensDetails.reasoningTokens model_response.usage = Usage( # type: ignore[attr-defined] prompt_tokens=oci_usage.promptTokens, @@ -456,9 +419,7 @@ def handle_generic_stream_chunk(dict_chunk: dict) -> ModelResponseStream: for i, tc in enumerate(typed_chunk.message.toolCalls) ] - finish_reason: Optional[str] = _normalize_oci_finish_reason( - typed_chunk.finishReason - ) + finish_reason: Optional[str] = _normalize_oci_finish_reason(typed_chunk.finishReason) return ModelResponseStream( choices=[ diff --git a/litellm/llms/oci/chat/transformation.py b/litellm/llms/oci/chat/transformation.py index 35d5aefeacb5..496656dd5ac1 100644 --- a/litellm/llms/oci/chat/transformation.py +++ b/litellm/llms/oci/chat/transformation.py @@ -154,9 +154,7 @@ def _normalize_tool_choice(selected_params: Dict) -> None: "required": {"type": "REQUIRED"}, "any": {"type": "REQUIRED"}, } - selected_params["toolChoice"] = tc_map.get( - tc.lower(), {"type": "FUNCTION", "name": tc} - ) + selected_params["toolChoice"] = tc_map.get(tc.lower(), {"type": "FUNCTION", "name": tc}) return if isinstance(tc, dict): raw_type = tc.get("type") @@ -188,10 +186,7 @@ def _normalize_tool_choice(selected_params: Dict) -> None: return raise OCIError( status_code=400, - message=( - f"Invalid tool_choice for OCI: expected str or dict, got " - f"{type(tc).__name__}" - ), + message=(f"Invalid tool_choice for OCI: expected str or dict, got {type(tc).__name__}"), ) @@ -239,9 +234,7 @@ def _normalize_response_format(selected_params: Dict, vendor: OCIVendors) -> Non return fmt = rf_type.upper() - selected_params["responseFormat"] = { - "type": "JSON_OBJECT" if fmt == "JSON" else fmt - } + selected_params["responseFormat"] = {"type": "JSON_OBJECT" if fmt == "JSON" else fmt} def get_vendor_from_model(model: str) -> OCIVendors: @@ -305,8 +298,7 @@ def __init__(self) -> None: # ``map_openai_params`` either drops them (under drop_params) or raises # a clear error, rather than silently passing them through. self.openai_to_oci_cohere_param_map = { - k: ("stopSequences" if k == "stop" else v) - for k, v in self.openai_to_oci_generic_param_map.items() + k: ("stopSequences" if k == "stop" else v) for k, v in self.openai_to_oci_generic_param_map.items() } self.openai_to_oci_cohere_param_map["tool_choice"] = False self.openai_to_oci_cohere_param_map["n"] = False @@ -350,9 +342,7 @@ def map_openai_params( adapted_params = {} vendor = get_vendor_from_model(model) param_map = ( - self.openai_to_oci_cohere_param_map - if vendor == OCIVendors.COHERE - else self.openai_to_oci_generic_param_map + self.openai_to_oci_cohere_param_map if vendor == OCIVendors.COHERE else self.openai_to_oci_generic_param_map ) for key, value in {**non_default_params, **optional_params}.items(): @@ -464,13 +454,9 @@ def get_complete_url( base = get_oci_base_url(optional_params, api_base or litellm.api_base) return f"{base}/{OCI_API_VERSION}/actions/chat" - def _get_optional_params( - self, vendor: OCIVendors, optional_params: dict, model: str = "" - ) -> Dict: + def _get_optional_params(self, vendor: OCIVendors, optional_params: dict, model: str = "") -> Dict: param_map = ( - self.openai_to_oci_cohere_param_map - if vendor == OCIVendors.COHERE - else self.openai_to_oci_generic_param_map + self.openai_to_oci_cohere_param_map if vendor == OCIVendors.COHERE else self.openai_to_oci_generic_param_map ) selected_params: Dict = {} @@ -480,9 +466,7 @@ def _get_optional_params( # endpoint uses "maxTokens" regardless, so the override is GENERIC-only. max_tokens_key = ( "maxCompletionTokens" - if vendor != OCIVendors.COHERE - and model - and _model_uses_max_completion_tokens(model) + if vendor != OCIVendors.COHERE and model and _model_uses_max_completion_tokens(model) else "maxTokens" ) @@ -589,18 +573,14 @@ def transform_request( system_messages = [m for m in messages if m.get("role") == "system"] preamble_override = None if system_messages: - preamble = "\n".join( - _extract_text_content(m["content"]) for m in system_messages - ) + preamble = "\n".join(_extract_text_content(m["content"]) for m in system_messages) if preamble: preamble_override = preamble chat_request = CohereChatRequest( apiFormat="COHERE", message=_extract_text_content(user_messages[-1]["content"]), - chatHistory=adapt_messages_to_cohere_standard( - [m for m in messages if m.get("role") != "system"] - ), + chatHistory=adapt_messages_to_cohere_standard([m for m in messages if m.get("role") != "system"]), preambleOverride=preamble_override, **self._get_optional_params(OCIVendors.COHERE, optional_params, model), ) @@ -652,13 +632,9 @@ def transform_response( vendor = get_vendor_from_model(model) if vendor == OCIVendors.COHERE: - model_response = handle_cohere_response( - response_json, model, model_response, raw_response - ) + model_response = handle_cohere_response(response_json, model, model_response, raw_response) else: - model_response = handle_generic_response( - response_json, model, model_response, raw_response - ) + model_response = handle_generic_response(response_json, model, model_response, raw_response) model_response._hidden_params["additional_headers"] = raw_response.headers return model_response @@ -684,11 +660,7 @@ def get_sync_custom_stream_wrapper( response = client.post( api_base, headers=headers, - data=( - signed_json_body - if signed_json_body is not None - else json.dumps(data) - ), + data=(signed_json_body if signed_json_body is not None else json.dumps(data)), stream=True, logging_obj=logging_obj, timeout=STREAMING_TIMEOUT, @@ -727,11 +699,7 @@ async def get_async_custom_stream_wrapper( response = await client.post( api_base, headers=headers, - data=( - signed_json_body - if signed_json_body is not None - else json.dumps(data) - ), + data=(signed_json_body if signed_json_body is not None else json.dumps(data)), stream=True, logging_obj=logging_obj, timeout=STREAMING_TIMEOUT, diff --git a/litellm/llms/oci/common_utils.py b/litellm/llms/oci/common_utils.py index 29c88cbd50fb..4ecbcbfb6569 100644 --- a/litellm/llms/oci/common_utils.py +++ b/litellm/llms/oci/common_utils.py @@ -33,8 +33,7 @@ def _require_cryptography() -> None: if not _CRYPTOGRAPHY_AVAILABLE: raise ImportError( - "cryptography package is required for OCI authentication. " - "Please install it with: pip install cryptography" + "cryptography package is required for OCI authentication. Please install it with: pip install cryptography" ) @@ -65,9 +64,7 @@ class OCISignerProtocol(Protocol): See: https://docs.oracle.com/en-us/iaas/tools/python/latest/api/signing.html """ - def do_request_sign( - self, request: Any, *, enforce_content_headers: bool = False - ) -> None: + def do_request_sign(self, request: Any, *, enforce_content_headers: bool = False) -> None: pass @@ -105,9 +102,7 @@ def sha256_base64(data: bytes) -> str: return base64.b64encode(digest).decode() -def build_signature_string( - method: str, path: str, headers: dict, signed_headers: list -) -> str: +def build_signature_string(method: str, path: str, headers: dict, signed_headers: list) -> str: lines = [] for header in signed_headers: if header == "(request-target)": @@ -125,9 +120,7 @@ def load_private_key_from_str(key_str: str) -> Any: password=None, ) if not isinstance(key, rsa.RSAPrivateKey): # type: ignore[union-attr] - raise TypeError( - "The provided private key is not an RSA key, which is required for OCI signing." - ) + raise TypeError("The provided private key is not an RSA key, which is required for OCI signing.") return key @@ -170,19 +163,13 @@ def resolve_oci_credentials(optional_params: dict) -> dict: oci_key, oci_key_file, oci_compartment_id """ return { - "oci_region": optional_params.get("oci_region") - or os.environ.get(_OCI_REGION_ENV) - or "us-ashburn-1", + "oci_region": optional_params.get("oci_region") or os.environ.get(_OCI_REGION_ENV) or "us-ashburn-1", "oci_user": optional_params.get("oci_user") or os.environ.get(_OCI_USER_ENV), - "oci_fingerprint": optional_params.get("oci_fingerprint") - or os.environ.get(_OCI_FINGERPRINT_ENV), - "oci_tenancy": optional_params.get("oci_tenancy") - or os.environ.get(_OCI_TENANCY_ENV), + "oci_fingerprint": optional_params.get("oci_fingerprint") or os.environ.get(_OCI_FINGERPRINT_ENV), + "oci_tenancy": optional_params.get("oci_tenancy") or os.environ.get(_OCI_TENANCY_ENV), "oci_key": optional_params.get("oci_key") or os.environ.get(_OCI_KEY_ENV), - "oci_key_file": optional_params.get("oci_key_file") - or os.environ.get(_OCI_KEY_FILE_ENV), - "oci_compartment_id": optional_params.get("oci_compartment_id") - or os.environ.get(_OCI_COMPARTMENT_ID_ENV), + "oci_key_file": optional_params.get("oci_key_file") or os.environ.get(_OCI_KEY_FILE_ENV), + "oci_compartment_id": optional_params.get("oci_compartment_id") or os.environ.get(_OCI_COMPARTMENT_ID_ENV), } @@ -205,8 +192,7 @@ def get_oci_base_url(optional_params: dict, api_base: Optional[str] = None) -> s raise OCIError( status_code=400, message=( - f"Invalid OCI region {region!r}: must match " - "^[a-z][a-z0-9-]{0,30}[a-z0-9]$ (e.g. 'us-ashburn-1')." + f"Invalid OCI region {region!r}: must match ^[a-z][a-z0-9-]{{0,30}}[a-z0-9]$ (e.g. 'us-ashburn-1')." ), ) return f"https://inference.generativeai.{region}.oci.oraclecloud.com" @@ -235,9 +221,7 @@ def sign_with_oci_signer( prepared_headers.setdefault("content-type", "application/json") prepared_headers.setdefault("content-length", str(len(body))) - request_wrapper = OCIRequestWrapper( - method=method, url=api_base, headers=prepared_headers, body=body - ) + request_wrapper = OCIRequestWrapper(method=method, url=api_base, headers=prepared_headers, body=body) if oci_signer is None: raise ValueError("oci_signer cannot be None when calling sign_with_oci_signer") @@ -273,12 +257,7 @@ def sign_with_manual_credentials( oci_key = creds["oci_key"] oci_key_file = creds["oci_key_file"] - if ( - not oci_user - or not oci_fingerprint - or not oci_tenancy - or not (oci_key or oci_key_file) - ): + if not oci_user or not oci_fingerprint or not oci_tenancy or not (oci_key or oci_key_file): raise OCIError( status_code=401, message=( @@ -317,9 +296,7 @@ def sign_with_manual_credentials( "content-type", "x-content-sha256", ] - signing_string = build_signature_string( - method, path, headers_to_sign, signed_header_names - ) + signing_string = build_signature_string(method, path, headers_to_sign, signed_header_names) _require_cryptography() @@ -401,9 +378,7 @@ def sign_oci_request( """ if optional_params.get("oci_signer") is not None: return sign_with_oci_signer(headers, optional_params, request_data, api_base) - return sign_with_manual_credentials( - headers, optional_params, request_data, api_base - ) + return sign_with_manual_credentials(headers, optional_params, request_data, api_base) def validate_oci_environment( @@ -485,11 +460,7 @@ def resolve_oci_schema_anyof(obj: Any) -> Any: """ if isinstance(obj, dict): if "anyOf" in obj and "type" not in obj: - non_null = [ - t - for t in obj["anyOf"] - if not (isinstance(t, dict) and t.get("type") == "null") - ] + non_null = [t for t in obj["anyOf"] if not (isinstance(t, dict) and t.get("type") == "null")] if non_null: resolved = {**obj, **non_null[0]} resolved.pop("anyOf", None) @@ -535,18 +506,14 @@ def sanitize_oci_schema(schema: Any) -> Any: properties = sanitized.get("properties") if "required" in sanitized: if isinstance(required, list) and isinstance(properties, dict): - sanitized["required"] = [ - f for f in required if isinstance(f, str) and f in properties - ] + sanitized["required"] = [f for f in required if isinstance(f, str) and f in properties] elif not isinstance(required, list): sanitized["required"] = [] return sanitized -def enrich_cohere_param_description( - description: str, param_schema: Dict[str, Any] -) -> str: +def enrich_cohere_param_description(description: str, param_schema: Dict[str, Any]) -> str: """Embed schema constraints into a Cohere parameter description. ``CohereParameterDefinition`` only has ``type``, ``description``, and diff --git a/litellm/llms/oci/embed/transformation.py b/litellm/llms/oci/embed/transformation.py index 6cfa85b4bc4d..44f5d941db4f 100644 --- a/litellm/llms/oci/embed/transformation.py +++ b/litellm/llms/oci/embed/transformation.py @@ -226,9 +226,7 @@ def transform_embedding_request( if serving_mode_type == "DEDICATED": endpoint_id = optional_params.get("oci_endpoint_id", model) - serving_mode = OCIServingMode( - servingType="DEDICATED", endpointId=endpoint_id - ) + serving_mode = OCIServingMode(servingType="DEDICATED", endpointId=endpoint_id) else: serving_mode = OCIServingMode(servingType="ON_DEMAND", modelId=model) diff --git a/litellm/llms/ollama/chat/transformation.py b/litellm/llms/ollama/chat/transformation.py index 5c0624fe5c98..3152ded23679 100644 --- a/litellm/llms/ollama/chat/transformation.py +++ b/litellm/llms/ollama/chat/transformation.py @@ -172,17 +172,9 @@ def map_openai_params( optional_params["repeat_penalty"] = value if param == "stop": optional_params["stop"] = value - if ( - param == "response_format" - and isinstance(value, dict) - and value.get("type") == "json_object" - ): + if param == "response_format" and isinstance(value, dict) and value.get("type") == "json_object": optional_params["format"] = "json" - if ( - param == "response_format" - and isinstance(value, dict) - and value.get("type") == "json_schema" - ): + if param == "response_format" and isinstance(value, dict) and value.get("type") == "json_schema": if value.get("json_schema") and value["json_schema"].get("schema"): optional_params["format"] = value["json_schema"]["schema"] if param == "reasoning_effort" and value is not None: @@ -281,9 +273,7 @@ def transform_request( ) ) new_tools.append(ollama_tool_call) - reasoning_content, parsed_content = _extract_reasoning_content( - cast(dict, m) - ) + reasoning_content, parsed_content = _extract_reasoning_content(cast(dict, m)) content_str = convert_content_list_to_str(cast(AllMessageValues, m)) images = extract_images_from_message(cast(AllMessageValues, m)) @@ -361,9 +351,7 @@ def transform_response( if response_json_message is not None: if "thinking" in response_json_message: # remap 'thinking' to 'reasoning_content' - response_json_message["reasoning_content"] = response_json_message[ - "thinking" - ] + response_json_message["reasoning_content"] = response_json_message["thinking"] del response_json_message["thinking"] elif response_json_message.get("content") is not None: # parse reasoning content from content @@ -371,16 +359,11 @@ def transform_response( _parse_content_for_reasoning, ) - reasoning_content, content = _parse_content_for_reasoning( - response_json_message["content"] - ) + reasoning_content, content = _parse_content_for_reasoning(response_json_message["content"]) response_json_message["reasoning_content"] = reasoning_content response_json_message["content"] = content - if ( - request_data.get("format", "") == "json" - and litellm_params.get("function_name") is not None - ): + if request_data.get("format", "") == "json" and litellm_params.get("function_name") is not None: function_call = json.loads(response_json_message["content"]) message = litellm.Message( content=None, @@ -388,12 +371,8 @@ def transform_response( { "id": f"call_{str(uuid.uuid4())}", "function": { - "name": function_call.get( - "name", litellm_params.get("function_name") - ), - "arguments": json.dumps( - function_call.get("arguments", function_call) - ), + "name": function_call.get("name", litellm_params.get("function_name")), + "arguments": json.dumps(function_call.get("arguments", function_call)), }, "type": "function", } @@ -411,9 +390,7 @@ def transform_response( model_response.choices[0].finish_reason = "tool_calls" model_response.created = int(time.time()) model_response.model = "ollama_chat/" + model - prompt_tokens = response_json.get( - "prompt_eval_count", litellm.token_counter(messages=messages) - ) # type: ignore + prompt_tokens = response_json.get("prompt_eval_count", litellm.token_counter(messages=messages)) # type: ignore completion_tokens = response_json.get( "eval_count", litellm.token_counter(text=response_json["message"]["content"]), @@ -429,12 +406,8 @@ def transform_response( ) return model_response - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return OllamaError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return OllamaError(status_code=status_code, message=error_message, headers=headers) def get_model_response_iterator( self, @@ -500,9 +473,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: for tool_call in tool_calls: function_args = tool_call.get("function").get("arguments") if function_args is not None and len(function_args) > 0: - is_function_call_complete = self._is_function_call_complete( - function_args - ) + is_function_call_complete = self._is_function_call_complete(function_args) if is_function_call_complete: tool_call["id"] = str(uuid.uuid4()) @@ -513,10 +484,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: reasoning_content = chunk["message"].get("thinking") self.started_reasoning_content = True if chunk["message"].get("content"): - if ( - self.started_reasoning_content - and not self.finished_reasoning_content - ): + if self.started_reasoning_content and not self.finished_reasoning_content: self.finished_reasoning_content = True message_content = chunk["message"].get("content") @@ -529,10 +497,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: message_content = message_content.replace("", "") self.finished_reasoning_content = True - if ( - self.started_reasoning_content - and not self.finished_reasoning_content - ): + if self.started_reasoning_content and not self.finished_reasoning_content: reasoning_content = message_content else: content = message_content @@ -565,8 +530,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: usage = ChatCompletionUsageBlock( prompt_tokens=chunk.get("prompt_eval_count", 0), completion_tokens=chunk.get("eval_count", 0), - total_tokens=chunk.get("prompt_eval_count", 0) - + chunk.get("eval_count", 0), + total_tokens=chunk.get("prompt_eval_count", 0) + chunk.get("eval_count", 0), ) return ModelResponseStream( diff --git a/litellm/llms/ollama/common_utils.py b/litellm/llms/ollama/common_utils.py index 7d52ef14dd95..21ff3612a49f 100644 --- a/litellm/llms/ollama/common_utils.py +++ b/litellm/llms/ollama/common_utils.py @@ -7,9 +7,7 @@ class OllamaError(BaseLLMException): - def __init__( - self, status_code: int, message: str, headers: Union[dict, httpx.Headers] - ): + def __init__(self, status_code: int, message: str, headers: Union[dict, httpx.Headers]): super().__init__(status_code=status_code, message=message, headers=headers) @@ -27,9 +25,7 @@ def _convert_image(image): try: from PIL import Image except Exception: - raise Exception( - "ollama image conversion failed please run `pip install Pillow`" - ) + raise Exception("ollama image conversion failed please run `pip install Pillow`") orig = image if image.startswith("data:"): @@ -101,9 +97,7 @@ def get_models(self, api_key=None, api_base: Optional[str] = None) -> List[str]: passed_api_base = api_base base = self.get_server_api_base(api_base) - api_key = ( - self.get_api_key(api_key) if passed_api_base is None or api_key else None - ) + api_key = self.get_api_key(api_key) if passed_api_base is None or api_key else None headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} names: set[str] = set() @@ -113,11 +107,7 @@ def get_models(self, api_key=None, api_base: Optional[str] = None) -> List[str]: data = resp.json() # Expecting a dict with a 'models' list models_list = [] - if ( - isinstance(data, dict) - and "models" in data - and isinstance(data["models"], list) - ): + if isinstance(data, dict) and "models" in data and isinstance(data["models"], list): models_list = data["models"] elif isinstance(data, list): models_list = data @@ -137,9 +127,7 @@ def get_models(self, api_key=None, api_base: Optional[str] = None) -> List[str]: static = models_by_provider.get("ollama", []) or [] return [f"ollama/{m}" for m in static] except Exception as e1: - verbose_logger.warning( - f"Error retrieving static ollama models as fallback: {e1}" - ) + verbose_logger.warning(f"Error retrieving static ollama models as fallback: {e1}") return [] # assemble full model names result = sorted(names) @@ -190,9 +178,7 @@ def get_runtime_model_info( model = self._strip_ollama_model_prefix(model) passed_api_base = api_base api_base = self.get_server_api_base(api_base) - api_key = ( - self.get_api_key(api_key) if passed_api_base is None or api_key else None - ) + api_key = self.get_api_key(api_key) if passed_api_base is None or api_key else None headers = {"Authorization": f"Bearer {api_key}"} if api_key else {} try: @@ -238,9 +224,7 @@ def get_model_info( ) -> Optional[dict[str, Any]]: if self._is_static_ollama_model(model): return None - return self.get_runtime_model_info( - model=model, api_base=api_base, api_key=api_key - ) + return self.get_runtime_model_info(model=model, api_base=api_base, api_key=api_key) def validate_environment( self, diff --git a/litellm/llms/ollama/completion/handler.py b/litellm/llms/ollama/completion/handler.py index 97e4f13b5606..7f229be53ae1 100644 --- a/litellm/llms/ollama/completion/handler.py +++ b/litellm/llms/ollama/completion/handler.py @@ -46,15 +46,11 @@ def _process_ollama_embedding_response( if encoding is not None: input_tokens = len(encoding.encode("".join(prompts))) if logging_obj: - logging_obj.debug( - "Ollama response missing prompt_eval_count; estimated with encoding." - ) + logging_obj.debug("Ollama response missing prompt_eval_count; estimated with encoding.") else: input_tokens = 0 if logging_obj: - logging_obj.warning( - "Missing prompt_eval_count and no encoding provided; defaulted to 0." - ) + logging_obj.warning("Missing prompt_eval_count and no encoding provided; defaulted to 0.") model_response.object = "list" model_response.data = output_data diff --git a/litellm/llms/ollama/completion/transformation.py b/litellm/llms/ollama/completion/transformation.py index a8cdbff87d04..204b0d15c03d 100644 --- a/litellm/llms/ollama/completion/transformation.py +++ b/litellm/llms/ollama/completion/transformation.py @@ -91,9 +91,7 @@ class OllamaConfig(BaseConfig): repeat_penalty: Optional[float] = None temperature: Optional[float] = None seed: Optional[int] = None - stop: Optional[list] = ( - None # stop is a list based on this - https://github.com/ollama/ollama/pull/442 - ) + stop: Optional[list] = None # stop is a list based on this - https://github.com/ollama/ollama/pull/442 tfs_z: Optional[float] = None num_predict: Optional[int] = None top_k: Optional[int] = None @@ -232,16 +230,10 @@ def get_model_info( "name": "mistral" }' """ - return OllamaModelInfo().get_model_info( - model=model, api_base=api_base, api_key=api_key - ) + return OllamaModelInfo().get_model_info(model=model, api_base=api_base, api_key=api_key) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return OllamaError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return OllamaError(status_code=status_code, message=error_message, headers=headers) def transform_response( self, @@ -292,9 +284,7 @@ def transform_response( "id": f"call_{str(uuid.uuid4())}", "function": { "name": function_call["name"], - "arguments": json.dumps( - function_call["arguments"] - ), + "arguments": json.dumps(function_call["arguments"]), }, "type": "function", } @@ -315,12 +305,8 @@ def transform_response( reasoning_content: Optional[str] = None content: Optional[str] = None if response_text is not None: - reasoning_content, content = _parse_content_for_reasoning( - response_text - ) - message = litellm.Message( - content=content, reasoning_content=reasoning_content - ) + reasoning_content, content = _parse_content_for_reasoning(response_text) + message = litellm.Message(content=content, reasoning_content=reasoning_content) model_response.choices[0].message = message # type: ignore model_response.choices[0].finish_reason = "stop" else: @@ -362,9 +348,7 @@ def transform_request( litellm_params: dict, headers: dict, ) -> dict: - custom_prompt_dict = ( - litellm_params.get("custom_prompt_dict") or litellm.custom_prompt_dict - ) + custom_prompt_dict = litellm_params.get("custom_prompt_dict") or litellm.custom_prompt_dict text_completion_request = litellm_params.get("text_completion") if model in custom_prompt_dict: @@ -402,9 +386,7 @@ def transform_request( if format is not None: data["format"] = format if images is not None: - data["images"] = [ - _convert_image(convert_to_ollama_image(image)) for image in images - ] + data["images"] = [_convert_image(convert_to_ollama_image(image)) for image in images] if think is not None: data["think"] = think @@ -461,21 +443,15 @@ def get_model_response_iterator( class OllamaTextCompletionResponseIterator(BaseModelResponseIterator): - def __init__( - self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False - ): + def __init__(self, streaming_response, sync_stream: bool, json_mode: Optional[bool] = False): super().__init__(streaming_response, sync_stream, json_mode) self.started_reasoning_content: bool = False self.finished_reasoning_content: bool = False - def _handle_string_chunk( - self, str_line: str - ) -> Union[GenericStreamingChunk, ModelResponseStream]: + def _handle_string_chunk(self, str_line: str) -> Union[GenericStreamingChunk, ModelResponseStream]: return self.chunk_parser(json.loads(str_line)) - def chunk_parser( - self, chunk: dict - ) -> Union[GenericStreamingChunk, ModelResponseStream]: + def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]: try: if "error" in chunk: raise Exception(f"Ollama Error - {chunk}") @@ -515,10 +491,7 @@ def chunk_parser( text = text.replace("", "") self.finished_reasoning_content = True - if ( - self.started_reasoning_content - and not self.finished_reasoning_content - ): + if self.started_reasoning_content and not self.finished_reasoning_content: reasoning_content = text else: content = text @@ -527,9 +500,7 @@ def chunk_parser( choices=[ StreamingChoices( index=0, - delta=Delta( - reasoning_content=reasoning_content, content=content - ), + delta=Delta(reasoning_content=reasoning_content, content=content), ) ], finish_reason=finish_reason, diff --git a/litellm/llms/oobabooga/chat/oobabooga.py b/litellm/llms/oobabooga/chat/oobabooga.py index 5eb68a03d4bd..fe2bb9dc6d14 100644 --- a/litellm/llms/oobabooga/chat/oobabooga.py +++ b/litellm/llms/oobabooga/chat/oobabooga.py @@ -113,9 +113,7 @@ def embedding( # Logging before API call if logging_obj: - logging_obj.pre_call( - input=input, api_key=api_key, additional_args={"complete_input_dict": data} - ) + logging_obj.pre_call(input=input, api_key=api_key, additional_args={"complete_input_dict": data}) # Send POST request headers = oobabooga_config.validate_environment( @@ -126,9 +124,7 @@ def embedding( optional_params=optional_params, litellm_params={}, ) - response = litellm.module_level_client.post( - embeddings_url, headers=headers, json=data - ) + response = litellm.module_level_client.post(embeddings_url, headers=headers, json=data) completion_response = response.json() # Check for errors in response diff --git a/litellm/llms/oobabooga/chat/transformation.py b/litellm/llms/oobabooga/chat/transformation.py index 0c118efbc359..608fbc5cb35f 100644 --- a/litellm/llms/oobabooga/chat/transformation.py +++ b/litellm/llms/oobabooga/chat/transformation.py @@ -25,9 +25,7 @@ def get_error_class( status_code: int, headers: Optional[Union[dict, httpx.Headers]] = None, ) -> BaseLLMException: - return OobaboogaError( - status_code=status_code, message=error_message, headers=headers - ) + return OobaboogaError(status_code=status_code, message=error_message, headers=headers) def transform_response( self, @@ -55,9 +53,7 @@ def transform_response( try: completion_response = raw_response.json() except Exception: - raise OobaboogaError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OobaboogaError(message=raw_response.text, status_code=raw_response.status_code) if "error" in completion_response: raise OobaboogaError( message=completion_response["error"], @@ -65,9 +61,7 @@ def transform_response( ) else: try: - model_response.choices[0].message.content = completion_response[ - "choices" - ][0]["message"]["content"] # type: ignore + model_response.choices[0].message.content = completion_response["choices"][0]["message"]["content"] # type: ignore except Exception as e: raise OobaboogaError( message=str(e), diff --git a/litellm/llms/openai/chat/gpt_5_transformation.py b/litellm/llms/openai/chat/gpt_5_transformation.py index 9ccb2e1c267f..f0a859deba04 100644 --- a/litellm/llms/openai/chat/gpt_5_transformation.py +++ b/litellm/llms/openai/chat/gpt_5_transformation.py @@ -129,9 +129,7 @@ def _supports_reasoning_effort_level(cls, model: str, level: str) -> bool: ) @classmethod - def _is_reasoning_effort_level_explicitly_disabled( - cls, model: str, level: str - ) -> bool: + def _is_reasoning_effort_level_explicitly_disabled(cls, model: str, level: str) -> bool: """Return True only when the model map explicitly sets the capability to False. Unlike ``_supports_reasoning_effort_level`` (which requires an explicit True), @@ -188,11 +186,7 @@ def get_supported_openai_params(self, model: str) -> list: if not self._supports_reasoning_effort_level(model, "none"): non_supported_params.extend(["logprobs", "top_p", "top_logprobs"]) - return [ - param - for param in base_gpt_series_params - if param not in non_supported_params - ] + return [param for param in base_gpt_series_params if param not in non_supported_params] def map_openai_params( self, @@ -203,9 +197,7 @@ def map_openai_params( ) -> dict: if self.is_model_gpt_5_search_model(model): if "max_tokens" in non_default_params: - optional_params["max_completion_tokens"] = non_default_params.pop( - "max_tokens" - ) + optional_params["max_completion_tokens"] = non_default_params.pop("max_tokens") return super()._map_openai_params( non_default_params=non_default_params, optional_params=optional_params, @@ -217,17 +209,13 @@ def map_openai_params( # Use effective_effort (extracted string) for xhigh validation, "none" checks, and # tool/sampling guards — dict inputs like {"effort": "none", "summary": "detailed"} # must be treated as effort="none" to avoid incorrect tool-drop or sampling errors. - raw_reasoning_effort = non_default_params.get( - "reasoning_effort" - ) or optional_params.get("reasoning_effort") + raw_reasoning_effort = non_default_params.get("reasoning_effort") or optional_params.get("reasoning_effort") effective_effort = _get_effort_level(raw_reasoning_effort) # Normalize dict reasoning_effort to string for Chat Completions API. # Example: {"effort": "high", "summary": "detailed"} -> "high" if isinstance(raw_reasoning_effort, dict) and "effort" in raw_reasoning_effort: - normalized = _normalize_reasoning_effort_for_chat_completion( - raw_reasoning_effort - ) + normalized = _normalize_reasoning_effort_for_chat_completion(raw_reasoning_effort) if normalized is not None: if "reasoning_effort" in non_default_params: non_default_params["reasoning_effort"] = normalized @@ -242,9 +230,7 @@ def map_openai_params( optional_params.pop("reasoning_effort", None) else: raise litellm.utils.UnsupportedParamsError( - message=( - f"reasoning_effort={effective_effort} is not supported for this model." - ), + message=(f"reasoning_effort={effective_effort} is not supported for this model."), status_code=400, ) elif effective_effort in ("minimal", "low"): @@ -252,17 +238,13 @@ def map_openai_params( # the model map explicitly sets supports_{level}_reasoning_effort=false. # Example: gpt-5.5-pro only accepts {medium, high, xhigh}, so it sets # supports_low_reasoning_effort=false (and supports_minimal=false). - if self._is_reasoning_effort_level_explicitly_disabled( - model, effective_effort - ): + if self._is_reasoning_effort_level_explicitly_disabled(model, effective_effort): if litellm.drop_params or drop_params: non_default_params.pop("reasoning_effort", None) optional_params.pop("reasoning_effort", None) else: raise litellm.utils.UnsupportedParamsError( - message=( - f"reasoning_effort={effective_effort} is not supported for this model." - ), + message=(f"reasoning_effort={effective_effort} is not supported for this model."), status_code=400, ) @@ -271,9 +253,7 @@ def map_openai_params( # Relevant issue: https://github.com/BerriAI/litellm/issues/13381 ################################################################ if "max_tokens" in non_default_params: - optional_params["max_completion_tokens"] = non_default_params.pop( - "max_tokens" - ) + optional_params["max_completion_tokens"] = non_default_params.pop("max_tokens") # gpt-5.1/5.2 support logprobs, top_p, top_logprobs only when reasoning_effort="none" supports_none = self._supports_reasoning_effort_level(model, "none") @@ -298,9 +278,7 @@ def map_openai_params( temperature_value: Optional[float] = non_default_params.pop("temperature") if temperature_value is not None: # models supporting reasoning_effort="none" also support flexible temperature - if supports_none and ( - effective_effort == "none" or effective_effort is None - ): + if supports_none and (effective_effort == "none" or effective_effort is None): optional_params["temperature"] = temperature_value elif temperature_value == 1: optional_params["temperature"] = temperature_value diff --git a/litellm/llms/openai/chat/gpt_transformation.py b/litellm/llms/openai/chat/gpt_transformation.py index e4d554047434..396ad5b105e5 100644 --- a/litellm/llms/openai/chat/gpt_transformation.py +++ b/litellm/llms/openai/chat/gpt_transformation.py @@ -172,15 +172,11 @@ def get_supported_openai_params(self, model: str) -> list: ] # works across all models model_specific_params = [] - if ( - model != "gpt-3.5-turbo-16k" and model != "gpt-4" - ): # gpt-4 does not support 'response_format' + if model != "gpt-3.5-turbo-16k" and model != "gpt-4": # gpt-4 does not support 'response_format' model_specific_params.append("response_format") # Normalize model name for responses API (e.g., "responses/gpt-4.1" -> "gpt-4.1") - model_for_check = ( - model.split("responses/", 1)[1] if "responses/" in model else model - ) + model_for_check = model.split("responses/", 1)[1] if "responses/" in model else model if ( model_for_check in litellm.open_ai_chat_completion_models ) or model_for_check in litellm.open_ai_text_completion_models: @@ -230,15 +226,11 @@ def map_openai_params( def contains_pdf_url(self, content_item: ChatCompletionFileObjectFile) -> bool: potential_pdf_url_starts = ["https://", "http://", "www."] file_id = content_item.get("file_id") - if file_id and any( - file_id.startswith(start) for start in potential_pdf_url_starts - ): + if file_id and any(file_id.startswith(start) for start in potential_pdf_url_starts): return True return False - def _handle_pdf_url( - self, content_item: ChatCompletionFileObjectFile - ) -> ChatCompletionFileObjectFile: + def _handle_pdf_url(self, content_item: ChatCompletionFileObjectFile) -> ChatCompletionFileObjectFile: content_copy = content_item.copy() file_id = content_copy.get("file_id") if file_id is not None: @@ -248,9 +240,7 @@ def _handle_pdf_url( content_copy.pop("file_id") return content_copy - async def _async_handle_pdf_url( - self, content_item: ChatCompletionFileObjectFile - ) -> ChatCompletionFileObjectFile: + async def _async_handle_pdf_url(self, content_item: ChatCompletionFileObjectFile) -> ChatCompletionFileObjectFile: file_id = content_item.get("file_id") if file_id is not None: # check for file id being url done in _handle_pdf_url base64_data = await async_convert_url_to_base64(file_id) @@ -259,9 +249,7 @@ async def _async_handle_pdf_url( content_item.pop("file_id") return content_item - def _common_file_data_check( - self, content_item: ChatCompletionFileObjectFile - ) -> ChatCompletionFileObjectFile: + def _common_file_data_check(self, content_item: ChatCompletionFileObjectFile) -> ChatCompletionFileObjectFile: file_data = content_item.get("file_data") filename = content_item.get("filename") if file_data is not None and filename is None: @@ -282,9 +270,7 @@ def _apply_common_transform_content_item( elif isinstance(content_item["image_url"], dict): new_image_url_obj = ChatCompletionImageUrlObject( **{ # type: ignore - k: v - for k, v in content_item["image_url"].items() - if k not in litellm_specific_params + k: v for k, v in content_item["image_url"].items() if k not in litellm_specific_params } ) content_item["image_url"] = new_image_url_obj @@ -299,9 +285,7 @@ def _apply_common_transform_content_item( ) new_file_obj = ChatCompletionFileObjectFile( **{ # type: ignore - k: v - for k, v in file_obj.items() - if k not in litellm_specific_params + k: v for k, v in file_obj.items() if k not in litellm_specific_params } ) content_item["file"] = new_file_obj @@ -370,18 +354,10 @@ async def _async_transform(): message_content = message.get("content") message_role = message.get("role") - if ( - message_role == "user" - and message_content - and isinstance(message_content, list) - ): - message_content_types = cast( - List[OpenAIMessageContentListBlock], message_content - ) + if message_role == "user" and message_content and isinstance(message_content, list): + message_content_types = cast(List[OpenAIMessageContentListBlock], message_content) for i, content_item in enumerate(message_content_types): - message_content_types[ - i - ] = await self._async_transform_content_item( + message_content_types[i] = await self._async_transform_content_item( cast(OpenAIMessageContentListBlock, content_item), ) return messages @@ -392,14 +368,8 @@ async def _async_transform(): for message in messages: message_content = message.get("content") message_role = message.get("role") - if ( - message_role == "user" - and message_content - and isinstance(message_content, list) - ): - message_content_types = cast( - List[OpenAIMessageContentListBlock], message_content - ) + if message_role == "user" and message_content and isinstance(message_content, list): + message_content_types = cast(List[OpenAIMessageContentListBlock], message_content) for i, content_item in enumerate(message_content): message_content_types[i] = self._transform_content_item( cast(OpenAIMessageContentListBlock, content_item) @@ -443,12 +413,7 @@ def _should_preserve_cache_control_for_endpoint( """ if custom_llm_provider != "openai": return False - resolved_api_base = ( - api_base - or litellm.api_base - or os.getenv("OPENAI_BASE_URL") - or os.getenv("OPENAI_API_BASE") - ) + resolved_api_base = api_base or litellm.api_base or os.getenv("OPENAI_BASE_URL") or os.getenv("OPENAI_API_BASE") if not resolved_api_base: return False hostname = urlparse(resolved_api_base).hostname @@ -496,9 +461,7 @@ async def async_transform_request( litellm_params: dict, headers: dict, ) -> dict: - transformed_messages = await self._transform_messages( - messages=messages, model=model, is_async=True - ) + transformed_messages = await self._transform_messages(messages=messages, model=model, is_async=True) if not self._should_preserve_cache_control_for_endpoint( litellm_params.get("custom_llm_provider"), litellm_params.get("api_base") ): @@ -520,9 +483,7 @@ async def async_transform_request( } else: ## allow for any object specific behaviour to be handled - return self.transform_request( - model, messages, optional_params, litellm_params, headers - ) + return self.transform_request(model, messages, optional_params, litellm_params, headers) def _passed_in_tools(self, optional_params: dict) -> bool: return optional_params.get("tools", None) is not None @@ -540,10 +501,7 @@ def _check_and_fix_if_content_is_tool_call( tool_call_names = get_tool_call_names(optional_params.get("tools", [])) try: json_content = json.loads(content) - if ( - json_content.get("type") == "function" - and json_content.get("name") in tool_call_names - ): + if json_content.get("type") == "function" and json_content.get("name") in tool_call_names: return ChatCompletionMessageToolCall( function=Function( name=json_content.get("name"), @@ -579,20 +537,12 @@ def _transform_choices( for _tc in tool_calls: _openai_tc = ChatCompletionMessageToolCall(**_tc) # type: ignore _openai_tool_calls.append(_openai_tc) - fixed_tool_calls = _handle_invalid_parallel_tool_calls( - _openai_tool_calls - ) + fixed_tool_calls = _handle_invalid_parallel_tool_calls(_openai_tool_calls) if fixed_tool_calls is not None: new_tool_calls = fixed_tool_calls - elif ( - optional_params is not None - and message_content - and isinstance(message_content, str) - ): - new_tool_call = self._check_and_fix_if_content_is_tool_call( - message_content, optional_params - ) + elif optional_params is not None and message_content and isinstance(message_content, str): + new_tool_call = self._check_and_fix_if_content_is_tool_call(message_content, optional_params) if new_tool_call is not None: choice["message"]["content"] = None # remove the content new_tool_calls = [new_tool_call] @@ -604,9 +554,7 @@ def _transform_choices( convert_tool_call_to_json_mode=json_mode, ): # to support response_format on claude models - json_mode_content_str: Optional[str] = ( - str(new_tool_calls[0]["function"].get("arguments", "")) or None - ) + json_mode_content_str: Optional[str] = str(new_tool_calls[0]["function"].get("arguments", "")) or None if json_mode_content_str is not None: translated_message = Message(content=json_mode_content_str) finish_reason = "stop" @@ -679,9 +627,7 @@ def transform_response( except Exception as e: response_headers = getattr(raw_response, "headers", None) raise OpenAIError( - message="Unable to get json response - {}, Original Response: {}".format( - str(e), raw_response.text - ), + message="Unable to get json response - {}, Original Response: {}".format(str(e), raw_response.text), status_code=raw_response.status_code, headers=response_headers, ) @@ -751,9 +697,7 @@ def validate_environment( return headers - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: """ Calls OpenAI's `/v1/models` endpoint and returns the list of models. """ @@ -782,12 +726,7 @@ def get_models( @staticmethod def get_api_key(api_key: Optional[str] = None) -> Optional[str]: - return ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + return api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") @staticmethod def get_api_base(api_base: Optional[str] = None) -> Optional[str]: diff --git a/litellm/llms/openai/chat/guardrail_translation/handler.py b/litellm/llms/openai/chat/guardrail_translation/handler.py index 3b5980023c77..c7a49a2e47f7 100644 --- a/litellm/llms/openai/chat/guardrail_translation/handler.py +++ b/litellm/llms/openai/chat/guardrail_translation/handler.py @@ -107,13 +107,9 @@ async def process_input_messages( structured_messages = self.get_structured_messages(data) if structured_messages: if skip_system: - structured_messages = openai_messages_without_system( - structured_messages - ) + structured_messages = openai_messages_without_system(structured_messages) if skip_tool: - structured_messages = openai_messages_without_tool( - structured_messages - ) + structured_messages = openai_messages_without_tool(structured_messages) inputs["structured_messages"] = structured_messages # Pass tools (function definitions) to the guardrail tools = data.get("tools") @@ -124,6 +120,7 @@ async def process_input_messages( if model: inputs["model"] = model + original_structured_messages = inputs.get("structured_messages") guardrailed_inputs = await guardrail_to_apply.apply_guardrail( inputs=inputs, request_data=data, @@ -137,26 +134,32 @@ async def process_input_messages( if guardrailed_tools is not None: data["tools"] = guardrailed_tools - # Step 3: Map guardrail responses back to original message structure - if guardrailed_texts and texts_to_check: - await self._apply_guardrail_responses_to_input_texts( - messages=messages, - responses=guardrailed_texts, - task_mappings=text_task_mappings, - ) + guardrailed_structured_messages = guardrailed_inputs.get("structured_messages") + if ( + guardrailed_structured_messages is not None + and guardrailed_structured_messages is not original_structured_messages + ): + data["messages"] = guardrailed_structured_messages + else: + # Step 3: Map guardrail responses back to original message structure + if guardrailed_texts and texts_to_check: + await self._apply_guardrail_responses_to_input_texts( + messages=messages, + responses=guardrailed_texts, + task_mappings=text_task_mappings, + ) - # Step 4: Apply guardrailed tool calls back to messages - if guardrailed_tool_calls: - # Note: The guardrail may modify tool_calls_to_check in place - # or we may need to handle returned tool calls differently - await self._apply_guardrail_responses_to_input_tool_calls( - messages=messages, - tool_calls=guardrailed_tool_calls, # type: ignore - task_mappings=tool_call_task_mappings, - ) + # Step 4: Apply guardrailed tool calls back to messages + if guardrailed_tool_calls: + await self._apply_guardrail_responses_to_input_tool_calls( + messages=messages, + tool_calls=guardrailed_tool_calls, # type: ignore + task_mappings=tool_call_task_mappings, + ) verbose_proxy_logger.debug( - "OpenAI Chat Completions: Processed input messages: %s", messages + "OpenAI Chat Completions: Processed input messages: %s", + data.get("messages"), ) return data @@ -259,9 +262,7 @@ async def _apply_guardrail_responses_to_input_texts( elif isinstance(content, list) and content_idx_optional is not None: # Replace specific text item in list content - messages[msg_idx]["content"][content_idx_optional]["text"] = ( - guardrail_response - ) + messages[msg_idx]["content"][content_idx_optional]["text"] = guardrail_response async def _apply_guardrail_responses_to_input_tool_calls( self, @@ -281,9 +282,7 @@ async def _apply_guardrail_responses_to_input_tool_calls( if task_idx < len(tool_calls): guardrailed_tool_call = tool_calls[task_idx] message_tool_calls = messages[msg_idx].get("tool_calls", None) - if message_tool_calls is not None and isinstance( - message_tool_calls, list - ): + if message_tool_calls is not None and isinstance(message_tool_calls, list): if tool_call_idx < len(message_tool_calls): # Replace the tool call with the guardrailed version message_tool_calls[tool_call_idx] = guardrailed_tool_call @@ -315,9 +314,7 @@ async def process_output_response( # Step 0: Check if response has any text content to process if not self._has_text_content(response): - verbose_proxy_logger.warning( - "OpenAI Chat Completions: No text content in response, skipping guardrail" - ) + verbose_proxy_logger.warning("OpenAI Chat Completions: No text content in response, skipping guardrail") return response texts_to_check: List[str] = [] @@ -353,9 +350,7 @@ async def process_output_response( # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata @@ -379,8 +374,7 @@ async def process_output_response( returned_tool_calls = guardrailed_inputs.get("tool_calls") guardrailed_tool_calls: List[Dict[str, Any]] = ( cast(List[Dict[str, Any]], returned_tool_calls) - if isinstance(returned_tool_calls, list) - and len(returned_tool_calls) == len(tool_calls_to_check) + if isinstance(returned_tool_calls, list) and len(returned_tool_calls) == len(tool_calls_to_check) else tool_calls_to_check ) @@ -400,9 +394,7 @@ async def process_output_response( task_mappings=tool_call_task_mappings, ) - verbose_proxy_logger.debug( - "OpenAI Chat Completions: Processed output response: %s", response - ) + verbose_proxy_logger.debug("OpenAI Chat Completions: Processed output response: %s", response) return response @@ -441,9 +433,7 @@ async def process_output_streaming_response( # convert to model response model_response = cast( ModelResponse, - stream_chunk_builder( - chunks=responses_so_far, logging_obj=litellm_logging_obj - ), + stream_chunk_builder(chunks=responses_so_far, logging_obj=litellm_logging_obj), ) # run process_output_response await self.process_output_response( @@ -496,9 +486,7 @@ async def process_output_streaming_response( # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata @@ -506,11 +494,7 @@ async def process_output_streaming_response( if images_to_check: inputs["images"] = images_to_check # Include model information from the first response if available - if ( - responses_so_far - and hasattr(responses_so_far[0], "model") - and responses_so_far[0].model - ): + if responses_so_far and hasattr(responses_so_far[0], "model") and responses_so_far[0].model: inputs["model"] = responses_so_far[0].model guardrailed_inputs = await guardrail_to_apply.apply_guardrail( inputs=inputs, @@ -586,9 +570,7 @@ def _combine_streaming_texts( return combined_texts - def _has_text_content( - self, response: Union["ModelResponse", "ModelResponseStream"] - ) -> bool: + def _has_text_content(self, response: Union["ModelResponse", "ModelResponseStream"]) -> bool: """ Check if response has any text content or tool calls to process. @@ -600,28 +582,20 @@ def _has_text_content( for choice in response.choices: if isinstance(choice, litellm.Choices): # Check for text content - if choice.message.content and isinstance( - choice.message.content, str - ): + if choice.message.content and isinstance(choice.message.content, str): return True # Check for tool calls - if choice.message.tool_calls and isinstance( - choice.message.tool_calls, list - ): + if choice.message.tool_calls and isinstance(choice.message.tool_calls, list): if len(choice.message.tool_calls) > 0: return True elif isinstance(response, ModelResponseStream): for streaming_choice in response.choices: if isinstance(streaming_choice, litellm.StreamingChoices): # Check for text content - if streaming_choice.delta.content and isinstance( - streaming_choice.delta.content, str - ): + if streaming_choice.delta.content and isinstance(streaming_choice.delta.content, str): return True # Check for tool calls - if streaming_choice.delta.tool_calls and isinstance( - streaming_choice.delta.tool_calls, list - ): + if streaming_choice.delta.tool_calls and isinstance(streaming_choice.delta.tool_calls, list): if len(streaming_choice.delta.tool_calls) > 0: return True return False @@ -641,9 +615,7 @@ def _extract_output_text_images_and_tool_calls( Override this method to customize text/image/tool call extraction logic. """ - verbose_proxy_logger.debug( - "OpenAI Chat Completions: Processing choice: %s", choice - ) + verbose_proxy_logger.debug("OpenAI Chat Completions: Processing choice: %s", choice) # Determine content source and tool calls based on choice type content = None @@ -690,9 +662,7 @@ def _extract_output_text_images_and_tool_calls( tool_calls_to_check.append(tool_call_dict) tool_call_task_mappings.append((choice_idx, int(tool_call_idx))) - def _convert_tool_call_to_dict( - self, tool_call: Union[Dict[str, Any], Any] - ) -> Optional[Dict[str, Any]]: + def _convert_tool_call_to_dict(self, tool_call: Union[Dict[str, Any], Any]) -> Optional[Dict[str, Any]]: """ Convert a tool call object to dictionary format. @@ -746,9 +716,7 @@ async def _apply_guardrail_responses_to_output_texts( elif isinstance(content, list) and content_idx_optional is not None: # Replace specific text item in list content - choice.message.content[content_idx_optional]["text"] = ( - guardrail_response # type: ignore - ) + choice.message.content[content_idx_optional]["text"] = guardrail_response # type: ignore async def _apply_guardrail_responses_to_output_tool_calls( self, @@ -771,9 +739,7 @@ async def _apply_guardrail_responses_to_output_tool_calls( choice = cast(Choices, response.choices[choice_idx]) choice_tool_calls = choice.message.tool_calls - if choice_tool_calls is not None and isinstance( - choice_tool_calls, list - ): + if choice_tool_calls is not None and isinstance(choice_tool_calls, list): if tool_call_idx < len(choice_tool_calls): # Update the tool call with guardrailed version existing_tool_call = choice_tool_calls[tool_call_idx] @@ -781,9 +747,7 @@ async def _apply_guardrail_responses_to_output_tool_calls( if "function" in guardrailed_tool_call: func_dict = guardrailed_tool_call["function"] if "arguments" in func_dict: - existing_tool_call.function.arguments = func_dict[ - "arguments" - ] + existing_tool_call.function.arguments = func_dict["arguments"] if "name" in func_dict: existing_tool_call.function.name = func_dict["name"] diff --git a/litellm/llms/openai/chat/o_series_transformation.py b/litellm/llms/openai/chat/o_series_transformation.py index 8db7ecf7b3ad..78a5b3512a4a 100644 --- a/litellm/llms/openai/chat/o_series_transformation.py +++ b/litellm/llms/openai/chat/o_series_transformation.py @@ -36,9 +36,7 @@ class OpenAIOSeriesConfig(OpenAIGPTConfig): def get_config(cls): return super().get_config() - def translate_developer_role_to_system_role( - self, messages: List[AllMessageValues] - ) -> List[AllMessageValues]: + def translate_developer_role_to_system_role(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: """ O-series models support `developer` role. """ @@ -64,22 +62,16 @@ def get_supported_openai_params(self, model: str) -> list: all_openai_params.extend(o_series_only_param) try: - model, custom_llm_provider, api_base, api_key = get_llm_provider( - model=model - ) + model, custom_llm_provider, api_base, api_key = get_llm_provider(model=model) except Exception: verbose_logger.debug( f"Unable to infer model provider for model={model}, defaulting to openai for o1 supported param check" ) custom_llm_provider = "openai" - _supports_function_calling = supports_function_calling( - model, custom_llm_provider - ) + _supports_function_calling = supports_function_calling(model, custom_llm_provider) _supports_response_schema = supports_response_schema(model, custom_llm_provider) - _supports_parallel_tool_calls = supports_parallel_function_calling( - model, custom_llm_provider - ) + _supports_parallel_tool_calls = supports_parallel_function_calling(model, custom_llm_provider) if not _supports_function_calling: non_supported_params.append("tools") @@ -93,9 +85,7 @@ def get_supported_openai_params(self, model: str) -> list: if not _supports_response_schema: non_supported_params.append("response_format") - return [ - param for param in all_openai_params if param not in non_supported_params - ] + return [param for param in all_openai_params if param not in non_supported_params] def map_openai_params( self, @@ -105,9 +95,7 @@ def map_openai_params( drop_params: bool, ): if "max_tokens" in non_default_params: - optional_params["max_completion_tokens"] = non_default_params.pop( - "max_tokens" - ) + optional_params["max_completion_tokens"] = non_default_params.pop("max_tokens") if "temperature" in non_default_params: temperature_value: Optional[float] = non_default_params.pop("temperature") if temperature_value is not None: @@ -125,9 +113,7 @@ def map_openai_params( status_code=400, ) - return super()._map_openai_params( - non_default_params, optional_params, model, drop_params - ) + return super()._map_openai_params(non_default_params, optional_params, model, drop_params) def is_model_o_series_model(self, model: str) -> bool: model = model.split("/")[-1] # could be "openai/o3" or "o3" @@ -162,16 +148,10 @@ def _transform_messages( _supports_system_messages = supports_system_messages(model, "openai") for i, message in enumerate(messages): if message["role"] == "system" and not _supports_system_messages: - new_message = ChatCompletionUserMessage( - content=message["content"], role="user" - ) + new_message = ChatCompletionUserMessage(content=message["content"], role="user") messages[i] = new_message # Replace the old message with the new one if is_async: - return super()._transform_messages( - messages, model, is_async=cast(Literal[True], True) - ) + return super()._transform_messages(messages, model, is_async=cast(Literal[True], True)) else: - return super()._transform_messages( - messages, model, is_async=cast(Literal[False], False) - ) + return super()._transform_messages(messages, model, is_async=cast(Literal[False], False)) diff --git a/litellm/llms/openai/common_utils.py b/litellm/llms/openai/common_utils.py index 381f215a13f1..6731d4a6a4a4 100644 --- a/litellm/llms/openai/common_utils.py +++ b/litellm/llms/openai/common_utils.py @@ -64,9 +64,7 @@ def __init__( if response: self.response = response else: - self.response = httpx.Response( - status_code=status_code, request=self.request - ) + self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( status_code=status_code, message=self.message, @@ -100,11 +98,7 @@ def drop_params_from_unprocessable_entity_error( error_body = error_message else: error_body = e.body - if ( - error_body is not None - and isinstance(error_body, dict) - and error_body.get("message") - ): + if error_body is not None and isinstance(error_body, dict) and error_body.get("message"): message = error_body.get("message", {}) if isinstance(message, str): try: @@ -162,15 +156,11 @@ def set_cached_openai_client( ) @staticmethod - def get_openai_client_cache_key( - client_initialization_params: dict, client_type: Literal["openai", "azure"] - ) -> str: + def get_openai_client_cache_key(client_initialization_params: dict, client_type: Literal["openai", "azure"]) -> str: """Creates a cache key for the OpenAI client based on the client initialization parameters""" hashed_api_key = None if client_initialization_params.get("api_key") is not None: - hash_object = hashlib.sha256( - client_initialization_params.get("api_key", "").encode() - ) + hash_object = hashlib.sha256(client_initialization_params.get("api_key", "").encode()) # Hexadecimal representation of the hash hashed_api_key = hash_object.hexdigest() @@ -187,9 +177,7 @@ def get_openai_client_cache_key( "api_base", ) openai_client_fields = ( - BaseOpenAILLM.get_openai_client_initialization_param_fields( - client_type=client_type - ) + BaseOpenAILLM.get_openai_client_initialization_param_fields(client_type=client_type) + LITELLM_CLIENT_SPECIFIC_PARAMS ) @@ -227,9 +215,7 @@ def _get_async_http_client( return httpx.AsyncClient( verify=ssl_config, transport=AsyncHTTPHandler._create_async_transport( - ssl_context=( - ssl_config if isinstance(ssl_config, ssl.SSLContext) else None - ), + ssl_context=(ssl_config if isinstance(ssl_config, ssl.SSLContext) else None), ssl_verify=ssl_config if isinstance(ssl_config, bool) else None, shared_session=shared_session, ), @@ -274,15 +260,8 @@ def get_openai_credentials( or os.getenv("OPENAI_API_BASE") or "https://api.openai.com/v1" ) - resolved_organization = ( - organization - or litellm.organization - or os.getenv("OPENAI_ORGANIZATION", None) - or None - ) - resolved_api_key = ( - api_key or litellm.api_key or litellm.openai_key or os.getenv("OPENAI_API_KEY") - ) + resolved_organization = organization or litellm.organization or os.getenv("OPENAI_ORGANIZATION", None) or None + resolved_api_key = api_key or litellm.api_key or litellm.openai_key or os.getenv("OPENAI_API_KEY") return OpenAICredentials( api_base=resolved_api_base, api_key=resolved_api_key, diff --git a/litellm/llms/openai/completion/guardrail_translation/handler.py b/litellm/llms/openai/completion/guardrail_translation/handler.py index 593ab0ed2e5a..8537fefe1e28 100644 --- a/litellm/llms/openai/completion/guardrail_translation/handler.py +++ b/litellm/llms/openai/completion/guardrail_translation/handler.py @@ -47,9 +47,7 @@ async def process_input_messages( """ prompt = data.get("prompt") if prompt is None: - verbose_proxy_logger.debug( - "OpenAI Text Completion: No prompt found in request data" - ) + verbose_proxy_logger.debug("OpenAI Text Completion: No prompt found in request data") return data if isinstance(prompt, str): @@ -69,8 +67,7 @@ async def process_input_messages( data["prompt"] = guardrailed_texts[0] if guardrailed_texts else prompt verbose_proxy_logger.debug( - "OpenAI Text Completion: Applied guardrail to string prompt. " - "Original length: %d, New length: %d", + "OpenAI Text Completion: Applied guardrail to string prompt. Original length: %d, New length: %d", len(prompt), len(data["prompt"]), ) @@ -140,9 +137,7 @@ async def process_output_response( Modified response with guardrails applied to completion text """ if not hasattr(response, "choices") or not response.choices: - verbose_proxy_logger.debug( - "OpenAI Text Completion: No choices in response to process" - ) + verbose_proxy_logger.debug("OpenAI Text Completion: No choices in response to process") return response # Collect all texts to check @@ -166,9 +161,7 @@ async def process_output_response( # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata diff --git a/litellm/llms/openai/completion/handler.py b/litellm/llms/openai/completion/handler.py index f08ef844bb3d..376d2636ba76 100644 --- a/litellm/llms/openai/completion/handler.py +++ b/litellm/llms/openai/completion/handler.py @@ -136,9 +136,7 @@ def completion( else: openai_client = client - raw_response = openai_client.completions.with_raw_response.create( - **data - ) # type: ignore + raw_response = openai_client.completions.with_raw_response.create(**data) # type: ignore response = raw_response.parse() response_json = response.model_dump() @@ -161,9 +159,7 @@ def completion( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) async def acompletion( self, @@ -192,9 +188,7 @@ async def acompletion( else: openai_aclient = client - raw_response = await openai_aclient.completions.with_raw_response.create( - **data - ) + raw_response = await openai_aclient.completions.with_raw_response.create(**data) response = raw_response.parse() response_json = response.model_dump() @@ -218,9 +212,7 @@ async def acompletion( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) def streaming( self, @@ -258,9 +250,7 @@ def streaming( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) streamwrapper = CustomStreamWrapper( completion_stream=response, model=model, @@ -279,9 +269,7 @@ def streaming( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) async def async_streaming( self, @@ -329,6 +317,4 @@ async def async_streaming( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) diff --git a/litellm/llms/openai/completion/utils.py b/litellm/llms/openai/completion/utils.py index 8b3efb4cda85..a7b7e7a67ceb 100644 --- a/litellm/llms/openai/completion/utils.py +++ b/litellm/llms/openai/completion/utils.py @@ -16,8 +16,7 @@ def is_tokens_or_list_of_tokens(value: List): return True # Check if it's a list of lists of integers (list of tokens) if isinstance(value, list) and all( - isinstance(item, list) and all(isinstance(i, int) for i in item) - for item in value + isinstance(item, list) and all(isinstance(i, int) for i in item) for item in value ): return True return False @@ -28,11 +27,7 @@ def _transform_prompt( ) -> AllPromptValues: if len(messages) == 1: # base case message_content = messages[0].get("content") - if ( - message_content - and isinstance(message_content, list) - and is_tokens_or_list_of_tokens(message_content) - ): + if message_content and isinstance(message_content, list) and is_tokens_or_list_of_tokens(message_content): openai_prompt: AllPromptValues = cast(AllPromptValues, message_content) else: openai_prompt = "" diff --git a/litellm/llms/openai/containers/transformation.py b/litellm/llms/openai/containers/transformation.py index 7f874ffd3b13..b5f4334af0ac 100644 --- a/litellm/llms/openai/containers/transformation.py +++ b/litellm/llms/openai/containers/transformation.py @@ -60,12 +60,7 @@ def validate_environment( headers: dict, api_key: Optional[str] = None, ) -> dict: - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") headers.update( { "Authorization": f"Bearer {api_key}", @@ -99,9 +94,7 @@ def transform_container_create_request( """Transform the container creation request for OpenAI API.""" # Remove extra_headers from optional params as they're handled separately container_create_optional_request_params = { - k: v - for k, v in container_create_optional_request_params.items() - if k not in ["extra_headers"] + k: v for k, v in container_create_optional_request_params.items() if k not in ["extra_headers"] } # Create the request data @@ -131,16 +124,11 @@ def transform_container_create_response( provider="openai", ) - if ( - not hasattr(container_obj, "_hidden_params") - or container_obj._hidden_params is None - ): + if not hasattr(container_obj, "_hidden_params") or container_obj._hidden_params is None: container_obj._hidden_params = {} if "additional_headers" not in container_obj._hidden_params: container_obj._hidden_params["additional_headers"] = {} - container_obj._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = container_cost + container_obj._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = container_cost return container_obj @@ -199,9 +187,7 @@ def transform_container_retrieve_request( ) -> Tuple[str, Dict]: """Transform the OpenAI container retrieve request.""" # For container retrieve, we just need to construct the URL - encoded_container_id = encode_url_path_segment( - container_id, field_name="container_id" - ) + encoded_container_id = encode_url_path_segment(container_id, field_name="container_id") url = join_container_api_base_path(api_base, f"/{encoded_container_id}") # No additional data needed for GET request @@ -234,9 +220,7 @@ def transform_container_delete_request( - DELETE /v1/containers/{container_id} """ # Construct the URL for container delete - encoded_container_id = encode_url_path_segment( - container_id, field_name="container_id" - ) + encoded_container_id = encode_url_path_segment(container_id, field_name="container_id") url = join_container_api_base_path(api_base, f"/{encoded_container_id}") # No data needed for DELETE request @@ -274,9 +258,7 @@ def transform_container_file_list_request( - GET /v1/containers/{container_id}/files """ # Construct the URL for container files - encoded_container_id = encode_url_path_segment( - container_id, field_name="container_id" - ) + encoded_container_id = encode_url_path_segment(container_id, field_name="container_id") url = join_container_api_base_path(api_base, f"/{encoded_container_id}/files") # Prepare query parameters @@ -321,13 +303,9 @@ def transform_container_file_content_request( - GET /v1/containers/{container_id}/files/{file_id}/content """ # Construct the URL for container file content - encoded_container_id = encode_url_path_segment( - container_id, field_name="container_id" - ) + encoded_container_id = encode_url_path_segment(container_id, field_name="container_id") encoded_file_id = encode_url_path_segment(file_id, field_name="file_id") - url = join_container_api_base_path( - api_base, f"/{encoded_container_id}/files/{encoded_file_id}/content" - ) + url = join_container_api_base_path(api_base, f"/{encoded_container_id}/files/{encoded_file_id}/content") # No query parameters needed params: Dict[str, Any] = {} diff --git a/litellm/llms/openai/cost_calculation.py b/litellm/llms/openai/cost_calculation.py index 6935cafd0d95..25376419b9e9 100644 --- a/litellm/llms/openai/cost_calculation.py +++ b/litellm/llms/openai/cost_calculation.py @@ -90,9 +90,7 @@ def cost_per_token( # return prompt_cost, completion_cost -def cost_per_second( - model: str, custom_llm_provider: Optional[str], duration: float = 0.0 -) -> Tuple[float, float]: +def cost_per_second(model: str, custom_llm_provider: Optional[str], duration: float = 0.0) -> Tuple[float, float]: """ Calculates the cost per second for a given model, prompt tokens, and completion tokens. @@ -106,25 +104,17 @@ def cost_per_second( """ ## GET MODEL INFO - model_info = get_model_info( - model=model, custom_llm_provider=custom_llm_provider or "openai" - ) + model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider or "openai") prompt_cost = 0.0 completion_cost = 0.0 ## Speech / Audio cost calculation - if ( - "output_cost_per_second" in model_info - and model_info["output_cost_per_second"] is not None - ): + if "output_cost_per_second" in model_info and model_info["output_cost_per_second"] is not None: verbose_logger.debug( f"For model={model} - output_cost_per_second: {model_info.get('output_cost_per_second')}; duration: {duration}" ) ## COST PER SECOND ## completion_cost = model_info["output_cost_per_second"] * duration - elif ( - "input_cost_per_second" in model_info - and model_info["input_cost_per_second"] is not None - ): + elif "input_cost_per_second" in model_info and model_info["input_cost_per_second"] is not None: verbose_logger.debug( f"For model={model} - input_cost_per_second: {model_info.get('input_cost_per_second')}; duration: {duration}" ) @@ -202,9 +192,7 @@ def video_generation_cost( """ ## GET MODEL INFO if model_info is None: - model_info = get_model_info( - model=model, custom_llm_provider=custom_llm_provider or "openai" - ) + model_info = get_model_info(model=model, custom_llm_provider=custom_llm_provider or "openai") # Check for video-specific cost per second video_cost_per_second = model_info.get("output_cost_per_video_per_second") diff --git a/litellm/llms/openai/data_residency.py b/litellm/llms/openai/data_residency.py index 7162f70ca5f5..db3c49d7583b 100644 --- a/litellm/llms/openai/data_residency.py +++ b/litellm/llms/openai/data_residency.py @@ -20,9 +20,7 @@ } -def infer_openai_data_residency( - custom_llm_provider: Optional[str], api_base: Optional[str] -) -> Optional[str]: +def infer_openai_data_residency(custom_llm_provider: Optional[str], api_base: Optional[str]) -> Optional[str]: """ Derive the OpenAI data-residency region from an api_base URL. diff --git a/litellm/llms/openai/embeddings/guardrail_translation/handler.py b/litellm/llms/openai/embeddings/guardrail_translation/handler.py index ff5021b8ce07..d208c98b0e46 100644 --- a/litellm/llms/openai/embeddings/guardrail_translation/handler.py +++ b/litellm/llms/openai/embeddings/guardrail_translation/handler.py @@ -50,19 +50,13 @@ async def process_input_messages( """ input_data = data.get("input") if input_data is None: - verbose_proxy_logger.debug( - "OpenAI Embeddings: No input found in request data" - ) + verbose_proxy_logger.debug("OpenAI Embeddings: No input found in request data") return data if isinstance(input_data, str): - data = await self._process_string_input( - data, input_data, guardrail_to_apply, litellm_logging_obj - ) + data = await self._process_string_input(data, input_data, guardrail_to_apply, litellm_logging_obj) elif isinstance(input_data, list): - data = await self._process_list_input( - data, input_data, guardrail_to_apply, litellm_logging_obj - ) + data = await self._process_list_input(data, input_data, guardrail_to_apply, litellm_logging_obj) else: verbose_proxy_logger.warning( "OpenAI Embeddings: Unexpected input type: %s. Expected string or list.", @@ -93,8 +87,7 @@ async def _process_string_input( if guardrailed_texts := guardrailed_inputs.get("texts"): data["input"] = guardrailed_texts[0] verbose_proxy_logger.debug( - "OpenAI Embeddings: Applied guardrail to string input. " - "Original length: %d, New length: %d", + "OpenAI Embeddings: Applied guardrail to string input. Original length: %d, New length: %d", len(input_data), len(data["input"]), ) @@ -116,9 +109,7 @@ async def _process_list_input( # Skip non-text inputs (token IDs) if isinstance(first_item, (int, list)): - verbose_proxy_logger.debug( - "OpenAI Embeddings: Input is token IDs, skipping guardrail processing" - ) + verbose_proxy_logger.debug("OpenAI Embeddings: Input is token IDs, skipping guardrail processing") return data if not isinstance(first_item, str): @@ -174,7 +165,6 @@ async def process_output_response( Unmodified response (embeddings don't have text output to guard) """ verbose_proxy_logger.debug( - "OpenAI Embeddings: Output response processing skipped - " - "embeddings contain vectors, not text" + "OpenAI Embeddings: Output response processing skipped - embeddings contain vectors, not text" ) return response diff --git a/litellm/llms/openai/evals/transformation.py b/litellm/llms/openai/evals/transformation.py index 66537e56a6f0..8a55fec58a6a 100644 --- a/litellm/llms/openai/evals/transformation.py +++ b/litellm/llms/openai/evals/transformation.py @@ -38,9 +38,7 @@ class OpenAIEvalsConfig(BaseEvalsAPIConfig): def custom_llm_provider(self) -> LlmProviders: return LlmProviders.OPENAI - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """Add OpenAI-specific headers""" import litellm from litellm.secret_managers.main import get_secret_str @@ -50,12 +48,7 @@ def validate_environment( if litellm_params: api_key = litellm_params.api_key - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") if not api_key: raise ValueError("OPENAI_API_KEY is required for Evals API") @@ -158,9 +151,7 @@ def transform_get_eval_request( headers: dict, ) -> Tuple[str, Dict]: """Transform get eval request for OpenAI""" - url = self.get_complete_url( - api_base=api_base, endpoint="evals", eval_id=eval_id - ) + url = self.get_complete_url(api_base=api_base, endpoint="evals", eval_id=eval_id) verbose_logger.debug("Get eval request - URL: %s", url) @@ -186,16 +177,12 @@ def transform_update_eval_request( headers: dict, ) -> Tuple[str, Dict, Dict]: """Transform update eval request for OpenAI""" - url = self.get_complete_url( - api_base=api_base, endpoint="evals", eval_id=eval_id - ) + url = self.get_complete_url(api_base=api_base, endpoint="evals", eval_id=eval_id) # Build request body request_body = {k: v for k, v in update_request.items() if v is not None} - verbose_logger.debug( - "Update eval request - URL: %s, body: %s", url, request_body - ) + verbose_logger.debug("Update eval request - URL: %s, body: %s", url, request_body) return url, headers, request_body @@ -218,9 +205,7 @@ def transform_delete_eval_request( headers: dict, ) -> Tuple[str, Dict]: """Transform delete eval request for OpenAI""" - url = self.get_complete_url( - api_base=api_base, endpoint="evals", eval_id=eval_id - ) + url = self.get_complete_url(api_base=api_base, endpoint="evals", eval_id=eval_id) verbose_logger.debug("Delete eval request - URL: %s", url) @@ -284,9 +269,7 @@ def transform_create_run_request( # Build request body request_body = {k: v for k, v in create_request.items() if v is not None} - verbose_logger.debug( - "Create run request - URL: %s, body: %s", url, request_body - ) + verbose_logger.debug("Create run request - URL: %s, body: %s", url, request_body) return url, request_body diff --git a/litellm/llms/openai/fine_tuning/handler.py b/litellm/llms/openai/fine_tuning/handler.py index ca93622d9de0..e0914a9ff0d8 100644 --- a/litellm/llms/openai/fine_tuning/handler.py +++ b/litellm/llms/openai/fine_tuning/handler.py @@ -19,9 +19,7 @@ # because LiteLLMFineTuningJob schema has no intermediate cancellation state. -def _normalize_fine_tuning_job_dict( - data: Dict[str, Any], is_azure: bool = False -) -> Dict[str, Any]: +def _normalize_fine_tuning_job_dict(data: Dict[str, Any], is_azure: bool = False) -> Dict[str, Any]: """ Normalize Azure OpenAI FineTuningJob response to match OpenAI schema. @@ -48,12 +46,8 @@ def _normalize_fine_tuning_job_dict( return normalized -def _litellm_fine_tuning_job_from_response( - response: Any, is_azure: bool = False -) -> LiteLLMFineTuningJob: - return LiteLLMFineTuningJob( - **_normalize_fine_tuning_job_dict(response.model_dump(), is_azure=is_azure) - ) +def _litellm_fine_tuning_job_from_response(response: Any, is_azure: bool = False) -> LiteLLMFineTuningJob: + return LiteLLMFineTuningJob(**_normalize_fine_tuning_job_dict(response.model_dump(), is_azure=is_azure)) class OpenAIFineTuningAPI: @@ -71,9 +65,7 @@ def get_openai_client( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, _is_async: bool = False, api_version: Optional[str] = None, litellm_params: Optional[dict] = None, @@ -86,9 +78,7 @@ def get_openai_client( ] ]: received_args = locals() - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None if client is None: data = {} for k, v in received_args.items(): @@ -112,9 +102,7 @@ async def acreate_fine_tuning_job( create_fine_tuning_job_data: dict, openai_client: Union[AsyncOpenAI, AsyncAzureOpenAI], ) -> LiteLLMFineTuningJob: - response = await openai_client.fine_tuning.jobs.create( - **create_fine_tuning_job_data - ) + response = await openai_client.fine_tuning.jobs.create(**create_fine_tuning_job_data) return _litellm_fine_tuning_job_from_response(response) @@ -128,13 +116,9 @@ def create_fine_tuning_job( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -158,12 +142,8 @@ def create_fine_tuning_job( create_fine_tuning_job_data=create_fine_tuning_job_data, openai_client=openai_client, ) - verbose_logger.debug( - "creating fine tuning job, args= %s", create_fine_tuning_job_data - ) - response = cast(OpenAI, openai_client).fine_tuning.jobs.create( - **create_fine_tuning_job_data - ) + verbose_logger.debug("creating fine tuning job, args= %s", create_fine_tuning_job_data) + response = cast(OpenAI, openai_client).fine_tuning.jobs.create(**create_fine_tuning_job_data) return _litellm_fine_tuning_job_from_response(response) async def acancel_fine_tuning_job( @@ -171,9 +151,7 @@ async def acancel_fine_tuning_job( fine_tuning_job_id: str, openai_client: Union[AsyncOpenAI, AsyncAzureOpenAI], ) -> LiteLLMFineTuningJob: - response = await openai_client.fine_tuning.jobs.cancel( - fine_tuning_job_id=fine_tuning_job_id - ) + response = await openai_client.fine_tuning.jobs.cancel(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response) def cancel_fine_tuning_job( @@ -186,13 +164,9 @@ def cancel_fine_tuning_job( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -217,9 +191,7 @@ def cancel_fine_tuning_job( openai_client=openai_client, ) verbose_logger.debug("canceling fine tuning job, args= %s", fine_tuning_job_id) - response = cast(OpenAI, openai_client).fine_tuning.jobs.cancel( - fine_tuning_job_id=fine_tuning_job_id - ) + response = cast(OpenAI, openai_client).fine_tuning.jobs.cancel(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response) async def alist_fine_tuning_jobs( @@ -240,15 +212,11 @@ def list_fine_tuning_jobs( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, after: Optional[str] = None, limit: Optional[int] = None, ): - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -282,9 +250,7 @@ async def aretrieve_fine_tuning_job( fine_tuning_job_id: str, openai_client: Union[AsyncOpenAI, AsyncAzureOpenAI], ) -> LiteLLMFineTuningJob: - response = await openai_client.fine_tuning.jobs.retrieve( - fine_tuning_job_id=fine_tuning_job_id - ) + response = await openai_client.fine_tuning.jobs.retrieve(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response) def retrieve_fine_tuning_job( @@ -297,13 +263,9 @@ def retrieve_fine_tuning_job( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], organization: Optional[str], - client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = None, + client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = None, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: - openai_client: Optional[ - Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI] - ] = self.get_openai_client( + openai_client: Optional[Union[OpenAI, AsyncOpenAI, AzureOpenAI, AsyncAzureOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, timeout=timeout, @@ -328,7 +290,5 @@ def retrieve_fine_tuning_job( openai_client=openai_client, ) verbose_logger.debug("retrieving fine tuning job, id= %s", fine_tuning_job_id) - response = cast(OpenAI, openai_client).fine_tuning.jobs.retrieve( - fine_tuning_job_id=fine_tuning_job_id - ) + response = cast(OpenAI, openai_client).fine_tuning.jobs.retrieve(fine_tuning_job_id=fine_tuning_job_id) return _litellm_fine_tuning_job_from_response(response) diff --git a/litellm/llms/openai/image_edit/dalle2_transformation.py b/litellm/llms/openai/image_edit/dalle2_transformation.py index 04995ce95143..ac08d056a341 100644 --- a/litellm/llms/openai/image_edit/dalle2_transformation.py +++ b/litellm/llms/openai/image_edit/dalle2_transformation.py @@ -58,16 +58,12 @@ def transform_image_edit_request( ######################################################### _image_list = request_dict.get("image") _mask = request_dict.get("mask") - data_without_files = { - k: v for k, v in request_dict.items() if k not in ["image", "mask"] - } + data_without_files = {k: v for k, v in request_dict.items() if k not in ["image", "mask"]} files_list: List[Tuple[str, Any]] = [] # Handle image parameter - DALL-E-2 only supports single image if _image_list is not None: - image_list = ( - [_image_list] if not isinstance(_image_list, list) else _image_list - ) + image_list = [_image_list] if not isinstance(_image_list, list) else _image_list # Validate only one image is provided if len(image_list) > 1: @@ -93,9 +89,7 @@ def transform_image_edit_request( _mask = _mask[0] if _mask else None if _mask is not None: - mask_content_type: str = ImageEditRequestUtils.get_image_content_type( - _mask - ) + mask_content_type: str = ImageEditRequestUtils.get_image_content_type(_mask) if isinstance(_mask, BufferedReader): files_list.append(("mask", (_mask.name, _mask, mask_content_type))) else: diff --git a/litellm/llms/openai/image_edit/transformation.py b/litellm/llms/openai/image_edit/transformation.py index 9c0daca80221..f53c1731f58f 100644 --- a/litellm/llms/openai/image_edit/transformation.py +++ b/litellm/llms/openai/image_edit/transformation.py @@ -110,16 +110,12 @@ def transform_image_edit_request( ######################################################### _image_list = request_dict.get("image") _mask = request_dict.get("mask") - data_without_files = { - k: v for k, v in request_dict.items() if k not in ["image", "mask"] - } + data_without_files = {k: v for k, v in request_dict.items() if k not in ["image", "mask"]} files_list: List[Tuple[str, Any]] = [] # Handle image parameter if _image_list is not None: - image_list = ( - [_image_list] if not isinstance(_image_list, list) else _image_list - ) + image_list = [_image_list] if not isinstance(_image_list, list) else _image_list for _image in image_list: if _image is not None: @@ -135,9 +131,7 @@ def transform_image_edit_request( _mask = _mask[0] if _mask else None if _mask is not None: - mask_content_type: str = ImageEditRequestUtils.get_image_content_type( - _mask - ) + mask_content_type: str = ImageEditRequestUtils.get_image_content_type(_mask) if isinstance(_mask, BufferedReader): files_list.append(("mask", (_mask.name, _mask, mask_content_type))) else: @@ -155,9 +149,7 @@ def transform_image_edit_response( try: raw_response_json = raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) return ImageResponse(**raw_response_json) def validate_environment( @@ -168,12 +160,7 @@ def validate_environment( litellm_params: Optional[dict] = None, api_base: Optional[str] = None, ) -> dict: - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") headers.update( { "Authorization": f"Bearer {api_key}", diff --git a/litellm/llms/openai/image_generation/cost_calculator.py b/litellm/llms/openai/image_generation/cost_calculator.py index dab277a7ba81..effda2fa3eef 100644 --- a/litellm/llms/openai/image_generation/cost_calculator.py +++ b/litellm/llms/openai/image_generation/cost_calculator.py @@ -22,18 +22,14 @@ def cost_calculator( """Calculate cost for OpenAI gpt-image models (token-based pricing).""" usage = getattr(image_response, "usage", None) if usage is None: - verbose_logger.debug( - f"No usage data available for {model}, cannot calculate token-based cost" - ) + verbose_logger.debug(f"No usage data available for {model}, cannot calculate token-based cost") return 0.0 provider = custom_llm_provider or "openai" # A chat Usage with an explicit output breakdown: cost via generic_cost_per_token. if isinstance(usage, Usage) and usage.completion_tokens_details is not None: - prompt_cost, completion_cost = generic_cost_per_token( - model=model, usage=usage, custom_llm_provider=provider - ) + prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider=provider) return prompt_cost + completion_cost # ImageUsage / ResponseAPIUsage: reuse the shared helper (same path as @@ -50,9 +46,7 @@ def cost_calculator( # Fallback: a Usage with no output breakdown that the image helper can't read — # cost via generic_cost_per_token (text rate) instead of returning 0.0. if isinstance(usage, Usage): - prompt_cost, completion_cost = generic_cost_per_token( - model=model, usage=usage, custom_llm_provider=provider - ) + prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=usage, custom_llm_provider=provider) return prompt_cost + completion_cost return 0.0 diff --git a/litellm/llms/openai/image_generation/dall_e_2_transformation.py b/litellm/llms/openai/image_generation/dall_e_2_transformation.py index 22c2349a8370..fbc2e8dec3d8 100644 --- a/litellm/llms/openai/image_generation/dall_e_2_transformation.py +++ b/litellm/llms/openai/image_generation/dall_e_2_transformation.py @@ -18,9 +18,7 @@ class DallE2ImageGenerationConfig(BaseImageGenerationConfig): OpenAI dall-e-2 image generation config """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return ["n", "response_format", "quality", "size", "user"] def map_openai_params( @@ -74,14 +72,8 @@ def transform_image_generation_response( ) # set optional params - image_response.size = optional_params.get( - "size", "1024x1024" - ) # default is always 1024x1024 - image_response.quality = optional_params.get( - "quality", "standard" - ) # always standard for dall-e-2 - image_response.output_format = optional_params.get( - "output_format", "png" - ) # always png for dall-e-2 + image_response.size = optional_params.get("size", "1024x1024") # default is always 1024x1024 + image_response.quality = optional_params.get("quality", "standard") # always standard for dall-e-2 + image_response.output_format = optional_params.get("output_format", "png") # always png for dall-e-2 return image_response diff --git a/litellm/llms/openai/image_generation/dall_e_3_transformation.py b/litellm/llms/openai/image_generation/dall_e_3_transformation.py index 9e2bdabc3a14..3434c708113f 100644 --- a/litellm/llms/openai/image_generation/dall_e_3_transformation.py +++ b/litellm/llms/openai/image_generation/dall_e_3_transformation.py @@ -18,9 +18,7 @@ class DallE3ImageGenerationConfig(BaseImageGenerationConfig): OpenAI dall-e-3 image generation config """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return ["n", "response_format", "quality", "size", "user", "style"] def map_openai_params( @@ -74,14 +72,8 @@ def transform_image_generation_response( ) # set optional params - image_response.size = optional_params.get( - "size", "1024x1024" - ) # default is always 1024x1024 - image_response.quality = optional_params.get( - "quality", "hd" - ) # always hd for dall-e-3 - image_response.output_format = optional_params.get( - "output_format", "png" - ) # always png for dall-e-3 + image_response.size = optional_params.get("size", "1024x1024") # default is always 1024x1024 + image_response.quality = optional_params.get("quality", "hd") # always hd for dall-e-3 + image_response.output_format = optional_params.get("output_format", "png") # always png for dall-e-3 return image_response diff --git a/litellm/llms/openai/image_generation/gpt_transformation.py b/litellm/llms/openai/image_generation/gpt_transformation.py index 68f799e57470..b9c2368d4bec 100644 --- a/litellm/llms/openai/image_generation/gpt_transformation.py +++ b/litellm/llms/openai/image_generation/gpt_transformation.py @@ -18,9 +18,7 @@ class GPTImageGenerationConfig(BaseImageGenerationConfig): OpenAI gpt-image image generation config """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return [ "background", "moderation", @@ -83,14 +81,8 @@ def transform_image_generation_response( ) # set optional params - image_response.size = optional_params.get( - "size", "1024x1024" - ) # default is always 1024x1024 - image_response.quality = optional_params.get( - "quality", "high" - ) # always hd for dall-e-3 - image_response.output_format = optional_params.get( - "response_format", "png" - ) # always png for dall-e-3 + image_response.size = optional_params.get("size", "1024x1024") # default is always 1024x1024 + image_response.quality = optional_params.get("quality", "high") # always hd for dall-e-3 + image_response.output_format = optional_params.get("response_format", "png") # always png for dall-e-3 return image_response diff --git a/litellm/llms/openai/image_generation/guardrail_translation/handler.py b/litellm/llms/openai/image_generation/guardrail_translation/handler.py index 76610088d0cd..56bc00f319c2 100644 --- a/litellm/llms/openai/image_generation/guardrail_translation/handler.py +++ b/litellm/llms/openai/image_generation/guardrail_translation/handler.py @@ -46,9 +46,7 @@ async def process_input_messages( """ prompt = data.get("prompt") if prompt is None: - verbose_proxy_logger.debug( - "OpenAI Image Generation: No prompt found in request data" - ) + verbose_proxy_logger.debug("OpenAI Image Generation: No prompt found in request data") return data # Apply guardrail to the prompt @@ -68,8 +66,7 @@ async def process_input_messages( data["prompt"] = guardrailed_texts[0] if guardrailed_texts else prompt verbose_proxy_logger.debug( - "OpenAI Image Generation: Applied guardrail to prompt. " - "Original length: %d, New length: %d", + "OpenAI Image Generation: Applied guardrail to prompt. Original length: %d, New length: %d", len(prompt), len(data["prompt"]), ) @@ -105,7 +102,5 @@ async def process_output_response( Returns: Unmodified response (images don't need text guardrails) """ - verbose_proxy_logger.debug( - "OpenAI Image Generation: Output processing not needed for image responses" - ) + verbose_proxy_logger.debug("OpenAI Image Generation: Output processing not needed for image responses") return response diff --git a/litellm/llms/openai/image_variations/handler.py b/litellm/llms/openai/image_variations/handler.py index dae3fa9d457c..00cbb87e31da 100644 --- a/litellm/llms/openai/image_variations/handler.py +++ b/litellm/llms/openai/image_variations/handler.py @@ -30,9 +30,7 @@ def get_sync_client( openai_client = client return openai_client - def get_async_client( - self, client: Optional[AsyncOpenAI], init_client_params: dict - ) -> AsyncOpenAI: + def get_async_client(self, client: Optional[AsyncOpenAI], init_client_params: dict) -> AsyncOpenAI: if client is None: openai_client = AsyncOpenAI( **init_client_params, @@ -69,13 +67,9 @@ async def async_image_variations( "organization": organization, } - client = self.get_async_client( - client=client, init_client_params=init_client_params - ) + client = self.get_async_client(client=client, init_client_params=init_client_params) - raw_response = await client.images.with_raw_response.create_variation( - **data - ) # type: ignore + raw_response = await client.images.with_raw_response.create_variation(**data) # type: ignore response = raw_response.parse() response_json = response.model_dump() @@ -95,9 +89,7 @@ async def async_image_variations( model_response=ImageResponse(**response_json), raw_response=httpx.Response( status_code=200, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), # mock request object + request=httpx.Request(method="GET", url="https://litellm.ai"), # mock request object ), logging_obj=logging_obj, request_data=data, @@ -114,9 +106,7 @@ async def async_image_variations( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) def image_variations( self, @@ -143,9 +133,7 @@ def image_variations( ) if provider_config is None: - raise ValueError( - f"image variation provider not found: {custom_llm_provider}." - ) + raise ValueError(f"image variation provider not found: {custom_llm_provider}.") max_retries = optional_params.pop("max_retries", 2) @@ -157,9 +145,7 @@ def image_variations( ) json_data = data.get("data") if not json_data: - raise ValueError( - f"data field is required, for openai image variations. Got={data}" - ) + raise ValueError(f"data field is required, for openai image variations. Got={data}") ## LOGGING logging_obj.pre_call( input="", @@ -198,9 +184,7 @@ def image_variations( "organization": organization, } - client = self.get_sync_client( - client=client, init_client_params=init_client_params - ) + client = self.get_sync_client(client=client, init_client_params=init_client_params) raw_response = client.images.with_raw_response.create_variation(**json_data) # type: ignore response = raw_response.parse() @@ -222,9 +206,7 @@ def image_variations( model_response=ImageResponse(**response_json), raw_response=httpx.Response( status_code=200, - request=httpx.Request( - method="GET", url="https://litellm.ai" - ), # mock request object + request=httpx.Request(method="GET", url="https://litellm.ai"), # mock request object ), logging_obj=logging_obj, request_data=json_data, @@ -241,6 +223,4 @@ def image_variations( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) diff --git a/litellm/llms/openai/image_variations/transformation.py b/litellm/llms/openai/image_variations/transformation.py index 96d1a302761f..2f16c6f3d23c 100644 --- a/litellm/llms/openai/image_variations/transformation.py +++ b/litellm/llms/openai/image_variations/transformation.py @@ -13,9 +13,7 @@ class OpenAIImageVariationConfig(BaseImageVariationConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageVariationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageVariationOptionalParams]: return ["n", "size", "response_format", "user"] def map_openai_params( @@ -72,9 +70,7 @@ def transform_response_image_variation( ) -> ImageResponse: return model_response - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: return OpenAIError( status_code=status_code, message=error_message, diff --git a/litellm/llms/openai/openai.py b/litellm/llms/openai/openai.py index 0b90381ba59b..6b191144a117 100644 --- a/litellm/llms/openai/openai.py +++ b/litellm/llms/openai/openai.py @@ -198,18 +198,14 @@ def get_supported_openai_params(self, model: str) -> list: else: return litellm.openAIGPTConfig.get_supported_openai_params(model=model) - def _map_openai_params( - self, non_default_params: dict, optional_params: dict, model: str - ) -> dict: + def _map_openai_params(self, non_default_params: dict, optional_params: dict, model: str) -> dict: supported_openai_params = self.get_supported_openai_params(model) for param, value in non_default_params.items(): if param in supported_openai_params: optional_params[param] = value return optional_params - def _transform_messages( - self, messages: List[AllMessageValues], model: str - ) -> List[AllMessageValues]: + def _transform_messages(self, messages: List[AllMessageValues], model: str) -> List[AllMessageValues]: return messages def map_openai_params( @@ -368,9 +364,7 @@ def _get_openai_client( if not isinstance(max_retries, int): raise OpenAIError( status_code=422, - message="max retries must be an int. Passed in value: {}".format( - max_retries - ), + message="max retries must be an int. Passed in value: {}".format(max_retries), ) cached_client = self.get_cached_openai_client( client_initialization_params=client_initialization_params, @@ -378,17 +372,13 @@ def _get_openai_client( ) if cached_client: - if isinstance(cached_client, OpenAI) or isinstance( - cached_client, AsyncOpenAI - ): + if isinstance(cached_client, OpenAI) or isinstance(cached_client, AsyncOpenAI): return cached_client if is_async: _new_client: Union[OpenAI, AsyncOpenAI] = AsyncOpenAI( api_key=api_key, base_url=api_base, - http_client=OpenAIChatCompletion._get_async_http_client( - shared_session=shared_session - ), + http_client=OpenAIChatCompletion._get_async_http_client(shared_session=shared_session), timeout=timeout, max_retries=max_retries, organization=organization, @@ -434,11 +424,7 @@ async def make_openai_chat_completion_request( """ start_time = time.time() try: - raw_response = ( - await openai_aclient.chat.completions.with_raw_response.create( - **data, timeout=timeout - ) - ) + raw_response = await openai_aclient.chat.completions.with_raw_response.create(**data, timeout=timeout) end_time = time.time() if hasattr(raw_response, "headers"): @@ -475,9 +461,7 @@ def make_sync_openai_chat_completion_request( """ raw_response = None try: - raw_response = openai_client.chat.completions.with_raw_response.create( - **data, timeout=timeout - ) + raw_response = openai_client.chat.completions.with_raw_response.create(**data, timeout=timeout) if hasattr(raw_response, "headers"): headers = dict(raw_response.headers) @@ -539,9 +523,7 @@ async def _call_agentic_completion_hooks_openai( try: if isinstance(callback, CustomLogger): # Check if the callback has the chat completion agentic loop methods - if not hasattr( - callback, "async_should_run_chat_completion_agentic_loop" - ): + if not hasattr(callback, "async_should_run_chat_completion_agentic_loop"): continue # First: Check if agentic loop should run (using chat completion method) @@ -560,25 +542,19 @@ async def _call_agentic_completion_hooks_openai( if should_run: # Second: Execute agentic loop - kwargs_with_provider = ( - litellm_params.copy() if litellm_params else {} - ) - kwargs_with_provider["custom_llm_provider"] = ( - custom_llm_provider - ) + kwargs_with_provider = litellm_params.copy() if litellm_params else {} + kwargs_with_provider["custom_llm_provider"] = custom_llm_provider # For OpenAI Chat Completions, use the chat completion agentic loop method - agentic_response = ( - await callback.async_run_chat_completion_agentic_loop( - tools=tool_calls, - model=model, - messages=messages, - response=response, - optional_params=optional_params, - logging_obj=logging_obj, - stream=stream, - kwargs=kwargs_with_provider, - ) + agentic_response = await callback.async_run_chat_completion_agentic_loop( + tools=tool_calls, + model=model, + messages=messages, + response=response, + optional_params=optional_params, + logging_obj=logging_obj, + stream=stream, + kwargs=kwargs_with_provider, ) # First hook that runs agentic loop wins return agentic_response @@ -637,9 +613,7 @@ def completion( # type: ignore try: fake_stream: bool = False inference_params = optional_params.copy() - stream_options: Optional[dict] = inference_params.pop( - "stream_options", None - ) + stream_options: Optional[dict] = inference_params.pop("stream_options", None) stream: Optional[bool] = inference_params.pop("stream", False) provider_config: Optional[BaseConfig] = None @@ -665,9 +639,7 @@ def completion( # type: ignore if model is None or messages is None: raise OpenAIError(status_code=422, message="Missing model or messages") - if not isinstance(timeout, float) and not isinstance( - timeout, httpx.Timeout - ): + if not isinstance(timeout, float) and not isinstance(timeout, httpx.Timeout): raise OpenAIError( status_code=422, message="Timeout needs to be a float or httpx.Timeout", @@ -676,9 +648,7 @@ def completion( # type: ignore if custom_llm_provider is not None and custom_llm_provider != "openai": model_response.model = f"{custom_llm_provider}/{model}" - for _ in range( - 2 - ): # if call fails due to alternating messages, retry with reformatted message + for _ in range(2): # if call fails due to alternating messages, retry with reformatted message try: max_retries = inference_params.pop("max_retries", 2) if acompletion is True: @@ -748,9 +718,7 @@ def completion( # type: ignore ) else: if not isinstance(max_retries, int): - raise OpenAIError( - status_code=422, message="max retries must be an int" - ) + raise OpenAIError(status_code=422, message="max retries must be an int") openai_client: OpenAI = self._get_openai_client( # type: ignore is_async=False, api_key=api_key, @@ -785,11 +753,7 @@ def completion( # type: ignore ) logging_obj.model_call_details["response_headers"] = headers - stringified_response = ( - provider_config.transform_parsed_response_dict( - response.model_dump() - ) - ) + stringified_response = provider_config.transform_parsed_response_dict(response.model_dump()) logging_obj.post_call( input=messages, api_key=api_key, @@ -814,9 +778,7 @@ def completion( # type: ignore except openai.UnprocessableEntityError as e: ## check if body contains unprocessable params - related issue https://github.com/BerriAI/litellm/issues/4800 if litellm.drop_params is True or drop_params is True: - inference_params = drop_params_from_unprocessable_entity_error( - e, inference_params - ) + inference_params = drop_params_from_unprocessable_entity_error(e, inference_params) else: raise e # e.message @@ -835,22 +797,16 @@ def completion( # type: ignore new_messages.append(messages[i]) if messages[i]["role"] == messages[i + 1]["role"]: if messages[i]["role"] == "user": - new_messages.append( - {"role": "assistant", "content": ""} - ) + new_messages.append({"role": "assistant", "content": ""}) else: new_messages.append({"role": "user", "content": ""}) new_messages.append(messages[-1]) messages = new_messages - elif ( - "Last message must have role `user`" in str(e) - ) and messages is not None: + elif ("Last message must have role `user`" in str(e)) and messages is not None: new_messages = messages new_messages.append({"role": "user", "content": ""}) messages = new_messages - elif "unknown field: parameter index is not a valid field" in str( - e - ): + elif "unknown field: parameter index is not a valid field" in str(e): litellm.remove_index_from_tool_calls(messages=messages) else: raise e @@ -901,9 +857,7 @@ async def acompletion( litellm_params=litellm_params, headers=headers or {}, ) - for _ in range( - 2 - ): # if call fails due to alternating messages, retry with reformatted message + for _ in range(2): # if call fails due to alternating messages, retry with reformatted message try: openai_aclient: AsyncOpenAI = self._get_openai_client( # type: ignore is_async=True, @@ -922,9 +876,7 @@ async def acompletion( input=data["messages"], api_key=openai_aclient.api_key, additional_args={ - "headers": { - "Authorization": f"Bearer {openai_aclient.api_key}" - }, + "headers": {"Authorization": f"Bearer {openai_aclient.api_key}"}, "api_base": openai_aclient._base_url._uri_reference, "acompletion": True, "complete_input_dict": data, @@ -937,9 +889,7 @@ async def acompletion( timeout=timeout, logging_obj=logging_obj, ) - stringified_response = provider_config.transform_parsed_response_dict( - response.model_dump() - ) + stringified_response = provider_config.transform_parsed_response_dict(response.model_dump()) logging_obj.post_call( input=data["messages"], api_key=api_key, @@ -1016,9 +966,7 @@ def streaming( stream_options: Optional[dict] = None, ): data["stream"] = True - data.update( - self.get_stream_options(stream_options=stream_options, api_base=api_base) - ) + data.update(self.get_stream_options(stream_options=stream_options, api_base=api_base)) openai_client: OpenAI = self._get_openai_client( # type: ignore is_async=False, @@ -1088,9 +1036,7 @@ async def async_streaming( headers=headers or {}, ) data["stream"] = True - data.update( - self.get_stream_options(stream_options=stream_options, api_base=api_base) - ) + data.update(self.get_stream_options(stream_options=stream_options, api_base=api_base)) for _ in range(2): try: openai_aclient: AsyncOpenAI = self._get_openai_client( # type: ignore @@ -1138,7 +1084,9 @@ async def async_streaming( data = drop_params_from_unprocessable_entity_error(e, data) else: raise e - except Exception as e: # need to exception handle here. async exceptions don't get caught in sync functions. + except ( + Exception + ) as e: # need to exception handle here. async exceptions don't get caught in sync functions. if isinstance(e, OpenAIError): raise e @@ -1178,9 +1126,7 @@ async def async_streaming( body=exception_body, ) - def get_stream_options( - self, stream_options: Optional[dict], api_base: Optional[str] - ) -> dict: + def get_stream_options(self, stream_options: Optional[dict], api_base: Optional[str]) -> dict: """ Pass `stream_options` to the data dict for OpenAI requests """ @@ -1207,9 +1153,7 @@ async def make_openai_embedding_request( - call embeddings.create by default """ try: - raw_response = await openai_aclient.embeddings.with_raw_response.create( - **data, timeout=timeout - ) # type: ignore + raw_response = await openai_aclient.embeddings.with_raw_response.create(**data, timeout=timeout) # type: ignore headers = dict(raw_response.headers) response = raw_response.parse() return headers, response @@ -1230,9 +1174,7 @@ def make_sync_openai_embedding_request( - call embeddings.create by default """ try: - raw_response = openai_client.embeddings.with_raw_response.create( - **data, timeout=timeout - ) # type: ignore + raw_response = openai_client.embeddings.with_raw_response.create(**data, timeout=timeout) # type: ignore headers = dict(raw_response.headers) response = raw_response.parse() @@ -1308,9 +1250,7 @@ async def aembedding( error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) def embedding( # type: ignore self, @@ -1396,9 +1336,7 @@ def embedding( # type: ignore error_response = getattr(e, "response", None) if error_headers is None and error_response: error_headers = getattr(error_response, "headers", None) - raise OpenAIError( - status_code=status_code, message=error_text, headers=error_headers - ) + raise OpenAIError(status_code=status_code, message=error_text, headers=error_headers) async def aimage_generation( self, @@ -1546,9 +1484,7 @@ def image_generation( original_response=str(e), ) if hasattr(e, "status_code"): - raise OpenAIError( - status_code=getattr(e, "status_code", 500), message=str(e) - ) + raise OpenAIError(status_code=getattr(e, "status_code", 500), message=str(e)) else: raise OpenAIError(status_code=500, message=str(e)) @@ -1746,9 +1682,7 @@ def file_content( max_retries: Optional[int], organization: Optional[str], client: Optional[Union[OpenAI, AsyncOpenAI]] = None, - ) -> Union[ - HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent] - ]: + ) -> Union[HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent]]: openai_client: Optional[Union[OpenAI, AsyncOpenAI]] = self.get_openai_client( api_key=api_key, api_base=api_base, @@ -1782,9 +1716,7 @@ async def afile_content_streaming( openai_client: AsyncOpenAI, chunk_size: int = 1024 * 1024, ) -> FileContentStreamingResult: - response_cm = openai_client.files.with_streaming_response.content( - **file_content_request - ) + response_cm = openai_client.files.with_streaming_response.content(**file_content_request) response = await response_cm.__aenter__() headers = dict(response.headers) @@ -1841,9 +1773,7 @@ def file_content_streaming( chunk_size=chunk_size, ) - response_cm = cast(OpenAI, openai_client).files.with_streaming_response.content( - **file_content_request - ) + response_cm = cast(OpenAI, openai_client).files.with_streaming_response.content(**file_content_request) response = response_cm.__enter__() headers = dict(response.headers) @@ -2185,9 +2115,7 @@ def cancel_batch( # At this point, openai_client is guaranteed to be a sync OpenAI client if not isinstance(openai_client, OpenAI): - raise ValueError( - "OpenAI client is not an instance of OpenAI. Make sure you passed a sync OpenAI client." - ) + raise ValueError("OpenAI client is not an instance of OpenAI. Make sure you passed a sync OpenAI client.") response = openai_client.batches.cancel(**cancel_batch_data) return LiteLLMBatch(**response.model_dump()) @@ -2541,11 +2469,9 @@ async def a_add_message( client=client, ) - thread_message: OpenAIMessage = ( - await openai_client.beta.threads.messages.create( # type: ignore - thread_id, - **message_data, # type: ignore - ) + thread_message: OpenAIMessage = await openai_client.beta.threads.messages.create( # type: ignore + thread_id, + **message_data, # type: ignore ) response_obj: Optional[OpenAIMessage] = None diff --git a/litellm/llms/openai/realtime/handler.py b/litellm/llms/openai/realtime/handler.py index cebab20adde7..626d2f3a28e7 100644 --- a/litellm/llms/openai/realtime/handler.py +++ b/litellm/llms/openai/realtime/handler.py @@ -142,9 +142,7 @@ async def async_realtime( "If your client expects beta event names, add 'OpenAI-Beta: realtime=v1' " "to the WebSocket headers sent to the LiteLLM proxy." ) - headers = self._get_additional_headers( - api_key, openai_beta_realtime=openai_beta_realtime - ) + headers = self._get_additional_headers(api_key, openai_beta_realtime=openai_beta_realtime) # Log a masked request preview consistent with other endpoints. logging_obj.pre_call( @@ -170,9 +168,7 @@ async def async_realtime( user_api_key_dict=user_api_key_dict, request_data={"litellm_metadata": litellm_metadata or {}}, force_transcription_model=( - model - if (query_params or {}).get("intent") == "transcription" - else None + model if (query_params or {}).get("intent") == "transcription" else None ), event_normalizer=self._make_event_normalizer(), ) @@ -182,17 +178,11 @@ async def async_realtime( await websocket.close(code=e.status_code, reason=_redact_string(str(e))) except Exception as e: try: - await websocket.close( - code=1011, reason=_redact_string(f"Internal server error: {str(e)}") - ) + await websocket.close(code=1011, reason=_redact_string(f"Internal server error: {str(e)}")) except RuntimeError as close_error: - if "already completed" in str(close_error) or "websocket.close" in str( - close_error - ): + if "already completed" in str(close_error) or "websocket.close" in str(close_error): # The WebSocket is already closed or the response is completed, so we can ignore this error pass else: # If it's a different RuntimeError, we might want to log it or handle it differently - raise Exception( - f"Unexpected error while closing WebSocket: {close_error}" - ) + raise Exception(f"Unexpected error while closing WebSocket: {close_error}") diff --git a/litellm/llms/openai/realtime/http_transformation.py b/litellm/llms/openai/realtime/http_transformation.py index 7a6af39ba655..0a7e65dfea2d 100644 --- a/litellm/llms/openai/realtime/http_transformation.py +++ b/litellm/llms/openai/realtime/http_transformation.py @@ -9,33 +9,18 @@ class OpenAIRealtimeHTTPConfig(BaseRealtimeHTTPConfig): def get_api_base(self, api_base: Optional[str], **kwargs) -> str: - return ( - api_base - or litellm.api_base - or get_secret_str("OPENAI_API_BASE") - or "https://api.openai.com" - ) + return api_base or litellm.api_base or get_secret_str("OPENAI_API_BASE") or "https://api.openai.com" def get_api_key(self, api_key: Optional[str], **kwargs) -> str: - return ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - or "" - ) - - def get_complete_url( - self, api_base: Optional[str], model: str, api_version: Optional[str] = None - ) -> str: + return api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") or "" + + def get_complete_url(self, api_base: Optional[str], model: str, api_version: Optional[str] = None) -> str: base = self.get_api_base(api_base).rstrip("/") if base.endswith("/v1"): base = base[:-3] return f"{base}/v1/realtime/client_secrets" - def get_realtime_calls_url( - self, api_base: Optional[str], model: str, api_version: Optional[str] = None - ) -> str: + def get_realtime_calls_url(self, api_base: Optional[str], model: str, api_version: Optional[str] = None) -> str: base = self.get_api_base(api_base).rstrip("/") if base.endswith("/v1"): base = base[:-3] diff --git a/litellm/llms/openai/responses/count_tokens/handler.py b/litellm/llms/openai/responses/count_tokens/handler.py index 7fb5f6dad781..3dded042de86 100644 --- a/litellm/llms/openai/responses/count_tokens/handler.py +++ b/litellm/llms/openai/responses/count_tokens/handler.py @@ -45,9 +45,7 @@ async def handle_count_tokens_request( try: self.validate_request(model, input) - verbose_logger.debug( - f"Processing OpenAI CountTokens request for model: {model}" - ) + verbose_logger.debug(f"Processing OpenAI CountTokens request for model: {model}") request_body = self.transform_request_to_count_tokens( model=model, @@ -62,13 +60,9 @@ async def handle_count_tokens_request( headers = self.get_required_headers(api_key) - async_client = get_async_httpx_client( - llm_provider=litellm.LlmProviders.OPENAI - ) + async_client = get_async_httpx_client(llm_provider=litellm.LlmProviders.OPENAI) - request_timeout = ( - timeout if timeout is not None else litellm.request_timeout - ) + request_timeout = timeout if timeout is not None else litellm.request_timeout response = await async_client.post( endpoint_url, diff --git a/litellm/llms/openai/responses/count_tokens/token_counter.py b/litellm/llms/openai/responses/count_tokens/token_counter.py index 3d3a659075ee..8e700ecafa14 100644 --- a/litellm/llms/openai/responses/count_tokens/token_counter.py +++ b/litellm/llms/openai/responses/count_tokens/token_counter.py @@ -60,9 +60,7 @@ async def count_tokens( api_base = litellm_params.get("api_base") # Convert chat messages to Responses API input format - input_items, instructions = OpenAICountTokensConfig.messages_to_responses_input( - messages - ) + input_items, instructions = OpenAICountTokensConfig.messages_to_responses_input(messages) # Use system param if instructions not extracted from messages if instructions is None and system is not None: @@ -91,9 +89,7 @@ async def count_tokens( original_response=result, ) except OpenAIError as e: - verbose_logger.warning( - f"OpenAI CountTokens API error: status={e.status_code}, message={e.message}" - ) + verbose_logger.warning(f"OpenAI CountTokens API error: status={e.status_code}, message={e.message}") return TokenCountResponse( total_tokens=0, request_model=request_model, diff --git a/litellm/llms/openai/responses/guardrail_translation/handler.py b/litellm/llms/openai/responses/guardrail_translation/handler.py index 83ec69a9d7a4..6ac33ffa44a2 100644 --- a/litellm/llms/openai/responses/guardrail_translation/handler.py +++ b/litellm/llms/openai/responses/guardrail_translation/handler.py @@ -80,11 +80,9 @@ def get_structured_messages(self, data: dict) -> Optional[List[AllMessageValues] input_data = data.get("input") if input_data is None: return None - messages = ( - LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages( - input=input_data, - responses_api_request=data, - ) + messages = LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages( + input=input_data, + responses_api_request=data, ) return cast(List[AllMessageValues], messages) if messages else None @@ -132,9 +130,7 @@ async def process_input_messages( ) guardrailed_texts = guardrailed_inputs.get("texts", []) data["input"] = guardrailed_texts[0] if guardrailed_texts else input_data - self._apply_guardrailed_tools_to_data( - data, original_tools, guardrailed_inputs.get("tools") - ) + self._apply_guardrailed_tools_to_data(data, original_tools, guardrailed_inputs.get("tools")) verbose_proxy_logger.debug("OpenAI Responses API: Processed string input") return data @@ -195,9 +191,7 @@ async def process_input_messages( task_mappings=task_mappings, ) - verbose_proxy_logger.debug( - "OpenAI Responses API: Processed input messages: %s", input_data - ) + verbose_proxy_logger.debug("OpenAI Responses API: Processed input messages: %s", input_data) return data @@ -232,13 +226,9 @@ def _extract_and_transform_tools( ) = LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools( tools # type: ignore ) - tools_to_check.extend( - cast(List[ChatCompletionToolParam], transformed_tools) - ) + tools_to_check.extend(cast(List[ChatCompletionToolParam], transformed_tools)) - def _remap_tools_to_responses_api_format( - self, guardrailed_tools: List[Any] - ) -> List[Dict[str, Any]]: + def _remap_tools_to_responses_api_format(self, guardrailed_tools: List[Any]) -> List[Dict[str, Any]]: """ Remap guardrail-returned tools (Chat Completion format) back to Responses API request tool format. @@ -350,9 +340,7 @@ async def _apply_guardrail_responses_to_input( elif isinstance(content, list) and content_idx_optional is not None: # Replace specific text item in list content if isinstance(messages[msg_idx]["content"][content_idx_optional], dict): - messages[msg_idx]["content"][content_idx_optional]["text"] = ( - guardrail_response - ) + messages[msg_idx]["content"][content_idx_optional]["text"] = guardrail_response async def process_output_response( self, @@ -394,9 +382,7 @@ async def process_output_response( elif hasattr(response, "output"): response_output = response.output or [] else: - verbose_proxy_logger.debug( - "OpenAI Responses API: No output found in response" - ) + verbose_proxy_logger.debug("OpenAI Responses API: No output found in response") return response if not response_output: @@ -426,9 +412,7 @@ async def process_output_response( # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata @@ -462,9 +446,7 @@ async def process_output_response( task_mappings=task_mappings, ) - verbose_proxy_logger.debug( - "OpenAI Responses API: Processed output response: %s", response - ) + verbose_proxy_logger.debug("OpenAI Responses API: Processed output response: %s", response) return response @@ -527,17 +509,13 @@ async def process_output_streaming_response( if "response" not in request_data: request_data["response"] = response_obj if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata inputs = GenericGuardrailAPIInputs(texts=texts_to_check) if tool_calls_to_check: - inputs["tool_calls"] = cast( - List[ChatCompletionToolCallChunk], tool_calls_to_check - ) + inputs["tool_calls"] = cast(List[ChatCompletionToolCallChunk], tool_calls_to_check) response_model = response_obj.get("model") if response_model: inputs["model"] = response_model @@ -566,19 +544,14 @@ async def process_output_streaming_response( # Case 2: response.output_item.done — extract tool calls only. # # ------------------------------------------------------------------ # if final_chunk.get("type") == "response.output_item.done": - model_response_stream = OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream( - final_chunk + model_response_stream = ( + OpenAiResponsesToChatCompletionStreamIterator.translate_responses_chunk_to_openai_stream(final_chunk) ) tool_calls = model_response_stream.choices[0].delta.tool_calls if tool_calls: inputs = GenericGuardrailAPIInputs() - inputs["tool_calls"] = cast( - List[ChatCompletionToolCallChunk], tool_calls - ) - if ( - hasattr(model_response_stream, "model") - and model_response_stream.model - ): + inputs["tool_calls"] = cast(List[ChatCompletionToolCallChunk], tool_calls) + if hasattr(model_response_stream, "model") and model_response_stream.model: inputs["model"] = model_response_stream.model await guardrail_to_apply.apply_guardrail( inputs=inputs, @@ -597,9 +570,7 @@ async def process_output_streaming_response( if string_so_far: fallback_inputs = GenericGuardrailAPIInputs(texts=[string_so_far]) response_model = ( - final_chunk.get("response", {}).get("model") - if isinstance(final_chunk.get("response"), dict) - else None + final_chunk.get("response", {}).get("model") if isinstance(final_chunk.get("response"), dict) else None ) if response_model: fallback_inputs["model"] = response_model @@ -615,10 +586,7 @@ def _check_streaming_has_ended(self, responses_so_far: List[Any]) -> bool: """ Check if the streaming has ended. """ - return all( - response.choices[0].finish_reason is not None - for response in responses_so_far - ) + return all(response.choices[0].finish_reason is not None for response in responses_so_far) def get_streaming_string_so_far(self, responses_so_far: List[Any]) -> str: """ @@ -638,11 +606,7 @@ def _has_text_content(self, response: "ResponsesAPIResponse") -> bool: for output_item in response.output: if isinstance(output_item, BaseModel): try: - generic_response_output_item = ( - GenericResponseOutputItem.model_validate( - output_item.model_dump() - ) - ) + generic_response_output_item = GenericResponseOutputItem.model_validate(output_item.model_dump()) if generic_response_output_item.content: output_item = generic_response_output_item except Exception: @@ -682,13 +646,13 @@ def _extract_output_text_and_images( # Check if this is a tool call (OutputFunctionToolCall) if isinstance(output_item, OutputFunctionToolCall): if tool_calls_to_check is not None: - tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( - tool_call_item=output_item, - index=output_idx, - ) - tool_calls_to_check.append( - cast(ChatCompletionToolCallChunk, tool_call_dict) + tool_call_dict = ( + LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( + tool_call_item=output_item, + index=output_idx, + ) ) + tool_calls_to_check.append(cast(ChatCompletionToolCallChunk, tool_call_dict)) return elif ( isinstance(output_item, BaseModel) @@ -696,17 +660,15 @@ def _extract_output_text_and_images( and getattr(output_item, "type") == "function_call" ): if tool_calls_to_check is not None: - tool_call_dict = LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( - tool_call_item=output_item, - index=output_idx, - ) - tool_calls_to_check.append( - cast(ChatCompletionToolCallChunk, tool_call_dict) + tool_call_dict = ( + LiteLLMCompletionResponsesConfig.convert_response_function_tool_call_to_chat_completion_tool_call( + tool_call_item=output_item, + index=output_idx, + ) ) + tool_calls_to_check.append(cast(ChatCompletionToolCallChunk, tool_call_dict)) return - elif ( - isinstance(output_item, dict) and output_item.get("type") == "function_call" - ): + elif isinstance(output_item, dict) and output_item.get("type") == "function_call": # Handle dict representation of tool call if tool_calls_to_check is not None: # Convert dict to ResponseFunctionToolCall for processing @@ -716,9 +678,7 @@ def _extract_output_text_and_images( tool_call_item=tool_call_obj, index=output_idx, ) - tool_calls_to_check.append( - cast(ChatCompletionToolCallChunk, tool_call_dict) - ) + tool_calls_to_check.append(cast(ChatCompletionToolCallChunk, tool_call_dict)) except Exception: pass return @@ -728,9 +688,7 @@ def _extract_output_text_and_images( if isinstance(output_item, BaseModel): try: output_item_dump = output_item.model_dump() - generic_response_output_item = GenericResponseOutputItem.model_validate( - output_item_dump - ) + generic_response_output_item = GenericResponseOutputItem.model_validate(output_item_dump) if generic_response_output_item.content: content = generic_response_output_item.content except Exception: @@ -747,9 +705,7 @@ def _extract_output_text_and_images( if not content: return - verbose_proxy_logger.debug( - "OpenAI Responses API: Processing output item: %s", output_item - ) + verbose_proxy_logger.debug("OpenAI Responses API: Processing output item: %s", output_item) # Iterate through content items (list of OutputText objects) for content_idx, content_item in enumerate(content): @@ -805,9 +761,7 @@ async def _apply_guardrail_responses_to_output( elif isinstance(output_item, BaseModel): # Handle other Pydantic models by converting to GenericResponseOutputItem try: - generic_item = GenericResponseOutputItem.model_validate( - output_item.model_dump() - ) + generic_item = GenericResponseOutputItem.model_validate(output_item.model_dump()) if generic_item.content and content_idx < len(generic_item.content): content_item = generic_item.content[content_idx] if isinstance(content_item, OutputText): diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py index c18f2216f612..d107ca7a0d74 100644 --- a/litellm/llms/openai/responses/transformation.py +++ b/litellm/llms/openai/responses/transformation.py @@ -96,9 +96,7 @@ def map_openai_params( temperature = params.get("temperature") if temperature is not None and temperature != 1: reasoning = params.get("reasoning") or {} - effort = ( - reasoning.get("effort") if isinstance(reasoning, dict) else None - ) + effort = reasoning.get("effort") if isinstance(reasoning, dict) else None supports_none = self._supports_reasoning_effort_none(model=model) if supports_none and (effort == "none" or effort is None): pass # flexible temperature allowed @@ -136,15 +134,11 @@ def transform_responses_api_request( input = self._validate_input_param(input) tools = response_api_optional_request_params.get("tools") - input, tools = self.remove_cache_control_flag_from_input_and_tools( - model=model, input=input, tools=tools - ) + input, tools = self.remove_cache_control_flag_from_input_and_tools(model=model, input=input, tools=tools) if tools is not None: response_api_optional_request_params["tools"] = tools final_request_params = dict( - ResponsesAPIRequestParams( - model=model, input=input, **response_api_optional_request_params - ) + ResponsesAPIRequestParams(model=model, input=input, **response_api_optional_request_params) ) return final_request_params @@ -181,9 +175,7 @@ def remove_cache_control_flag_from_input_and_tools( return input, tools - def _validate_input_param( - self, input: Union[str, ResponseInputParam] - ) -> Union[str, ResponseInputParam]: + def _validate_input_param(self, input: Union[str, ResponseInputParam]) -> Union[str, ResponseInputParam]: """ Ensure all input fields if pydantic are converted to dict @@ -241,15 +233,12 @@ def _handle_reasoning_item(self, item: Dict[str, Any]) -> Dict[str, Any]: return dict_reasoning_item except Exception as e: - verbose_logger.debug( - f"Failed to create ResponseReasoningItem, falling back to manual filtering: {e}" - ) + verbose_logger.debug(f"Failed to create ResponseReasoningItem, falling back to manual filtering: {e}") # Fallback: manually filter out known None fields filtered_item = { k: v for k, v in item.items() - if v is not None - or k not in {"status", "content", "encrypted_content"} + if v is not None or k not in {"status", "content", "encrypted_content"} } return filtered_item return item @@ -267,21 +256,15 @@ def transform_response_api_response( additional_args={"complete_input_dict": {}}, ) raw_response_json = raw_response.json() - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["created_at"] - ) + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["created_at"]) except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) try: response = ResponsesAPIResponse(**raw_response_json) except Exception: - verbose_logger.debug( - f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" - ) + verbose_logger.debug(f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct") response = ResponsesAPIResponse.model_construct(**raw_response_json) # Store processed headers in additional_headers so they get returned to the client @@ -289,16 +272,9 @@ def transform_response_api_response( response._hidden_params["headers"] = raw_response_headers return response - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() - api_key = ( - litellm_params.api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = litellm_params.api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") headers.setdefault("Content-Type", "application/json") headers["Authorization"] = f"Bearer {api_key}" return headers @@ -336,9 +312,7 @@ def transform_streaming_response( # Convert the dictionary to a properly typed ResponsesAPIStreamingResponse verbose_logger.debug("Raw OpenAI Chunk=%s", parsed_chunk) event_type = str(parsed_chunk.get("type")) - event_pydantic_model = OpenAIResponsesAPIConfig.get_event_model_class( - event_type=event_type - ) + event_pydantic_model = OpenAIResponsesAPIConfig.get_event_model_class(event_type=event_type) # Some OpenAI-compatible providers send error.code: null; coalesce so validation succeeds. try: error_obj = parsed_chunk.get("error") @@ -353,8 +327,7 @@ def transform_streaming_response( return event_pydantic_model(**parsed_chunk) except ValidationError: verbose_logger.debug( - "Pydantic validation failed for %s with chunk %s, " - "falling back to model_construct", + "Pydantic validation failed for %s with chunk %s, falling back to model_construct", event_pydantic_model.__name__, parsed_chunk, ) @@ -438,9 +411,7 @@ def should_fake_stream( ): return True except Exception as e: - verbose_logger.debug( - f"Error getting model info in OpenAIResponsesAPIConfig: {e}" - ) + verbose_logger.debug(f"Error getting model info in OpenAIResponsesAPIConfig: {e}") return False def supports_native_websocket(self) -> bool: @@ -463,9 +434,7 @@ def transform_delete_response_api_request( OpenAI API expects the following request - DELETE /v1/responses/{response_id} """ - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}" data: Dict = {} return url, data @@ -481,9 +450,7 @@ def transform_delete_response_api_response( try: raw_response_json = raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) return DeleteResponseResult(**raw_response_json) ######################################################### @@ -502,9 +469,7 @@ def transform_get_response_api_request( OpenAI API expects the following request - GET /v1/responses/{response_id} """ - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}" data: Dict = {} return url, data @@ -520,9 +485,7 @@ def transform_get_response_api_response( try: raw_response_json = raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) response = ResponsesAPIResponse(**raw_response_json) @@ -546,9 +509,7 @@ def transform_list_input_items_request( limit: int = 20, order: Literal["asc", "desc"] = "desc", ) -> Tuple[str, Dict]: - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}/input_items" params: Dict[str, Any] = {} if after is not None: @@ -571,9 +532,7 @@ def transform_list_input_items_response( try: return raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) ######################################################### ########## CANCEL RESPONSE API TRANSFORMATION ########## @@ -591,9 +550,7 @@ def transform_cancel_response_api_request( OpenAI API expects the following request - POST /v1/responses/{response_id}/cancel """ - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}/cancel" data: Dict = {} return url, data @@ -609,9 +566,7 @@ def transform_cancel_response_api_response( try: raw_response_json = raw_response.json() except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) @@ -646,16 +601,10 @@ def transform_compact_response_api_request( input = self._validate_input_param(input) tools = response_api_optional_request_params.get("tools") - input, tools = self.remove_cache_control_flag_from_input_and_tools( - model=model, input=input, tools=tools - ) + input, tools = self.remove_cache_control_flag_from_input_and_tools(model=model, input=input, tools=tools) if tools is not None: response_api_optional_request_params["tools"] = tools - data = dict( - ResponsesAPIRequestParams( - model=model, input=input, **response_api_optional_request_params - ) - ) + data = dict(ResponsesAPIRequestParams(model=model, input=input, **response_api_optional_request_params)) return url, data @@ -673,22 +622,16 @@ def transform_compact_response_api_response( additional_args={"complete_input_dict": {}}, ) raw_response_json = raw_response.json() - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["created_at"] - ) + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["created_at"]) except Exception: - raise OpenAIError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise OpenAIError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) try: response = ResponsesAPIResponse(**raw_response_json) except Exception: - verbose_logger.debug( - f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct" - ) + verbose_logger.debug(f"Error constructing ResponsesAPIResponse: {raw_response_json}, using model_construct") response = ResponsesAPIResponse.model_construct(**raw_response_json) response._hidden_params["additional_headers"] = processed_headers diff --git a/litellm/llms/openai/speech/guardrail_translation/handler.py b/litellm/llms/openai/speech/guardrail_translation/handler.py index f0c3149d0aee..3f29a8055d8a 100644 --- a/litellm/llms/openai/speech/guardrail_translation/handler.py +++ b/litellm/llms/openai/speech/guardrail_translation/handler.py @@ -45,9 +45,7 @@ async def process_input_messages( """ input_text = data.get("input") if input_text is None: - verbose_proxy_logger.debug( - "OpenAI Text-to-Speech: No input text found in request data" - ) + verbose_proxy_logger.debug("OpenAI Text-to-Speech: No input text found in request data") return data if isinstance(input_text, str): @@ -66,8 +64,7 @@ async def process_input_messages( data["input"] = guardrailed_texts[0] if guardrailed_texts else input_text verbose_proxy_logger.debug( - "OpenAI Text-to-Speech: Applied guardrail to input text. " - "Original length: %d, New length: %d", + "OpenAI Text-to-Speech: Applied guardrail to input text. Original length: %d, New length: %d", len(input_text), len(data["input"]), ) @@ -103,7 +100,6 @@ async def process_output_response( Unmodified response (audio data doesn't need text guardrails) """ verbose_proxy_logger.debug( - "OpenAI Text-to-Speech: Output processing not applicable " - "(output is audio data, not text)" + "OpenAI Text-to-Speech: Output processing not applicable (output is audio data, not text)" ) return response diff --git a/litellm/llms/openai/transcriptions/gpt_transformation.py b/litellm/llms/openai/transcriptions/gpt_transformation.py index 34621c44e22d..56a1e39ecefa 100644 --- a/litellm/llms/openai/transcriptions/gpt_transformation.py +++ b/litellm/llms/openai/transcriptions/gpt_transformation.py @@ -10,9 +10,7 @@ class OpenAIGPTAudioTranscriptionConfig(OpenAIWhisperAudioTranscriptionConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: """ Get the supported OpenAI params for the `gpt-4o-transcribe` models """ diff --git a/litellm/llms/openai/transcriptions/guardrail_translation/handler.py b/litellm/llms/openai/transcriptions/guardrail_translation/handler.py index 92cf4398f053..fc1cae75b807 100644 --- a/litellm/llms/openai/transcriptions/guardrail_translation/handler.py +++ b/litellm/llms/openai/transcriptions/guardrail_translation/handler.py @@ -47,8 +47,7 @@ async def process_input_messages( Unmodified data (audio files don't need text guardrails) """ verbose_proxy_logger.debug( - "OpenAI Audio Transcription: Input processing not applicable " - "(input is audio file, not text)" + "OpenAI Audio Transcription: Input processing not applicable (input is audio file, not text)" ) return data @@ -73,9 +72,7 @@ async def process_output_response( Modified response with guardrails applied to transcribed text """ if not hasattr(response, "text") or response.text is None: - verbose_proxy_logger.debug( - "OpenAI Audio Transcription: No text in response to process" - ) + verbose_proxy_logger.debug("OpenAI Audio Transcription: No text in response to process") return response if isinstance(response.text, str): @@ -90,9 +87,7 @@ async def process_output_response( # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata diff --git a/litellm/llms/openai/transcriptions/handler.py b/litellm/llms/openai/transcriptions/handler.py index 44fb5da85903..76178051ca1f 100644 --- a/litellm/llms/openai/transcriptions/handler.py +++ b/litellm/llms/openai/transcriptions/handler.py @@ -37,11 +37,7 @@ async def make_openai_audio_transcriptions_request( - call openai_aclient.audio.transcriptions.create by default """ try: - raw_response = ( - await openai_aclient.audio.transcriptions.with_raw_response.create( - **data, timeout=timeout - ) - ) # type: ignore + raw_response = await openai_aclient.audio.transcriptions.with_raw_response.create(**data, timeout=timeout) # type: ignore headers = dict(raw_response.headers) response = raw_response.parse() @@ -62,18 +58,12 @@ def make_sync_openai_audio_transcriptions_request( """ try: if litellm.return_response_headers is True: - raw_response = ( - openai_client.audio.transcriptions.with_raw_response.create( - **data, timeout=timeout - ) - ) # type: ignore + raw_response = openai_client.audio.transcriptions.with_raw_response.create(**data, timeout=timeout) # type: ignore headers = dict(raw_response.headers) response = raw_response.parse() return headers, response else: - response = openai_client.audio.transcriptions.create( - **data, timeout=timeout - ) # type: ignore + response = openai_client.audio.transcriptions.create(**data, timeout=timeout) # type: ignore return None, response except Exception as e: raise e diff --git a/litellm/llms/openai/transcriptions/whisper_transformation.py b/litellm/llms/openai/transcriptions/whisper_transformation.py index 2c01156fe05b..ae7d0bb30b29 100644 --- a/litellm/llms/openai/transcriptions/whisper_transformation.py +++ b/litellm/llms/openai/transcriptions/whisper_transformation.py @@ -47,9 +47,7 @@ def get_complete_url( return api_base or "" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: """ Get the supported OpenAI params for the `whisper-1` models """ @@ -109,17 +107,13 @@ def transform_audio_transcription_request( data = {"model": model, "file": audio_file, **optional_params} if "response_format" not in data: - data["response_format"] = ( - "verbose_json" # ensures 'duration' is received - used for cost calculation - ) + data["response_format"] = "verbose_json" # ensures 'duration' is received - used for cost calculation return AudioTranscriptionRequestData( data=data, ) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: return OpenAIError( status_code=status_code, message=error_message, @@ -138,10 +132,7 @@ def transform_audio_transcription_response( raise return TranscriptionResponse(text=raw_response.text) - if any( - key in raw_response_json - for key in TranscriptionResponse.model_fields.keys() - ): + if any(key in raw_response_json for key in TranscriptionResponse.model_fields.keys()): return TranscriptionResponse(**raw_response_json) else: raise ValueError( diff --git a/litellm/llms/openai/vector_store_files/transformation.py b/litellm/llms/openai/vector_store_files/transformation.py index 52202f57fd34..653a31f2e80f 100644 --- a/litellm/llms/openai/vector_store_files/transformation.py +++ b/litellm/llms/openai/vector_store_files/transformation.py @@ -30,9 +30,7 @@ class OpenAIVectorStoreFilesConfig(BaseVectorStoreFilesConfig): ASSISTANTS_HEADER_KEY = "OpenAI-Beta" ASSISTANTS_HEADER_VALUE = "assistants=v2" - def get_auth_credentials( - self, litellm_params: Dict[str, Any] - ) -> VectorStoreFileAuthCredentials: + def get_auth_credentials(self, litellm_params: Dict[str, Any]) -> VectorStoreFileAuthCredentials: api_key = litellm_params.get("api_key") if api_key is None: raise ValueError("api_key is required") @@ -68,12 +66,7 @@ def validate_environment( litellm_params: Optional[GenericLiteLLMParams], ) -> Dict[str, str]: litellm_params = litellm_params or GenericLiteLLMParams() - api_key = ( - litellm_params.api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = litellm_params.api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") headers.update( { "Authorization": f"Bearer {api_key}", @@ -99,9 +92,7 @@ def get_complete_url( or "https://api.openai.com/v1" ) base_url = base_url.rstrip("/") - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") return f"{base_url}/vector_stores/{encoded_vector_store_id}/files" def transform_create_vector_store_file_request( diff --git a/litellm/llms/openai/vector_stores/transformation.py b/litellm/llms/openai/vector_stores/transformation.py index bd095a0a1b7c..6ccf8e271e58 100644 --- a/litellm/llms/openai/vector_stores/transformation.py +++ b/litellm/llms/openai/vector_stores/transformation.py @@ -31,9 +31,7 @@ class OpenAIVectorStoreConfig(BaseVectorStoreConfig): ASSISTANTS_HEADER_KEY = "OpenAI-Beta" ASSISTANTS_HEADER_VALUE = "assistants=v2" - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: api_key = litellm_params.get("api_key") if api_key is None: raise ValueError("api_key is required") @@ -49,16 +47,9 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [("POST", "/vector_stores")], } - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() - api_key = ( - litellm_params.api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = litellm_params.api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") headers.update( { "Authorization": f"Bearer {api_key}", @@ -109,22 +100,14 @@ def transform_search_vector_store_request( litellm_params: dict, extra_body: Optional[Dict[str, Any]] = None, ) -> Tuple[str, Dict]: - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}/search" typed_request_body = VectorStoreSearchRequest( query=query, filters=vector_store_search_optional_params.get("filters", None), - max_num_results=vector_store_search_optional_params.get( - "max_num_results", None - ), - ranking_options=vector_store_search_optional_params.get( - "ranking_options", None - ), - rewrite_query=vector_store_search_optional_params.get( - "rewrite_query", None - ), + max_num_results=vector_store_search_optional_params.get("max_num_results", None), + ranking_options=vector_store_search_optional_params.get("ranking_options", None), + rewrite_query=vector_store_search_optional_params.get("rewrite_query", None), ) dict_request_body = cast(dict, typed_request_body) @@ -155,21 +138,15 @@ def transform_create_vector_store_request( typed_request_body = VectorStoreCreateRequest( name=vector_store_create_optional_params.get("name", None), file_ids=vector_store_create_optional_params.get("file_ids", None), - expires_after=vector_store_create_optional_params.get( - "expires_after", None - ), - chunking_strategy=vector_store_create_optional_params.get( - "chunking_strategy", None - ), + expires_after=vector_store_create_optional_params.get("expires_after", None), + chunking_strategy=vector_store_create_optional_params.get("chunking_strategy", None), metadata=metadata_payload, ) dict_request_body = cast(dict, typed_request_body) return url, dict_request_body - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: try: response_json = response.json() return VectorStoreCreateResponse(**response_json) diff --git a/litellm/llms/openai/videos/transformation.py b/litellm/llms/openai/videos/transformation.py index 520a42e9dd16..684601367b62 100644 --- a/litellm/llms/openai/videos/transformation.py +++ b/litellm/llms/openai/videos/transformation.py @@ -79,12 +79,7 @@ def validate_environment( if litellm_params and litellm_params.api_key: api_key = api_key or litellm_params.api_key - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") headers.update( { "Authorization": f"Bearer {api_key}", @@ -126,17 +121,13 @@ def transform_video_create_request( } # Create the request data - video_create_request = CreateVideoRequest( - model=model, prompt=prompt, **video_create_optional_request_params - ) + video_create_request = CreateVideoRequest(model=model, prompt=prompt, **video_create_optional_request_params) request_dict = cast(Dict, video_create_request) request_dict = self._decode_character_ids_in_create_video_request(request_dict) # Handle input_reference parameter if provided _input_reference = video_create_optional_request_params.get("input_reference") - data_without_files = { - k: v for k, v in request_dict.items() if k not in ["input_reference"] - } + data_without_files = {k: v for k, v in request_dict.items() if k not in ["input_reference"]} files_list: List[Tuple[str, Any]] = [] # Handle input_reference parameter @@ -191,9 +182,7 @@ def transform_video_create_response( video_obj = VideoObject(**response_data) # type: ignore[arg-type] if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, model - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model) usage_data = {} if video_obj: @@ -222,9 +211,7 @@ def transform_video_content_request( - GET /v1/videos/{video_id}/content?variant=thumbnail """ original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # Construct the URL for video content download url = f"{api_base.rstrip('/')}/{encoded_video_id}/content" @@ -256,9 +243,7 @@ def transform_video_remix_request( - POST /v1/videos/{video_id}/remix """ original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # Construct the URL for video remix url = f"{api_base.rstrip('/')}/{encoded_video_id}/remix" @@ -295,9 +280,7 @@ def transform_video_remix_response( video_obj = VideoObject(**response_data) # type: ignore[arg-type] if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, None - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) # Create usage object with duration information for cost calculation # Video remix API doesn't provide usage, so we create one with duration @@ -403,9 +386,7 @@ def transform_video_delete_request( - DELETE /v1/videos/{video_id} """ original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # Construct the URL for video delete url = f"{api_base.rstrip('/')}/{encoded_video_id}" @@ -442,9 +423,7 @@ def transform_video_status_retrieve_request( """ # Extract the original video_id (remove provider encoding if present) original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # For video retrieve, we just need to construct the URL url = f"{api_base.rstrip('/')}/{encoded_video_id}" @@ -468,9 +447,7 @@ def transform_video_status_retrieve_response( video_obj = VideoObject(**response_data) # type: ignore[arg-type] if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, None - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) return video_obj @@ -513,9 +490,7 @@ def transform_video_get_character_request( headers: dict, ) -> Tuple[str, Dict]: original_character_id = extract_original_character_id(character_id) - encoded_character_id = encode_url_path_segment( - original_character_id, field_name="character_id" - ) + encoded_character_id = encode_url_path_segment(original_character_id, field_name="character_id") url = f"{api_base.rstrip('/')}/characters/{encoded_character_id}" return url, {} @@ -552,9 +527,7 @@ def transform_video_edit_response( ) -> VideoObject: video_obj = VideoObject(**raw_response.json()) if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, None - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) return video_obj def transform_video_extension_request( @@ -586,9 +559,7 @@ def transform_video_extension_response( ) -> VideoObject: video_obj = VideoObject(**raw_response.json()) if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, None - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) return video_obj def _add_image_to_files( @@ -603,9 +574,7 @@ def _add_image_to_files( if isinstance(image, BufferedReader): files_list.append((field_name, (image.name, image, image_content_type))) else: - files_list.append( - (field_name, ("input_reference.png", image, image_content_type)) - ) + files_list.append((field_name, ("input_reference.png", image, image_content_type))) def _add_video_to_files( self, diff --git a/litellm/llms/openai_like/chat/handler.py b/litellm/llms/openai_like/chat/handler.py index 821fc9b7f157..0da0f3d90f05 100644 --- a/litellm/llms/openai_like/chat/handler.py +++ b/litellm/llms/openai_like/chat/handler.py @@ -37,21 +37,15 @@ async def make_call( if client is None: client = litellm.module_level_aclient - response = await client.post( - api_base, headers=headers, data=data, stream=not fake_stream - ) + response = await client.post(api_base, headers=headers, data=data, stream=not fake_stream) if streaming_decoder is not None: - completion_stream: Any = streaming_decoder.aiter_bytes( - response.aiter_bytes(chunk_size=1024) - ) + completion_stream: Any = streaming_decoder.aiter_bytes(response.aiter_bytes(chunk_size=1024)) elif fake_stream: model_response = ModelResponse(**response.json()) completion_stream = MockResponseIterator(model_response=model_response) else: - completion_stream = ModelResponseIterator( - streaming_response=response.aiter_lines(), sync_stream=False - ) + completion_stream = ModelResponseIterator(streaming_response=response.aiter_lines(), sync_stream=False) # LOGGING logging_obj.post_call( input=messages, @@ -78,24 +72,18 @@ def make_sync_call( if client is None: client = litellm.module_level_client # Create a new client if none provided - response = client.post( - api_base, headers=headers, data=data, stream=not fake_stream, timeout=timeout - ) + response = client.post(api_base, headers=headers, data=data, stream=not fake_stream, timeout=timeout) if response.status_code != 200: raise OpenAILikeError(status_code=response.status_code, message=response.read()) if streaming_decoder is not None: - completion_stream = streaming_decoder.iter_bytes( - response.iter_bytes(chunk_size=1024) - ) + completion_stream = streaming_decoder.iter_bytes(response.iter_bytes(chunk_size=1024)) elif fake_stream: model_response = ModelResponse(**response.json()) completion_stream = MockResponseIterator(model_response=model_response) else: - completion_stream = ModelResponseIterator( - streaming_response=response.iter_lines(), sync_stream=True - ) + completion_stream = ModelResponseIterator(streaming_response=response.iter_lines(), sync_stream=True) # LOGGING logging_obj.post_call( @@ -184,9 +172,7 @@ async def acompletion_function( client = litellm.module_level_aclient try: - response = await client.post( - api_base, headers=headers, data=json.dumps(data), timeout=timeout - ) + response = await client.post(api_base, headers=headers, data=json.dumps(data), timeout=timeout) response.raise_for_status() except httpx.HTTPStatusError as e: raise OpenAILikeError( @@ -241,9 +227,7 @@ def completion( ] = None, # if openai-compatible api needs custom stream decoder - e.g. sagemaker fake_stream: bool = False, ): - custom_endpoint = custom_endpoint or optional_params.pop( - "custom_endpoint", None - ) + custom_endpoint = custom_endpoint or optional_params.pop("custom_endpoint", None) base_model: Optional[str] = optional_params.pop("base_model", None) api_base, headers = self._validate_environment( api_base=api_base, @@ -264,12 +248,8 @@ def completion( provider_config = ProviderConfigManager.get_provider_chat_config( model=model, provider=LlmProviders(custom_llm_provider) ) - if isinstance(provider_config, OpenAIGPTConfig) or isinstance( - provider_config, OpenAIConfig - ): - messages = provider_config._transform_messages( - messages=messages, model=model - ) + if isinstance(provider_config, OpenAIGPTConfig) or isinstance(provider_config, OpenAIConfig): + messages = provider_config._transform_messages(messages=messages, model=model) data = { "model": model, @@ -343,11 +323,7 @@ def completion( ## COMPLETION CALL if stream is True: completion_stream = make_sync_call( - client=( - client - if client is not None and isinstance(client, HTTPHandler) - else None - ), + client=(client if client is not None and isinstance(client, HTTPHandler) else None), api_base=api_base, headers=headers, data=json.dumps(data), @@ -369,9 +345,7 @@ def completion( if client is None or not isinstance(client, HTTPHandler): client = HTTPHandler(timeout=timeout) # type: ignore try: - response = client.post( - url=api_base, headers=headers, data=json.dumps(data) - ) + response = client.post(url=api_base, headers=headers, data=json.dumps(data)) response.raise_for_status() except httpx.HTTPStatusError as e: @@ -380,9 +354,7 @@ def completion( message=e.response.text, ) except httpx.TimeoutException: - raise OpenAILikeError( - status_code=408, message="Timeout error occurred." - ) + raise OpenAILikeError(status_code=408, message="Timeout error occurred.") except Exception as e: raise OpenAILikeError(status_code=500, message=str(e)) return OpenAILikeChatConfig._transform_response( diff --git a/litellm/llms/openai_like/chat/transformation.py b/litellm/llms/openai_like/chat/transformation.py index 1c8cd574c011..a2c847a410f4 100644 --- a/litellm/llms/openai_like/chat/transformation.py +++ b/litellm/llms/openai_like/chat/transformation.py @@ -27,9 +27,7 @@ def _get_openai_compatible_provider_info( api_key: Optional[str], ) -> Tuple[Optional[str], Optional[str]]: api_base = api_base or get_secret_str("OPENAI_LIKE_API_BASE") # type: ignore - dynamic_api_key = ( - api_key or get_secret_str("OPENAI_LIKE_API_KEY") or "" - ) # vllm does not require an api key + dynamic_api_key = api_key or get_secret_str("OPENAI_LIKE_API_KEY") or "" # vllm does not require an api key return api_base, dynamic_api_key @staticmethod @@ -107,19 +105,15 @@ def _transform_response( if json_mode: for choice in response_json["choices"]: - message = ( - OpenAILikeChatConfig._json_mode_convert_tool_response_to_message( - choice.get("message"), json_mode - ) + message = OpenAILikeChatConfig._json_mode_convert_tool_response_to_message( + choice.get("message"), json_mode ) choice["message"] = message returned_response = ModelResponse(**response_json) if custom_llm_provider is not None: - returned_response.model = ( - custom_llm_provider + "/" + (returned_response.model or "") - ) + returned_response.model = custom_llm_provider + "/" + (returned_response.model or "") if base_model is not None: returned_response._hidden_params["model"] = base_model @@ -164,13 +158,8 @@ def map_openai_params( drop_params: bool, replace_max_completion_tokens_with_max_tokens: bool = True, ) -> dict: - mapped_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) - if ( - "max_completion_tokens" in non_default_params - and replace_max_completion_tokens_with_max_tokens - ): + mapped_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) + if "max_completion_tokens" in non_default_params and replace_max_completion_tokens_with_max_tokens: mapped_params["max_tokens"] = non_default_params[ "max_completion_tokens" ] # most openai-compatible providers support 'max_tokens' not 'max_completion_tokens' diff --git a/litellm/llms/openai_like/common_utils.py b/litellm/llms/openai_like/common_utils.py index 116277b6dd39..40f2e5c3f5cc 100644 --- a/litellm/llms/openai_like/common_utils.py +++ b/litellm/llms/openai_like/common_utils.py @@ -9,9 +9,7 @@ def __init__(self, status_code, message): self.message = message self.request = httpx.Request(method="POST", url="https://www.litellm.ai") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class OpenAILikeBase: diff --git a/litellm/llms/openai_like/dynamic_config.py b/litellm/llms/openai_like/dynamic_config.py index 9ed9734edae9..3c763ed9b9b0 100644 --- a/litellm/llms/openai_like/dynamic_config.py +++ b/litellm/llms/openai_like/dynamic_config.py @@ -20,9 +20,7 @@ def create_config_class(provider: SimpleProviderConfig): """Generate config class dynamically from JSON configuration""" # Choose base class - base_class: type = ( - OpenAIGPTConfig if provider.base_class == "openai_gpt" else OpenAILikeChatConfig - ) + base_class: type = OpenAIGPTConfig if provider.base_class == "openai_gpt" else OpenAILikeChatConfig class JSONProviderConfig(base_class): # type: ignore[valid-type,misc] @overload @@ -48,13 +46,9 @@ def _transform_messages( messages = handle_messages_with_content_list_to_str_conversion(messages) if is_async: - return super()._transform_messages( - messages=messages, model=model, is_async=True - ) + return super()._transform_messages(messages=messages, model=model, is_async=True) else: - return super()._transform_messages( - messages=messages, model=model, is_async=False - ) + return super()._transform_messages(messages=messages, model=model, is_async=False) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] @@ -101,9 +95,7 @@ def get_supported_openai_params(self, model: str) -> list: supported_params = super().get_supported_openai_params(model=model) - _supports_fc = supports_function_calling( - model=model, custom_llm_provider=provider.slug - ) + _supports_fc = supports_function_calling(model=model, custom_llm_provider=provider.slug) if not _supports_fc: tool_params = [ diff --git a/litellm/llms/openai_like/embedding/handler.py b/litellm/llms/openai_like/embedding/handler.py index 285595d2791b..52eafc05b2c2 100644 --- a/litellm/llms/openai_like/embedding/handler.py +++ b/litellm/llms/openai_like/embedding/handler.py @@ -59,9 +59,7 @@ async def aembedding( message=e.response.text if e.response else str(e), ) except httpx.TimeoutException: - raise OpenAILikeError( - status_code=408, message="Timeout error occurred." - ) + raise OpenAILikeError(status_code=408, message="Timeout error occurred.") except Exception as e: raise OpenAILikeError(status_code=500, message=str(e)) @@ -105,9 +103,7 @@ def embedding( custom_endpoint=custom_endpoint, ) model = model - filtered_optional_params = { - k: v for k, v in optional_params.items() if v not in (None, "") - } + filtered_optional_params = {k: v for k, v in optional_params.items() if v not in (None, "")} data = {"model": model, "input": input, **filtered_optional_params} ## LOGGING diff --git a/litellm/llms/openai_like/json_loader.py b/litellm/llms/openai_like/json_loader.py index c6ff0f7a394a..4640bb8a422c 100644 --- a/litellm/llms/openai_like/json_loader.py +++ b/litellm/llms/openai_like/json_loader.py @@ -52,9 +52,7 @@ def load(cls): cls._loaded = True except Exception as e: - verbose_logger.warning( - f"Warning: Failed to load JSON provider configs: {e}" - ) + verbose_logger.warning(f"Warning: Failed to load JSON provider configs: {e}") cls._loaded = True @classmethod diff --git a/litellm/llms/openrouter/chat/transformation.py b/litellm/llms/openrouter/chat/transformation.py index 107d5c25e6d8..ca287f5de04f 100644 --- a/litellm/llms/openrouter/chat/transformation.py +++ b/litellm/llms/openrouter/chat/transformation.py @@ -39,9 +39,9 @@ def get_supported_openai_params(self, model: str) -> list: """ supported_params = super().get_supported_openai_params(model=model) try: - if litellm.supports_reasoning( - model=model, custom_llm_provider="openrouter" - ) or litellm.supports_reasoning(model=model): + if litellm.supports_reasoning(model=model, custom_llm_provider="openrouter") or litellm.supports_reasoning( + model=model + ): supported_params.append("reasoning_effort") supported_params.append("thinking") except Exception: @@ -59,9 +59,7 @@ def map_openai_params( if non_default_params.get("reasoning_effort") == "max": non_default_params = {**non_default_params, "reasoning_effort": "xhigh"} - mapped_openai_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_openai_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) # OpenRouter-only parameters extra_body = {} @@ -74,9 +72,7 @@ def map_openai_params( extra_body["models"] = models if route is not None: extra_body["route"] = route - mapped_openai_params["extra_body"] = ( - extra_body # openai client supports `extra_body` param - ) + mapped_openai_params["extra_body"] = extra_body # openai client supports `extra_body` param return mapped_openai_params def _supports_cache_control_in_content(self, model: str) -> bool: @@ -87,10 +83,7 @@ def _supports_cache_control_in_content(self, model: str) -> bool: bool: True if model supports cache_control (Claude or Gemini models) """ model_lower = model.lower() - return any( - supported_model.value in model_lower - for supported_model in CacheControlSupportedModels - ) + return any(supported_model.value in model_lower for supported_model in CacheControlSupportedModels) def remove_cache_control_flag_from_messages_and_tools( self, @@ -101,13 +94,9 @@ def remove_cache_control_flag_from_messages_and_tools( if self._supports_cache_control_in_content(model): return messages, tools else: - return super().remove_cache_control_flag_from_messages_and_tools( - model, messages, tools - ) + return super().remove_cache_control_flag_from_messages_and_tools(model, messages, tools) - def _move_cache_control_to_content( - self, messages: List[AllMessageValues] - ) -> List[AllMessageValues]: + def _move_cache_control_to_content(self, messages: List[AllMessageValues]) -> List[AllMessageValues]: """ Move cache_control from message level to content blocks. OpenRouter requires cache_control to be inside content blocks, not at message level. @@ -167,9 +156,7 @@ def transform_request( messages = self._move_cache_control_to_content(messages) extra_body = optional_params.pop("extra_body", {}) - response = super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + response = super().transform_request(model, messages, optional_params, litellm_params, headers) response.update(extra_body) # ALWAYS add usage parameter to get cost data from OpenRouter @@ -228,9 +215,9 @@ def transform_response( model_response._hidden_params = {} if "additional_headers" not in model_response._hidden_params: model_response._hidden_params["additional_headers"] = {} - model_response._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = float(response_cost) + model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float( + response_cost + ) except Exception: # If we can't extract cost, continue without it - don't fail the response pass diff --git a/litellm/llms/openrouter/embedding/transformation.py b/litellm/llms/openrouter/embedding/transformation.py index 8b836e8e5d2e..c6c3df083a10 100644 --- a/litellm/llms/openrouter/embedding/transformation.py +++ b/litellm/llms/openrouter/embedding/transformation.py @@ -170,9 +170,7 @@ def map_openai_params( optional_params[param] = value return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Any - ) -> Any: + def get_error_class(self, error_message: str, status_code: int, headers: Any) -> Any: """ Get the error class for OpenRouter errors. """ diff --git a/litellm/llms/openrouter/image_edit/transformation.py b/litellm/llms/openrouter/image_edit/transformation.py index 0d96b62425f7..f4531932f96f 100644 --- a/litellm/llms/openrouter/image_edit/transformation.py +++ b/litellm/llms/openrouter/image_edit/transformation.py @@ -97,9 +97,7 @@ def map_openai_params( if key == "size": if "image_config" not in mapped_params: mapped_params["image_config"] = {} - mapped_params["image_config"]["aspect_ratio"] = ( - self._map_size_to_aspect_ratio(cast(str, value)) - ) + mapped_params["image_config"]["aspect_ratio"] = self._map_size_to_aspect_ratio(cast(str, value)) elif key == "quality": image_size = self._map_quality_to_image_size(cast(str, value)) if image_size: @@ -139,11 +137,7 @@ def get_complete_url( api_base: Optional[str], litellm_params: dict, ) -> str: - base_url = ( - api_base - or get_secret_str("OPENROUTER_API_BASE") - or "https://openrouter.ai/api/v1" - ) + base_url = api_base or get_secret_str("OPENROUTER_API_BASE") or "https://openrouter.ai/api/v1" base_url = base_url.rstrip("/") if not base_url.endswith("/chat/completions"): return f"{base_url}/chat/completions" @@ -344,17 +338,15 @@ def _set_usage_and_cost( model_response._hidden_params = {} if "additional_headers" not in model_response._hidden_params: model_response._hidden_params["additional_headers"] = {} - model_response._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = float(cost) + model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float( + cost + ) cost_details = usage_data.get("cost_details", {}) if cost_details: if "response_cost_details" not in model_response._hidden_params: model_response._hidden_params["response_cost_details"] = {} - model_response._hidden_params["response_cost_details"].update( - cost_details - ) + model_response._hidden_params["response_cost_details"].update(cost_details) model_response._hidden_params["model"] = response_json.get("model", model) diff --git a/litellm/llms/openrouter/image_generation/transformation.py b/litellm/llms/openrouter/image_generation/transformation.py index 9c2293eb3f13..eabb76f00c0d 100644 --- a/litellm/llms/openrouter/image_generation/transformation.py +++ b/litellm/llms/openrouter/image_generation/transformation.py @@ -64,9 +64,7 @@ class OpenRouterImageGenerationConfig(BaseImageGenerationConfig): and extract images from chat responses. """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for OpenRouter image generation. @@ -224,17 +222,15 @@ def _set_usage_and_cost( model_response._hidden_params = {} if "additional_headers" not in model_response._hidden_params: model_response._hidden_params["additional_headers"] = {} - model_response._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = float(cost) + model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float( + cost + ) cost_details = usage_data.get("cost_details", {}) if cost_details: if "response_cost_details" not in model_response._hidden_params: model_response._hidden_params["response_cost_details"] = {} - model_response._hidden_params["response_cost_details"].update( - cost_details - ) + model_response._hidden_params["response_cost_details"].update(cost_details) model_response._hidden_params["model"] = response_json.get("model", model) diff --git a/litellm/llms/openrouter/responses/transformation.py b/litellm/llms/openrouter/responses/transformation.py index 864e1549274b..217a419ed227 100644 --- a/litellm/llms/openrouter/responses/transformation.py +++ b/litellm/llms/openrouter/responses/transformation.py @@ -49,8 +49,7 @@ def validate_environment( if not api_key: raise ValueError( - "OpenRouter API key is required. Set OPENROUTER_API_KEY " - "environment variable or pass api_key parameter." + "OpenRouter API key is required. Set OPENROUTER_API_KEY environment variable or pass api_key parameter." ) headers.update( @@ -66,10 +65,7 @@ def get_complete_url( litellm_params: dict, ) -> str: api_base = ( - api_base - or litellm.api_base - or get_secret_str("OPENROUTER_API_BASE") - or "https://openrouter.ai/api/v1" + api_base or litellm.api_base or get_secret_str("OPENROUTER_API_BASE") or "https://openrouter.ai/api/v1" ) api_base = api_base.rstrip("/") diff --git a/litellm/llms/opensandbox/sandbox/transformation.py b/litellm/llms/opensandbox/sandbox/transformation.py index dc9f8440d306..60266c988df3 100644 --- a/litellm/llms/opensandbox/sandbox/transformation.py +++ b/litellm/llms/opensandbox/sandbox/transformation.py @@ -71,12 +71,8 @@ async def acreate_sandbox( ) -> ContainerHandle: key = self.validate_environment(api_key=api_key) base = self._api_base(api_base) - ready_timeout_seconds = ( - float(ready_timeout) if ready_timeout is not None else DEFAULT_READY_TIMEOUT - ) - poll_interval_seconds = ( - float(poll_interval) if poll_interval is not None else DEFAULT_POLL_INTERVAL - ) + ready_timeout_seconds = float(ready_timeout) if ready_timeout is not None else DEFAULT_READY_TIMEOUT + poll_interval_seconds = float(poll_interval) if poll_interval is not None else DEFAULT_POLL_INTERVAL body = self._create_body( template=template, timeout=timeout, @@ -150,25 +146,13 @@ async def arun_code( api_key=api_key, api_base=api_base, use_server_proxy=use_server_proxy, - ready_timeout=( - float(ready_timeout) - if ready_timeout is not None - else DEFAULT_READY_TIMEOUT - ), - poll_interval=( - float(poll_interval) - if poll_interval is not None - else DEFAULT_POLL_INTERVAL - ), + ready_timeout=(float(ready_timeout) if ready_timeout is not None else DEFAULT_READY_TIMEOUT), + poll_interval=(float(poll_interval) if poll_interval is not None else DEFAULT_POLL_INTERVAL), client=client, ) endpoint = str(handle._hidden_params["execd_endpoint"]) endpoint_headers = self._as_str_dict(handle._hidden_params.get("execd_headers")) - base = str( - handle._hidden_params.get("api_base") - or handle.domain - or self._api_base(api_base) - ) + base = str(handle._hidden_params.get("api_base") or handle.domain or self._api_base(api_base)) lines = await self._post_code( url=f"{self._endpoint_base_url(endpoint, base)}/code", headers={ @@ -228,9 +212,7 @@ async def _ensure_handle( base = str(handle._hidden_params.get("api_base") or self._api_base(api_base)) key = self._api_key(api_key=api_key, handle=handle) - resolved_use_server_proxy = bool( - handle._hidden_params.get("use_server_proxy", use_server_proxy) - ) + resolved_use_server_proxy = bool(handle._hidden_params.get("use_server_proxy", use_server_proxy)) endpoint, endpoint_headers = await self._wait_for_execd_endpoint( sandbox_id=handle.id, api_base=base, @@ -277,10 +259,7 @@ async def _wait_until_running( if state in {"Failed", "Stopping", "Terminated"}: raise ValueError(f"OpenSandbox sandbox {sandbox_id} entered {state}") if time.monotonic() >= deadline: - raise TimeoutError( - f"OpenSandbox sandbox {sandbox_id} was not Running within " - f"{ready_timeout} seconds" - ) + raise TimeoutError(f"OpenSandbox sandbox {sandbox_id} was not Running within {ready_timeout} seconds") await asyncio.sleep(poll_interval) async def _wait_for_execd_endpoint( @@ -314,8 +293,7 @@ async def _wait_for_execd_endpoint( if time.monotonic() >= deadline: raise TimeoutError( - f"OpenSandbox execd endpoint for {sandbox_id} was not ready within " - f"{ready_timeout} seconds" + f"OpenSandbox execd endpoint for {sandbox_id} was not ready within {ready_timeout} seconds" ) from last_error await asyncio.sleep(poll_interval) @@ -339,9 +317,7 @@ async def _get_execd_endpoint( data = response.json() endpoint = data.get("endpoint") if not endpoint: - raise ValueError( - f"OpenSandbox did not return an execd endpoint for {sandbox_id}" - ) + raise ValueError(f"OpenSandbox did not return an execd endpoint for {sandbox_id}") return str(endpoint), self._as_str_dict(data.get("headers")) async def _post_code( @@ -390,8 +366,7 @@ def _create_body( "image": {"uri": template or OPEN_SANDBOX_DEFAULT_TEMPLATE}, "entrypoint": list(entrypoint or OPEN_SANDBOX_DEFAULT_ENTRYPOINT), "timeout": timeout if timeout is not None else DEFAULT_SANDBOX_TIMEOUT, - "resourceLimits": resource_limits - or OpenSandboxSandboxConfig._default_resource_limits(), + "resourceLimits": resource_limits or OpenSandboxSandboxConfig._default_resource_limits(), } if metadata: body["metadata"] = metadata @@ -434,10 +409,7 @@ def _as_str_dict(value: object) -> dict[str, str]: def _api_base(api_base: str | None) -> str: base = api_base or get_secret_str(OPEN_SANDBOX_API_BASE_ENV_VAR) if not base: - raise ValueError( - "OpenSandbox api_base is required. Pass api_base or set " - f"{OPEN_SANDBOX_API_BASE_ENV_VAR}." - ) + raise ValueError(f"OpenSandbox api_base is required. Pass api_base or set {OPEN_SANDBOX_API_BASE_ENV_VAR}.") return str(base).rstrip("/") @staticmethod @@ -456,9 +428,7 @@ def _endpoint_base_url(endpoint: str, api_base: str) -> str: return f"{protocol}://{normalized_endpoint}" @staticmethod - def _as_handle( - container: Union[ContainerHandle, str], *, api_base: str | None - ) -> ContainerHandle: + def _as_handle(container: Union[ContainerHandle, str], *, api_base: str | None) -> ContainerHandle: if isinstance(container, ContainerHandle): return container handle = ContainerHandle( @@ -472,9 +442,7 @@ def _as_handle( @staticmethod def _parse_lines(lines: list[str]) -> CodeExecutionResult: messages = tuple( - event - for line in lines - if (event := OpenSandboxSandboxConfig._parse_sse_line(line)) is not None + event for line in lines if (event := OpenSandboxSandboxConfig._parse_sse_line(line)) is not None ) def of_type(message_type: str): @@ -488,8 +456,7 @@ def of_type(message_type: str): ( OpenSandboxSandboxConfig._as_int(m.get("execution_count")) for m in of_type("execution_count") - if OpenSandboxSandboxConfig._as_int(m.get("execution_count")) - is not None + if OpenSandboxSandboxConfig._as_int(m.get("execution_count")) is not None ), None, ) @@ -497,9 +464,7 @@ def of_type(message_type: str): return CodeExecutionResult( stdout="".join(str(m.get("text", "")) for m in of_type("stdout")), stderr="".join(str(m.get("text", "")) for m in of_type("stderr")), - results=[ - OpenSandboxSandboxConfig._normalize_result(m) for m in of_type("result") - ], + results=[OpenSandboxSandboxConfig._normalize_result(m) for m in of_type("result")], error=error, execution_count=execution_count, ) @@ -541,40 +506,24 @@ def _normalize_result(message: dict[str, object]) -> dict[str, object]: results = message.get("results") if isinstance(results, dict): return {str(k): v for k, v in results.items()} - return { - str(k): v - for k, v in message.items() - if k not in {"type", "timestamp", "execution_count"} - } + return {str(k): v for k, v in message.items() if k not in {"type", "timestamp", "execution_count"}} @staticmethod def _normalize_error(message: dict[str, object]) -> dict[str, object]: raw_error = message.get("error") if isinstance(raw_error, dict): - name = OpenSandboxSandboxConfig._first_non_none_value( - raw_error, "ename", "name", default="" - ) - value = OpenSandboxSandboxConfig._first_non_none_value( - raw_error, "evalue", "value", default="" - ) - traceback = OpenSandboxSandboxConfig._first_non_none_value( - raw_error, "traceback", default=[] - ) + name = OpenSandboxSandboxConfig._first_non_none_value(raw_error, "ename", "name", default="") + value = OpenSandboxSandboxConfig._first_non_none_value(raw_error, "evalue", "value", default="") + traceback = OpenSandboxSandboxConfig._first_non_none_value(raw_error, "traceback", default=[]) return { "name": name, "value": value, "traceback": traceback, } return { - "name": OpenSandboxSandboxConfig._first_non_none_value( - message, "name", default="" - ), - "value": OpenSandboxSandboxConfig._first_non_none_value( - message, "value", "text", default="" - ), - "traceback": OpenSandboxSandboxConfig._first_non_none_value( - message, "traceback", default=[] - ), + "name": OpenSandboxSandboxConfig._first_non_none_value(message, "name", default=""), + "value": OpenSandboxSandboxConfig._first_non_none_value(message, "value", "text", default=""), + "traceback": OpenSandboxSandboxConfig._first_non_none_value(message, "traceback", default=[]), } @staticmethod @@ -589,9 +538,7 @@ def _as_int(value: object) -> int | None: return None @staticmethod - def _first_non_none_value( - values: dict[str, object], *keys: str, default: object - ) -> object: + def _first_non_none_value(values: dict[str, object], *keys: str, default: object) -> object: return next( (values[key] for key in keys if key in values and values[key] is not None), default, diff --git a/litellm/llms/ovhcloud/audio_transcription/transformation.py b/litellm/llms/ovhcloud/audio_transcription/transformation.py index f49f31d7ecde..43b68c6503d7 100644 --- a/litellm/llms/ovhcloud/audio_transcription/transformation.py +++ b/litellm/llms/ovhcloud/audio_transcription/transformation.py @@ -26,9 +26,7 @@ class OVHCloudAudioTranscriptionConfig(BaseAudioTranscriptionConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: # OVHCloud implements the OpenAI-compatible Whisper interface. # We pass through the same optional params as the OpenAI Whisper API. return [ @@ -61,11 +59,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = ( - "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" - if api_base is None - else api_base.rstrip("/") - ) + api_base = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" if api_base is None else api_base.rstrip("/") complete_url = f"{api_base}/audio/transcriptions" return complete_url diff --git a/litellm/llms/ovhcloud/chat/transformation.py b/litellm/llms/ovhcloud/chat/transformation.py index 62f51f1e9daf..0090ae168f76 100644 --- a/litellm/llms/ovhcloud/chat/transformation.py +++ b/litellm/llms/ovhcloud/chat/transformation.py @@ -31,11 +31,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = ( - "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" - if api_base is None - else api_base.rstrip("/") - ) + api_base = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" if api_base is None else api_base.rstrip("/") complete_url = f"{api_base}/chat/completions" return complete_url @@ -55,9 +51,7 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - mapped_openai_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_openai_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) return mapped_openai_params def transform_request( @@ -69,9 +63,7 @@ def transform_request( headers: dict, ) -> dict: extra_body = optional_params.pop("extra_body", {}) - response = super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + response = super().transform_request(model, messages, optional_params, litellm_params, headers) response.update(extra_body) return response @@ -88,9 +80,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: try: if "error" in chunk: error_chunk = chunk["error"] - error_message = "OVHCloud Error: {}".format( - error_chunk.get("message", "Unknown error") - ) + error_message = "OVHCloud Error: {}".format(error_chunk.get("message", "Unknown error")) raise OVHCloudException( message=error_message, status_code=error_chunk.get("code", 400), diff --git a/litellm/llms/ovhcloud/embedding/transformation.py b/litellm/llms/ovhcloud/embedding/transformation.py index 6b5c43e2d06b..006f2a2349b9 100644 --- a/litellm/llms/ovhcloud/embedding/transformation.py +++ b/litellm/llms/ovhcloud/embedding/transformation.py @@ -30,11 +30,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = ( - "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" - if api_base is None - else api_base.rstrip("/") - ) + api_base = "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1" if api_base is None else api_base.rstrip("/") complete_url = f"{api_base}/embeddings" return complete_url @@ -122,6 +118,4 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return OVHCloudException( - message=error_message, status_code=status_code, headers=headers - ) + return OVHCloudException(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/parallel_ai/search/transformation.py b/litellm/llms/parallel_ai/search/transformation.py index 35a0d84df40c..56566aea0b12 100644 --- a/litellm/llms/parallel_ai/search/transformation.py +++ b/litellm/llms/parallel_ai/search/transformation.py @@ -75,9 +75,7 @@ def validate_environment( default_api_base=self.PARALLEL_AI_API_BASE, ) if not api_key: - raise ValueError( - "PARALLEL_API_KEY is not set. Set `PARALLEL_API_KEY` environment variable." - ) + raise ValueError("PARALLEL_API_KEY is not set. Set `PARALLEL_API_KEY` environment variable.") headers["x-api-key"] = api_key headers["Content-Type"] = "application/json" return headers @@ -89,11 +87,7 @@ def get_complete_url( data: Optional[Union[Dict, List[Dict]]] = None, **kwargs, ) -> str: - api_base = ( - api_base - or get_secret_str("PARALLEL_AI_API_BASE") - or self.PARALLEL_AI_API_BASE - ) + api_base = api_base or get_secret_str("PARALLEL_AI_API_BASE") or self.PARALLEL_AI_API_BASE api_base = api_base.rstrip("/") if not api_base.endswith("/v1/search"): @@ -155,9 +149,7 @@ def transform_search_request( advanced_settings["location"] = params.pop("country") if "max_chars_per_result" in params: - advanced_settings["excerpt_settings"] = { - "max_chars_per_result": params.pop("max_chars_per_result") - } + advanced_settings["excerpt_settings"] = {"max_chars_per_result": params.pop("max_chars_per_result")} source_policy: _ParallelAISourcePolicy = {} diff --git a/litellm/llms/pass_through/guardrail_translation/handler.py b/litellm/llms/pass_through/guardrail_translation/handler.py index db8d519d9bef..8ca600b0bcf8 100644 --- a/litellm/llms/pass_through/guardrail_translation/handler.py +++ b/litellm/llms/pass_through/guardrail_translation/handler.py @@ -43,15 +43,11 @@ def _get_guardrail_settings( if litellm_logging_obj is None: return None - passthrough_config = getattr( - litellm_logging_obj, "passthrough_guardrails_config", None - ) + passthrough_config = getattr(litellm_logging_obj, "passthrough_guardrails_config", None) if not passthrough_config or not guardrail_name: return None - return PassthroughGuardrailHandler.get_settings( - passthrough_config, guardrail_name - ) + return PassthroughGuardrailHandler.get_settings(passthrough_config, guardrail_name) def _extract_text_for_guardrail( self, @@ -83,13 +79,9 @@ def _extract_text_for_guardrail( from litellm.litellm_core_utils.safe_json_dumps import safe_dumps payload_to_check = { - k: v - for k, v in data.items() - if not k.startswith("_") and k not in ("metadata", "litellm_logging_obj") + k: v for k, v in data.items() if not k.startswith("_") and k not in ("metadata", "litellm_logging_obj") } - verbose_proxy_logger.debug( - "PassThroughEndpointHandler: Using full payload for guardrail" - ) + verbose_proxy_logger.debug("PassThroughEndpointHandler: Using full payload for guardrail") return safe_dumps(payload_to_check) async def process_input_messages( @@ -115,9 +107,7 @@ async def process_input_messages( text_to_check = self._extract_text_for_guardrail(data, field_expressions) if not text_to_check: - verbose_proxy_logger.debug( - "PassThroughEndpointHandler: No text to check, skipping guardrail" - ) + verbose_proxy_logger.debug("PassThroughEndpointHandler: No text to check, skipping guardrail") return data # Apply guardrail (pass-through doesn't modify the text, just checks it) @@ -153,9 +143,7 @@ async def process_output_response( user_api_key_dict: User API key metadata to pass to guardrails """ if not isinstance(response, dict): - verbose_proxy_logger.debug( - "PassThroughEndpointHandler: Response is not a dict, skipping" - ) + verbose_proxy_logger.debug("PassThroughEndpointHandler: Response is not a dict, skipping") return response guardrail_name = guardrail_to_apply.guardrail_name @@ -177,22 +165,14 @@ async def process_output_response( # Use the real request_data if provided (proxy path), otherwise # create a standalone dict (SDK / direct-call path). if request_data is None: - request_data = ( - {"response": response} - if not isinstance(response, dict) - else response.copy() - ) + request_data = {"response": response} if not isinstance(response, dict) else response.copy() else: if "response" not in request_data: - request_data["response"] = ( - response if not isinstance(response, dict) else response.copy() - ) + request_data["response"] = response if not isinstance(response, dict) else response.copy() # Add user API key metadata with prefixed keys if "litellm_metadata" not in request_data: - user_metadata = self.transform_user_api_key_dict_to_metadata( - user_api_key_dict - ) + user_metadata = self.transform_user_api_key_dict_to_metadata(user_api_key_dict) if user_metadata: request_data["litellm_metadata"] = user_metadata @@ -300,13 +280,9 @@ def _resolve_event_stream_de_anonymizer(provider: Optional[str]): return getattr(handler_cls, "de_anonymize_event_stream", None) @staticmethod - def supports_event_stream_de_anonymization( - provider: Optional[str], endpoint: Optional[str] - ) -> bool: + def supports_event_stream_de_anonymization(provider: Optional[str], endpoint: Optional[str]) -> bool: handler_cls = _get_provider_handlers().get(provider or "") - endpoint_check = getattr( - handler_cls, "event_stream_endpoint_is_de_anonymizable", None - ) + endpoint_check = getattr(handler_cls, "event_stream_endpoint_is_de_anonymizable", None) if endpoint_check is None: return False return endpoint_check(endpoint or "") @@ -319,13 +295,10 @@ async def de_anonymize_event_stream( data: dict, ) -> bytes: provider = data.get("custom_llm_provider") - de_anonymize = LlmPassthroughRouteHandler._resolve_event_stream_de_anonymizer( - provider - ) + de_anonymize = LlmPassthroughRouteHandler._resolve_event_stream_de_anonymizer(provider) if de_anonymize is None: verbose_proxy_logger.debug( - "LlmPassthroughRouteHandler: no event-stream handler for provider=%s, " - "leaving stream unmodified", + "LlmPassthroughRouteHandler: no event-stream handler for provider=%s, leaving stream unmodified", provider, ) return body_bytes diff --git a/litellm/llms/perplexity/chat/transformation.py b/litellm/llms/perplexity/chat/transformation.py index cc0738697d13..93afccd5c9df 100644 --- a/litellm/llms/perplexity/chat/transformation.py +++ b/litellm/llms/perplexity/chat/transformation.py @@ -25,16 +25,8 @@ def custom_llm_provider(self) -> Optional[str]: def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( - api_base - or get_secret_str("PERPLEXITY_API_BASE") - or "https://api.perplexity.ai" - ) # type: ignore - dynamic_api_key = ( - api_key - or get_secret_str("PERPLEXITYAI_API_KEY") - or get_secret_str("PERPLEXITY_API_KEY") - ) + api_base = api_base or get_secret_str("PERPLEXITY_API_BASE") or "https://api.perplexity.ai" # type: ignore + dynamic_api_key = api_key or get_secret_str("PERPLEXITYAI_API_KEY") or get_secret_str("PERPLEXITY_API_KEY") return api_base, dynamic_api_key def get_supported_openai_params(self, model: str) -> list: @@ -59,17 +51,13 @@ def get_supported_openai_params(self, model: str) -> list: ] try: - if litellm.supports_reasoning( - model=model, custom_llm_provider=self.custom_llm_provider - ): + if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider): base_openai_params.append("reasoning_effort") except Exception as e: verbose_logger.debug(f"Error checking if model supports reasoning: {e}") try: - if litellm.supports_web_search( - model=model, custom_llm_provider=self.custom_llm_provider - ): + if litellm.supports_web_search(model=model, custom_llm_provider=self.custom_llm_provider): base_openai_params.append("web_search_options") except Exception as e: verbose_logger.debug(f"Error checking if model supports web search: {e}") @@ -108,20 +96,14 @@ def transform_response( # Extract and enhance usage with Perplexity-specific fields try: raw_response_json = raw_response.json() - self._enhance_usage_with_perplexity_fields( - model_response, raw_response_json - ) + self._enhance_usage_with_perplexity_fields(model_response, raw_response_json) self._add_citations_as_annotations(model_response, raw_response_json) except Exception as e: - verbose_logger.debug( - f"Error extracting Perplexity-specific usage fields: {e}" - ) + verbose_logger.debug(f"Error extracting Perplexity-specific usage fields: {e}") return model_response - def _enhance_usage_with_perplexity_fields( - self, model_response: ModelResponse, raw_response_json: dict - ) -> None: + def _enhance_usage_with_perplexity_fields(self, model_response: ModelResponse, raw_response_json: dict) -> None: """ Extract citation tokens and search queries from Perplexity API response and add them to the usage object using standard LiteLLM fields. @@ -140,9 +122,7 @@ def _enhance_usage_with_perplexity_fields( if citations: # Count total characters in citations as a proxy for citation tokens # This is an estimation - in practice, you might want to use proper tokenization - total_citation_chars = sum( - len(str(citation)) for citation in citations if citation - ) + total_citation_chars = sum(len(str(citation)) for citation in citations if citation) # Rough estimation: ~4 characters per token (OpenAI's general rule) if total_citation_chars > 0: citation_tokens = max(1, total_citation_chars // 4) @@ -161,9 +141,7 @@ def _enhance_usage_with_perplexity_fields( num_search_queries = raw_response_json.get("search_queries") # Create or update prompt_tokens_details to include web search requests and citation tokens - if citation_tokens > 0 or ( - num_search_queries is not None and num_search_queries > 0 - ): + if citation_tokens > 0 or (num_search_queries is not None and num_search_queries > 0): if usage.prompt_tokens_details is None: usage.prompt_tokens_details = PromptTokensDetailsWrapper() @@ -175,9 +153,7 @@ def _enhance_usage_with_perplexity_fields( if num_search_queries is not None and num_search_queries > 0: usage.prompt_tokens_details.web_search_requests = num_search_queries - def _add_citations_as_annotations( - self, model_response: ModelResponse, raw_response_json: dict - ) -> None: + def _add_citations_as_annotations(self, model_response: ModelResponse, raw_response_json: dict) -> None: """ Extract citations and search_results from Perplexity API response and add them as ChatCompletionAnnotation objects to the message. diff --git a/litellm/llms/perplexity/cost_calculator.py b/litellm/llms/perplexity/cost_calculator.py index ec7ec397ea66..c9574f3be807 100644 --- a/litellm/llms/perplexity/cost_calculator.py +++ b/litellm/llms/perplexity/cost_calculator.py @@ -34,9 +34,7 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: ## GET MODEL INFO model_info = get_model_info(model=model, custom_llm_provider="perplexity") - def _safe_float_cast( - value: Union[str, int, float, None, object], default: float = 0.0 - ) -> float: + def _safe_float_cast(value: Union[str, int, float, None, object], default: float = 0.0) -> float: """Safely cast a value to float with proper type handling for mypy.""" if value is None: return default @@ -60,14 +58,8 @@ def _safe_float_cast( output_cost_per_token = _safe_float_cast(model_info.get("output_cost_per_token")) reasoning_tokens = getattr(usage, "reasoning_tokens", 0) or 0 - if ( - reasoning_tokens == 0 - and hasattr(usage, "completion_tokens_details") - and usage.completion_tokens_details - ): - reasoning_tokens = ( - getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0 - ) + if reasoning_tokens == 0 and hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details: + reasoning_tokens = getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0 reasoning_cost_value = model_info.get("output_cost_per_reasoning_token") @@ -76,9 +68,7 @@ def _safe_float_cast( # configured we subtract before the output-rate multiplication so the reasoning # tokens are not billed twice. if reasoning_tokens > 0 and reasoning_cost_value is not None: - non_reasoning_completion_tokens = max( - 0, (usage.completion_tokens or 0) - reasoning_tokens - ) + non_reasoning_completion_tokens = max(0, (usage.completion_tokens or 0) - reasoning_tokens) completion_cost: float = non_reasoning_completion_tokens * output_cost_per_token completion_cost += reasoning_tokens * _safe_float_cast(reasoning_cost_value) else: @@ -87,23 +77,19 @@ def _safe_float_cast( ## ADD SEARCH QUERIES COST (if present) num_search_queries = 0 if hasattr(usage, "prompt_tokens_details") and usage.prompt_tokens_details: - num_search_queries = ( - getattr(usage.prompt_tokens_details, "web_search_requests", 0) or 0 - ) + num_search_queries = getattr(usage.prompt_tokens_details, "web_search_requests", 0) or 0 # Check both possible keys for search cost (legacy and current) - search_cost_value = model_info.get( - "search_queries_cost_per_query" - ) or model_info.get("search_context_cost_per_query") + search_cost_value = model_info.get("search_queries_cost_per_query") or model_info.get( + "search_context_cost_per_query" + ) if num_search_queries > 0 and search_cost_value is not None: # Handle both dict and float formats if isinstance(search_cost_value, dict): # search_context_cost_per_query stores the per-request price in USD # (e.g. sonar low = $0.005/request). Use it directly, matching the # gemini cost calculator which reads the same field per request. - search_cost_per_query = _safe_float_cast( - search_cost_value.get("search_context_size_low", 0) - ) + search_cost_per_query = _safe_float_cast(search_cost_value.get("search_context_size_low", 0)) else: search_cost_per_query = _safe_float_cast(search_cost_value) search_cost = num_search_queries * search_cost_per_query diff --git a/litellm/llms/perplexity/embedding/transformation.py b/litellm/llms/perplexity/embedding/transformation.py index 24881ccebf86..a52eab34c085 100644 --- a/litellm/llms/perplexity/embedding/transformation.py +++ b/litellm/llms/perplexity/embedding/transformation.py @@ -34,9 +34,7 @@ def __init__( ): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.perplexity.ai/v1/embeddings" - ) + self.request = httpx.Request(method="POST", url="https://api.perplexity.ai/v1/embeddings") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( status_code=status_code, @@ -99,9 +97,7 @@ def validate_environment( api_base: Optional[str] = None, ) -> dict: if api_key is None: - api_key = get_secret_str("PERPLEXITYAI_API_KEY") or get_secret_str( - "PERPLEXITY_API_KEY" - ) + api_key = get_secret_str("PERPLEXITYAI_API_KEY") or get_secret_str("PERPLEXITY_API_KEY") return { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", @@ -152,9 +148,7 @@ def transform_embedding_response( try: raw_response_json = raw_response.json() except Exception: - raise PerplexityEmbeddingError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise PerplexityEmbeddingError(message=raw_response.text, status_code=raw_response.status_code) model_response.model = raw_response_json.get("model", model) model_response.object = raw_response_json.get("object", "list") @@ -163,16 +157,13 @@ def transform_embedding_response( decoded_data: List[Dict[str, Any]] = [] for item in raw_data: decoded_item = dict(item) - decoded_item["embedding"] = self._decode_base64_embedding( - item.get("embedding") - ) + decoded_item["embedding"] = self._decode_base64_embedding(item.get("embedding")) decoded_data.append(decoded_item) model_response.data = decoded_data usage_data = raw_response_json.get("usage", {}) usage = Usage( - prompt_tokens=usage_data.get("prompt_tokens", 0) - or usage_data.get("total_tokens", 0), + prompt_tokens=usage_data.get("prompt_tokens", 0) or usage_data.get("total_tokens", 0), total_tokens=usage_data.get("total_tokens", 0), ) model_response.usage = usage @@ -184,6 +175,4 @@ def get_error_class( status_code: int, headers: Union[dict, httpx.Headers], ) -> BaseLLMException: - return PerplexityEmbeddingError( - message=error_message, status_code=status_code, headers=headers - ) + return PerplexityEmbeddingError(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/perplexity/responses/transformation.py b/litellm/llms/perplexity/responses/transformation.py index e09dc01f1c1c..dd5517f6c336 100644 --- a/litellm/llms/perplexity/responses/transformation.py +++ b/litellm/llms/perplexity/responses/transformation.py @@ -40,30 +40,20 @@ def get_supported_openai_params(self, model: str) -> list: def custom_llm_provider(self) -> LlmProviders: return LlmProviders.PERPLEXITY - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: litellm_params = litellm_params or GenericLiteLLMParams() api_key = ( - litellm_params.api_key - or get_secret_str("PERPLEXITYAI_API_KEY") - or get_secret_str("PERPLEXITY_API_KEY") + litellm_params.api_key or get_secret_str("PERPLEXITYAI_API_KEY") or get_secret_str("PERPLEXITY_API_KEY") ) if api_key: headers["Authorization"] = f"Bearer {api_key}" return headers def get_complete_url(self, api_base: Optional[str], litellm_params: dict) -> str: - api_base = ( - api_base - or get_secret_str("PERPLEXITY_API_BASE") - or "https://api.perplexity.ai" - ) + api_base = api_base or get_secret_str("PERPLEXITY_API_BASE") or "https://api.perplexity.ai" return f"{api_base.rstrip('/')}/v1/responses" - def _ensure_message_type( - self, input: Union[str, ResponseInputParam] - ) -> Union[str, ResponseInputParam]: + def _ensure_message_type(self, input: Union[str, ResponseInputParam]) -> Union[str, ResponseInputParam]: """Ensure list input items have type='message' (required by Perplexity).""" if isinstance(input, str): return input @@ -71,9 +61,7 @@ def _ensure_message_type( result: List[Any] = [] for item in input: if isinstance(item, dict) and "type" not in item: - new_item = dict( - item - ) # convert to plain dict to avoid TypedDict checking + new_item = dict(item) # convert to plain dict to avoid TypedDict checking new_item["type"] = "message" result.append(new_item) else: @@ -119,10 +107,7 @@ def transform_response_api_response( except Exception: raw_response_json = None - if ( - isinstance(raw_response_json, dict) - and raw_response_json.get("status") == "failed" - ): + if isinstance(raw_response_json, dict) and raw_response_json.get("status") == "failed": error = raw_response_json.get("error", {}) raise BaseLLMException( status_code=raw_response.status_code, diff --git a/litellm/llms/perplexity/search/transformation.py b/litellm/llms/perplexity/search/transformation.py index 55de52c5384f..8ed165de7423 100644 --- a/litellm/llms/perplexity/search/transformation.py +++ b/litellm/llms/perplexity/search/transformation.py @@ -58,9 +58,7 @@ def validate_environment( default_api_base=self.PERPLEXITY_API_BASE, ) if not api_key: - raise ValueError( - "PERPLEXITYAI_API_KEY is not set. Set `PERPLEXITYAI_API_KEY` environment variable." - ) + raise ValueError("PERPLEXITYAI_API_KEY is not set. Set `PERPLEXITYAI_API_KEY` environment variable.") headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -75,11 +73,7 @@ def get_complete_url( """ Get complete URL for Search endpoint. """ - api_base = ( - api_base - or get_secret_str("PERPLEXITY_API_BASE") - or self.PERPLEXITY_API_BASE - ) + api_base = api_base or get_secret_str("PERPLEXITY_API_BASE") or self.PERPLEXITY_API_BASE # append "/search" to the api base if it's not already there if not api_base.endswith("/search"): diff --git a/litellm/llms/petals/completion/handler.py b/litellm/llms/petals/completion/handler.py index ae38baecf222..4a4a820d56dd 100644 --- a/litellm/llms/petals/completion/handler.py +++ b/litellm/llms/petals/completion/handler.py @@ -97,9 +97,7 @@ def completion( model = model - tokenizer = AutoTokenizer.from_pretrained( - model, use_fast=False, add_bos_token=False - ) + tokenizer = AutoTokenizer.from_pretrained(model, use_fast=False, add_bos_token=False) model_obj = AutoDistributedModelForCausalLM.from_pretrained(model) ## LOGGING @@ -129,9 +127,7 @@ def completion( model_response.choices[0].message.content = output_text # type: ignore prompt_tokens = len(encoding.encode(prompt)) - completion_tokens = len( - encoding.encode(model_response["choices"][0]["message"].get("content")) - ) + completion_tokens = len(encoding.encode(model_response["choices"][0]["message"].get("content"))) model_response.created = int(time.time()) model_response.model = model diff --git a/litellm/llms/petals/completion/transformation.py b/litellm/llms/petals/completion/transformation.py index d50afc4625af..ae6415680b17 100644 --- a/litellm/llms/petals/completion/transformation.py +++ b/litellm/llms/petals/completion/transformation.py @@ -37,9 +37,7 @@ class PetalsConfig(BaseConfig): """ max_length: Optional[int] = None - max_new_tokens: Optional[int] = ( - litellm.max_tokens - ) # petals requires max tokens to be set + max_new_tokens: Optional[int] = litellm.max_tokens # petals requires max tokens to be set do_sample: Optional[bool] = None temperature: Optional[float] = None top_k: Optional[int] = None @@ -49,9 +47,7 @@ class PetalsConfig(BaseConfig): def __init__( self, max_length: Optional[int] = None, - max_new_tokens: Optional[ - int - ] = litellm.max_tokens, # petals requires max tokens to be set + max_new_tokens: Optional[int] = litellm.max_tokens, # petals requires max tokens to be set do_sample: Optional[bool] = None, temperature: Optional[float] = None, top_k: Optional[int] = None, @@ -67,12 +63,8 @@ def __init__( def get_config(cls): return super().get_config() - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return PetalsError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return PetalsError(status_code=status_code, message=error_message, headers=headers) def get_supported_openai_params(self, model: str) -> List: return ["max_tokens", "temperature", "top_p", "stream"] diff --git a/litellm/llms/pg_vector/vector_stores/transformation.py b/litellm/llms/pg_vector/vector_stores/transformation.py index fc4cfc7b083e..b58b6e7f4988 100644 --- a/litellm/llms/pg_vector/vector_stores/transformation.py +++ b/litellm/llms/pg_vector/vector_stores/transformation.py @@ -27,9 +27,7 @@ class PGVectorStoreConfig(OpenAIVectorStoreConfig): - api_key: API key for authentication with the PG vector service """ - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate environment and set headers for PG vector service authentication """ @@ -83,9 +81,7 @@ def transform_search_vector_store_request( litellm_params: dict, extra_body: Optional[Dict[str, Any]] = None, ) -> Tuple[str, Dict]: - encoded_vector_store_id = encode_url_path_segment( - vector_store_id, field_name="vector_store_id" - ) + encoded_vector_store_id = encode_url_path_segment(vector_store_id, field_name="vector_store_id") url = f"{api_base}/{encoded_vector_store_id}/search" _, request_body = super().transform_search_vector_store_request( vector_store_id=vector_store_id, diff --git a/litellm/llms/predibase/chat/handler.py b/litellm/llms/predibase/chat/handler.py index 07f2738aa964..fe8ee508fcd8 100644 --- a/litellm/llms/predibase/chat/handler.py +++ b/litellm/llms/predibase/chat/handler.py @@ -27,9 +27,7 @@ async def make_call( logging_obj, timeout: Optional[Union[float, httpx.Timeout]], ): - response = await client.post( - api_base, headers=headers, data=data, stream=True, timeout=timeout - ) + response = await client.post(api_base, headers=headers, data=data, stream=True, timeout=timeout) if response.status_code != 200: raise PredibaseError(status_code=response.status_code, message=response.text) @@ -216,9 +214,7 @@ async def async_completion( params={"timeout": timeout}, ) try: - response = await async_handler.post( - api_base, headers=headers, data=json.dumps(data) - ) + response = await async_handler.post(api_base, headers=headers, data=json.dumps(data)) except httpx.HTTPStatusError as e: raise PredibaseError( status_code=e.response.status_code, diff --git a/litellm/llms/predibase/chat/transformation.py b/litellm/llms/predibase/chat/transformation.py index ce004f60bfc5..fcb21272be2a 100644 --- a/litellm/llms/predibase/chat/transformation.py +++ b/litellm/llms/predibase/chat/transformation.py @@ -35,13 +35,9 @@ class PredibaseConfig(BaseConfig): best_of: Optional[int] = None decoder_input_details: Optional[bool] = None details: bool = True # enables returning logprobs + best of - max_new_tokens: int = ( - DEFAULT_MAX_TOKENS # openai default - requests hang if max_new_tokens not given - ) + max_new_tokens: int = DEFAULT_MAX_TOKENS # openai default - requests hang if max_new_tokens not given repetition_penalty: Optional[float] = None - return_full_text: Optional[bool] = ( - False # by default don't return the input as part of the output - ) + return_full_text: Optional[bool] = False # by default don't return the input as part of the output seed: Optional[int] = None stop: Optional[List[str]] = None temperature: Optional[float] = None @@ -108,9 +104,7 @@ def map_openai_params( optional_params["top_p"] = value if param == "n": optional_params["best_of"] = value - optional_params["do_sample"] = ( - True # Need to sample if you want best of for hf inference endpoints - ) + optional_params["do_sample"] = True # Need to sample if you want best of for hf inference endpoints if param == "stream": optional_params["stream"] = value if param == "stop": @@ -175,13 +169,8 @@ def transform_response( completion_response["generated_text"] ) - if ( - "details" in completion_response - and "tokens" in completion_response["details"] - ): - model_response.choices[0].finish_reason = map_finish_reason( - completion_response["details"]["finish_reason"] - ) + if "details" in completion_response and "tokens" in completion_response["details"]: + model_response.choices[0].finish_reason = map_finish_reason(completion_response["details"]["finish_reason"]) sum_logprob = 0 for token in completion_response["details"]["tokens"]: if token["logprob"] is not None: @@ -201,14 +190,9 @@ def transform_response( best_of_value = 0 if best_of_value > 1: - if ( - "details" in completion_response - and "best_of_sequences" in completion_response["details"] - ): + if "details" in completion_response and "best_of_sequences" in completion_response["details"]: choices_list = [] - for idx, item in enumerate( - completion_response["details"]["best_of_sequences"] - ): + for idx, item in enumerate(completion_response["details"]["best_of_sequences"]): sum_logprob = 0 for token in item["tokens"]: if token["logprob"] is not None: @@ -238,11 +222,7 @@ def transform_response( if output_text is not None and len(output_text) > 0: completion_tokens = 0 try: - completion_tokens = len( - encoding.encode( - model_response["choices"][0]["message"].get("content", "") - ) - ) + completion_tokens = len(encoding.encode(model_response["choices"][0]["message"].get("content", ""))) except Exception: # Keep usage calculation non-blocking if encoding fails. pass @@ -332,9 +312,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - tenant_id = litellm_params.get("predibase_tenant_id") or litellm_params.get( - "tenant_id" - ) + tenant_id = litellm_params.get("predibase_tenant_id") or litellm_params.get("tenant_id") if tenant_id is None: raise ValueError( "Missing Predibase Tenant ID - Required for making the request. Set dynamically (e.g. `completion(..tenant_id=)`) or in env - `PREDIBASE_TENANT_ID`." @@ -347,21 +325,15 @@ def get_complete_url( base_url = os.getenv("PREDIBASE_API_BASE", "") completion_url = f"{base_url}/{tenant_id}/deployments/v2/llms/{model}" - should_stream = ( - stream if stream is not None else optional_params.get("stream", False) - ) + should_stream = stream if stream is not None else optional_params.get("stream", False) if should_stream is True: completion_url += "/generate_stream" else: completion_url += "/generate" return completion_url - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return PredibaseError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return PredibaseError(status_code=status_code, message=error_message, headers=headers) def validate_environment( self, diff --git a/litellm/llms/ragflow/chat/transformation.py b/litellm/llms/ragflow/chat/transformation.py index 990fc2b2e61c..be3417d1aadd 100644 --- a/litellm/llms/ragflow/chat/transformation.py +++ b/litellm/llms/ragflow/chat/transformation.py @@ -49,20 +49,14 @@ def _parse_ragflow_model(self, model: str) -> Tuple[str, str, str]: ) if parts[0] != "ragflow": - raise ValueError( - f"Invalid RAGFlow model format: {model}. Must start with 'ragflow/'" - ) + raise ValueError(f"Invalid RAGFlow model format: {model}. Must start with 'ragflow/'") endpoint_type = parts[1] if endpoint_type not in ["chat", "agent"]: - raise ValueError( - f"Invalid RAGFlow endpoint type: {endpoint_type}. Must be 'chat' or 'agent'" - ) + raise ValueError(f"Invalid RAGFlow endpoint type: {endpoint_type}. Must be 'chat' or 'agent'") entity_id = parts[2] - model_name = "/".join( - parts[3:] - ) # Handle model names that might contain slashes + model_name = "/".join(parts[3:]) # Handle model names that might contain slashes return endpoint_type, entity_id, model_name @@ -94,19 +88,10 @@ def get_complete_url( Complete URL for the API call """ # Get api_base from multiple sources: input param, litellm_params, environment, or global litellm setting - if ( - litellm_params - and hasattr(litellm_params, "api_base") - and litellm_params.api_base - ): + if litellm_params and hasattr(litellm_params, "api_base") and litellm_params.api_base: api_base = api_base or litellm_params.api_base - api_base = ( - api_base - or litellm.api_base - or get_secret("RAGFLOW_API_BASE") - or get_secret_str("RAGFLOW_API_BASE") - ) + api_base = api_base or litellm.api_base or get_secret("RAGFLOW_API_BASE") or get_secret_str("RAGFLOW_API_BASE") if api_base is None: raise ValueError( @@ -164,16 +149,11 @@ def _get_openai_compatible_provider_info( # Get api_base from multiple sources: input param, environment, or global litellm setting dynamic_api_base = ( - api_base - or litellm.api_base - or get_secret("RAGFLOW_API_BASE") - or get_secret_str("RAGFLOW_API_BASE") + api_base or litellm.api_base or get_secret("RAGFLOW_API_BASE") or get_secret_str("RAGFLOW_API_BASE") ) # Get api_key from multiple sources: input param, environment, or global litellm setting - dynamic_api_key = ( - api_key or litellm.api_key or get_secret_str("RAGFLOW_API_KEY") - ) + dynamic_api_key = api_key or litellm.api_key or get_secret_str("RAGFLOW_API_KEY") return dynamic_api_base, dynamic_api_key, custom_llm_provider @@ -203,11 +183,7 @@ def validate_environment( Updated headers dictionary """ # Use api_key from litellm_params if available, otherwise fall back to other sources - if ( - litellm_params - and hasattr(litellm_params, "api_key") - and litellm_params.api_key - ): + if litellm_params and hasattr(litellm_params, "api_key") and litellm_params.api_key: api_key = api_key or litellm_params.api_key # Get api_key from multiple sources: input param, litellm_params, environment, or global litellm setting @@ -266,6 +242,4 @@ def transform_request( actual_model = model # Use parent's transform_request with the actual model name - return super().transform_request( - actual_model, messages, optional_params, litellm_params, headers - ) + return super().transform_request(actual_model, messages, optional_params, litellm_params, headers) diff --git a/litellm/llms/ragflow/vector_stores/transformation.py b/litellm/llms/ragflow/vector_stores/transformation.py index 3238d3e9c14e..d8bdd9814258 100644 --- a/litellm/llms/ragflow/vector_stores/transformation.py +++ b/litellm/llms/ragflow/vector_stores/transformation.py @@ -24,17 +24,13 @@ class RAGFlowVectorStoreConfig(BaseVectorStoreConfig): """Vector store configuration for RAGFlow datasets.""" - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: api_key = litellm_params.get("api_key") if api_key is None: # Try to get from environment variable api_key = get_secret_str("RAGFLOW_API_KEY") if api_key is None: - raise ValueError( - "api_key is required (set RAGFLOW_API_KEY env var or pass in litellm_params)" - ) + raise ValueError("api_key is required (set RAGFLOW_API_KEY env var or pass in litellm_params)") return { "headers": { "Authorization": f"Bearer {api_key}", @@ -48,17 +44,13 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [], } - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """Validate environment and set headers for RAGFlow API.""" litellm_params = litellm_params or GenericLiteLLMParams() api_key = litellm_params.api_key or get_secret_str("RAGFLOW_API_KEY") if api_key is None: - raise ValueError( - "RAGFLOW_API_KEY is required (set env var or pass in litellm_params)" - ) + raise ValueError("RAGFLOW_API_KEY is required (set env var or pass in litellm_params)") headers.update( { @@ -82,10 +74,7 @@ def get_complete_url( - Default: http://localhost:9380 """ api_base = ( - api_base - or litellm_params.get("api_base") - or get_secret_str("RAGFLOW_API_BASE") - or "http://localhost:9380" + api_base or litellm_params.get("api_base") or get_secret_str("RAGFLOW_API_BASE") or "http://localhost:9380" ) # Remove trailing slashes @@ -105,17 +94,13 @@ def transform_search_vector_store_request( extra_body: Optional[Dict[str, Any]] = None, ) -> Tuple[str, Dict]: """RAGFlow vector stores are management-only, search is not supported.""" - raise NotImplementedError( - "RAGFlow vector stores support dataset management only, not search/retrieval" - ) + raise NotImplementedError("RAGFlow vector stores support dataset management only, not search/retrieval") def transform_search_vector_store_response( self, response: httpx.Response, litellm_logging_obj: LiteLLMLoggingObj ) -> VectorStoreSearchResponse: """RAGFlow vector stores are management-only, search is not supported.""" - raise NotImplementedError( - "RAGFlow vector stores support dataset management only, not search/retrieval" - ) + raise NotImplementedError("RAGFlow vector stores support dataset management only, not search/retrieval") def transform_create_vector_store_request( self, @@ -172,9 +157,7 @@ def transform_create_vector_store_request( return url, request_body - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: """ Transform RAGFlow response to VectorStoreCreateResponse format. diff --git a/litellm/llms/recraft/cost_calculator.py b/litellm/llms/recraft/cost_calculator.py index 27b9108e5fe1..5ab47e9395ec 100644 --- a/litellm/llms/recraft/cost_calculator.py +++ b/litellm/llms/recraft/cost_calculator.py @@ -22,6 +22,4 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") diff --git a/litellm/llms/recraft/image_edit/transformation.py b/litellm/llms/recraft/image_edit/transformation.py index 1dccd4060586..61c669b50c0e 100644 --- a/litellm/llms/recraft/image_edit/transformation.py +++ b/litellm/llms/recraft/image_edit/transformation.py @@ -68,9 +68,7 @@ def get_complete_url( Some providers need `model` in `api_base` """ - complete_url: str = ( - api_base or get_secret_str("RECRAFT_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("RECRAFT_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") complete_url = f"{complete_url}/{self.IMAGE_EDIT_ENDPOINT}" @@ -109,9 +107,7 @@ def transform_image_edit_request( request_params = { "model": model, - "strength": image_edit_optional_request_params.pop( - "strength", self.DEFAULT_STRENGTH - ), + "strength": image_edit_optional_request_params.pop("strength", self.DEFAULT_STRENGTH), **image_edit_optional_request_params, } if prompt is not None: @@ -122,9 +118,7 @@ def transform_image_edit_request( ######################################################### # Reuse OpenAI logic: Separate images as `files` and send other parameters as `data` ######################################################### - files_list = ( - self._get_image_files_for_request(image=image) if image is not None else [] - ) + files_list = self._get_image_files_for_request(image=image) if image is not None else [] data_without_images = {k: v for k, v in request_dict.items() if k != "image"} return data_without_images, files_list @@ -144,17 +138,11 @@ def _get_image_files_for_request( _image = image if _image is not None: - image_content_type: str = ImageEditRequestUtils.get_image_content_type( - _image - ) + image_content_type: str = ImageEditRequestUtils.get_image_content_type(_image) if isinstance(_image, BufferedReader): - files_list.append( - ("image", (_image.name, _image, image_content_type)) - ) + files_list.append(("image", (_image.name, _image, image_content_type))) else: - files_list.append( - ("image", ("image.png", _image, image_content_type)) - ) + files_list.append(("image", ("image.png", _image, image_content_type))) return files_list diff --git a/litellm/llms/recraft/image_generation/transformation.py b/litellm/llms/recraft/image_generation/transformation.py index 4a00512dfb94..9f48273c3061 100644 --- a/litellm/llms/recraft/image_generation/transformation.py +++ b/litellm/llms/recraft/image_generation/transformation.py @@ -25,9 +25,7 @@ class RecraftImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://external.api.recraft.ai" IMAGE_GENERATION_ENDPOINT: str = "v1/images/generations" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ https://www.recraft.ai/docs#generate-image """ @@ -68,9 +66,7 @@ def get_complete_url( Some providers need `model` in `api_base` """ - complete_url: str = ( - api_base or get_secret_str("RECRAFT_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("RECRAFT_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") complete_url = f"{complete_url}/{self.IMAGE_GENERATION_ENDPOINT}" diff --git a/litellm/llms/reducto/common.py b/litellm/llms/reducto/common.py index 4e7d96dbe87a..364f269feb1d 100644 --- a/litellm/llms/reducto/common.py +++ b/litellm/llms/reducto/common.py @@ -51,9 +51,7 @@ def extract_file_id_or_bytes( _raise_bad_request("Invalid Reducto data URI provided.", model=model) if ";base64" not in header: - _raise_bad_request( - "Reducto only supports base64-encoded data URIs.", model=model - ) + _raise_bad_request("Reducto only supports base64-encoded data URIs.", model=model) mime = header.removeprefix("data:").split(";")[0] or "application/octet-stream" try: @@ -68,16 +66,10 @@ def _extract_file_id_from_upload_response(response: Any) -> str: try: payload = response.json() except ValueError as exc: - raise ValueError( - "Reducto /upload returned a non-JSON 200 response: {}".format(response.text) - ) from exc + raise ValueError("Reducto /upload returned a non-JSON 200 response: {}".format(response.text)) from exc file_id = (payload or {}).get("file_id") if isinstance(payload, dict) else None if not isinstance(file_id, str) or not file_id: - raise ValueError( - "Reducto /upload returned 200 without a file_id; got payload={}".format( - payload - ) - ) + raise ValueError("Reducto /upload returned 200 without a file_id; got payload={}".format(payload)) return file_id @@ -135,18 +127,14 @@ def build_pages_from_reducto(result: Dict[str, Any]) -> List["OCRPage"]: blocks_by_page[normalized_page].append(block) if not blocks_by_page: - fallback_markdown = "\n\n".join( - chunk.get("content", "") for chunk in chunks if chunk.get("content") - ) + fallback_markdown = "\n\n".join(chunk.get("content", "") for chunk in chunks if chunk.get("content")) if fallback_markdown == "": return [] return [OCRPage(index=0, markdown=fallback_markdown)] pages: List["OCRPage"] = [] for page_no, blocks in sorted(blocks_by_page.items()): - markdown = "\n\n".join( - block.get("content", "") for block in blocks if block.get("content") - ) + markdown = "\n\n".join(block.get("content", "") for block in blocks if block.get("content")) page_index = max(page_no - 1, 0) page = OCRPage( index=page_index, diff --git a/litellm/llms/reducto/ocr/transformation.py b/litellm/llms/reducto/ocr/transformation.py index cc338ecc484d..e8bfcceea2a5 100644 --- a/litellm/llms/reducto/ocr/transformation.py +++ b/litellm/llms/reducto/ocr/transformation.py @@ -69,16 +69,12 @@ def _get_source_url(self, document: DocumentType, model: str) -> str: source_url = document.get("document_url") or document.get("image_url") if source_url is None: raise ValueError( - "Reducto expected OCR preprocessing to produce document_url or image_url for model={}".format( - model - ) + "Reducto expected OCR preprocessing to produce document_url or image_url for model={}".format(model) ) return source_url @staticmethod - def _resolve_credentials( - api_key: Optional[str], api_base: Optional[str] - ) -> Tuple[str, str]: + def _resolve_credentials(api_key: Optional[str], api_base: Optional[str]) -> Tuple[str, str]: from litellm.secret_managers.main import get_secret_str resolved_key = api_key or get_secret_str("REDUCTO_API_KEY") @@ -213,9 +209,7 @@ def transform_ocr_request( api_base=kwargs.get("api_base"), ) return OCRRequestData( - data=self._build_legacy_body( - file_id=file_id, optional_params=optional_params - ), + data=self._build_legacy_body(file_id=file_id, optional_params=optional_params), files=None, ) @@ -234,8 +228,6 @@ async def async_transform_ocr_request( api_base=kwargs.get("api_base"), ) return OCRRequestData( - data=self._build_legacy_body( - file_id=file_id, optional_params=optional_params - ), + data=self._build_legacy_body(file_id=file_id, optional_params=optional_params), files=None, ) diff --git a/litellm/llms/replicate/chat/handler.py b/litellm/llms/replicate/chat/handler.py index a2eddb65a544..57381e57dabc 100644 --- a/litellm/llms/replicate/chat/handler.py +++ b/litellm/llms/replicate/chat/handler.py @@ -29,9 +29,7 @@ def handle_prediction_response_streaming( status = "" while True and (status not in ["succeeded", "failed", "canceled"]): - time.sleep( - REPLICATE_POLLING_DELAY_SECONDS - ) # prevent being rate limited by replicate + time.sleep(REPLICATE_POLLING_DELAY_SECONDS) # prevent being rate limited by replicate print_verbose(f"replicate: polling endpoint: {prediction_url}") response = http_client.get(prediction_url, headers=headers) if response.status_code == 200: @@ -43,9 +41,7 @@ def handle_prediction_response_streaming( except Exception: raise ReplicateError( status_code=422, - message="Unable to parse response. Got={}".format( - response_data["output"] - ), + message="Unable to parse response. Got={}".format(response_data["output"]), headers=response.headers, ) new_output = output_string[len(previous_output) :] @@ -80,17 +76,13 @@ async def async_handle_prediction_response_streaming( status = "" while True and (status not in ["succeeded", "failed", "canceled"]): - await asyncio.sleep( - REPLICATE_POLLING_DELAY_SECONDS - ) # prevent being rate limited by replicate + await asyncio.sleep(REPLICATE_POLLING_DELAY_SECONDS) # prevent being rate limited by replicate response = await http_client.get(prediction_url, headers=headers) if response.status_code == 200: response_data = response.json() status = response_data.get("status", "") # Check that "output" exists and is not None or empty - output_present = ( - "output" in response_data and response_data["output"] is not None - ) + output_present = "output" in response_data and response_data["output"] is not None if output_present: try: # If output is None or not a list, treat as empty string @@ -104,9 +96,7 @@ async def async_handle_prediction_response_streaming( except Exception: raise ReplicateError( status_code=422, - message="Unable to parse response. Got={}".format( - response_data.get("output", None) - ), + message="Unable to parse response. Got={}".format(response_data.get("output", None)), headers=response.headers, ) new_output = output_string[len(previous_output) :] @@ -180,9 +170,7 @@ def completion( headers=headers, ) # type: ignore ## COMPLETION CALL - model_response.created = int( - time.time() - ) # for pricing this must remain right before calling api + model_response.created = int(time.time()) # for pricing this must remain right before calling api prediction_url = replicate_config.get_complete_url( api_base=api_base, @@ -214,9 +202,7 @@ def completion( headers=headers, http_client=httpx_client, ) - return CustomStreamWrapper( - _response, model, logging_obj=logging_obj, custom_llm_provider="replicate" - ) # type: ignore + return CustomStreamWrapper(_response, model, logging_obj=logging_obj, custom_llm_provider="replicate") # type: ignore else: for retry in range(litellm.DEFAULT_REPLICATE_POLLING_RETRIES): time.sleep( @@ -274,9 +260,7 @@ async def async_completion( llm_provider=litellm.LlmProviders.REPLICATE, params={"timeout": 600.0}, ) - response = await async_handler.post( - url=prediction_url, headers=headers, data=json.dumps(input_data) - ) + response = await async_handler.post(url=prediction_url, headers=headers, data=json.dumps(input_data)) prediction_url = replicate_config.get_prediction_url(response) if "stream" in optional_params and optional_params["stream"] is True: @@ -287,9 +271,7 @@ async def async_completion( headers=headers, http_client=async_handler, ) - return CustomStreamWrapper( - _response, model, logging_obj=logging_obj, custom_llm_provider="replicate" - ) # type: ignore + return CustomStreamWrapper(_response, model, logging_obj=logging_obj, custom_llm_provider="replicate") # type: ignore for retry in range(litellm.DEFAULT_REPLICATE_POLLING_RETRIES): await asyncio.sleep( diff --git a/litellm/llms/replicate/chat/transformation.py b/litellm/llms/replicate/chat/transformation.py index 4c610868018f..6da26b966f38 100644 --- a/litellm/llms/replicate/chat/transformation.py +++ b/litellm/llms/replicate/chat/transformation.py @@ -133,9 +133,7 @@ def model_to_version_id(self, model: str) -> str: def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return ReplicateError( - status_code=status_code, message=error_message, headers=headers - ) + return ReplicateError(status_code=status_code, message=error_message, headers=headers) def get_complete_url( self, @@ -191,9 +189,7 @@ def transform_request( model_prompt_details = litellm.custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", {}), - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), final_prompt_value=model_prompt_details.get("final_prompt_value", ""), bos_token=model_prompt_details.get("bos_token", ""), eos_token=model_prompt_details.get("eos_token", ""), @@ -225,8 +221,7 @@ def transform_request( if ":" in version_id and len(version_id) > REPLICATE_MODEL_NAME_WITH_ID_LENGTH: model_parts = version_id.split(":") if ( - len(model_parts) > 1 - and len(model_parts[1]) == REPLICATE_MODEL_NAME_WITH_ID_LENGTH + len(model_parts) > 1 and len(model_parts[1]) == REPLICATE_MODEL_NAME_WITH_ID_LENGTH ): ## checks if model name has a 64 digit code - e.g. "meta/llama-2-70b-chat:02e509c789964a7ea8736978a43525956ef40397be9033abf9fd2badfe68c9e3" request_data["version"] = model_parts[1] @@ -256,9 +251,7 @@ def transform_response( if raw_response_json.get("status") != "succeeded": raise ReplicateError( status_code=422, - message="LiteLLM Error - prediction not succeeded - {}".format( - raw_response_json - ), + message="LiteLLM Error - prediction not succeeded - {}".format(raw_response_json), headers=raw_response.headers, ) outputs = raw_response_json.get("output", []) @@ -299,9 +292,7 @@ def get_prediction_url(self, response: httpx.Response) -> str: if prediction_url is None: raise ReplicateError( status_code=400, - message="LiteLLM Error - prediction url is None - {}".format( - response_json - ), + message="LiteLLM Error - prediction url is None - {}".format(response_json), headers=response.headers, ) return prediction_url diff --git a/litellm/llms/runwayml/cost_calculator.py b/litellm/llms/runwayml/cost_calculator.py index 35b6086f196c..564f4814eec4 100644 --- a/litellm/llms/runwayml/cost_calculator.py +++ b/litellm/llms/runwayml/cost_calculator.py @@ -25,6 +25,4 @@ def cost_calculator( num_images = len(image_response.data) return output_cost_per_image * num_images else: - raise ValueError( - f"image_response must be of type ImageResponse, got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse, got type={type(image_response)}") diff --git a/litellm/llms/runwayml/image_generation/transformation.py b/litellm/llms/runwayml/image_generation/transformation.py index 448dcd4a67bf..fddd0b1350bc 100644 --- a/litellm/llms/runwayml/image_generation/transformation.py +++ b/litellm/llms/runwayml/image_generation/transformation.py @@ -49,9 +49,7 @@ def get_complete_url( Some providers need `model` in `api_base` """ - complete_url: str = ( - api_base or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url: str = api_base or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") if self.IMAGE_GENERATION_ENDPOINT: @@ -69,9 +67,7 @@ def validate_environment( api_base: Optional[str] = None, ) -> dict: final_api_key: Optional[str] = ( - api_key - or get_secret_str("RUNWAYML_API_SECRET") - or get_secret_str("RUNWAYML_API_KEY") + api_key or get_secret_str("RUNWAYML_API_SECRET") or get_secret_str("RUNWAYML_API_KEY") ) if not final_api_key: raise ValueError("RUNWAYML_API_SECRET or RUNWAYML_API_KEY is not set") @@ -154,9 +150,7 @@ def _check_timeout(start_time: float, timeout_secs: float) -> None: TimeoutError: If operation has exceeded timeout """ if time.time() - start_time > timeout_secs: - raise TimeoutError( - f"RunwayML task polling timed out after {timeout_secs} seconds" - ) + raise TimeoutError(f"RunwayML task polling timed out after {timeout_secs} seconds") @staticmethod def _check_task_status(response_data: Dict[str, Any]) -> str: @@ -183,9 +177,7 @@ def _check_task_status(response_data: Dict[str, Any]) -> str: elif status == "FAILED": failure_reason = response_data.get("failure", "Unknown error") failure_code = response_data.get("failureCode", "unknown") - raise ValueError( - f"RunwayML image generation failed: {failure_reason} (code: {failure_code})" - ) + raise ValueError(f"RunwayML image generation failed: {failure_reason} (code: {failure_code})") elif status == "CANCELLED": raise ValueError("RunwayML image generation was cancelled") elif status in ["PENDING", "RUNNING", "THROTTLED"]: @@ -346,9 +338,7 @@ def transform_image_generation_response( # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), - "X-Runway-Version": raw_response.request.headers.get( - "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION - ), + "X-Runway-Version": raw_response.request.headers.get("X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION), } # Poll until task completes @@ -408,9 +398,7 @@ async def async_transform_image_generation_response( # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), - "X-Runway-Version": raw_response.request.headers.get( - "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION - ), + "X-Runway-Version": raw_response.request.headers.get("X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION), } # Poll until task completes (async) @@ -424,9 +412,7 @@ async def async_transform_image_generation_response( # Update response_data with polled result response_data = raw_response.json() - verbose_logger.debug( - "RunwayML polling complete (async), transforming to OpenAI format" - ) + verbose_logger.debug("RunwayML polling complete (async), transforming to OpenAI format") # Transform RunwayML response to OpenAI format return self._transform_runwayml_response_to_openai( @@ -434,9 +420,7 @@ async def async_transform_image_generation_response( model_response=model_response, ) - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Get supported OpenAI parameters for RunwayML image generation """ diff --git a/litellm/llms/runwayml/text_to_speech/transformation.py b/litellm/llms/runwayml/text_to_speech/transformation.py index 314a538f7c57..0f3da5f7ac53 100644 --- a/litellm/llms/runwayml/text_to_speech/transformation.py +++ b/litellm/llms/runwayml/text_to_speech/transformation.py @@ -200,11 +200,7 @@ def validate_environment( """ validated_headers = headers.copy() - final_api_key = ( - api_key - or get_secret_str("RUNWAYML_API_SECRET") - or get_secret_str("RUNWAYML_API_KEY") - ) + final_api_key = api_key or get_secret_str("RUNWAYML_API_SECRET") or get_secret_str("RUNWAYML_API_KEY") if not final_api_key: raise ValueError("RUNWAYML_API_SECRET or RUNWAYML_API_KEY is not set") @@ -224,9 +220,7 @@ def get_complete_url( """ Get the complete URL for RunwayML TTS request """ - complete_url = ( - api_base or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL - ) + complete_url = api_base or get_secret_str("RUNWAYML_API_BASE") or self.DEFAULT_BASE_URL complete_url = complete_url.rstrip("/") return f"{complete_url}/{self.TTS_ENDPOINT_PATH}" @@ -244,9 +238,7 @@ def _check_timeout(start_time: float, timeout_secs: float) -> None: TimeoutError: If operation has exceeded timeout """ if time.time() - start_time > timeout_secs: - raise TimeoutError( - f"RunwayML TTS task polling timed out after {timeout_secs} seconds" - ) + raise TimeoutError(f"RunwayML TTS task polling timed out after {timeout_secs} seconds") @staticmethod def _check_task_status(response_data: Dict[str, Any]) -> str: @@ -273,9 +265,7 @@ def _check_task_status(response_data: Dict[str, Any]) -> str: elif status == "FAILED": failure_reason = response_data.get("failure", "Unknown error") failure_code = response_data.get("failureCode", "unknown") - raise ValueError( - f"RunwayML TTS failed: {failure_reason} (code: {failure_code})" - ) + raise ValueError(f"RunwayML TTS failed: {failure_reason} (code: {failure_code})") elif status == "CANCELLED": raise ValueError("RunwayML TTS was cancelled") elif status in ["PENDING", "RUNNING", "THROTTLED"]: @@ -480,9 +470,7 @@ def transform_text_to_speech_response( # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), - "X-Runway-Version": raw_response.request.headers.get( - "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION - ), + "X-Runway-Version": raw_response.request.headers.get("X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION), } # Poll until task completes @@ -551,9 +539,7 @@ async def async_transform_text_to_speech_response( # Get headers for polling (need auth) poll_headers = { "Authorization": raw_response.request.headers.get("Authorization", ""), - "X-Runway-Version": raw_response.request.headers.get( - "X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION - ), + "X-Runway-Version": raw_response.request.headers.get("X-Runway-Version", RUNWAYML_DEFAULT_API_VERSION), } # Poll until task completes (async) diff --git a/litellm/llms/runwayml/videos/transformation.py b/litellm/llms/runwayml/videos/transformation.py index b1723f494ecf..b11671c9431b 100644 --- a/litellm/llms/runwayml/videos/transformation.py +++ b/litellm/llms/runwayml/videos/transformation.py @@ -97,11 +97,7 @@ def map_openai_params( seconds = video_create_optional_params["seconds"] if seconds is not None: try: - mapped_params["duration"] = ( - int(float(seconds)) - if isinstance(seconds, str) - else int(seconds) - ) + mapped_params["duration"] = int(float(seconds)) if isinstance(seconds, str) else int(seconds) except (ValueError, TypeError): # If conversion fails, use default duration pass @@ -130,16 +126,12 @@ def validate_environment( api_key = api_key or litellm_params.api_key api_key = ( - api_key - or litellm.api_key - or get_secret_str("RUNWAYML_API_SECRET") - or get_secret_str("RUNWAYML_API_KEY") + api_key or litellm.api_key or get_secret_str("RUNWAYML_API_SECRET") or get_secret_str("RUNWAYML_API_KEY") ) if api_key is None: raise ValueError( - "RunwayML API key is required. Set RUNWAYML_API_SECRET environment variable " - "or pass api_key parameter." + "RunwayML API key is required. Set RUNWAYML_API_SECRET environment variable or pass api_key parameter." ) headers.update( @@ -238,15 +230,11 @@ def transform_video_create_response( if "output" in response_data and response_data["output"]: # RunwayML returns output as array of URLs when task succeeds video_data["output_url"] = ( - response_data["output"][0] - if isinstance(response_data["output"], list) - else response_data["output"] + response_data["output"][0] if isinstance(response_data["output"], list) else response_data["output"] ) if "completedAt" in response_data: - video_data["completed_at"] = self._parse_runway_timestamp( - response_data.get("completedAt") - ) + video_data["completed_at"] = self._parse_runway_timestamp(response_data.get("completedAt")) if "failureCode" in response_data or "failure" in response_data: video_data["error"] = { @@ -269,9 +257,7 @@ def transform_video_create_response( video_obj = VideoObject(**video_data) # type: ignore[arg-type] if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, model - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model) # Add usage data for cost tracking usage_data = {} @@ -335,9 +321,7 @@ def transform_video_content_request( We'll retrieve the task and extract the video URL. """ original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # Get task status to retrieve video URL url = f"{api_base}/tasks/{encoded_video_id}" @@ -361,16 +345,12 @@ def _extract_video_url_from_response(self, response_data: Dict[str, Any]) -> str # Check if the video generation failed or is still processing status = response_data.get("status", "UNKNOWN") if status in ["PENDING", "RUNNING", "THROTTLED"]: - raise ValueError( - f"Video is still processing (status: {status}). Please wait and try again." - ) + raise ValueError(f"Video is still processing (status: {status}). Please wait and try again.") elif status == "FAILED": failure_reason = response_data.get("failure", "Unknown error") raise ValueError(f"Video generation failed: {failure_reason}") else: - raise ValueError( - "Video URL not found in response. Video may not be ready yet." - ) + raise ValueError("Video URL not found in response. Video may not be ready yet.") return video_url @@ -499,9 +479,7 @@ def transform_video_delete_request( RunwayML uses task cancellation. """ original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # Construct the URL for task cancellation url = f"{api_base}/tasks/{encoded_video_id}/cancel" @@ -540,9 +518,7 @@ def transform_video_status_retrieve_request( RunwayML uses GET /v1/tasks/{task_id} to retrieve task status. """ original_video_id = extract_original_video_id(video_id) - encoded_video_id = encode_url_path_segment( - original_video_id, field_name="video_id" - ) + encoded_video_id = encode_url_path_segment(original_video_id, field_name="video_id") # Construct the full URL for task status retrieval url = f"{api_base}/tasks/{encoded_video_id}" @@ -574,15 +550,11 @@ def transform_video_status_retrieve_response( # Add optional fields if present if "output" in response_data and response_data["output"]: video_data["output_url"] = ( - response_data["output"][0] - if isinstance(response_data["output"], list) - else response_data["output"] + response_data["output"][0] if isinstance(response_data["output"], list) else response_data["output"] ) if "completedAt" in response_data: - video_data["completed_at"] = self._parse_runway_timestamp( - response_data.get("completedAt") - ) + video_data["completed_at"] = self._parse_runway_timestamp(response_data.get("completedAt")) if "progress" in response_data: video_data["progress"] = response_data["progress"] @@ -596,27 +568,17 @@ def transform_video_status_retrieve_response( video_obj = VideoObject(**video_data) # type: ignore[arg-type] if custom_llm_provider and video_obj.id: - video_obj.id = encode_video_id_with_provider( - video_obj.id, custom_llm_provider, None - ) + video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None) return video_obj - def transform_video_create_character_request( - self, name, video, api_base, litellm_params, headers - ): - raise NotImplementedError( - "video create character is not supported for RunwayML" - ) + def transform_video_create_character_request(self, name, video, api_base, litellm_params, headers): + raise NotImplementedError("video create character is not supported for RunwayML") def transform_video_create_character_response(self, raw_response, logging_obj): - raise NotImplementedError( - "video create character is not supported for RunwayML" - ) + raise NotImplementedError("video create character is not supported for RunwayML") - def transform_video_get_character_request( - self, character_id, api_base, litellm_params, headers - ): + def transform_video_get_character_request(self, character_id, api_base, litellm_params, headers): raise NotImplementedError("video get character is not supported for RunwayML") def transform_video_get_character_response(self, raw_response, logging_obj): @@ -655,9 +617,7 @@ def transform_video_extension_request( ): raise NotImplementedError("video extension is not supported for RunwayML") - def transform_video_extension_response( - self, raw_response, logging_obj, custom_llm_provider=None - ): + def transform_video_extension_response(self, raw_response, logging_obj, custom_llm_provider=None): raise NotImplementedError("video extension is not supported for RunwayML") def get_error_class( diff --git a/litellm/llms/s3_vectors/vector_stores/transformation.py b/litellm/llms/s3_vectors/vector_stores/transformation.py index 8270e99d4567..b31e6f4511a3 100644 --- a/litellm/llms/s3_vectors/vector_stores/transformation.py +++ b/litellm/llms/s3_vectors/vector_stores/transformation.py @@ -29,9 +29,7 @@ def __init__(self) -> None: BaseVectorStoreConfig.__init__(self) BaseAWSLLM.__init__(self) - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: return {} def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: @@ -40,9 +38,7 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [], } - def get_supported_openai_params( - self, model: str - ) -> List[VECTOR_STORE_OPENAI_PARAMS]: + def get_supported_openai_params(self, model: str) -> List[VECTOR_STORE_OPENAI_PARAMS]: return ["max_num_results"] def map_openai_params( @@ -56,9 +52,7 @@ def map_openai_params( optional_params["maxResults"] = value return optional_params - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: headers = headers or {} headers.setdefault("Content-Type", "application/json") return headers @@ -92,9 +86,7 @@ def transform_search_vector_store_request( else: # Try to get bucket_name from litellm_params bucket_name_from_params = litellm_params.get("vector_bucket_name") - if not bucket_name_from_params or not isinstance( - bucket_name_from_params, str - ): + if not bucket_name_from_params or not isinstance(bucket_name_from_params, str): raise ValueError( "vector_store_id must be in format 'bucket_name:index_name' for S3 Vectors, " "or vector_bucket_name must be provided in litellm_params" @@ -106,15 +98,11 @@ def transform_search_vector_store_request( query = " ".join(query) # Generate embedding for the query - embedding_model = litellm_params.get( - "embedding_model", "text-embedding-3-small" - ) + embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small") import litellm as litellm_module - embedding_response = litellm_module.embedding( - model=embedding_model, input=[query] - ) + embedding_response = litellm_module.embedding(model=embedding_model, input=[query]) query_embedding = embedding_response.data[0]["embedding"] url = f"{api_base}/QueryVectors" @@ -123,9 +111,7 @@ def transform_search_vector_store_request( "vectorBucketName": bucket_name, "indexName": index_name, "queryVector": {"float32": query_embedding}, - "topK": vector_store_search_optional_params.get( - "max_num_results", 5 - ), # Default to 5 + "topK": vector_store_search_optional_params.get("max_num_results", 5), # Default to 5 "returnDistance": True, "returnMetadata": True, } @@ -154,9 +140,7 @@ async def atransform_search_vector_store_request( else: # Try to get bucket_name from litellm_params bucket_name_from_params = litellm_params.get("vector_bucket_name") - if not bucket_name_from_params or not isinstance( - bucket_name_from_params, str - ): + if not bucket_name_from_params or not isinstance(bucket_name_from_params, str): raise ValueError( "vector_store_id must be in format 'bucket_name:index_name' for S3 Vectors, " "or vector_bucket_name must be provided in litellm_params" @@ -168,15 +152,11 @@ async def atransform_search_vector_store_request( query = " ".join(query) # Generate embedding for the query asynchronously - embedding_model = litellm_params.get( - "embedding_model", "text-embedding-3-small" - ) + embedding_model = litellm_params.get("embedding_model", "text-embedding-3-small") import litellm as litellm_module - embedding_response = await litellm_module.aembedding( - model=embedding_model, input=[query] - ) + embedding_response = await litellm_module.aembedding(model=embedding_model, input=[query]) query_embedding = embedding_response.data[0]["embedding"] url = f"{api_base}/QueryVectors" @@ -185,9 +165,7 @@ async def atransform_search_vector_store_request( "vectorBucketName": bucket_name, "indexName": index_name, "queryVector": {"float32": query_embedding}, - "topK": vector_store_search_optional_params.get( - "max_num_results", 5 - ), # Default to 5 + "topK": vector_store_search_optional_params.get("max_num_results", 5), # Default to 5 "returnDistance": True, "returnMetadata": True, } @@ -246,9 +224,7 @@ def transform_search_vector_store_response( results.append( VectorStoreSearchResult( score=score, - content=[ - VectorStoreResultContent(text=source_text, type="text") - ], + content=[VectorStoreResultContent(text=source_text, type="text")], file_id=file_id, filename=filename, attributes=metadata, diff --git a/litellm/llms/sagemaker/chat/handler.py b/litellm/llms/sagemaker/chat/handler.py index b86cda7aeafb..c01e93c4bf49 100644 --- a/litellm/llms/sagemaker/chat/handler.py +++ b/litellm/llms/sagemaker/chat/handler.py @@ -30,9 +30,7 @@ def _load_credentials( aws_role_name = optional_params.pop("aws_role_name", None) aws_session_name = optional_params.pop("aws_session_name", None) aws_profile_name = optional_params.pop("aws_profile_name", None) - optional_params.pop( - "aws_bedrock_runtime_endpoint", None - ) # https://bedrock-runtime.{region_name}.amazonaws.com + optional_params.pop("aws_bedrock_runtime_endpoint", None) # https://bedrock-runtime.{region_name}.amazonaws.com aws_web_identity_token = optional_params.pop("aws_web_identity_token", None) aws_sts_endpoint = optional_params.pop("aws_sts_endpoint", None) @@ -41,15 +39,11 @@ def _load_credentials( # check env # litellm_aws_region_name = get_secret("AWS_REGION_NAME", None) - if litellm_aws_region_name is not None and isinstance( - litellm_aws_region_name, str - ): + if litellm_aws_region_name is not None and isinstance(litellm_aws_region_name, str): aws_region_name = litellm_aws_region_name standard_aws_region_name = get_secret("AWS_REGION", None) - if standard_aws_region_name is not None and isinstance( - standard_aws_region_name, str - ): + if standard_aws_region_name is not None and isinstance(standard_aws_region_name, str): aws_region_name = standard_aws_region_name if aws_region_name is None: @@ -97,9 +91,7 @@ def _prepare_request( headers = {"Content-Type": "application/json"} if extra_headers is not None: headers = {"Content-Type": "application/json", **extra_headers} - request = AWSRequest( - method="POST", url=api_base, data=encoded_data, headers=headers - ) + request = AWSRequest(method="POST", url=api_base, data=encoded_data, headers=headers) sigv4.add_auth(request) if ( extra_headers is not None and "Authorization" in extra_headers diff --git a/litellm/llms/sagemaker/chat/transformation.py b/litellm/llms/sagemaker/chat/transformation.py index 3e42c1e8c15e..4e4e088f4914 100644 --- a/litellm/llms/sagemaker/chat/transformation.py +++ b/litellm/llms/sagemaker/chat/transformation.py @@ -41,12 +41,8 @@ def __init__(self, **kwargs): OpenAIGPTConfig.__init__(self, **kwargs) BaseAWSLLM.__init__(self, **kwargs) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return SagemakerError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return SagemakerError(status_code=status_code, message=error_message, headers=headers) def validate_environment( self, @@ -79,9 +75,7 @@ def get_complete_url( else: api_base = f"https://runtime.sagemaker.{aws_region_name}.amazonaws.com/endpoints/{model}/invocations" - sagemaker_base_url = cast( - Optional[str], optional_params.get("sagemaker_base_url") - ) + sagemaker_base_url = cast(Optional[str], optional_params.get("sagemaker_base_url")) if sagemaker_base_url is not None: api_base = sagemaker_base_url @@ -143,19 +137,13 @@ def get_sync_custom_stream_wrapper( logging_obj=logging_obj, ) except httpx.HTTPStatusError as e: - raise SagemakerError( - status_code=e.response.status_code, message=e.response.text - ) + raise SagemakerError(status_code=e.response.status_code, message=e.response.text) if response.status_code != 200: - raise SagemakerError( - status_code=response.status_code, message=response.text - ) + raise SagemakerError(status_code=response.status_code, message=response.text) custom_stream_decoder = AWSEventStreamDecoder(model="", is_messages_api=True) - completion_stream = custom_stream_decoder.iter_bytes( - response.iter_bytes(chunk_size=1024) - ) + completion_stream = custom_stream_decoder.iter_bytes(response.iter_bytes(chunk_size=1024)) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, @@ -195,19 +183,13 @@ async def get_async_custom_stream_wrapper( logging_obj=logging_obj, ) except httpx.HTTPStatusError as e: - raise SagemakerError( - status_code=e.response.status_code, message=e.response.text - ) + raise SagemakerError(status_code=e.response.status_code, message=e.response.text) if response.status_code != 200: - raise SagemakerError( - status_code=response.status_code, message=response.text - ) + raise SagemakerError(status_code=response.status_code, message=response.text) custom_stream_decoder = AWSEventStreamDecoder(model="", is_messages_api=True) - completion_stream = custom_stream_decoder.aiter_bytes( - response.aiter_bytes(chunk_size=1024) - ) + completion_stream = custom_stream_decoder.aiter_bytes(response.aiter_bytes(chunk_size=1024)) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, diff --git a/litellm/llms/sagemaker/common_utils.py b/litellm/llms/sagemaker/common_utils.py index 6c15d642f8cc..2fddde291f48 100644 --- a/litellm/llms/sagemaker/common_utils.py +++ b/litellm/llms/sagemaker/common_utils.py @@ -18,9 +18,7 @@ def _load_sagemaker_response_stream_shape(): loader = Loader() service_dict = loader.load_service_model("sagemaker-runtime", "service-2") - return ServiceModel(service_dict).shape_for( - "InvokeEndpointWithResponseStreamOutput" - ) + return ServiceModel(service_dict).shape_for("InvokeEndpointWithResponseStreamOutput") except Exception as e: verbose_logger.warning( "litellm: could not load sagemaker-runtime response stream shape " @@ -60,12 +58,8 @@ def __init__(self, model: str, is_messages_api: Optional[bool] = None) -> None: self.content_blocks: List = [] self.is_messages_api = is_messages_api - def _chunk_parser_messages_api( - self, chunk_data: dict - ) -> StreamingChatCompletionChunk: - openai_chunk = StreamingChatCompletionChunk( - **{"model": self.model, **chunk_data} - ) + def _chunk_parser_messages_api(self, chunk_data: dict) -> StreamingChatCompletionChunk: + openai_chunk = StreamingChatCompletionChunk(**{"model": self.model, **chunk_data}) return openai_chunk @@ -94,9 +88,7 @@ def _chunk_parser(self, chunk_data: dict) -> GChunk: usage=None, ) - def iter_bytes( - self, iterator: Iterator[bytes] - ) -> Iterator[Optional[Union[GChunk, StreamingChatCompletionChunk]]]: + def iter_bytes(self, iterator: Iterator[bytes]) -> Iterator[Optional[Union[GChunk, StreamingChatCompletionChunk]]]: """Given an iterator that yields lines, iterate over it & yield every event encountered""" from botocore.eventstream import EventStreamBuffer @@ -109,10 +101,7 @@ def iter_bytes( message = self._parse_message_from_event(event) if message: # remove data: prefix and "\n\n" at the end - message = ( - litellm.CustomStreamWrapper._strip_sse_data_from_chunk(message) - or "" - ) + message = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(message) or "" message = message.replace("\n\n", "") # Accumulate JSON data @@ -141,9 +130,7 @@ def iter_bytes( yield self._chunk_parser(chunk_data=_data) except json.JSONDecodeError: # Handle or log any unparseable data at the end - verbose_logger.error( - f"Warning: Unparseable JSON data remained: {accumulated_json}" - ) + verbose_logger.error(f"Warning: Unparseable JSON data remained: {accumulated_json}") yield None async def aiter_bytes( @@ -161,16 +148,9 @@ async def aiter_bytes( try: message = self._parse_message_from_event(event) if message: - verbose_logger.debug( - "sagemaker parsed chunk bytes %s", message - ) + verbose_logger.debug("sagemaker parsed chunk bytes %s", message) # remove data: prefix and "\n\n" at the end - message = ( - litellm.CustomStreamWrapper._strip_sse_data_from_chunk( - message - ) - or "" - ) + message = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(message) or "" message = message.replace("\n\n", "") # Accumulate JSON data @@ -188,14 +168,10 @@ async def aiter_bytes( # If it's not valid JSON yet, continue to the next event continue except UnicodeDecodeError as e: - verbose_logger.warning( - f"UnicodeDecodeError: {e}. Attempting to combine with next event." - ) + verbose_logger.warning(f"UnicodeDecodeError: {e}. Attempting to combine with next event.") continue except Exception as e: - verbose_logger.error( - f"Error parsing message: {e}. Attempting to combine with next event." - ) + verbose_logger.error(f"Error parsing message: {e}. Attempting to combine with next event.") continue # Handle any remaining data after the iterator is exhausted @@ -208,9 +184,7 @@ async def aiter_bytes( yield self._chunk_parser(chunk_data=_data) except json.JSONDecodeError: # Handle or log any unparseable data at the end - verbose_logger.error( - f"Warning: Unparseable JSON data remained: {accumulated_json}" - ) + verbose_logger.error(f"Warning: Unparseable JSON data remained: {accumulated_json}") yield None except Exception as e: verbose_logger.error(f"Final error parsing accumulated JSON: {e}") diff --git a/litellm/llms/sagemaker/completion/handler.py b/litellm/llms/sagemaker/completion/handler.py index aa4663666c23..4b87271fd445 100644 --- a/litellm/llms/sagemaker/completion/handler.py +++ b/litellm/llms/sagemaker/completion/handler.py @@ -52,9 +52,7 @@ def _load_credentials( aws_role_name = optional_params.pop("aws_role_name", None) aws_session_name = optional_params.pop("aws_session_name", None) aws_profile_name = optional_params.pop("aws_profile_name", None) - optional_params.pop( - "aws_bedrock_runtime_endpoint", None - ) # https://bedrock-runtime.{region_name}.amazonaws.com + optional_params.pop("aws_bedrock_runtime_endpoint", None) # https://bedrock-runtime.{region_name}.amazonaws.com aws_web_identity_token = optional_params.pop("aws_web_identity_token", None) aws_sts_endpoint = optional_params.pop("aws_sts_endpoint", None) @@ -63,15 +61,11 @@ def _load_credentials( # check env # litellm_aws_region_name = get_secret("AWS_REGION_NAME", None) - if litellm_aws_region_name is not None and isinstance( - litellm_aws_region_name, str - ): + if litellm_aws_region_name is not None and isinstance(litellm_aws_region_name, str): aws_region_name = litellm_aws_region_name standard_aws_region_name = get_secret("AWS_REGION", None) - if standard_aws_region_name is not None and isinstance( - standard_aws_region_name, str - ): + if standard_aws_region_name is not None and isinstance(standard_aws_region_name, str): aws_region_name = standard_aws_region_name if aws_region_name is None: @@ -125,9 +119,7 @@ def _prepare_request( optional_params=optional_params, litellm_params=litellm_params, ) - request = AWSRequest( - method="POST", url=api_base, data=encoded_data, headers=headers - ) + request = AWSRequest(method="POST", url=api_base, data=encoded_data, headers=headers) sigv4.add_auth(request) if ( extra_headers is not None and "Authorization" in extra_headers @@ -207,9 +199,7 @@ def completion( if model_id is not None: # Add model_id as InferenceComponentName header # boto3 doc: https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html - prepared_request.headers.update( - {"X-Amzn-SageMaker-Inference-Component": model_id} - ) + prepared_request.headers.update({"X-Amzn-SageMaker-Inference-Component": model_id}) sync_handler = _get_httpx_client() sync_response = sync_handler.post( url=prepared_request.url, @@ -226,9 +216,7 @@ def completion( decoder = AWSEventStreamDecoder(model="") - completion_stream = decoder.iter_bytes( - sync_response.iter_bytes(chunk_size=1024) - ) + completion_stream = decoder.iter_bytes(sync_response.iter_bytes(chunk_size=1024)) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, model=model, @@ -287,9 +275,7 @@ def completion( if model_id is not None: # Add model_id as InferenceComponentName header # boto3 doc: https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html - prepared_request.headers.update( - {"X-Amzn-SageMaker-Inference-Component": model_id} - ) + prepared_request.headers.update({"X-Amzn-SageMaker-Inference-Component": model_id}) ## LOGGING timeout = 300.0 @@ -330,14 +316,8 @@ def completion( raise e except Exception as e: verbose_logger.error("Sagemaker error %s", str(e)) - status_code = ( - getattr(e, "response", {}) - .get("ResponseMetadata", {}) - .get("HTTPStatusCode", 500) - ) - error_message = ( - getattr(e, "response", {}).get("Error", {}).get("Message", str(e)) - ) + status_code = getattr(e, "response", {}).get("ResponseMetadata", {}).get("HTTPStatusCode", 500) + error_message = getattr(e, "response", {}).get("Error", {}).get("Message", str(e)) if "Inference Component Name header is required" in error_message: error_message += "\n pass in via `litellm.completion(..., model_id={InferenceComponentName})`" raise SagemakerError(status_code=status_code, message=error_message) @@ -375,14 +355,10 @@ async def make_async_call( ) if response.status_code != 200: - raise SagemakerError( - status_code=response.status_code, message=response.text - ) + raise SagemakerError(status_code=response.status_code, message=response.text) decoder = AWSEventStreamDecoder(model="") - completion_stream = decoder.aiter_bytes( - response.aiter_bytes(chunk_size=1024) - ) + completion_stream = decoder.aiter_bytes(response.aiter_bytes(chunk_size=1024)) return completion_stream @@ -437,9 +413,7 @@ async def async_streaming( } prepared_request = await asyncified_prepare_request(**prepared_request_args) if model_id is not None: # Fixes https://github.com/BerriAI/litellm/issues/8889 - prepared_request.headers.update( - {"X-Amzn-SageMaker-Inference-Component": model_id} - ) + prepared_request.headers.update({"X-Amzn-SageMaker-Inference-Component": model_id}) if not prepared_request.body: raise ValueError("Prepared request body is empty") @@ -484,9 +458,7 @@ async def async_completion( litellm_params: dict, ): timeout = 300.0 - async_handler = get_async_httpx_client( - llm_provider=litellm.LlmProviders.SAGEMAKER - ) + async_handler = get_async_httpx_client(llm_provider=litellm.LlmProviders.SAGEMAKER) data = await sagemaker_config.async_transform_request( model=model, @@ -522,9 +494,7 @@ async def async_completion( if model_id is not None: # Add model_id as InferenceComponentName header # boto3 doc: https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_runtime_InvokeEndpoint.html - prepared_request.headers.update( - {"X-Amzn-SageMaker-Inference-Component": model_id} - ) + prepared_request.headers.update({"X-Amzn-SageMaker-Inference-Component": model_id}) # make async httpx post request here try: response = await async_handler.post( @@ -535,9 +505,7 @@ async def async_completion( ) if response.status_code != 200: - raise SagemakerError( - status_code=response.status_code, message=response.text - ) + raise SagemakerError(status_code=response.status_code, message=response.text) except Exception as e: ## LOGGING logging_obj.post_call( @@ -610,9 +578,7 @@ def embedding( #### EMBEDDING LOGIC # Transform request based on model type provider_config = SagemakerEmbeddingConfig.get_model_config(model) - request_data = provider_config.transform_embedding_request( - model, input, optional_params, {} - ) + request_data = provider_config.transform_embedding_request(model, input, optional_params, {}) data = json.dumps(request_data).encode("utf-8") ## LOGGING @@ -637,14 +603,8 @@ def embedding( CustomAttributes="accept_eula=true", ) except Exception as e: - status_code = ( - getattr(e, "response", {}) - .get("ResponseMetadata", {}) - .get("HTTPStatusCode", 500) - ) - error_message = ( - getattr(e, "response", {}).get("Error", {}).get("Message", str(e)) - ) + status_code = getattr(e, "response", {}).get("ResponseMetadata", {}).get("HTTPStatusCode", 500) + error_message = getattr(e, "response", {}).get("Error", {}).get("Message", str(e)) raise SagemakerError(status_code=status_code, message=error_message) response = json.loads(response["Body"].read().decode("utf8")) diff --git a/litellm/llms/sagemaker/completion/transformation.py b/litellm/llms/sagemaker/completion/transformation.py index 8fd32bc4460d..918af7f586d4 100644 --- a/litellm/llms/sagemaker/completion/transformation.py +++ b/litellm/llms/sagemaker/completion/transformation.py @@ -60,12 +60,8 @@ def __init__( def get_config(cls): return super().get_config() - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return SagemakerError( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return SagemakerError(message=error_message, status_code=status_code, headers=headers) def get_supported_openai_params(self, model: str) -> List: return [ @@ -90,9 +86,7 @@ def map_openai_params( if value == 0.0 or value == 0: # hugging face exception raised when temp==0 # Failed: Error occurred: HuggingfaceException - Input validation error: `temperature` must be strictly positive - if not non_default_params.get( - "aws_sagemaker_allow_zero_temp", False - ): + if not non_default_params.get("aws_sagemaker_allow_zero_temp", False): value = 0.01 optional_params["temperature"] = value @@ -100,9 +94,7 @@ def map_openai_params( optional_params["top_p"] = value if param == "n": optional_params["best_of"] = value - optional_params["do_sample"] = ( - True # Need to sample if you want best of for hf inference endpoints - ) + optional_params["do_sample"] = True # Need to sample if you want best of for hf inference endpoints if param == "stream": optional_params["stream"] = value if param == "stop": @@ -130,9 +122,7 @@ def _transform_prompt( model_prompt_details = custom_prompt_dict[model] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", None), - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), final_prompt_value=model_prompt_details.get("final_prompt_value", ""), messages=messages, ) @@ -141,9 +131,7 @@ def _transform_prompt( model_prompt_details = custom_prompt_dict[hf_model_name] prompt = custom_prompt( role_dict=model_prompt_details.get("roles", None), - initial_prompt_value=model_prompt_details.get( - "initial_prompt_value", "" - ), + initial_prompt_value=model_prompt_details.get("initial_prompt_value", ""), final_prompt_value=model_prompt_details.get("final_prompt_value", ""), messages=messages, ) @@ -175,9 +163,7 @@ def transform_request( if stream is True: data["stream"] = True - custom_prompt_dict = ( - litellm_params.get("custom_prompt_dict", None) or litellm.custom_prompt_dict - ) + custom_prompt_dict = litellm_params.get("custom_prompt_dict", None) or litellm.custom_prompt_dict hf_model_name = litellm_params.get("hf_model_name", None) @@ -199,9 +185,7 @@ async def async_transform_request( litellm_params: dict, headers: dict, ) -> dict: - return await asyncify(self.transform_request)( - model, messages, optional_params, litellm_params, headers - ) + return await asyncify(self.transform_request)(model, messages, optional_params, litellm_params, headers) def transform_response( self, diff --git a/litellm/llms/sagemaker/embedding/cohere_transformation.py b/litellm/llms/sagemaker/embedding/cohere_transformation.py index fdb67202ebb6..126f153222da 100644 --- a/litellm/llms/sagemaker/embedding/cohere_transformation.py +++ b/litellm/llms/sagemaker/embedding/cohere_transformation.py @@ -55,12 +55,8 @@ def map_openai_params( optional_params["input_type"] = non_default_params["input_type"] return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return SagemakerError( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return SagemakerError(message=error_message, status_code=status_code, headers=headers) def transform_embedding_request( self, @@ -109,10 +105,7 @@ def transform_embedding_response( invoking this transform. """ input_value = ( - logging_obj.model_call_details.get("input") - or request_data.get("texts") - or request_data.get("images") - or [] + logging_obj.model_call_details.get("input") or request_data.get("texts") or request_data.get("images") or [] ) if isinstance(input_value, str): input_value = [input_value] diff --git a/litellm/llms/sagemaker/embedding/transformation.py b/litellm/llms/sagemaker/embedding/transformation.py index 5e2aa99534f7..fce2bfd22e7c 100644 --- a/litellm/llms/sagemaker/embedding/transformation.py +++ b/litellm/llms/sagemaker/embedding/transformation.py @@ -63,12 +63,8 @@ def map_openai_params( ) -> dict: return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return SagemakerError( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return SagemakerError(message=error_message, status_code=status_code, headers=headers) def transform_embedding_request( self, @@ -126,9 +122,7 @@ def transform_embedding_response( output_data = [] for idx, embedding in enumerate(embeddings): - output_data.append( - {"object": "embedding", "index": idx, "embedding": embedding} - ) + output_data.append({"object": "embedding", "index": idx, "embedding": embedding}) model_response.object = "list" model_response.data = output_data diff --git a/litellm/llms/sambanova/embedding/transformation.py b/litellm/llms/sambanova/embedding/transformation.py index 5c88188b84e5..611507bcf0d1 100644 --- a/litellm/llms/sambanova/embedding/transformation.py +++ b/litellm/llms/sambanova/embedding/transformation.py @@ -135,6 +135,4 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return SambaNovaError( - message=error_message, status_code=status_code, headers=headers - ) + return SambaNovaError(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/sap/chat/handler.py b/litellm/llms/sap/chat/handler.py index 713143d895f2..a679e4cf7041 100755 --- a/litellm/llms/sap/chat/handler.py +++ b/litellm/llms/sap/chat/handler.py @@ -139,9 +139,7 @@ def __next__(self) -> OpenAIChatCompletionChunk: if not line: continue - payload = ( - line[len(self._prefix) :] if line.startswith(self._prefix) else line - ) + payload = line[len(self._prefix) :] if line.startswith(self._prefix) else line if payload == self._final: self._safe_close() raise StopIteration @@ -213,9 +211,7 @@ async def __anext__(self): continue # now = lambda: int(time.time() * 1000) - payload = ( - line[len(self._prefix) :] if line.startswith(self._prefix) else line - ) + payload = line[len(self._prefix) :] if line.startswith(self._prefix) else line if payload == self._final: await self._aclose() raise StopAsyncIteration @@ -250,9 +246,7 @@ async def _aclose(self): # LLM handler # ------------------------------- class GenAIHubOrchestration(BaseLLMHTTPHandler): - def _add_stream_param_to_request_body( - self, data: dict, provider_config: BaseConfig, fake_stream: bool - ): + def _add_stream_param_to_request_body(self, data: dict, provider_config: BaseConfig, fake_stream: bool): if data.get("config", {}).get("stream", None) is not None: data["config"]["stream"]["enabled"] = True else: diff --git a/litellm/llms/sap/chat/models.py b/litellm/llms/sap/chat/models.py index a107901de762..2756dd0e67ea 100644 --- a/litellm/llms/sap/chat/models.py +++ b/litellm/llms/sap/chat/models.py @@ -90,16 +90,12 @@ class SAPMessage(BaseModel): role: Literal["system", "developer"] = "system" content: str - _content_validator = field_validator("content", mode="before")( - validate_different_content - ) + _content_validator = field_validator("content", mode="before")(validate_different_content) class SAPUserMessage(BaseModel): role: Literal["user"] = "user" - content: Union[ - str, TextContent, ImageContent, list[Union[TextContent, ImageContent]] - ] + content: Union[str, TextContent, ImageContent, list[Union[TextContent, ImageContent]]] class SAPAssistantMessage(BaseModel): @@ -108,9 +104,7 @@ class SAPAssistantMessage(BaseModel): refusal: str = "" tool_calls: list[MessageToolCall] = [] - _content_validator = field_validator("content", mode="before")( - validate_different_content - ) + _content_validator = field_validator("content", mode="before")(validate_different_content) class SAPToolChatMessage(BaseModel): @@ -118,9 +112,7 @@ class SAPToolChatMessage(BaseModel): tool_call_id: str content: str - _content_validator = field_validator("content", mode="before")( - validate_different_content - ) + _content_validator = field_validator("content", mode="before")(validate_different_content) ChatMessage = Union[SAPMessage, SAPUserMessage, SAPAssistantMessage, SAPToolChatMessage] @@ -184,9 +176,7 @@ class DocumentGroundingConfig(BaseModel): class GroundingModuleConfig(BaseModel): - type_: Literal["document_grounding_service"] = Field( - default="document_grounding_service", alias="type" - ) + type_: Literal["document_grounding_service"] = Field(default="document_grounding_service", alias="type") config: DocumentGroundingConfig @@ -329,9 +319,7 @@ class DPIStandardEntity(BaseModel): """ type_: SAPMaskingProfileEntity = Field(..., alias="type") - replacement_strategy: Optional[ - Union[DPIMethodConstant, DPIMethodFabricatedData] - ] = None + replacement_strategy: Optional[Union[DPIMethodConstant, DPIMethodFabricatedData]] = None class MaskGroundingInput(BaseModel): @@ -361,9 +349,7 @@ class MaskingProviderConfig(BaseModel): mask_grounding_input: A flag indicating whether to mask input to the grounding module. """ - type_: Literal["sap_data_privacy_integration"] = Field( - default="sap_data_privacy_integration", alias="type" - ) + type_: Literal["sap_data_privacy_integration"] = Field(default="sap_data_privacy_integration", alias="type") method: Literal["anonymization", "pseudonymization"] entities: list[Union[DPIStandardEntity, DPICustomEntity]] allowlist: Optional[list[str]] = None @@ -382,9 +368,7 @@ class MaskingModuleConfig(BaseModel): """ providers: Optional[list[MaskingProviderConfig]] = Field(min_length=1, default=None) - masking_providers: Optional[list[MaskingProviderConfig]] = Field( - min_length=1, default=None - ) + masking_providers: Optional[list[MaskingProviderConfig]] = Field(min_length=1, default=None) @model_validator(mode="after") def enforce_exactly_one_provider_list(self): @@ -392,9 +376,7 @@ def enforce_exactly_one_provider_list(self): has_masking_providers = self.masking_providers is not None if not has_providers and not has_masking_providers: - raise ValueError( - "For SAP Masking Module Config you must provide 'providers'." - ) + raise ValueError("For SAP Masking Module Config you must provide 'providers'.") if has_providers and has_masking_providers: raise ValueError( "For SAP Masking Module Config you must set exactly one of: 'providers' or 'masking_providers', not both." @@ -556,16 +538,12 @@ class LlamaGuard38bFilterConfig(BaseModel): class AzureContentSafetyInputFilterConfig(BaseModel): - type_: Literal["azure_content_safety"] = Field( - default="azure_content_safety", alias="type" - ) + type_: Literal["azure_content_safety"] = Field(default="azure_content_safety", alias="type") config: Optional[AzureContentSafetyInput] = None class AzureContentSafetyOutputFilterConfig(BaseModel): - type_: Literal["azure_content_safety"] = Field( - default="azure_content_safety", alias="type" - ) + type_: Literal["azure_content_safety"] = Field(default="azure_content_safety", alias="type") config: Optional[AzureContentSafetyOutput] = None @@ -585,9 +563,7 @@ class InputFiltering(BaseModel): filters: List of ContentFilter objects to be applied to input content. """ - filters: list[ - Union[AzureContentSafetyInputFilterConfig, LlamaGuard38bFilterConfig] - ] = Field(min_length=1) + filters: list[Union[AzureContentSafetyInputFilterConfig, LlamaGuard38bFilterConfig]] = Field(min_length=1) class OutputFiltering(BaseModel): @@ -599,9 +575,7 @@ class OutputFiltering(BaseModel): stream_options: Module-specific streaming options. """ - filters: list[ - Union[AzureContentSafetyOutputFilterConfig, LlamaGuard38bFilterConfig] - ] = Field(min_length=1) + filters: list[Union[AzureContentSafetyOutputFilterConfig, LlamaGuard38bFilterConfig]] = Field(min_length=1) stream_options: Optional[FilteringStreamOptions] = None @@ -677,9 +651,7 @@ class SAPDocumentTranslationInput(BaseModel): config: Configuration object for the translation module. """ - type_: Literal["sap_document_translation"] = Field( - default="sap_document_translation", alias="type" - ) + type_: Literal["sap_document_translation"] = Field(default="sap_document_translation", alias="type") translate_messages_history: Optional[bool] = None config: InputTranslationConfig @@ -694,9 +666,7 @@ class SAPDocumentTranslationOutput(BaseModel): config: Configuration object for the translation module. """ - type_: Literal["sap_document_translation"] = Field( - default="sap_document_translation", alias="type" - ) + type_: Literal["sap_document_translation"] = Field(default="sap_document_translation", alias="type") config: OutputTranslationConfig @@ -716,9 +686,7 @@ class TranslationModuleConfig(BaseModel): @model_validator(mode="after") def enforce_min_properties(self) -> "TranslationModuleConfig": if self.input is None and self.output is None: - raise ValueError( - "TranslationModuleConfig requires at least one of 'input' or 'output'." - ) + raise ValueError("TranslationModuleConfig requires at least one of 'input' or 'output'.") return self diff --git a/litellm/llms/sap/chat/transformation.py b/litellm/llms/sap/chat/transformation.py index 9899e3be9ade..d9d0f9bc2369 100755 --- a/litellm/llms/sap/chat/transformation.py +++ b/litellm/llms/sap/chat/transformation.py @@ -79,9 +79,7 @@ def _messages_to_sap_template(messages: List[Dict[str, str]]) -> list: # type: return template -def _tools_response_format_and_stream( - optional_params: dict, model_params: dict -) -> Tuple[dict, dict, dict]: +def _tools_response_format_and_stream(optional_params: dict, model_params: dict) -> Tuple[dict, dict, dict]: tools_ = optional_params.pop("tools", []) tools_ = [validate_dict(tool, ChatCompletionTool) for tool in tools_] tools: dict = {"tools": tools_} if tools_ else {} @@ -149,9 +147,7 @@ def __init__( def run_env_setup(self, service_key: Optional[str] = None) -> None: try: - self.token_creator, self._base_url, self._resource_group = ( - get_token_creator(service_key) - ) # type: ignore + self.token_creator, self._base_url, self._resource_group = get_token_creator(service_key) # type: ignore except ValueError as err: raise GenAIHubOrchestrationError(status_code=400, message=err.args[0]) @@ -184,9 +180,7 @@ def deployment_url(self) -> str: # Keep a short, tight client lifecycle here to avoid fd leaks client = litellm.module_level_client # with httpx.Client(timeout=30) as client: - deployments = client.get( - f"{self.base_url}/lm/deployments", headers=self.headers - ).json() + deployments = client.get(f"{self.base_url}/lm/deployments", headers=self.headers).json() valid: List[Tuple[str, str]] = [] for dep in deployments.get("resources", []): if dep.get("scenarioId") == "orchestration": @@ -289,9 +283,7 @@ def _build_prompt_module( resp_type = response_format.get("type", None) if resp_type: if resp_type == "json_schema": - response_format = validate_dict( - response_format, ResponseFormatJSONSchema - ) + response_format = validate_dict(response_format, ResponseFormatJSONSchema) else: response_format = validate_dict(response_format, ResponseFormat) response_format = {"response_format": response_format} @@ -299,9 +291,7 @@ def _build_prompt_module( response_format = {} placeholder_defaults = params.pop("placeholder_defaults", {}) - placeholder_defaults = ( - {"defaults": placeholder_defaults} if placeholder_defaults else {} - ) + placeholder_defaults = {"defaults": placeholder_defaults} if placeholder_defaults else {} optional_modules = {} optional_modules_lst = ["grounding", "masking", "filtering", "translation"] @@ -365,9 +355,7 @@ def transform_request( modules_dict = dict(modules_dict) fallback_model = modules_dict.pop("model", None) if fallback_model is None: - raise ValueError( - "Each entry in `fallback_sap_modules` must include a 'model' key." - ) + raise ValueError("Each entry in `fallback_sap_modules` must include a 'model' key.") if fallback_model.startswith("sap/"): fallback_model = fallback_model[4:] fallback_template = modules_dict.pop("messages", []) diff --git a/litellm/llms/sap/credentials.py b/litellm/llms/sap/credentials.py index 8cb19f195f25..54e6b1af50ef 100644 --- a/litellm/llms/sap/credentials.py +++ b/litellm/llms/sap/credentials.py @@ -37,9 +37,7 @@ def _get_nested(d: Union[Dict[str, Any], str], path: Sequence[str]) -> Any: try: cur = json.loads(cur) except json.JSONDecodeError: - verbose_logger.warning( - "SAP service key or VCAP service is a string but not valid JSON." - ) + verbose_logger.warning("SAP service key or VCAP service is a string but not valid JSON.") return None for k in path: if not isinstance(cur, dict): @@ -102,36 +100,24 @@ class CredentialsValue: CredentialsValue( "auth_url", ("url",), - transform_fn=lambda url: ( - url.rstrip("/") - + ("" if url.endswith(AUTH_ENDPOINT_SUFFIX) else AUTH_ENDPOINT_SUFFIX) - ), + transform_fn=lambda url: url.rstrip("/") + ("" if url.endswith(AUTH_ENDPOINT_SUFFIX) else AUTH_ENDPOINT_SUFFIX), ), CredentialsValue( "base_url", ("serviceurls", "AI_API_URL"), - transform_fn=lambda url: ( - url.rstrip("/") + ("" if url.endswith("/v2") else "/v2") - ), + transform_fn=lambda url: url.rstrip("/") + ("" if url.endswith("/v2") else "/v2"), ), CredentialsValue( "cert_url", ("certurl",), - transform_fn=lambda url: ( - url.rstrip("/") - + ("" if url.endswith(AUTH_ENDPOINT_SUFFIX) else AUTH_ENDPOINT_SUFFIX) - ), + transform_fn=lambda url: url.rstrip("/") + ("" if url.endswith(AUTH_ENDPOINT_SUFFIX) else AUTH_ENDPOINT_SUFFIX), ), # file paths (kept for config compatibility) CredentialsValue("cert_file_path"), CredentialsValue("key_file_path"), # inline PEMs from VCAP - CredentialsValue( - "cert_str", ("certificate",), transform_fn=lambda s: s.replace("\\n", "\n") - ), - CredentialsValue( - "key_str", ("key",), transform_fn=lambda s: s.replace("\\n", "\n") - ), + CredentialsValue("cert_str", ("certificate",), transform_fn=lambda s: s.replace("\\n", "\n")), + CredentialsValue("key_str", ("key",), transform_fn=lambda s: s.replace("\\n", "\n")), ] @@ -148,14 +134,7 @@ def init_conf(profile: Optional[str] = None) -> Dict[str, Any]: cfg_path = ( Path(cfg_env) if cfg_env - else ( - home - / ( - "config.json" - if profile in (None, "", "default") - else f"config_{profile}.json" - ) - ) + else (home / ("config.json" if profile in (None, "", "default") else f"config_{profile}.json")) ) if cfg_path and cfg_path.exists(): @@ -167,9 +146,7 @@ def init_conf(profile: Optional[str] = None) -> Dict[str, Any]: # If an explicit non-default profile was requested but not found, raise. if cfg_env or (profile not in (None, "", "default")): - raise FileNotFoundError( - f"Unable to locate profile config file at '{cfg_path}' in AICORE_HOME '{home}'" - ) + raise FileNotFoundError(f"Unable to locate profile config file at '{cfg_path}' in AICORE_HOME '{home}'") return {} @@ -204,9 +181,7 @@ def resolve_resource_group(sources: List[Source]) -> Optional[str]: for source in sources: value = source.get(rg_cred) if value is not None: - verbose_logger.debug( - f"Resolved GEN AI Hub resource_group from source {source.name}" - ) + verbose_logger.debug(f"Resolved GEN AI Hub resource_group from source {source.name}") return value return rg_cred.default @@ -227,9 +202,7 @@ def _parse_service_key_once( try: return json.loads(service_key) except json.JSONDecodeError: - verbose_logger.warning( - "SAP service key is a string but not valid JSON. Skipping this source." - ) + verbose_logger.warning("SAP service key is a string but not valid JSON. Skipping this source.") return None verbose_logger.warning( f"SAP service key has unexpected type '{type(service_key).__name__}'. Expected str or dict. Ignoring." @@ -242,15 +215,9 @@ def _resolve_credential_from_service_key( ) -> Optional[str]: if service_key is None: return None - val = _str_or_none( - _get_nested( - service_key, (("credentials",) + cv.vcap_key) if cv.vcap_key else (cv.name,) - ) - ) + val = _str_or_none(_get_nested(service_key, (("credentials",) + cv.vcap_key) if cv.vcap_key else (cv.name,))) if val is None: - return _str_or_none( - _get_nested(service_key, cv.vcap_key if cv.vcap_key else (cv.name,)) - ) + return _str_or_none(_get_nested(service_key, cv.vcap_key if cv.vcap_key else (cv.name,))) return val @@ -280,9 +247,7 @@ def fetch_credentials( """ config = init_conf(profile) - service_key = _parse_service_key_once( - service_key or litellm.sap_service_key or os.environ.get(SERVICE_KEY_ENV_VAR) - ) + service_key = _parse_service_key_once(service_key or litellm.sap_service_key or os.environ.get(SERVICE_KEY_ENV_VAR)) vcap_service = _get_vcap_service(VCAP_AICORE_SERVICE_NAME) sources = [ @@ -437,9 +402,7 @@ def get_token_creator( """ # Resolve credentials using your helper - credentials: Dict[str, str] = fetch_credentials( - service_key=service_key, profile=profile, **overrides - ) + credentials: Dict[str, str] = fetch_credentials(service_key=service_key, profile=profile, **overrides) auth_url = credentials.get("auth_url") base_url = credentials.get("base_url") @@ -501,19 +464,13 @@ def _fetch_token() -> tuple[str, datetime]: cert_pair=(cert_file_path, key_file_path), ) # Defensive guard: should never reach here due to validate_credentials() - raise ValueError( - "Invalid authentication configuration: no valid credentials found. " - ) + raise ValueError("Invalid authentication configuration: no valid credentials found. ") def get_token() -> str: nonlocal token, token_expiry with lock: now = datetime.now(timezone.utc) - if ( - token is None - or token_expiry is None - or token_expiry - now < timedelta(minutes=expiry_buffer_minutes) - ): + if token is None or token_expiry is None or token_expiry - now < timedelta(minutes=expiry_buffer_minutes): token, token_expiry = _fetch_token() return token diff --git a/litellm/llms/sap/embed/transformation.py b/litellm/llms/sap/embed/transformation.py index 4344c2cc545a..8368be718ad5 100644 --- a/litellm/llms/sap/embed/transformation.py +++ b/litellm/llms/sap/embed/transformation.py @@ -27,9 +27,7 @@ class Usage(BaseModel): class EmbeddingItem(BaseModel): object: Literal["embedding"] - embedding: List[float] = Field( - ..., description="Vector of floats (length varies by model)." - ) + embedding: List[float] = Field(..., description="Vector of floats (length varies by model).") index: int @@ -102,20 +100,15 @@ def headers(self) -> Dict: def deployment_url(self) -> str: with httpx.Client(timeout=30) as client: valid_deployments = [] - deployments = client.get( - self.base_url + "/lm/deployments", headers=self.headers - ).json() + deployments = client.get(self.base_url + "/lm/deployments", headers=self.headers).json() for deployment in deployments.get("resources", []): if deployment["scenarioId"] == "orchestration": config_details = client.get( - self.base_url - + f"/lm/configurations/{deployment['configurationId']}", + self.base_url + f"/lm/configurations/{deployment['configurationId']}", headers=self.headers, ).json() if config_details["executableId"] == "orchestration": - valid_deployments.append( - (deployment["deploymentUrl"], deployment["createdAt"]) - ) + valid_deployments.append((deployment["deploymentUrl"], deployment["createdAt"])) return sorted(valid_deployments, key=lambda x: x[1], reverse=True)[0][0] def get_error_class(self, error_message, status_code, headers): diff --git a/litellm/llms/scaleway/audio_transcription/transformation.py b/litellm/llms/scaleway/audio_transcription/transformation.py index b45f287afb44..d5438cbf930a 100644 --- a/litellm/llms/scaleway/audio_transcription/transformation.py +++ b/litellm/llms/scaleway/audio_transcription/transformation.py @@ -27,9 +27,7 @@ class ScalewayAudioTranscriptionException(BaseLLMException): class ScalewayAudioTranscriptionConfig(BaseAudioTranscriptionConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: return [ "language", "prompt", @@ -60,9 +58,7 @@ def get_complete_url( litellm_params: dict, stream: Optional[bool] = None, ) -> str: - api_base = ( - "https://api.scaleway.ai/v1" if api_base is None else api_base.rstrip("/") - ) + api_base = "https://api.scaleway.ai/v1" if api_base is None else api_base.rstrip("/") return f"{api_base}/audio/transcriptions" def get_error_class( @@ -90,8 +86,7 @@ def validate_environment( if not api_key: raise ScalewayAudioTranscriptionException( message=( - "Scaleway API key not found. Pass `api_key=...` or set the " - "SCW_SECRET_KEY environment variable." + "Scaleway API key not found. Pass `api_key=...` or set the SCW_SECRET_KEY environment variable." ), status_code=401, headers={}, diff --git a/litellm/llms/searchapi/search/transformation.py b/litellm/llms/searchapi/search/transformation.py index ae8413684cc3..5f3e535d7fd2 100644 --- a/litellm/llms/searchapi/search/transformation.py +++ b/litellm/llms/searchapi/search/transformation.py @@ -83,9 +83,7 @@ def validate_environment( ) if not api_key: - raise ValueError( - "SEARCHAPI_API_KEY is not set. Set `SEARCHAPI_API_KEY` environment variable." - ) + raise ValueError("SEARCHAPI_API_KEY is not set. Set `SEARCHAPI_API_KEY` environment variable.") headers["Content-Type"] = "application/json" @@ -103,9 +101,7 @@ def get_complete_url( SearchAPI.io uses GET requests and includes api_key in query params. """ - api_base = ( - api_base or get_secret_str("SEARCHAPI_API_BASE") or self.SEARCHAPI_API_BASE - ) + api_base = api_base or get_secret_str("SEARCHAPI_API_BASE") or self.SEARCHAPI_API_BASE # Build query parameters from the transformed request body if data and isinstance(data, dict) and "_searchapi_params" in data: @@ -155,9 +151,7 @@ def transform_search_request( default_api_base=self.SEARCHAPI_API_BASE, ) if not api_key: - raise ValueError( - "SEARCHAPI_API_KEY is not set. Set `SEARCHAPI_API_KEY` environment variable." - ) + raise ValueError("SEARCHAPI_API_KEY is not set. Set `SEARCHAPI_API_KEY` environment variable.") request_data: SearchAPIRequest = { "engine": "google", @@ -178,9 +172,7 @@ def transform_search_request( # Convert to multiple "site:domain" clauses domains = optional_params["search_domain_filter"] if isinstance(domains, list) and len(domains) > 0: - result_data["q"] = self._append_domain_filters( - str(result_data["q"]), domains - ) + result_data["q"] = self._append_domain_filters(str(result_data["q"]), domains) if "country" in optional_params: # Map to gl parameter @@ -188,10 +180,7 @@ def transform_search_request( # Pass through all other SearchAPI.io-specific parameters for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # Store params in special key for URL building (GET request) diff --git a/litellm/llms/searxng/search/transformation.py b/litellm/llms/searxng/search/transformation.py index ff68be5709eb..b5f410151120 100644 --- a/litellm/llms/searxng/search/transformation.py +++ b/litellm/llms/searxng/search/transformation.py @@ -174,10 +174,7 @@ def transform_search_request( # Pass through all other SearXNG-specific parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value # Store params in special key for GET request URL building diff --git a/litellm/llms/serper/search/transformation.py b/litellm/llms/serper/search/transformation.py index dd43f2d2dc97..31a0d3f2baca 100644 --- a/litellm/llms/serper/search/transformation.py +++ b/litellm/llms/serper/search/transformation.py @@ -63,9 +63,7 @@ def validate_environment( default_api_base=self.SERPER_API_BASE, ) if not api_key: - raise ValueError( - "SERPER_API_KEY is not set. Set `SERPER_API_KEY` environment variable." - ) + raise ValueError("SERPER_API_KEY is not set. Set `SERPER_API_KEY` environment variable.") headers["X-API-KEY"] = api_key headers["Content-Type"] = "application/json" return headers @@ -131,10 +129,7 @@ def transform_search_request( # pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value return result_data diff --git a/litellm/llms/snowflake/chat/transformation.py b/litellm/llms/snowflake/chat/transformation.py index ed30522876a1..8b23ae135b52 100644 --- a/litellm/llms/snowflake/chat/transformation.py +++ b/litellm/llms/snowflake/chat/transformation.py @@ -146,9 +146,7 @@ def _transform_tools_to_anthropic(self, tools: List[Dict]) -> List[Dict]: anthropic_tools.append(tool) return anthropic_tools - def _extract_system_and_messages( - self, messages: List[AllMessageValues] - ) -> tuple[Optional[str], List[Dict]]: + def _extract_system_and_messages(self, messages: List[AllMessageValues]) -> tuple[Optional[str], List[Dict]]: """ Split messages into system prompt and conversation turns for Anthropic format. @@ -171,50 +169,22 @@ def _extract_system_and_messages( if isinstance(content, str) and content: system_parts.append(content) elif isinstance(content, list): - system_parts.append( - "\n".join( - b.get("text", "") - for b in content - if b.get("type") == "text" - ) - ) + system_parts.append("\n".join(b.get("text", "") for b in content if b.get("type") == "text")) elif role == "assistant": - tool_calls = ( - msg.get("tool_calls") - if isinstance(msg, dict) - else getattr(msg, "tool_calls", None) - ) + tool_calls = msg.get("tool_calls") if isinstance(msg, dict) else getattr(msg, "tool_calls", None) if tool_calls: # type: ignore[truthy-bool] content_blocks: List[Dict[str, Any]] = [] if content: content_blocks.append({"type": "text", "text": content}) for tc in tool_calls: # type: ignore[attr-defined] - func = ( - tc.get("function", {}) - if isinstance(tc, dict) - else getattr(tc, "function", {}) - ) - tc_id = ( - tc.get("id", "") - if isinstance(tc, dict) - else getattr(tc, "id", "") - ) - func_name = ( - func.get("name", "") - if isinstance(func, dict) - else getattr(func, "name", "") - ) + func = tc.get("function", {}) if isinstance(tc, dict) else getattr(tc, "function", {}) + tc_id = tc.get("id", "") if isinstance(tc, dict) else getattr(tc, "id", "") + func_name = func.get("name", "") if isinstance(func, dict) else getattr(func, "name", "") func_args = ( - func.get("arguments", "{}") - if isinstance(func, dict) - else getattr(func, "arguments", "{}") + func.get("arguments", "{}") if isinstance(func, dict) else getattr(func, "arguments", "{}") ) try: - input_data = ( - json.loads(func_args) - if isinstance(func_args, str) - else func_args - ) + input_data = json.loads(func_args) if isinstance(func_args, str) else func_args except (json.JSONDecodeError, TypeError): input_data = {} content_blocks.append( @@ -225,20 +195,14 @@ def _extract_system_and_messages( "input": input_data, } ) - conversation.append( - {"role": "assistant", "content": content_blocks} - ) + conversation.append({"role": "assistant", "content": content_blocks}) else: conversation.append({"role": "assistant", "content": content}) elif role == "tool": tool_call_id = ( - msg.get("tool_call_id", "") - if isinstance(msg, dict) - else getattr(msg, "tool_call_id", "") - ) - tool_content = ( - content if isinstance(content, str) else json.dumps(content) + msg.get("tool_call_id", "") if isinstance(msg, dict) else getattr(msg, "tool_call_id", "") ) + tool_content = content if isinstance(content, str) else json.dumps(content) tool_result_block = { "type": "tool_result", "tool_use_id": tool_call_id, @@ -253,9 +217,7 @@ def _extract_system_and_messages( ): conversation[-1]["content"].append(tool_result_block) else: - conversation.append( - {"role": "user", "content": [tool_result_block]} - ) + conversation.append({"role": "user", "content": [tool_result_block]}) else: conversation.append({"role": role, "content": content}) @@ -274,12 +236,8 @@ def transform_request( extra_body = optional_params.pop("extra_body", {}) if _is_claude_model(model): - return self._transform_request_anthropic( - model, messages, optional_params, stream, extra_body - ) - return self._transform_request_openai( - model, messages, optional_params, stream, extra_body - ) + return self._transform_request_anthropic(model, messages, optional_params, stream, extra_body) + return self._transform_request_openai(model, messages, optional_params, stream, extra_body) def _transform_request_openai( self, @@ -341,14 +299,10 @@ def _transform_request_anthropic( system, conversation = self._extract_system_and_messages(messages) if "tools" in optional_params: - optional_params["tools"] = self._transform_tools_to_anthropic( - optional_params["tools"] - ) + optional_params["tools"] = self._transform_tools_to_anthropic(optional_params["tools"]) if "tool_choice" in optional_params: - optional_params["tool_choice"] = self._transform_tool_choice_to_anthropic( - optional_params["tool_choice"] - ) + optional_params["tool_choice"] = self._transform_tool_choice_to_anthropic(optional_params["tool_choice"]) max_completion_tokens = optional_params.pop("max_completion_tokens", None) if max_completion_tokens and "max_tokens" not in optional_params: @@ -368,9 +322,7 @@ def _transform_request_anthropic( body["system"] = system if "max_tokens" not in body: - body["max_tokens"] = ( - 4096 # reasonable default; Anthropic API max varies by model - ) + body["max_tokens"] = 4096 # reasonable default; Anthropic API max varies by model return body @@ -392,9 +344,7 @@ def transform_response( return self._transform_response_anthropic( model, raw_response, model_response, logging_obj, request_data, messages ) - return self._transform_response_openai( - model, raw_response, model_response, logging_obj, request_data, messages - ) + return self._transform_response_openai(model, raw_response, model_response, logging_obj, request_data, messages) def _transform_response_openai( self, @@ -466,9 +416,7 @@ def _transform_response_anthropic( "tool_use": "tool_calls", "stop_sequence": "stop", } - finish_reason = _stop_reason_map.get( - response_json.get("stop_reason", "end_turn"), "stop" - ) + finish_reason = _stop_reason_map.get(response_json.get("stop_reason", "end_turn"), "stop") message = Message(content=text_content or None, role="assistant") if tool_calls: @@ -484,8 +432,7 @@ def _transform_response_anthropic( usage = Usage( prompt_tokens=usage_data.get("input_tokens", 0), completion_tokens=usage_data.get("output_tokens", 0), - total_tokens=usage_data.get("input_tokens", 0) - + usage_data.get("output_tokens", 0), + total_tokens=usage_data.get("input_tokens", 0) + usage_data.get("output_tokens", 0), ) model_response.choices = [choice] diff --git a/litellm/llms/snowflake/embedding/transformation.py b/litellm/llms/snowflake/embedding/transformation.py index 83716f3ef262..44abb66b9001 100644 --- a/litellm/llms/snowflake/embedding/transformation.py +++ b/litellm/llms/snowflake/embedding/transformation.py @@ -64,6 +64,4 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return SnowflakeException( - message=error_message, status_code=status_code, headers=headers - ) + return SnowflakeException(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/soniox/audio_transcription/handler.py b/litellm/llms/soniox/audio_transcription/handler.py index d4774fea460c..88fa8f105809 100644 --- a/litellm/llms/soniox/audio_transcription/handler.py +++ b/litellm/llms/soniox/audio_transcription/handler.py @@ -168,15 +168,9 @@ def _prepare( # Pull handler-only kwargs out of params so they aren't sent # to Soniox. - poll_interval = float( - params.pop("soniox_polling_interval", SONIOX_DEFAULT_POLL_INTERVAL) - ) + poll_interval = float(params.pop("soniox_polling_interval", SONIOX_DEFAULT_POLL_INTERVAL)) try: - max_attempts = int( - params.pop( - "soniox_max_polling_attempts", SONIOX_DEFAULT_MAX_POLL_ATTEMPTS - ) - ) + max_attempts = int(params.pop("soniox_max_polling_attempts", SONIOX_DEFAULT_MAX_POLL_ATTEMPTS)) except (ValueError, OverflowError): max_attempts = SONIOX_DEFAULT_MAX_POLL_ATTEMPTS cleanup_raw = params.pop("soniox_cleanup", SONIOX_DEFAULT_CLEANUP) @@ -195,9 +189,7 @@ def _prepare( # SONIOX_MAX_POLL_ATTEMPTS * SONIOX_MAX_POLL_INTERVAL. if not math.isfinite(poll_interval): poll_interval = SONIOX_DEFAULT_POLL_INTERVAL - clamped_poll_interval = max( - SONIOX_MIN_POLL_INTERVAL, min(poll_interval, SONIOX_MAX_POLL_INTERVAL) - ) + clamped_poll_interval = max(SONIOX_MIN_POLL_INTERVAL, min(poll_interval, SONIOX_MAX_POLL_INTERVAL)) clamped_max_attempts = max(1, min(max_attempts, SONIOX_MAX_POLL_ATTEMPTS)) handler_opts: Dict[str, Any] = { @@ -273,9 +265,7 @@ def _safe_log_pre_call( additional_args={ "api_base": f"{api_base}/v1/transcriptions", "atranscription": True, - "complete_input_dict": SonioxAudioTranscriptionHandler._redact_body_for_logging( - body - ), + "complete_input_dict": SonioxAudioTranscriptionHandler._redact_body_for_logging(body), }, ) except Exception: @@ -295,11 +285,7 @@ def _safe_log_post_call( logging_obj.post_call( input=get_audio_file_name(audio_file) if audio_file else None, api_key=api_key, - additional_args={ - "complete_input_dict": SonioxAudioTranscriptionHandler._redact_body_for_logging( - body - ) - }, + additional_args={"complete_input_dict": SonioxAudioTranscriptionHandler._redact_body_for_logging(body)}, original_response=original_response, ) except Exception: @@ -316,11 +302,7 @@ def _raise_for_response( if response.status_code >= 400: try: payload = response.json() - message = ( - payload.get("error_message") - or payload.get("error") - or response.text - ) + message = payload.get("error_message") or payload.get("error") or response.text except Exception: message = response.text raise provider_config.get_error_class( @@ -403,9 +385,7 @@ def _sync_audio_transcriptions( json=body, timeout=timeout, ) - self._raise_for_response( - create_resp, provider_config, "create transcription" - ) + self._raise_for_response(create_resp, provider_config, "create transcription") transcription_id = create_resp.json()["id"] transcription_meta = self._sync_poll_until_completed( @@ -424,9 +404,7 @@ def _sync_audio_transcriptions( headers=auth_headers, timeout=timeout, ) - self._raise_for_response( - transcript_resp, provider_config, "fetch transcript" - ) + self._raise_for_response(transcript_resp, provider_config, "fetch transcript") transcript = transcript_resp.json() payload = {"transcription": transcription_meta, "transcript": transcript} @@ -444,9 +422,7 @@ def _sync_audio_transcriptions( "model": model, "custom_llm_provider": "soniox", "audio_transcription_duration": ( - float(audio_duration_ms) / 1000.0 - if audio_duration_ms is not None - else None + float(audio_duration_ms) / 1000.0 if audio_duration_ms is not None else None ), } ) @@ -641,9 +617,7 @@ async def _async_audio_transcriptions( json=body, timeout=timeout, ) - self._raise_for_response( - create_resp, provider_config, "create transcription" - ) + self._raise_for_response(create_resp, provider_config, "create transcription") transcription_id = create_resp.json()["id"] transcription_meta = await self._async_poll_until_completed( @@ -662,9 +636,7 @@ async def _async_audio_transcriptions( headers=auth_headers, timeout=timeout, ) - self._raise_for_response( - transcript_resp, provider_config, "fetch transcript" - ) + self._raise_for_response(transcript_resp, provider_config, "fetch transcript") transcript = transcript_resp.json() payload = {"transcription": transcription_meta, "transcript": transcript} @@ -682,9 +654,7 @@ async def _async_audio_transcriptions( "model": model, "custom_llm_provider": "soniox", "audio_transcription_duration": ( - float(audio_duration_ms) / 1000.0 - if audio_duration_ms is not None - else None + float(audio_duration_ms) / 1000.0 if audio_duration_ms is not None else None ), } ) diff --git a/litellm/llms/soniox/audio_transcription/transformation.py b/litellm/llms/soniox/audio_transcription/transformation.py index 681d4352dfef..7160d2548df1 100644 --- a/litellm/llms/soniox/audio_transcription/transformation.py +++ b/litellm/llms/soniox/audio_transcription/transformation.py @@ -61,9 +61,7 @@ class SonioxAudioTranscriptionConfig(BaseAudioTranscriptionConfig): """Configuration for Soniox async speech-to-text transcription.""" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: # `language` is mapped onto Soniox's `language_hints`. # `response_format` is handled by LiteLLM (Soniox doesn't support # SRT/VTT natively but we synthesize them from token timestamps). @@ -96,12 +94,8 @@ def map_openai_params( return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return SonioxException( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return SonioxException(message=error_message, status_code=status_code, headers=headers) def validate_environment( self, @@ -165,9 +159,7 @@ def transform_audio_transcription_request( if value is not None: body[key] = value - return AudioTranscriptionRequestData( - data=body, files=None, content_type="application/json" - ) + return AudioTranscriptionRequestData(data=body, files=None, content_type="application/json") def transform_audio_transcription_response( self, @@ -242,9 +234,7 @@ def _build_response_from_payload( # Best-effort metadata fields matching OpenAI's verbose_json shape. if transcription_meta.get("audio_duration_ms") is not None: try: - response["duration"] = ( - float(transcription_meta["audio_duration_ms"]) / 1000.0 - ) + response["duration"] = float(transcription_meta["audio_duration_ms"]) / 1000.0 except (TypeError, ValueError): pass diff --git a/litellm/llms/soniox/common_utils.py b/litellm/llms/soniox/common_utils.py index 01f8062fc967..76aa25522d04 100644 --- a/litellm/llms/soniox/common_utils.py +++ b/litellm/llms/soniox/common_utils.py @@ -178,9 +178,7 @@ def _flush() -> None: cues.append( { "start_ms": current_start, - "end_ms": ( - current_end if current_end is not None else current_start - ), + "end_ms": (current_end if current_end is not None else current_start), "text": text, } ) @@ -209,11 +207,7 @@ def _flush() -> None: should_break = False if len(current_tokens) >= _CUE_MAX_TOKENS: should_break = True - elif ( - current_start is not None - and start_ms is not None - and (start_ms - current_start) >= _CUE_MAX_DURATION_MS - ): + elif current_start is not None and start_ms is not None and (start_ms - current_start) >= _CUE_MAX_DURATION_MS: should_break = True if should_break: diff --git a/litellm/llms/stability/image_edit/transformations.py b/litellm/llms/stability/image_edit/transformations.py index 9c325c3cdda8..05a200246a14 100644 --- a/litellm/llms/stability/image_edit/transformations.py +++ b/litellm/llms/stability/image_edit/transformations.py @@ -80,9 +80,7 @@ def map_openai_params( if k in param_mapping: # Map param if mapping exists and value is valid if k == "size" and v in OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO: - mapped_params[param_mapping[k]] = ( - OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] - ) # type: ignore + mapped_params[param_mapping[k]] = OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] # type: ignore # Don't copy "size" itself to final dict elif k == "n": # Store for logic but do not add to outgoing params @@ -161,8 +159,7 @@ def validate_environment( if not final_api_key: raise ValueError( - "STABILITY_API_KEY is not set. " - "Please set it via environment variable or pass api_key parameter." + "STABILITY_API_KEY is not set. Please set it via environment variable or pass api_key parameter." ) headers["Authorization"] = f"Bearer {final_api_key}" @@ -312,9 +309,9 @@ def transform_image_edit_response( model_info = get_model_info(model, custom_llm_provider="stability") cost_per_image = model_info.get("output_cost_per_image", 0) if cost_per_image is not None: - model_response._hidden_params["additional_headers"][ - "llm_provider-x-litellm-response-cost" - ] = float(cost_per_image) + model_response._hidden_params["additional_headers"]["llm_provider-x-litellm-response-cost"] = float( + cost_per_image + ) return model_response def use_multipart_form_data(self) -> bool: diff --git a/litellm/llms/stability/image_generation/transformation.py b/litellm/llms/stability/image_generation/transformation.py index c8c2a16fcd13..a5b18b0f325a 100644 --- a/litellm/llms/stability/image_generation/transformation.py +++ b/litellm/llms/stability/image_generation/transformation.py @@ -45,9 +45,7 @@ class StabilityImageGenerationConfig(BaseImageGenerationConfig): DEFAULT_BASE_URL: str = "https://api.stability.ai" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Return list of OpenAI params supported by Stability AI. @@ -80,9 +78,7 @@ def map_openai_params( if k in supported_params: # Map size to aspect_ratio if k == "size" and v in OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO: - optional_params["aspect_ratio"] = ( - OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] - ) + optional_params["aspect_ratio"] = OPENAI_SIZE_TO_STABILITY_ASPECT_RATIO[v] elif k == "n": # Store n for later, but don't pass to Stability optional_params["_n"] = v @@ -131,9 +127,7 @@ def get_complete_url( """ Get the complete URL for the Stability AI API request. """ - base_url: str = ( - api_base or get_secret_str("STABILITY_API_BASE") or self.DEFAULT_BASE_URL - ) + base_url: str = api_base or get_secret_str("STABILITY_API_BASE") or self.DEFAULT_BASE_URL base_url = base_url.rstrip("/") endpoint = self._get_model_endpoint(model) @@ -156,8 +150,7 @@ def validate_environment( if not final_api_key: raise ValueError( - "STABILITY_API_KEY is not set. " - "Please set it via environment variable or pass api_key parameter." + "STABILITY_API_KEY is not set. Please set it via environment variable or pass api_key parameter." ) headers["Authorization"] = f"Bearer {final_api_key}" diff --git a/litellm/llms/tavily/search/transformation.py b/litellm/llms/tavily/search/transformation.py index 647cfb5fa840..51b897d93b24 100644 --- a/litellm/llms/tavily/search/transformation.py +++ b/litellm/llms/tavily/search/transformation.py @@ -33,9 +33,7 @@ class TavilySearchRequest(_TavilySearchRequestRequired, total=False): include_domains: List[str] # Optional - list of domains to include (max 300) exclude_domains: List[str] # Optional - list of domains to exclude (max 150) topic: str # Optional - category of search ('general', 'news', 'finance'), default 'general' - search_depth: ( - str # Optional - depth of search ('basic', 'advanced'), default 'basic' - ) + search_depth: str # Optional - depth of search ('basic', 'advanced'), default 'basic' include_answer: Union[bool, str] # Optional - include LLM-generated answer include_raw_content: Union[bool, str] # Optional - include raw HTML content include_images: bool # Optional - perform image search @@ -72,9 +70,7 @@ def validate_environment( default_api_base=self.TAVILY_API_BASE, ) if not api_key: - raise ValueError( - "TAVILY_API_KEY is not set. Set `TAVILY_API_KEY` environment variable." - ) + raise ValueError("TAVILY_API_KEY is not set. Set `TAVILY_API_KEY` environment variable.") headers["Authorization"] = f"Bearer {api_key}" headers["Content-Type"] = "application/json" return headers @@ -151,10 +147,7 @@ def transform_search_request( # pass through all other parameters as-is for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value return result_data @@ -189,9 +182,7 @@ def transform_search_response( search_result = SearchResult( title=result.get("title", ""), url=result.get("url", ""), - snippet=result.get( - "content", "" - ), # Tavily uses "content" instead of "snippet" + snippet=result.get("content", ""), # Tavily uses "content" instead of "snippet" date=None, # Tavily doesn't provide date in response last_updated=None, # Tavily doesn't provide last_updated in response ) diff --git a/litellm/llms/tinyfish/search/transformation.py b/litellm/llms/tinyfish/search/transformation.py index 4a95f5196465..4b7d38e36613 100644 --- a/litellm/llms/tinyfish/search/transformation.py +++ b/litellm/llms/tinyfish/search/transformation.py @@ -75,9 +75,7 @@ def validate_environment( default_api_base=self.TINYFISH_API_BASE, ) if not resolved_key: - raise ValueError( - "TINYFISH_API_KEY is not set. Set `TINYFISH_API_KEY` environment variable." - ) + raise ValueError("TINYFISH_API_KEY is not set. Set `TINYFISH_API_KEY` environment variable.") return {**headers, "X-API-Key": resolved_key, "Accept": "application/json"} def get_complete_url( @@ -87,13 +85,9 @@ def get_complete_url( data: dict[str, object] | list[dict[str, object]] | None = None, **kwargs: object, ) -> str: - resolved_base = ( - api_base or get_secret_str("TINYFISH_API_BASE") or self.TINYFISH_API_BASE - ) + resolved_base = api_base or get_secret_str("TINYFISH_API_BASE") or self.TINYFISH_API_BASE if isinstance(data, dict) and _TINYFISH_PARAMS_KEY in data: - validated_params = _UrlEncodableParams.validate_python( - data[_TINYFISH_PARAMS_KEY] - ) + validated_params = _UrlEncodableParams.validate_python(data[_TINYFISH_PARAMS_KEY]) return f"{resolved_base}?{urlencode(validated_params, doseq=True)}" return resolved_base @@ -116,15 +110,11 @@ def transform_search_request( request_data["max_results"] = max(1, min(int(raw_max), 20)) try: - domains = _StrList.validate_python( - optional_params.get("search_domain_filter") - ) + domains = _StrList.validate_python(optional_params.get("search_domain_filter")) except (ValidationError, TypeError): domains = [] if domains: - request_data["query"] = _append_domain_filters( - request_data["query"], domains - ) + request_data["query"] = _append_domain_filters(request_data["query"], domains) result_data: dict[str, object] = dict(request_data) @@ -156,8 +146,7 @@ def transform_search_response( max_results: int = min(int(max_results_str), 20) results = [ - SearchResult(title=item.title, url=item.url, snippet=item.snippet) - for item in parsed.results[:max_results] + SearchResult(title=item.title, url=item.url, snippet=item.snippet) for item in parsed.results[:max_results] ] return SearchResponse(results=results, object="search") diff --git a/litellm/llms/together_ai/chat.py b/litellm/llms/together_ai/chat.py index 238849cc1ecf..a78b023f2879 100644 --- a/litellm/llms/together_ai/chat.py +++ b/litellm/llms/together_ai/chat.py @@ -29,9 +29,7 @@ def get_supported_openai_params(self, model: str) -> list: # exception in _get_model_info_helper is hit (~332 deep calls). supports_fc: Optional[bool] = None try: - supports_fc = supports_function_calling( - model, custom_llm_provider="together_ai" - ) + supports_fc = supports_function_calling(model, custom_llm_provider="together_ai") except Exception as e: verbose_logger.debug(f"Error getting supported openai params: {e}") pass @@ -54,12 +52,8 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - mapped_openai_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_openai_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) - if "response_format" in mapped_openai_params and mapped_openai_params[ - "response_format" - ] == {"type": "text"}: + if "response_format" in mapped_openai_params and mapped_openai_params["response_format"] == {"type": "text"}: mapped_openai_params.pop("response_format") return mapped_openai_params diff --git a/litellm/llms/together_ai/completion/transformation.py b/litellm/llms/together_ai/completion/transformation.py index 8b9dc750c636..6e0b862c183f 100644 --- a/litellm/llms/together_ai/completion/transformation.py +++ b/litellm/llms/together_ai/completion/transformation.py @@ -29,15 +29,9 @@ def _transform_prompt( """ initial_prompt: AllPromptValues = _transform_prompt(messages) ## TOGETHER AI SPECIFIC VALIDATION ## - if isinstance(initial_prompt, list) and is_tokens_or_list_of_tokens( - value=initial_prompt - ): + if isinstance(initial_prompt, list) and is_tokens_or_list_of_tokens(value=initial_prompt): raise ValueError("TogetherAI does not support integers as input") - if ( - isinstance(initial_prompt, list) - and len(initial_prompt) == 1 - and isinstance(initial_prompt[0], str) - ): + if isinstance(initial_prompt, list) and len(initial_prompt) == 1 and isinstance(initial_prompt[0], str): together_prompt = initial_prompt[0] elif isinstance(initial_prompt, list): raise ValueError("TogetherAI does not support multiple prompts.") diff --git a/litellm/llms/together_ai/cost_calculator.py b/litellm/llms/together_ai/cost_calculator.py index a1be097bc862..191521266e7f 100644 --- a/litellm/llms/together_ai/cost_calculator.py +++ b/litellm/llms/together_ai/cost_calculator.py @@ -29,9 +29,7 @@ def get_model_params_and_category(model_name, call_type: CallTypes) -> str: if call_type == CallTypes.embedding or call_type == CallTypes.aembedding: return get_model_params_and_category_embeddings(model_name=model_name) model_name = model_name.lower() - re_params_match = re.search( - r"(\d+b)", model_name - ) # catch all decimals like 3b, 70b, etc + re_params_match = re.search(r"(\d+b)", model_name) # catch all decimals like 3b, 70b, etc category = None if re_params_match is not None: params_match = str(re_params_match.group(1)) @@ -67,9 +65,7 @@ def get_model_params_and_category_embeddings(model_name) -> str: - str - model pricing category if mapped else received model name """ model_name = model_name.lower() - re_params_match = re.search( - r"(\d+m)", model_name - ) # catch all decimals like 100m, 200m, etc. + re_params_match = re.search(r"(\d+m)", model_name) # catch all decimals like 100m, 200m, etc. category = None if re_params_match is not None: params_match = str(re_params_match.group(1)) diff --git a/litellm/llms/together_ai/rerank/handler.py b/litellm/llms/together_ai/rerank/handler.py index c5b02731e1eb..08acdead386d 100644 --- a/litellm/llms/together_ai/rerank/handler.py +++ b/litellm/llms/together_ai/rerank/handler.py @@ -70,9 +70,7 @@ async def async_rerank( # New async method request_data_dict: Dict[str, Any], api_key: str, ) -> RerankResponse: - client = get_async_httpx_client( - llm_provider=litellm.LlmProviders.TOGETHER_AI - ) # Use async client + client = get_async_httpx_client(llm_provider=litellm.LlmProviders.TOGETHER_AI) # Use async client response = await client.post( "https://api.together.xyz/v1/rerank", diff --git a/litellm/llms/together_ai/rerank/transformation.py b/litellm/llms/together_ai/rerank/transformation.py index f4d642bd25a6..3610a5853ac5 100644 --- a/litellm/llms/together_ai/rerank/transformation.py +++ b/litellm/llms/together_ai/rerank/transformation.py @@ -37,11 +37,7 @@ def _transform_response(self, response: dict) -> RerankResponse: # Get document data if it exists document_data = result.get("document", {}) - document = ( - RerankResponseDocument(text=str(document_data.get("text", ""))) - if document_data - else None - ) + document = RerankResponseDocument(text=str(document_data.get("text", ""))) if document_data else None # Create typed result rerank_result = RerankResponseResult( diff --git a/litellm/llms/topaz/common_utils.py b/litellm/llms/topaz/common_utils.py index 95fe29149342..27603b3b4011 100644 --- a/litellm/llms/topaz/common_utils.py +++ b/litellm/llms/topaz/common_utils.py @@ -23,18 +23,14 @@ def validate_environment( api_base: Optional[str] = None, ) -> dict: if api_key is None: - raise ValueError( - "API key is required for Topaz image variations. Set via `TOPAZ_API_KEY` or `api_key=..`" - ) + raise ValueError("API key is required for Topaz image variations. Set via `TOPAZ_API_KEY` or `api_key=..`") return { # "Content-Type": "multipart/form-data", "Accept": "image/jpeg", "X-API-Key": api_key, } - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: return [ "topaz/Standard V2", "topaz/Low Resolution V2", @@ -49,9 +45,7 @@ def get_api_key(api_key: Optional[str] = None) -> Optional[str]: @staticmethod def get_api_base(api_base: Optional[str] = None) -> Optional[str]: - return ( - api_base or get_secret_str("TOPAZ_API_BASE") or "https://api.topazlabs.com" - ) + return api_base or get_secret_str("TOPAZ_API_BASE") or "https://api.topazlabs.com" @staticmethod def get_base_model(model: str) -> str: diff --git a/litellm/llms/topaz/image_variations/transformation.py b/litellm/llms/topaz/image_variations/transformation.py index 41b51a558c56..01239d600b65 100644 --- a/litellm/llms/topaz/image_variations/transformation.py +++ b/litellm/llms/topaz/image_variations/transformation.py @@ -23,9 +23,7 @@ class TopazImageVariationConfig(TopazModelInfo, BaseImageVariationConfig): - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageVariationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageVariationOptionalParams]: return ["response_format", "size"] def get_complete_url( @@ -144,9 +142,7 @@ async def async_transform_response_image_variation( response_ms = logging_obj.get_response_ms() - return self._common_transform_response_image_variation( - image_content, response_ms - ) + return self._common_transform_response_image_variation(image_content, response_ms) def transform_response_image_variation( self, @@ -163,17 +159,11 @@ def transform_response_image_variation( ) -> ImageResponse: image_content = raw_response.content - response_ms = ( - raw_response.elapsed.total_seconds() * 1000 - ) # Convert to milliseconds + response_ms = raw_response.elapsed.total_seconds() * 1000 # Convert to milliseconds - return self._common_transform_response_image_variation( - image_content, response_ms - ) + return self._common_transform_response_image_variation(image_content, response_ms) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: return TopazException( status_code=status_code, message=error_message, diff --git a/litellm/llms/triton/completion/transformation.py b/litellm/llms/triton/completion/transformation.py index 0db83b2d3de5..44fe32e2e5da 100644 --- a/litellm/llms/triton/completion/transformation.py +++ b/litellm/llms/triton/completion/transformation.py @@ -35,12 +35,8 @@ class TritonConfig(BaseConfig): Handles routing between /infer and /generate triton completion llms """ - def get_error_class( - self, error_message: str, status_code: int, headers: Union[Dict, Headers] - ) -> BaseLLMException: - return TritonError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[Dict, Headers]) -> BaseLLMException: + return TritonError(status_code=status_code, message=error_message, headers=headers) def validate_environment( self, @@ -198,9 +194,7 @@ def transform_request( data_for_triton: Dict[str, Any] = { "text_input": prompt_factory(model=model, messages=messages), "parameters": { - "max_tokens": int( - optional_params.get("max_tokens", DEFAULT_MAX_TOKENS_FOR_TRITON) - ), + "max_tokens": int(optional_params.get("max_tokens", DEFAULT_MAX_TOKENS_FOR_TRITON)), }, "stream": bool(stream), } @@ -224,12 +218,8 @@ def transform_response( try: raw_response_json = raw_response.json() except Exception: - raise TritonError( - message=raw_response.text, status_code=raw_response.status_code - ) - model_response.choices = [ - Choices(index=0, message=Message(content=raw_response_json["text_output"])) - ] + raise TritonError(message=raw_response.text, status_code=raw_response.status_code) + model_response.choices = [Choices(index=0, message=Message(content=raw_response_json["text_output"]))] return model_response @@ -263,9 +253,7 @@ def transform_request( if not (k == "stream" or k == "max_retries"): datatype = "INT32" if isinstance(v, int) else "BYTES" datatype = "FP32" if isinstance(v, float) else datatype - data_for_triton["inputs"].append( - {"name": k, "shape": [1], "datatype": datatype, "data": [v]} - ) + data_for_triton["inputs"].append({"name": k, "shape": [1], "datatype": datatype, "data": [v]}) if "max_tokens" not in optional_params: data_for_triton["inputs"].append( @@ -295,9 +283,7 @@ def transform_response( try: raw_response_json = raw_response.json() except Exception: - raise TritonError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise TritonError(message=raw_response.text, status_code=raw_response.status_code) _triton_response_data = raw_response_json["outputs"][0]["data"] triton_response_data: Optional[str] = None diff --git a/litellm/llms/triton/embedding/transformation.py b/litellm/llms/triton/embedding/transformation.py index 93d1c25f1696..2426520e6309 100644 --- a/litellm/llms/triton/embedding/transformation.py +++ b/litellm/llms/triton/embedding/transformation.py @@ -81,9 +81,7 @@ def transform_embedding_response( try: raw_response_json = raw_response.json() except Exception: - raise TritonError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise TritonError(message=raw_response.text, status_code=raw_response.status_code) _embedding_output = [] @@ -104,9 +102,7 @@ def transform_embedding_response( model_response.model = raw_response_json.get("model_name", "None") model_response.data = _embedding_output - model_response.usage = self._build_embedding_usage( - model=model, request_data=request_data - ) + model_response.usage = self._build_embedding_usage(model=model, request_data=request_data) return model_response def _build_embedding_usage(self, model: str, request_data: dict) -> Usage: @@ -137,17 +133,11 @@ def _build_embedding_usage(self, model: str, request_data: dict) -> Usage: def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return TritonError( - message=error_message, status_code=status_code, headers=headers - ) + return TritonError(message=error_message, status_code=status_code, headers=headers) @staticmethod - def split_embedding_by_shape( - data: List[float], shape: List[int] - ) -> List[List[float]]: + def split_embedding_by_shape(data: List[float], shape: List[int]) -> List[List[float]]: if len(shape) != 2: raise ValueError("Shape must be of length 2.") embedding_size = shape[1] - return [ - data[i * embedding_size : (i + 1) * embedding_size] for i in range(shape[0]) - ] + return [data[i * embedding_size : (i + 1) * embedding_size] for i in range(shape[0])] diff --git a/litellm/llms/v0/chat/transformation.py b/litellm/llms/v0/chat/transformation.py index 7b65cec9d399..5e0295124717 100644 --- a/litellm/llms/v0/chat/transformation.py +++ b/litellm/llms/v0/chat/transformation.py @@ -23,9 +23,7 @@ def _get_openai_compatible_provider_info( ) -> Tuple[Optional[str], Optional[str]]: # v0 is openai compatible, we just need to set the api_base api_base = ( - api_base - or get_secret_str("V0_API_BASE") - or "https://api.v0.dev/v1" # Default v0 API base URL + api_base or get_secret_str("V0_API_BASE") or "https://api.v0.dev/v1" # Default v0 API base URL ) # type: ignore dynamic_api_key = api_key or get_secret_str("V0_API_KEY") return api_base, dynamic_api_key diff --git a/litellm/llms/vercel_ai_gateway/chat/transformation.py b/litellm/llms/vercel_ai_gateway/chat/transformation.py index fda1c4a77cb3..1c2e29234e66 100644 --- a/litellm/llms/vercel_ai_gateway/chat/transformation.py +++ b/litellm/llms/vercel_ai_gateway/chat/transformation.py @@ -33,16 +33,8 @@ def get_supported_openai_params(self, model: str) -> list: def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: - api_base = ( - api_base - or get_secret_str("VERCEL_AI_GATEWAY_API_BASE") - or "https://ai-gateway.vercel.sh/v1" - ) - user_api_key = ( - api_key - or get_secret_str("VERCEL_AI_GATEWAY_API_KEY") - or get_secret_str("VERCEL_OIDC_TOKEN") - ) + api_base = api_base or get_secret_str("VERCEL_AI_GATEWAY_API_BASE") or "https://ai-gateway.vercel.sh/v1" + user_api_key = api_key or get_secret_str("VERCEL_AI_GATEWAY_API_KEY") or get_secret_str("VERCEL_OIDC_TOKEN") return api_base, user_api_key def map_openai_params( @@ -52,9 +44,7 @@ def map_openai_params( model: str, drop_params: bool, ) -> dict: - mapped_openai_params = super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + mapped_openai_params = super().map_openai_params(non_default_params, optional_params, model, drop_params) # Vercel AI Gateway-only parameters extra_body = {} @@ -63,9 +53,7 @@ def map_openai_params( if provider_options is not None: extra_body["providerOptions"] = provider_options - mapped_openai_params["extra_body"] = ( - extra_body # openai client supports `extra_body` param - ) + mapped_openai_params["extra_body"] = extra_body # openai client supports `extra_body` param return mapped_openai_params def transform_request( @@ -82,9 +70,7 @@ def transform_request( Returns: dict: The transformed request. Sent as the body of the API call. """ - return super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + return super().transform_request(model, messages, optional_params, litellm_params, headers) def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] @@ -95,9 +81,7 @@ def get_error_class( headers=headers, ) - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: api_base, _ = self._get_openai_compatible_provider_info(api_base, api_key) if api_base is None: diff --git a/litellm/llms/vercel_ai_gateway/embedding/transformation.py b/litellm/llms/vercel_ai_gateway/embedding/transformation.py index 7238b05f10d9..e4036f415a91 100644 --- a/litellm/llms/vercel_ai_gateway/embedding/transformation.py +++ b/litellm/llms/vercel_ai_gateway/embedding/transformation.py @@ -78,10 +78,7 @@ def get_complete_url( if api_base: api_base = api_base.rstrip("/") else: - api_base = ( - get_secret_str("VERCEL_AI_GATEWAY_API_BASE") - or "https://ai-gateway.vercel.sh/v1" - ) + api_base = get_secret_str("VERCEL_AI_GATEWAY_API_BASE") or "https://ai-gateway.vercel.sh/v1" return f"{api_base}/embeddings" @@ -163,9 +160,7 @@ def map_openai_params( optional_params[param] = value return optional_params - def get_error_class( - self, error_message: str, status_code: int, headers: Any - ) -> Any: + def get_error_class(self, error_message: str, status_code: int, headers: Any) -> Any: """ Get the error class for Vercel AI Gateway errors. """ diff --git a/litellm/llms/vertex_ai/agent_engine/sse_iterator.py b/litellm/llms/vertex_ai/agent_engine/sse_iterator.py index 06fb55e18480..d3e95f46be98 100644 --- a/litellm/llms/vertex_ai/agent_engine/sse_iterator.py +++ b/litellm/llms/vertex_ai/agent_engine/sse_iterator.py @@ -27,9 +27,7 @@ class VertexAgentEngineResponseIterator(BaseModelResponseIterator): def __init__(self, streaming_response: Any, sync_stream: bool) -> None: super().__init__(streaming_response=streaming_response, sync_stream=sync_stream) - def chunk_parser( - self, chunk: dict - ) -> Union[GenericStreamingChunk, ModelResponseStream]: + def chunk_parser(self, chunk: dict) -> Union[GenericStreamingChunk, ModelResponseStream]: """ Parse a Vertex Agent Engine response chunk into ModelResponseStream. diff --git a/litellm/llms/vertex_ai/agent_engine/transformation.py b/litellm/llms/vertex_ai/agent_engine/transformation.py index 0707a7b4c264..20c86a25f820 100644 --- a/litellm/llms/vertex_ai/agent_engine/transformation.py +++ b/litellm/llms/vertex_ai/agent_engine/transformation.py @@ -120,9 +120,7 @@ def get_complete_url( # Get project and location from litellm_params or environment vertex_project = self.safe_get_vertex_ai_project(litellm_params) - vertex_location = ( - self.safe_get_vertex_ai_location(litellm_params) or "us-central1" - ) + vertex_location = self.safe_get_vertex_ai_location(litellm_params) or "us-central1" # Build the full resource path if only engine_id was provided if not resource_path.startswith("projects/"): @@ -158,9 +156,7 @@ def _get_auth_headers( project_id=vertex_project, ) - verbose_logger.debug( - f"Vertex Agent Engine: Authenticated for project {project_id}" - ) + verbose_logger.debug(f"Vertex Agent Engine: Authenticated for project {project_id}") return { "Authorization": f"Bearer {access_token}", @@ -260,17 +256,13 @@ def _extract_text_from_response(self, response_data: dict) -> str: return "" - def _calculate_usage( - self, model: str, messages: List[AllMessageValues], content: str - ) -> Optional[Usage]: + def _calculate_usage(self, model: str, messages: List[AllMessageValues], content: str) -> Optional[Usage]: """Calculate token usage using LiteLLM's token counter.""" try: from litellm.utils import token_counter prompt_tokens = token_counter(model="gpt-3.5-turbo", messages=messages) - completion_tokens = token_counter( - model="gpt-3.5-turbo", text=content, count_response_tokens=True - ) + completion_tokens = token_counter(model="gpt-3.5-turbo", text=content, count_response_tokens=True) total_tokens = prompt_tokens + completion_tokens return Usage( @@ -304,9 +296,7 @@ def transform_response( """ try: content_type = raw_response.headers.get("content-type", "").lower() - verbose_logger.debug( - f"Vertex Agent Engine response Content-Type: {content_type}" - ) + verbose_logger.debug(f"Vertex Agent Engine response Content-Type: {content_type}") # Parse the SSE response response_text = raw_response.text @@ -346,9 +336,7 @@ def transform_response( return model_response except Exception as e: - verbose_logger.error( - f"Error processing Vertex Agent Engine response: {str(e)}" - ) + verbose_logger.error(f"Error processing Vertex Agent Engine response: {str(e)}") raise VertexAgentEngineError( message=f"Error processing response: {str(e)}", status_code=raw_response.status_code, @@ -401,14 +389,10 @@ def get_sync_custom_stream_wrapper( ) if response.status_code != 200: - raise VertexAgentEngineError( - status_code=response.status_code, message=str(response.read()) - ) + raise VertexAgentEngineError(status_code=response.status_code, message=str(response.read())) # Create iterator for SSE stream - completion_stream = self.get_streaming_response( - model=model, raw_response=response - ) + completion_stream = self.get_streaming_response(model=model, raw_response=response) streaming_response = CustomStreamWrapper( completion_stream=completion_stream, @@ -448,9 +432,7 @@ async def get_async_custom_stream_wrapper( from litellm.utils import CustomStreamWrapper if client is None or not isinstance(client, AsyncHTTPHandler): - client = get_async_httpx_client( - llm_provider=cast(Any, "vertex_ai"), params={} - ) + client = get_async_httpx_client(llm_provider=cast(Any, "vertex_ai"), params={}) # Avoid logging sensitive api_base directly verbose_logger.debug("Making async streaming request to Vertex AI endpoint.") @@ -465,9 +447,7 @@ async def get_async_custom_stream_wrapper( ) if response.status_code != 200: - raise VertexAgentEngineError( - status_code=response.status_code, message=str(await response.aread()) - ) + raise VertexAgentEngineError(status_code=response.status_code, message=str(await response.aread())) # Create iterator for SSE stream (async) completion_stream = VertexAgentEngineResponseIterator( diff --git a/litellm/llms/vertex_ai/batches/handler.py b/litellm/llms/vertex_ai/batches/handler.py index 00222faf2741..ada1356fb6b3 100644 --- a/litellm/llms/vertex_ai/batches/handler.py +++ b/litellm/llms/vertex_ai/batches/handler.py @@ -78,8 +78,10 @@ def create_batch( "Authorization": f"Bearer {access_token}", } - vertex_batch_request: VertexAIBatchPredictionJob = VertexAIBatchTransformation.transform_openai_batch_request_to_vertex_ai_batch_request( - request=create_batch_data + vertex_batch_request: VertexAIBatchPredictionJob = ( + VertexAIBatchTransformation.transform_openai_batch_request_to_vertex_ai_batch_request( + request=create_batch_data + ) ) if _is_async is True: @@ -366,8 +368,10 @@ def list_batches( raise Exception(f"Error: {response.status_code} {response.text}") _json_response = response.json() - vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_list_response_to_openai_list_response( - response=_json_response + vertex_batch_response = ( + VertexAIBatchTransformation.transform_vertex_ai_batch_list_response_to_openai_list_response( + response=_json_response + ) ) return vertex_batch_response @@ -389,8 +393,10 @@ async def _async_list_batches( raise Exception(f"Error: {response.status_code} {response.text}") _json_response = response.json() - vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_list_response_to_openai_list_response( - response=_json_response + vertex_batch_response = ( + VertexAIBatchTransformation.transform_vertex_ai_batch_list_response_to_openai_list_response( + response=_json_response + ) ) return vertex_batch_response @@ -482,9 +488,7 @@ def cancel_batch( retrieve_response.status_code, retrieve_response.text[:1000], ) - raise Exception( - f"Error: {retrieve_response.status_code} {retrieve_response.text}" - ) + raise Exception(f"Error: {retrieve_response.status_code} {retrieve_response.text}") _json_response = retrieve_response.json() vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response( @@ -530,9 +534,7 @@ async def _async_cancel_batch( retrieve_response.status_code, retrieve_response.text[:1000], ) - raise Exception( - f"Error: {retrieve_response.status_code} {retrieve_response.text}" - ) + raise Exception(f"Error: {retrieve_response.status_code} {retrieve_response.text}") _json_response = retrieve_response.json() vertex_batch_response = VertexAIBatchTransformation.transform_vertex_ai_batch_response_to_openai_batch_response( diff --git a/litellm/llms/vertex_ai/batches/transformation.py b/litellm/llms/vertex_ai/batches/transformation.py index c1144654908d..c75efdb43e8e 100644 --- a/litellm/llms/vertex_ai/batches/transformation.py +++ b/litellm/llms/vertex_ai/batches/transformation.py @@ -28,15 +28,11 @@ def transform_openai_batch_request_to_vertex_ai_batch_request( input_file_id = request.get("input_file_id") if input_file_id is None: raise ValueError("input_file_id is required, but not provided") - input_config: InputConfig = InputConfig( - gcsSource=GcsSource(uris=[input_file_id]), instancesFormat="jsonl" - ) + input_config: InputConfig = InputConfig(gcsSource=GcsSource(uris=[input_file_id]), instancesFormat="jsonl") model: str = cls._get_model_from_gcs_file(input_file_id) output_config: OutputConfig = OutputConfig( predictionsFormat="jsonl", - gcsDestination=GcsDestination( - outputUriPrefix=cls._get_gcs_uri_prefix_from_file(input_file_id) - ), + gcsDestination=GcsDestination(outputUriPrefix=cls._get_gcs_uri_prefix_from_file(input_file_id)), ) return VertexAIBatchPredictionJob( inputConfig=input_config, @@ -52,19 +48,13 @@ def transform_vertex_ai_batch_response_to_openai_batch_response( return LiteLLMBatch( id=cls._get_batch_id_from_vertex_ai_batch_response(response), completion_window="24hrs", - created_at=_convert_vertex_datetime_to_openai_datetime( - vertex_datetime=response.get("createTime", "") - ), + created_at=_convert_vertex_datetime_to_openai_datetime(vertex_datetime=response.get("createTime", "")), endpoint="", - input_file_id=cls._get_input_file_id_from_vertex_ai_batch_response( - response - ), + input_file_id=cls._get_input_file_id_from_vertex_ai_batch_response(response), object="batch", status=cls._get_batch_job_status_from_vertex_ai_batch_response(response), error_file_id=None, # Vertex AI doesn't seem to have a direct equivalent - output_file_id=cls._get_output_file_id_from_vertex_ai_batch_response( - response - ), + output_file_id=cls._get_output_file_id_from_vertex_ai_batch_response(response), ) @classmethod @@ -76,10 +66,7 @@ def transform_vertex_ai_batch_list_response_to_openai_list_response( """ batch_jobs = response.get("batchPredictionJobs", []) or [] - data = [ - cls.transform_vertex_ai_batch_response_to_openai_batch_response(job) - for job in batch_jobs - ] + data = [cls.transform_vertex_ai_batch_response_to_openai_batch_response(job) for job in batch_jobs] first_id = data[0].id if len(data) > 0 else None last_id = data[-1].id if len(data) > 0 else None @@ -95,9 +82,7 @@ def transform_vertex_ai_batch_list_response_to_openai_list_response( } @classmethod - def _get_batch_id_from_vertex_ai_batch_response( - cls, response: VertexBatchPredictionResponse - ) -> str: + def _get_batch_id_from_vertex_ai_batch_response(cls, response: VertexBatchPredictionResponse) -> str: """ Gets the batch id from the Vertex AI Batch response safely @@ -113,9 +98,7 @@ def _get_batch_id_from_vertex_ai_batch_response( return parts[-1] if parts else _name @classmethod - def _get_input_file_id_from_vertex_ai_batch_response( - cls, response: VertexBatchPredictionResponse - ) -> str: + def _get_input_file_id_from_vertex_ai_batch_response(cls, response: VertexBatchPredictionResponse) -> str: """ Gets the input file id from the Vertex AI Batch response """ @@ -135,16 +118,12 @@ def _get_input_file_id_from_vertex_ai_batch_response( return uris[0] @classmethod - def _get_output_file_id_from_vertex_ai_batch_response( - cls, response: VertexBatchPredictionResponse - ) -> str: + def _get_output_file_id_from_vertex_ai_batch_response(cls, response: VertexBatchPredictionResponse) -> str: """ Gets the output file id from the Vertex AI Batch response """ - output_file_id: str = response.get("outputInfo", OutputInfo()).get( - "gcsOutputDirectory", "" - ) + output_file_id: str = response.get("outputInfo", OutputInfo()).get("gcsOutputDirectory", "") if output_file_id: output_file_id = output_file_id.rstrip("/") + "/predictions.jsonl" if output_file_id and output_file_id != "/predictions.jsonl": diff --git a/litellm/llms/vertex_ai/common_utils.py b/litellm/llms/vertex_ai/common_utils.py index 96f016da94df..36522dfe396a 100644 --- a/litellm/llms/vertex_ai/common_utils.py +++ b/litellm/llms/vertex_ai/common_utils.py @@ -135,9 +135,7 @@ class VertexAIModelRoute(str, Enum): VERTEX_AI_MODEL_ROUTES = [f"{route.value}/" for route in VertexAIModelRoute] -def get_vertex_ai_model_route( - model: str, litellm_params: Optional[dict] = None -) -> VertexAIModelRoute: +def get_vertex_ai_model_route(model: str, litellm_params: Optional[dict] = None) -> VertexAIModelRoute: """ Determine which handler to use for a Vertex AI model based on the model name. @@ -216,9 +214,7 @@ def get_supports_system_message( _custom_llm_provider = custom_llm_provider if custom_llm_provider == "vertex_ai_beta": _custom_llm_provider = "vertex_ai" - supports_system_message = supports_system_messages( - model=model, custom_llm_provider=_custom_llm_provider - ) + supports_system_message = supports_system_messages(model=model, custom_llm_provider=_custom_llm_provider) # Vertex Models called in the `/gemini` request/response format also support system messages if litellm.VertexGeminiConfig._is_model_gemini_spec_model(model): @@ -241,9 +237,7 @@ def get_supports_response_schema( if custom_llm_provider == "vertex_ai_beta": _custom_llm_provider = "vertex_ai" - _supports_response_schema = supports_response_schema( - model=model, custom_llm_provider=_custom_llm_provider - ) + _supports_response_schema = supports_response_schema(model=model, custom_llm_provider=_custom_llm_provider) return _supports_response_schema @@ -278,9 +272,7 @@ def supports_response_json_schema(model: str) -> bool: from typing import Literal, Optional -all_gemini_url_modes = Literal[ - "chat", "embedding", "batch_embedding", "image_generation", "count_tokens" -] +all_gemini_url_modes = Literal["chat", "embedding", "batch_embedding", "image_generation", "count_tokens"] def get_vertex_base_model_name(model: str) -> str: @@ -453,9 +445,7 @@ def _get_gemini_url( ) _gemini_model_name = "models/{}".format(model) - api_version = ( - "v1alpha" if VertexGeminiConfig._is_gemini_3_or_newer(model) else "v1beta" - ) + api_version = "v1alpha" if VertexGeminiConfig._is_gemini_3_or_newer(model) else "v1beta" if mode == "chat": endpoint = "generateContent" @@ -465,24 +455,16 @@ def _get_gemini_url( api_version, _gemini_model_name, endpoint ) else: - url = "https://generativelanguage.googleapis.com/{}/{}:{}".format( - api_version, _gemini_model_name, endpoint - ) + url = "https://generativelanguage.googleapis.com/{}/{}:{}".format(api_version, _gemini_model_name, endpoint) elif mode == "embedding": endpoint = "embedContent" - url = "https://generativelanguage.googleapis.com/v1beta/{}:{}".format( - _gemini_model_name, endpoint - ) + url = "https://generativelanguage.googleapis.com/v1beta/{}:{}".format(_gemini_model_name, endpoint) elif mode == "batch_embedding": endpoint = "batchEmbedContents" - url = "https://generativelanguage.googleapis.com/v1beta/{}:{}".format( - _gemini_model_name, endpoint - ) + url = "https://generativelanguage.googleapis.com/v1beta/{}:{}".format(_gemini_model_name, endpoint) elif mode == "count_tokens": endpoint = "countTokens" - url = "https://generativelanguage.googleapis.com/v1beta/{}:{}".format( - _gemini_model_name, endpoint - ) + url = "https://generativelanguage.googleapis.com/v1beta/{}:{}".format(_gemini_model_name, endpoint) elif mode == "image_generation": raise ValueError( "LiteLLM's `gemini/` route does not support image generation yet. Let us know if you need this feature by opening an issue at https://github.com/BerriAI/litellm/issues" @@ -511,9 +493,7 @@ def _check_text_in_content(parts: List[PartType]) -> bool: def _fix_enum_empty_strings(schema, depth=0): """Fix empty strings in enum values by replacing them with None. Gemini doesn't accept empty strings in enums.""" if depth > DEFAULT_MAX_RECURSE_DEPTH: - raise ValueError( - f"Max depth of {DEFAULT_MAX_RECURSE_DEPTH} exceeded while processing schema." - ) + raise ValueError(f"Max depth of {DEFAULT_MAX_RECURSE_DEPTH} exceeded while processing schema.") if "enum" in schema and isinstance(schema["enum"], list): schema["enum"] = [None if value == "" else value for value in schema["enum"]] @@ -537,9 +517,7 @@ def _fix_enum_types(schema, depth=0): include a string type), remove the enum to avoid provider validation errors. """ if depth > DEFAULT_MAX_RECURSE_DEPTH: - raise ValueError( - f"Max depth of {DEFAULT_MAX_RECURSE_DEPTH} exceeded while processing schema." - ) + raise ValueError(f"Max depth of {DEFAULT_MAX_RECURSE_DEPTH} exceeded while processing schema.") if not isinstance(schema, dict): return @@ -672,11 +650,7 @@ def _filter_anyof_fields(schema_dict: Dict[str, Any]) -> Dict[str, Any]: if isinstance(schema_dict, dict) and schema_dict.get("anyOf"): any_of = schema_dict["anyOf"] - if ( - (title or description) - and isinstance(any_of, list) - and all(isinstance(item, dict) for item in any_of) - ): + if (title or description) and isinstance(any_of, list) and all(isinstance(item, dict) for item in any_of): for item in any_of: if title: item["title"] = title @@ -712,9 +686,7 @@ def process_items(schema, depth=0): process_items(item, depth + 1) -def set_schema_property_ordering( - schema: Dict[str, Any], depth: int = 0 -) -> Dict[str, Any]: +def set_schema_property_ordering(schema: Dict[str, Any], depth: int = 0) -> Dict[str, Any]: """ vertex ai and generativeai apis order output of fields alphabetically, unless you specify the order. python dicts retain order, so we just use that. Note that this field only applies to structured outputs, and not tools. @@ -741,9 +713,7 @@ def set_schema_property_ordering( return schema -def filter_schema_fields( - schema_dict: Dict[str, Any], valid_fields: Set[str], processed=None -) -> Dict[str, Any]: +def filter_schema_fields(schema_dict: Dict[str, Any], valid_fields: Set[str], processed=None) -> Dict[str, Any]: """ Recursively filter a schema dictionary to keep only valid fields. """ @@ -766,10 +736,7 @@ def filter_schema_fields( continue if key == "properties" and isinstance(value, dict): - result[key] = { - k: filter_schema_fields(v, valid_fields, processed) - for k, v in value.items() - } + result[key] = {k: filter_schema_fields(v, valid_fields, processed) for k, v in value.items()} elif key == "format": if value in {"enum", "date-time"}: result[key] = value @@ -809,8 +776,7 @@ def convert_anyof_null_to_nullable(schema, depth=0): if len(anyof) == 0: # Edge case: response schema with only null type present is invalid in Vertex AI raise ValueError( - "Invalid input: AnyOf schema with only null type is not supported. " - "Please provide a non-null type." + "Invalid input: AnyOf schema with only null type is not supported. Please provide a non-null type." ) if contains_null: @@ -834,12 +800,7 @@ def convert_anyof_null_to_nullable(schema, depth=0): def add_object_type(schema): # Gemini requires all function parameters to be type OBJECT # Handle case where schema has no properties and no type (e.g. tools with no arguments) - if ( - "type" not in schema - and "anyOf" not in schema - and "oneOf" not in schema - and "allOf" not in schema - ): + if "type" not in schema and "anyOf" not in schema and "oneOf" not in schema and "allOf" not in schema: schema["type"] = "object" properties = schema.get("properties", None) @@ -951,9 +912,7 @@ def _convert_schema_types(schema, depth=0): any_of.append({"type": t}) # Remove type-specific fields from parent if we moved them into anyOf - has_object_or_array = any( - t in ("object", "array") for t in type_val if isinstance(t, str) - ) + has_object_or_array = any(t in ("object", "array") for t in type_val if isinstance(t, str)) if has_object_or_array: for field in type_specific_fields: schema.pop(field, None) @@ -1009,9 +968,7 @@ def get_vertex_model_id_from_url(url: str) -> Optional[str]: return match.group(1) if match else None -def replace_project_and_location_in_route( - requested_route: str, vertex_project: str, vertex_location: str -) -> str: +def replace_project_and_location_in_route(requested_route: str, vertex_project: str, vertex_location: str) -> str: """ Replace project and location values in the route with the provided values """ @@ -1044,9 +1001,7 @@ def construct_target_url( new_base_url = httpx.URL(base_url) if "locations" in requested_route: # contains the target project id + location if vertex_project and vertex_location: - requested_route = replace_project_and_location_in_route( - requested_route, vertex_project, vertex_location - ) + requested_route = replace_project_and_location_in_route(requested_route, vertex_project, vertex_location) return new_base_url.copy_with(path=requested_route) """ @@ -1067,9 +1022,7 @@ def construct_target_url( vertex_version = "v1beta1" requested_route = requested_route.replace("/v1beta1/", "/", 1) - base_requested_route = "{}/projects/{}/locations/{}".format( - vertex_version, vertex_project, vertex_location - ) + base_requested_route = "{}/projects/{}/locations/{}".format(vertex_version, vertex_project, vertex_location) updated_requested_route = "/" + base_requested_route + requested_route @@ -1100,9 +1053,7 @@ def validate_environment( ) -> dict: raise NotImplementedError("Vertex AI models are not supported yet") - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: """ Returns a list of models supported by this provider. """ @@ -1157,9 +1108,7 @@ async def count_tokens( ) deployment = deployment or {} - count_tokens_params_request = copy.deepcopy( - deployment.get("litellm_params", {}) - ) + count_tokens_params_request = copy.deepcopy(deployment.get("litellm_params", {})) # Check if this is a partner model (Claude, Mistral, etc.) if VertexAIPartnerModels.is_vertex_partner_model(model_to_use): @@ -1167,19 +1116,16 @@ async def count_tokens( partner_models_handler = VertexAIPartnerModels() # Extract vertex-specific params from litellm_params - vertex_project = count_tokens_params_request.get( - "vertex_project" - ) or count_tokens_params_request.get("vertex_ai_project") + vertex_project = count_tokens_params_request.get("vertex_project") or count_tokens_params_request.get( + "vertex_ai_project" + ) - vertex_location = count_tokens_params_request.get( - "vertex_location" - ) or count_tokens_params_request.get("vertex_ai_location") + vertex_location = count_tokens_params_request.get("vertex_location") or count_tokens_params_request.get( + "vertex_ai_location" + ) # Count tokens not available on global location: https://docs.cloud.google.com/vertex-ai/generative-ai/docs/partner-models/claude/count-tokens - vertex_location = ( - count_tokens_params_request.get("vertex_count_tokens_location") - or vertex_location - ) + vertex_location = count_tokens_params_request.get("vertex_count_tokens_location") or vertex_location vertex_credentials = count_tokens_params_request.get( "vertex_credentials" diff --git a/litellm/llms/vertex_ai/context_caching/transformation.py b/litellm/llms/vertex_ai/context_caching/transformation.py index f73eb220cc61..f0ce3323ef66 100644 --- a/litellm/llms/vertex_ai/context_caching/transformation.py +++ b/litellm/llms/vertex_ai/context_caching/transformation.py @@ -145,9 +145,7 @@ def separate_cached_messages( last_cached_idx = filtered_messages[last_continuous_block_idx][0] cached_messages = messages[first_cached_idx : last_cached_idx + 1] - non_cached_messages = ( - messages[:first_cached_idx] + messages[last_cached_idx + 1 :] - ) + non_cached_messages = messages[:first_cached_idx] + messages[last_cached_idx + 1 :] else: non_cached_messages = messages @@ -165,9 +163,7 @@ def transform_openai_messages_to_gemini_context_caching( # Extract TTL from cached messages BEFORE system message transformation ttl = extract_ttl_from_cached_messages(messages) - supports_system_message = get_supports_system_message( - model=model, custom_llm_provider=custom_llm_provider - ) + supports_system_message = get_supports_system_message(model=model, custom_llm_provider=custom_llm_provider) transformed_system_messages, new_messages = _transform_system_message( supports_system_message=supports_system_message, messages=messages diff --git a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py index d29734c02943..0bf3715f7983 100644 --- a/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py +++ b/litellm/llms/vertex_ai/context_caching/vertex_ai_context_caching.py @@ -26,9 +26,7 @@ transform_openai_messages_to_gemini_context_caching, ) -local_cache_obj = Cache( - type=LiteLLMCacheType.LOCAL -) # only used for calling 'get_cache_key' function +local_cache_obj = Cache(type=LiteLLMCacheType.LOCAL) # only used for calling 'get_cache_key' function MAX_PAGINATION_PAGES = 100 # Reasonable upper bound for pagination @@ -88,9 +86,7 @@ def _get_token_and_url_context_caching( model=model, vertex_project=vertex_project, vertex_location=vertex_location, - vertex_api_version=( - "v1beta1" if custom_llm_provider == "vertex_ai_beta" else "v1" - ), + vertex_api_version=("v1beta1" if custom_llm_provider == "vertex_ai_beta" else "v1"), ) def check_cache( @@ -156,9 +152,7 @@ def check_cache( except httpx.HTTPStatusError as e: if e.response.status_code == 403: return None - raise VertexAIError( - status_code=e.response.status_code, message=e.response.text - ) + raise VertexAIError(status_code=e.response.status_code, message=e.response.text) except Exception as e: raise VertexAIError(status_code=500, message=str(e)) @@ -250,9 +244,7 @@ async def async_check_cache( except httpx.HTTPStatusError as e: if e.response.status_code == 403: return None - raise VertexAIError( - status_code=e.response.status_code, message=e.response.text - ) + raise VertexAIError(status_code=e.response.status_code, message=e.response.text) except Exception as e: raise VertexAIError(status_code=500, message=str(e)) @@ -311,9 +303,7 @@ def check_and_create_cache( if cached_content is not None: return messages, optional_params, cached_content - cached_messages, non_cached_messages = separate_cached_messages( - messages=messages - ) + cached_messages, non_cached_messages = separate_cached_messages(messages=messages) if len(cached_messages) == 0: return messages, optional_params, None @@ -387,15 +377,13 @@ def check_and_create_cache( return non_cached_messages, optional_params, google_cache_name ## TRANSFORM REQUEST - cached_content_request_body = ( - transform_openai_messages_to_gemini_context_caching( - model=model, - messages=cached_messages, - cache_key=generated_cache_key, - custom_llm_provider=custom_llm_provider, - vertex_project=vertex_project, - vertex_location=vertex_location, - ) + cached_content_request_body = transform_openai_messages_to_gemini_context_caching( + model=model, + messages=cached_messages, + cache_key=generated_cache_key, + custom_llm_provider=custom_llm_provider, + vertex_project=vertex_project, + vertex_location=vertex_location, ) cached_content_request_body["tools"] = tools @@ -466,9 +454,7 @@ async def async_check_and_create_cache( if cached_content is not None: return messages, optional_params, cached_content - cached_messages, non_cached_messages = separate_cached_messages( - messages=messages - ) + cached_messages, non_cached_messages = separate_cached_messages(messages=messages) if len(cached_messages) == 0: return messages, optional_params, None @@ -512,9 +498,7 @@ async def async_check_and_create_cache( headers.update(extra_headers) if client is None or not isinstance(client, AsyncHTTPHandler): - client = get_async_httpx_client( - params={"timeout": timeout}, llm_provider=litellm.LlmProviders.VERTEX_AI - ) + client = get_async_httpx_client(params={"timeout": timeout}, llm_provider=litellm.LlmProviders.VERTEX_AI) else: client = client @@ -540,15 +524,13 @@ async def async_check_and_create_cache( return non_cached_messages, optional_params, google_cache_name ## TRANSFORM REQUEST - cached_content_request_body = ( - transform_openai_messages_to_gemini_context_caching( - model=model, - messages=cached_messages, - cache_key=generated_cache_key, - custom_llm_provider=custom_llm_provider, - vertex_project=vertex_project, - vertex_location=vertex_location, - ) + cached_content_request_body = transform_openai_messages_to_gemini_context_caching( + model=model, + messages=cached_messages, + cache_key=generated_cache_key, + custom_llm_provider=custom_llm_provider, + vertex_project=vertex_project, + vertex_location=vertex_location, ) cached_content_request_body["tools"] = tools diff --git a/litellm/llms/vertex_ai/cost_calculator.py b/litellm/llms/vertex_ai/cost_calculator.py index 758fc0bae87c..84c9108847b5 100644 --- a/litellm/llms/vertex_ai/cost_calculator.py +++ b/litellm/llms/vertex_ai/cost_calculator.py @@ -47,9 +47,7 @@ def cost_router( or "gemma" in model ): return "cost_per_token" - elif custom_llm_provider == "vertex_ai" and ( - call_type == "embedding" or call_type == "aembedding" - ): + elif custom_llm_provider == "vertex_ai" and (call_type == "embedding" or call_type == "aembedding"): return "cost_per_token" elif custom_llm_provider == "vertex_ai" and ("gemini-2" in model): return "cost_per_token" @@ -78,14 +76,10 @@ def cost_per_character( Raises: Exception if model requires >128k pricing, but model cost not mapped """ - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) ## GET MODEL INFO - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) ## CALCULATE INPUT COST if prompt_characters is None: @@ -103,25 +97,18 @@ def cost_per_character( ## check if character pricing, else default to token pricing assert ( "input_cost_per_character_above_128k_tokens" in model_info - and model_info["input_cost_per_character_above_128k_tokens"] - is not None + and model_info["input_cost_per_character_above_128k_tokens"] is not None ), ( "model info for model={} does not have 'input_cost_per_character_above_128k_tokens'-pricing for > 128k tokens\nmodel_info={}".format( model, model_info ) ) - prompt_cost = ( - prompt_characters - * model_info["input_cost_per_character_above_128k_tokens"] - ) + prompt_cost = prompt_characters * model_info["input_cost_per_character_above_128k_tokens"] else: assert ( - "input_cost_per_character" in model_info - and model_info["input_cost_per_character"] is not None - ), ( - "model info for model={} does not have 'input_cost_per_character'-pricing\nmodel_info={}".format( - model, model_info - ) + "input_cost_per_character" in model_info and model_info["input_cost_per_character"] is not None + ), "model info for model={} does not have 'input_cost_per_character'-pricing\nmodel_info={}".format( + model, model_info ) prompt_cost = prompt_characters * model_info["input_cost_per_character"] except Exception as e: @@ -152,29 +139,20 @@ def cost_per_character( ): assert ( "output_cost_per_character_above_128k_tokens" in model_info - and model_info["output_cost_per_character_above_128k_tokens"] - is not None + and model_info["output_cost_per_character_above_128k_tokens"] is not None ), ( "model info for model={} does not have 'output_cost_per_character_above_128k_tokens' pricing\nmodel_info={}".format( model, model_info ) ) - completion_cost = ( - completion_tokens - * model_info["output_cost_per_character_above_128k_tokens"] - ) + completion_cost = completion_tokens * model_info["output_cost_per_character_above_128k_tokens"] else: assert ( - "output_cost_per_character" in model_info - and model_info["output_cost_per_character"] is not None - ), ( - "model info for model={} does not have 'output_cost_per_character'-pricing\nmodel_info={}".format( - model, model_info - ) - ) - completion_cost = ( - completion_characters * model_info["output_cost_per_character"] + "output_cost_per_character" in model_info and model_info["output_cost_per_character"] is not None + ), "model info for model={} does not have 'output_cost_per_character'-pricing\nmodel_info={}".format( + model, model_info ) + completion_cost = completion_characters * model_info["output_cost_per_character"] except Exception as e: verbose_logger.debug( "litellm.litellm_core_utils.llm_cost_calc.google.py::cost_per_character(): Exception occured - {}\nDefaulting to None".format( @@ -195,37 +173,23 @@ def _handle_128k_pricing( usage: Usage, ) -> Tuple[float, float]: ## CALCULATE INPUT COST - input_cost_per_token_above_128k_tokens = model_info.get( - "input_cost_per_token_above_128k_tokens" - ) - output_cost_per_token_above_128k_tokens = model_info.get( - "output_cost_per_token_above_128k_tokens" - ) + input_cost_per_token_above_128k_tokens = model_info.get("input_cost_per_token_above_128k_tokens") + output_cost_per_token_above_128k_tokens = model_info.get("output_cost_per_token_above_128k_tokens") prompt_tokens = usage.prompt_tokens completion_tokens = usage.completion_tokens - if ( - _is_above_128k(tokens=prompt_tokens) - and input_cost_per_token_above_128k_tokens is not None - ): + if _is_above_128k(tokens=prompt_tokens) and input_cost_per_token_above_128k_tokens is not None: prompt_cost = prompt_tokens * input_cost_per_token_above_128k_tokens else: prompt_cost = prompt_tokens * (model_info["input_cost_per_token"] or 0.0) ## CALCULATE OUTPUT COST - output_cost_per_token_above_128k_tokens = model_info.get( - "output_cost_per_token_above_128k_tokens" - ) - if ( - _is_above_128k(tokens=completion_tokens) - and output_cost_per_token_above_128k_tokens is not None - ): + output_cost_per_token_above_128k_tokens = model_info.get("output_cost_per_token_above_128k_tokens") + if _is_above_128k(tokens=completion_tokens) and output_cost_per_token_above_128k_tokens is not None: completion_cost = completion_tokens * output_cost_per_token_above_128k_tokens else: - completion_cost = completion_tokens * ( - model_info["output_cost_per_token"] or 0.0 - ) + completion_cost = completion_tokens * (model_info["output_cost_per_token"] or 0.0) return prompt_cost, completion_cost @@ -255,21 +219,12 @@ def cost_per_token( """ ## GET MODEL INFO - model_info = litellm.get_model_info( - model=model, custom_llm_provider=custom_llm_provider - ) + model_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_provider) ## HANDLE 128k+ PRICING - input_cost_per_token_above_128k_tokens = model_info.get( - "input_cost_per_token_above_128k_tokens" - ) - output_cost_per_token_above_128k_tokens = model_info.get( - "output_cost_per_token_above_128k_tokens" - ) - if ( - input_cost_per_token_above_128k_tokens is not None - or output_cost_per_token_above_128k_tokens is not None - ): + input_cost_per_token_above_128k_tokens = model_info.get("input_cost_per_token_above_128k_tokens") + output_cost_per_token_above_128k_tokens = model_info.get("output_cost_per_token_above_128k_tokens") + if input_cost_per_token_above_128k_tokens is not None or output_cost_per_token_above_128k_tokens is not None: return _handle_128k_pricing( model_info=model_info, usage=usage, diff --git a/litellm/llms/vertex_ai/count_tokens/handler.py b/litellm/llms/vertex_ai/count_tokens/handler.py index 9a175371a275..9f2826a4bb41 100644 --- a/litellm/llms/vertex_ai/count_tokens/handler.py +++ b/litellm/llms/vertex_ai/count_tokens/handler.py @@ -17,9 +17,7 @@ async def validate_environment( Returns a Tuple of headers and url for the Vertex AI countTokens endpoint. """ litellm_params = litellm_params or {} - vertex_credentials = self.get_vertex_ai_credentials( - litellm_params=litellm_params - ) + vertex_credentials = self.get_vertex_ai_credentials(litellm_params=litellm_params) vertex_project = self.get_vertex_ai_project(litellm_params=litellm_params) vertex_location = self.get_vertex_ai_location(litellm_params=litellm_params) should_use_v1beta1_features = self.is_using_v1beta1_features(litellm_params) diff --git a/litellm/llms/vertex_ai/files/handler.py b/litellm/llms/vertex_ai/files/handler.py index 176cfe984119..3bc09139f8ff 100644 --- a/litellm/llms/vertex_ai/files/handler.py +++ b/litellm/llms/vertex_ai/files/handler.py @@ -60,9 +60,7 @@ def _extract_bucket_and_object_from_file_id( scheme="gs://", configured_bucket_name=configured_bucket_name, allowed_object_prefixes=(VERTEX_AI_MANAGED_GCS_PREFIX,), - allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids( - litellm_params - ), + allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(litellm_params), ) async def afile_content( @@ -93,9 +91,7 @@ async def afile_content( if not file_id: raise ValueError("file_id is required in file_content_request") - gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config( - kwargs={} - ) + gcs_logging_config: GCSLoggingConfig = await self.get_gcs_logging_config(kwargs={}) bucket_name, object_path = self._extract_bucket_and_object_from_file_id( file_id=file_id, configured_bucket_name=gcs_logging_config["bucket_name"], @@ -109,9 +105,7 @@ async def afile_content( } } - file_content = await self.download_gcs_object( - object_name=object_path, **download_kwargs - ) + file_content = await self.download_gcs_object(object_name=object_path, **download_kwargs) decoded_file_id = unquote(file_id) if file_content is None: @@ -156,9 +150,7 @@ def file_content( timeout: Union[float, httpx.Timeout], max_retries: Optional[int], litellm_params: Optional[dict] = None, - ) -> Union[ - HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent] - ]: + ) -> Union[HttpxBinaryResponseContent, Coroutine[Any, Any, HttpxBinaryResponseContent]]: """ Download file content from GCS bucket for VertexAI files. Supports both sync and async operations. diff --git a/litellm/llms/vertex_ai/files/transformation.py b/litellm/llms/vertex_ai/files/transformation.py index d5164d8c1c2d..fcb7617d97ec 100644 --- a/litellm/llms/vertex_ai/files/transformation.py +++ b/litellm/llms/vertex_ai/files/transformation.py @@ -93,9 +93,7 @@ def _sanitize_gcp_label_value(value: str) -> str: def _encode_gcp_label_value_chunks(value: str) -> List[str]: """Encode arbitrary text across one or more GCP-label-safe values.""" max_encoded_len = _GCP_LABEL_VALUE_MAX_LEN - len(_CUSTOM_ID_RAW_LABEL_PREFIX) - encoded = ( - base64.b32encode(value.encode("utf-8")).decode("ascii").rstrip("=").lower() - ) + encoded = base64.b32encode(value.encode("utf-8")).decode("ascii").rstrip("=").lower() return [ f"{_CUSTOM_ID_RAW_LABEL_PREFIX}{encoded[i : i + max_encoded_len]}" for i in range(0, len(encoded), max_encoded_len) @@ -143,10 +141,7 @@ def _get_litellm_batch_custom_id_from_labels(labels: Dict[str, Any]) -> str: for key, value in labels.items(): if key.startswith(chunk_prefix) and key[len(chunk_prefix) :].isdigit(): indexed_chunks.append((int(key[len(chunk_prefix) :]), str(value))) - raw_chunks.extend( - raw_label_chunk - for _, raw_label_chunk in sorted(indexed_chunks, key=lambda item: item[0]) - ) + raw_chunks.extend(raw_label_chunk for _, raw_label_chunk in sorted(indexed_chunks, key=lambda item: item[0])) decoded = _decode_gcp_label_value_chunks(raw_chunks) if decoded is not None: return decoded @@ -279,9 +274,7 @@ def __init__( def _iter_vertex_jsonl_chunks(self) -> Iterator[bytes]: first = True for entry in _iter_openai_jsonl_entries(self._openai_file_content): - wrapped = _openai_batch_jsonl_entry_to_vertex_wrapped_request( - entry, self._map_openai_to_vertex_params - ) + wrapped = _openai_batch_jsonl_entry_to_vertex_wrapped_request(entry, self._map_openai_to_vertex_params) prefix = b"" if first else b"\n" first = False yield prefix + json.dumps(wrapped).encode("utf-8") @@ -361,9 +354,7 @@ def get_object_name(self, file_data: FileTypes, purpose: str) -> str: def _get_configured_bucket_name(self, litellm_params: Dict) -> str: bucket_name = ( - litellm_params.get("gcs_bucket_name") - or litellm_params.get("bucket_name") - or os.getenv("GCS_BUCKET_NAME") + litellm_params.get("gcs_bucket_name") or litellm_params.get("bucket_name") or os.getenv("GCS_BUCKET_NAME") ) if not bucket_name: raise ValueError("GCS bucket_name is required") @@ -398,9 +389,7 @@ def get_complete_file_url( # large uploads); everything else is a single simple-media upload. upload_type = ( "resumable" - if FilesAPIUtils.is_batch_jsonl_request( - create_file_data=data, content_type=content_type - ) + if FilesAPIUtils.is_batch_jsonl_request(create_file_data=data, content_type=content_type) else "media" ) endpoint = f"upload/storage/v1/b/{bucket_name}/o?uploadType={upload_type}&name={encoded_object_name}" @@ -410,9 +399,7 @@ def get_complete_file_url( return f"{api_base}/{endpoint}" - def get_supported_openai_params( - self, model: str - ) -> List[OpenAICreateFileRequestOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAICreateFileRequestOptionalParams]: return [] def map_openai_params( @@ -521,16 +508,10 @@ def transform_create_file_response( object="file", ) - def get_error_class( - self, error_message: str, status_code: int, headers: Union[Dict, Headers] - ) -> BaseLLMException: - return VertexAIError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[Dict, Headers]) -> BaseLLMException: + return VertexAIError(status_code=status_code, message=error_message, headers=headers) - def _parse_gcs_uri( - self, file_id: str, litellm_params: Optional[Dict] = None - ) -> Tuple[str, str]: + def _parse_gcs_uri(self, file_id: str, litellm_params: Optional[Dict] = None) -> Tuple[str, str]: """ Validate a managed GCS file_id and return (bucket, url-encoded-object-path). """ @@ -540,9 +521,7 @@ def _parse_gcs_uri( scheme="gs://", configured_bucket_name=configured_bucket_name, allowed_object_prefixes=(VERTEX_AI_MANAGED_GCS_PREFIX,), - allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids( - litellm_params - ), + allow_legacy_cloud_file_ids=should_allow_legacy_cloud_file_ids(litellm_params), ) return bucket_name, encode_gcs_object_name_for_url(object_path) @@ -761,13 +740,11 @@ def _try_transform_vertex_batch_output_to_openai( output = bytearray() for line in itertools.chain([first_line], lines): try: - openai_output = ( - self._transform_single_vertex_batch_output_to_openai( - vertex_output=json.loads(line), - vertex_gemini_config=vertex_gemini_config, - logging_obj=batch_transform_logging_obj, - mock_httpx_response=mock_httpx_response, - ) + openai_output = self._transform_single_vertex_batch_output_to_openai( + vertex_output=json.loads(line), + vertex_gemini_config=vertex_gemini_config, + logging_obj=batch_transform_logging_obj, + mock_httpx_response=mock_httpx_response, ) except Exception: return content diff --git a/litellm/llms/vertex_ai/fine_tuning/handler.py b/litellm/llms/vertex_ai/fine_tuning/handler.py index a5971de0e947..b220b1544b58 100644 --- a/litellm/llms/vertex_ai/fine_tuning/handler.py +++ b/litellm/llms/vertex_ai/fine_tuning/handler.py @@ -38,9 +38,7 @@ def __init__(self) -> None: def convert_response_created_at(self, response: ResponseTuningJob): try: create_time_str = response.get("createTime", "") or "" - create_time_datetime = datetime.fromisoformat( - create_time_str.replace("Z", "+00:00") - ) + create_time_datetime = datetime.fromisoformat(create_time_str.replace("Z", "+00:00")) # Convert to Unix timestamp (seconds since epoch) created_at = int(create_time_datetime.timestamp()) @@ -65,16 +63,12 @@ def convert_openai_request_to_vertex( ) if create_fine_tuning_job_data.validation_file: - supervised_tuning_spec["validation_dataset"] = ( - create_fine_tuning_job_data.validation_file - ) + supervised_tuning_spec["validation_dataset"] = create_fine_tuning_job_data.validation_file - _vertex_hyperparameters = ( - self._transform_openai_hyperparameters_to_vertex_hyperparameters( - create_fine_tuning_job_data=create_fine_tuning_job_data, - kwargs=kwargs, - original_hyperparameters=original_hyperparameters, - ) + _vertex_hyperparameters = self._transform_openai_hyperparameters_to_vertex_hyperparameters( + create_fine_tuning_job_data=create_fine_tuning_job_data, + kwargs=kwargs, + original_hyperparameters=original_hyperparameters, ) if _vertex_hyperparameters and len(_vertex_hyperparameters) > 0: @@ -98,9 +92,7 @@ def _transform_openai_hyperparameters_to_vertex_hyperparameters( _vertex_hyperparameters = FineTuneHyperparameters() if _oai_hyperparameters: if _oai_hyperparameters.n_epochs: - _vertex_hyperparameters["epoch_count"] = int( - _oai_hyperparameters.n_epochs - ) + _vertex_hyperparameters["epoch_count"] = int(_oai_hyperparameters.n_epochs) if _oai_hyperparameters.learning_rate_multiplier: _vertex_hyperparameters["learning_rate_multiplier"] = float( _oai_hyperparameters.learning_rate_multiplier @@ -112,12 +104,8 @@ def _transform_openai_hyperparameters_to_vertex_hyperparameters( return _vertex_hyperparameters - def convert_vertex_response_to_open_ai_response( - self, response: ResponseTuningJob - ) -> LiteLLMFineTuningJob: - status: Literal[ - "validating_files", "queued", "running", "succeeded", "failed", "cancelled" - ] = "queued" + def convert_vertex_response_to_open_ai_response(self, response: ResponseTuningJob) -> LiteLLMFineTuningJob: + status: Literal["validating_files", "queued", "running", "succeeded", "failed", "cancelled"] = "queued" if response["state"] == "JOB_STATE_PENDING": status = "queued" if response["state"] == "JOB_STATE_SUCCEEDED": @@ -131,9 +119,7 @@ def convert_vertex_response_to_open_ai_response( created_at = self.convert_response_created_at(response) - _supervisedTuningSpec: ResponseSupervisedTuningSpec = ( - response.get("supervisedTuningSpec", None) or {} - ) + _supervisedTuningSpec: ResponseSupervisedTuningSpec = response.get("supervisedTuningSpec", None) or {} training_uri: str = _supervisedTuningSpec.get("trainingDatasetUri", "") or "" return LiteLLMFineTuningJob( id=response.get("name", "") or "", @@ -141,10 +127,7 @@ def convert_vertex_response_to_open_ai_response( fine_tuned_model=response.get("tunedModelDisplayName", ""), finished_at=None, hyperparameters=self._translate_vertex_response_hyperparameters( - vertex_hyper_parameters=_supervisedTuningSpec.get( - "hyperParameters", FineTuneHyperparameters() - ) - or {} + vertex_hyper_parameters=_supervisedTuningSpec.get("hyperParameters", FineTuneHyperparameters()) or {} ), model=response.get("baseModel", "") or "", object="fine_tuning.job", @@ -184,9 +167,7 @@ async def acreate_fine_tuning_job( json.dumps(request_data, indent=4), ) if self.async_handler is None: - raise ValueError( - "VertexAI Fine Tuning - async_handler is not initialized" - ) + raise ValueError("VertexAI Fine Tuning - async_handler is not initialized") response = await self.async_handler.post( headers=headers, url=fine_tuning_url, @@ -198,18 +179,14 @@ async def acreate_fine_tuning_job( f"Error creating fine tuning job. Status code: {response.status_code}. Response: {response.text}" ) - verbose_logger.debug( - "got response from creating fine tuning job: %s", response.json() - ) + verbose_logger.debug("got response from creating fine tuning job: %s", response.json()) vertex_response = ResponseTuningJob( # type: ignore **response.json(), ) verbose_logger.debug("vertex_response %s", vertex_response) - open_ai_response = self.convert_vertex_response_to_open_ai_response( - vertex_response - ) + open_ai_response = self.convert_vertex_response_to_open_ai_response(vertex_response) return open_ai_response except Exception as e: @@ -230,9 +207,7 @@ def create_fine_tuning_job( kwargs: Optional[dict] = None, original_hyperparameters: Optional[dict] = {}, ) -> Union[LiteLLMFineTuningJob, Coroutine[Any, Any, LiteLLMFineTuningJob]]: - verbose_logger.debug( - "creating fine tuning job, args= %s", create_fine_tuning_job_data - ) + verbose_logger.debug("creating fine tuning job, args= %s", create_fine_tuning_job_data) _auth_header, vertex_project = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -288,17 +263,13 @@ def create_fine_tuning_job( f"Error creating fine tuning job. Status code: {response.status_code}. Response: {response.text}" ) - verbose_logger.debug( - "got response from creating fine tuning job: %s", response.json() - ) + verbose_logger.debug("got response from creating fine tuning job: %s", response.json()) vertex_response = ResponseTuningJob( # type: ignore **response.json(), ) verbose_logger.debug("vertex_response %s", vertex_response) - open_ai_response = self.convert_vertex_response_to_open_ai_response( - vertex_response - ) + open_ai_response = self.convert_vertex_response_to_open_ai_response(vertex_response) return open_ai_response async def pass_through_vertex_ai_POST_request( diff --git a/litellm/llms/vertex_ai/gemini/transformation.py b/litellm/llms/vertex_ai/gemini/transformation.py index 3bdcbd259495..0db1118a7b42 100644 --- a/litellm/llms/vertex_ai/gemini/transformation.py +++ b/litellm/llms/vertex_ai/gemini/transformation.py @@ -121,9 +121,7 @@ def _convert_detail_to_media_resolution_enum( return None -def _get_highest_media_resolution( - current: Optional[str], new_detail: Optional[str] -) -> Optional[str]: +def _get_highest_media_resolution(current: Optional[str], new_detail: Optional[str]) -> Optional[str]: """ Compare two media resolution values and return the highest one. Resolution hierarchy: ultra_high > high > medium > low > None @@ -169,9 +167,7 @@ def _extract_max_media_resolution_from_messages( if isinstance(file_obj, dict): detail = file_obj.get("detail") if detail: - max_resolution = _get_highest_media_resolution( - max_resolution, detail - ) + max_resolution = _get_highest_media_resolution(max_resolution, detail) return max_resolution @@ -194,9 +190,7 @@ def _apply_gemini_metadata( part_dict = dict(part) - if media_resolution_enum is not None and VertexGeminiConfig._is_gemini_3_or_newer( - model - ): + if media_resolution_enum is not None and VertexGeminiConfig._is_gemini_3_or_newer(model): part_dict["media_resolution"] = media_resolution_enum if video_metadata is not None: @@ -231,9 +225,7 @@ def _is_valid_gcs_bucket_name(bucket: str) -> bool: max_bucket_length = 222 if "." in bucket else 63 if bucket_length < 3 or bucket_length > max_bucket_length: return False - if "." in bucket and any( - len(label) == 0 or len(label) > 63 for label in bucket.split(".") - ): + if "." in bucket and any(len(label) == 0 or len(label) > 63 for label in bucket.split(".")): return False if not re.fullmatch(r"[a-z0-9][a-z0-9._-]*[a-z0-9]", bucket): return False @@ -269,11 +261,7 @@ def _image_url_payload_may_need_sync_gcs_metadata_fetch( url = raw_image_url.get("url") # type: ignore[assignment] if not isinstance(url, str): return False - fmt = ( - raw_image_url.get("format") - or raw_image_url.get("mime_type") - or raw_image_url.get("content_type") - ) + fmt = raw_image_url.get("format") or raw_image_url.get("mime_type") or raw_image_url.get("content_type") elif isinstance(raw_image_url, str): url = raw_image_url else: @@ -305,9 +293,7 @@ def _openai_messages_may_need_sync_gcs_metadata_fetch( for image_item in images_field: if not isinstance(image_item, dict): continue - if _image_url_payload_may_need_sync_gcs_metadata_fetch( - image_item.get("image_url") - ): + if _image_url_payload_may_need_sync_gcs_metadata_fetch(image_item.get("image_url")): return True content = msg.get("content") @@ -318,19 +304,13 @@ def _openai_messages_may_need_sync_gcs_metadata_fetch( continue itype = item.get("type") if itype == "image_url": - if _image_url_payload_may_need_sync_gcs_metadata_fetch( - item.get("image_url") - ): + if _image_url_payload_may_need_sync_gcs_metadata_fetch(item.get("image_url")): return True elif itype == "file": file_obj = item.get("file") if not isinstance(file_obj, dict): continue - fmt = ( - file_obj.get("format") - or file_obj.get("mime_type") - or file_obj.get("content_type") - ) + fmt = file_obj.get("format") or file_obj.get("mime_type") or file_obj.get("content_type") passed = file_obj.get("file_id") or file_obj.get("file_data") if ( isinstance(passed, str) @@ -365,9 +345,7 @@ def _get_gcs_object_content_type( return None headers: Dict[str, str] = {} - explicit_vertex_auth_provided = ( - vertex_project is not None or vertex_credentials is not None - ) + explicit_vertex_auth_provided = vertex_project is not None or vertex_credentials is not None if explicit_vertex_auth_provided: try: access_token, _ = _get_vertex_base().get_access_token( @@ -378,8 +356,7 @@ def _get_gcs_object_content_type( except Exception as e: raise litellm.BadRequestError( message=( - "Unable to fetch GCS metadata with provided Vertex credentials/project. " - f"Original error: {str(e)}" + f"Unable to fetch GCS metadata with provided Vertex credentials/project. Original error: {str(e)}" ), model=None, llm_provider="vertex_ai", @@ -470,9 +447,7 @@ def _get_gcs_object_content_type( return None -def _normalize_and_validate_gemini_mime_type( - mime_type: str, model: Optional[str] -) -> str: +def _normalize_and_validate_gemini_mime_type(mime_type: str, model: Optional[str]) -> str: # Import lazily to avoid a module-level cyclic-import alert with # litellm.types.files. from litellm.types.files import get_file_extension_from_mime_type @@ -581,12 +556,8 @@ def _process_gemini_media( ) file_data = FileDataType(mime_type=mime_type, file_uri=image_url) part: PartType = {"file_data": file_data} - return _apply_gemini_metadata( - part, model, media_resolution_enum, video_metadata - ) - elif image_url.startswith( - "https://generativelanguage.googleapis.com/v1beta/files/" - ): + return _apply_gemini_metadata(part, model, media_resolution_enum, video_metadata) + elif image_url.startswith("https://generativelanguage.googleapis.com/v1beta/files/"): # Gemini Files API URIs — the file is already uploaded to Google's # servers; pass the URI through as file_data without fetching it. # These URLs return 403 when accessed directly, so we must not try @@ -597,26 +568,16 @@ def _process_gemini_media( # Gemini Files API references can be passed through as URI-only. file_data = cast(FileDataType, {"file_uri": image_url}) part = {"file_data": file_data} - return _apply_gemini_metadata( - part, model, media_resolution_enum, video_metadata - ) - elif ( - "https://" in image_url - and (image_type := format or _get_image_mime_type_from_url(image_url)) - is not None - ): + return _apply_gemini_metadata(part, model, media_resolution_enum, video_metadata) + elif "https://" in image_url and (image_type := format or _get_image_mime_type_from_url(image_url)) is not None: file_data = FileDataType(mime_type=image_type, file_uri=image_url) part = {"file_data": file_data} - return _apply_gemini_metadata( - part, model, media_resolution_enum, video_metadata - ) + return _apply_gemini_metadata(part, model, media_resolution_enum, video_metadata) elif "http://" in image_url or "https://" in image_url or "base64" in image_url: image = convert_to_anthropic_image_obj(image_url, format=format) _blob: BlobType = {"data": image["data"], "mime_type": image["media_type"]} part = {"inline_data": cast(BlobType, _blob)} - return _apply_gemini_metadata( - part, model, media_resolution_enum, video_metadata - ) + return _apply_gemini_metadata(part, model, media_resolution_enum, video_metadata) raise Exception("Invalid image received - {}".format(image_url)) except Exception as e: raise e @@ -653,9 +614,7 @@ def _get_equivalent_key(key: str, available_keys: set) -> Optional[str]: return None -def check_if_part_exists_in_parts( - parts: List[PartType], part: PartType, excluded_keys: List[str] = [] -) -> bool: +def check_if_part_exists_in_parts(parts: List[PartType], part: PartType, excluded_keys: List[str] = []) -> bool: """ Check if a part exists in a list of parts Handles both camelCase and snake_case key variations (e.g., function_call vs functionCall) @@ -667,9 +626,7 @@ def check_if_part_exists_in_parts( match_found = True for key in keys_to_compare: equivalent_key = _get_equivalent_key(key, p_keys) - if equivalent_key is None or p.get(equivalent_key, None) != part.get( - key, None - ): + if equivalent_key is None or p.get(equivalent_key, None) != part.get(key, None): match_found = False break @@ -701,30 +658,20 @@ def _gemini_convert_messages_with_history( vertex_project = None vertex_credentials = None if litellm_params: - vertex_project = litellm_params.get("vertex_project") or litellm_params.get( - "vertex_ai_project" - ) - vertex_credentials = litellm_params.get( - "vertex_credentials" - ) or litellm_params.get("vertex_ai_credentials") + vertex_project = litellm_params.get("vertex_project") or litellm_params.get("vertex_ai_project") + vertex_credentials = litellm_params.get("vertex_credentials") or litellm_params.get("vertex_ai_credentials") try: while msg_i < len(messages): user_content: List[PartType] = [] init_msg_i = msg_i ## MERGE CONSECUTIVE USER CONTENT ## - while ( - msg_i < len(messages) and messages[msg_i]["role"] in user_message_types - ): + while msg_i < len(messages) and messages[msg_i]["role"] in user_message_types: _message_content = messages[msg_i].get("content") if _message_content is not None and isinstance(_message_content, list): _parts: List[PartType] = [] for element_idx, element in enumerate(_message_content): - if ( - element["type"] == "text" - and "text" in element - and len(element["text"]) > 0 - ): + if element["type"] == "text" and "text" in element and len(element["text"]) > 0: element = cast(ChatCompletionTextObject, element) _part = PartType(text=element["text"]) _parts.append(_part) @@ -757,9 +704,7 @@ def _gemini_convert_messages_with_history( or image_url_dict.get("content_type") ) detail = image_url_dict.get("detail") - media_resolution_enum = ( - _convert_detail_to_media_resolution_enum(detail) - ) + media_resolution_enum = _convert_detail_to_media_resolution_enum(detail) else: image_url = raw_image_url _part = _process_gemini_media( @@ -781,13 +726,11 @@ def _gemini_convert_messages_with_history( if audio_format.startswith("audio/") is False else audio_format ) # Gemini expects audio/wav, audio/mp3, etc. - openai_image_str = ( - convert_generic_image_chunk_to_openai_image_obj( - image_chunk=GenericImageParsingChunk( - type="base64", - media_type=audio_format_modified, - data=audio_data, - ) + openai_image_str = convert_generic_image_chunk_to_openai_image_obj( + image_chunk=GenericImageParsingChunk( + type="base64", + media_type=audio_format_modified, + data=audio_data, ) ) _part = _process_gemini_media( @@ -812,23 +755,17 @@ def _gemini_convert_messages_with_history( file_dict = cast(Dict[str, Any], _file_field) file_id = file_dict.get("file_id") format = ( - file_dict.get("format") - or file_dict.get("mime_type") - or file_dict.get("content_type") + file_dict.get("format") or file_dict.get("mime_type") or file_dict.get("content_type") ) file_data = file_dict.get("file_data") detail = file_dict.get("detail") video_metadata = file_dict.get("video_metadata") passed_file = file_id or file_data if passed_file is None: - raise Exception( - "Unknown file type. Please pass in a file_id or file_data" - ) + raise Exception("Unknown file type. Please pass in a file_id or file_data") # Convert detail to media_resolution_enum - media_resolution_enum = ( - _convert_detail_to_media_resolution_enum(detail) - ) + media_resolution_enum = _convert_detail_to_media_resolution_enum(detail) try: _part = _process_gemini_media( @@ -881,9 +818,7 @@ def _gemini_convert_messages_with_history( ## MERGE CONSECUTIVE ASSISTANT CONTENT ## while msg_i < len(messages) and messages[msg_i]["role"] == "assistant": if isinstance(messages[msg_i], BaseModel): - msg_dict: Union[ChatCompletionAssistantMessage, dict] = messages[ - msg_i - ].model_dump() # type: ignore + msg_dict: Union[ChatCompletionAssistantMessage, dict] = messages[msg_i].model_dump() # type: ignore else: msg_dict = messages[msg_i] # type: ignore assistant_msg = ChatCompletionAssistantMessage(**msg_dict) # type: ignore @@ -891,18 +826,13 @@ def _gemini_convert_messages_with_history( reasoning_content = assistant_msg.get("reasoning_content", None) thinking_blocks = assistant_msg.get("thinking_blocks") if reasoning_content is not None: - assistant_content.append( - PartType(thought=True, text=reasoning_content) - ) + assistant_content.append(PartType(thought=True, text=reasoning_content)) if thinking_blocks is not None: for block in thinking_blocks: if block["type"] == "thinking": block_thinking_str = block.get("thinking") block_signature = block.get("signature") - if ( - block_thinking_str is not None - and block_signature is not None - ): + if block_thinking_str is not None and block_signature is not None: try: assistant_content.append( PartType( @@ -929,23 +859,13 @@ def _gemini_convert_messages_with_history( elif _message_content is not None and isinstance(_message_content, str): assistant_text = _message_content # Check if message has thought_signatures in provider_specific_fields - provider_specific_fields = assistant_msg.get( - "provider_specific_fields" - ) + provider_specific_fields = assistant_msg.get("provider_specific_fields") thought_signatures = None - if provider_specific_fields and isinstance( - provider_specific_fields, dict - ): - thought_signatures = provider_specific_fields.get( - "thought_signatures" - ) + if provider_specific_fields and isinstance(provider_specific_fields, dict): + thought_signatures = provider_specific_fields.get("thought_signatures") # If we have thought signatures, add them to the part - if ( - thought_signatures - and isinstance(thought_signatures, list) - and len(thought_signatures) > 0 - ): + if thought_signatures and isinstance(thought_signatures, list) and len(thought_signatures) > 0: # Use the first signature for the text part (Gemini expects one signature per part) assistant_content.append( PartType( @@ -971,9 +891,7 @@ def _gemini_convert_messages_with_history( or image_url_obj.get("content_type") ) detail = image_url_obj.get("detail") - media_resolution_enum = ( - _convert_detail_to_media_resolution_enum(detail) - ) + media_resolution_enum = _convert_detail_to_media_resolution_enum(detail) if assistant_image_url: _part = _process_gemini_media( image_url=assistant_image_url, @@ -987,8 +905,7 @@ def _gemini_convert_messages_with_history( ## HANDLE ASSISTANT FUNCTION CALL if ( - assistant_msg.get("tool_calls", []) is not None - or assistant_msg.get("function_call") is not None + assistant_msg.get("tool_calls", []) is not None or assistant_msg.get("function_call") is not None ): # support assistant tool invoke conversion gemini_tool_call_parts = convert_to_gemini_tool_call_invoke( assistant_msg, @@ -1011,10 +928,7 @@ def _gemini_convert_messages_with_history( # reference. The following tool result would then be matched against # an assistant message that has no tool_calls, raising "Missing # corresponding tool call for tool response message". - if ( - assistant_msg.get("tool_calls") - or assistant_msg.get("function_call") is not None - ): + if assistant_msg.get("tool_calls") or assistant_msg.get("function_call") is not None: last_message_with_tool_calls = assistant_msg ## HANDLE SERVER-SIDE TOOL INVOCATIONS (context circulation) @@ -1032,9 +946,7 @@ def _gemini_convert_messages_with_history( } } if "thought_signature" in invocation: - tc_part["thoughtSignature"] = invocation[ - "thought_signature" - ] + tc_part["thoughtSignature"] = invocation["thought_signature"] assistant_content.append(tc_part) # type: ignore # Re-inject toolResponse part if response is present @@ -1047,9 +959,7 @@ def _gemini_convert_messages_with_history( tr_dict["toolType"] = invocation["tool_type"] tr_part: Dict[str, Any] = {"toolResponse": tr_dict} if "response_thought_signature" in invocation: - tr_part["thoughtSignature"] = invocation[ - "response_thought_signature" - ] + tr_part["thoughtSignature"] = invocation["response_thought_signature"] assistant_content.append(tr_part) # type: ignore msg_i += 1 @@ -1059,10 +969,7 @@ def _gemini_convert_messages_with_history( ## APPEND TOOL CALL MESSAGES ## tool_call_message_roles = ["tool", "function"] - if ( - msg_i < len(messages) - and messages[msg_i]["role"] in tool_call_message_roles - ): + if msg_i < len(messages) and messages[msg_i]["role"] in tool_call_message_roles: _part = convert_to_gemini_tool_call_result( messages[msg_i], # type: ignore last_message_with_tool_calls, # type: ignore @@ -1075,9 +982,7 @@ def _gemini_convert_messages_with_history( tool_call_responses.extend(_part) else: tool_call_responses.append(_part) - if msg_i < len(messages) and ( - messages[msg_i]["role"] not in tool_call_message_roles - ): + if msg_i < len(messages) and (messages[msg_i]["role"] not in tool_call_message_roles): if len(tool_call_responses) > 0: contents.append(ContentType(role="user", parts=tool_call_responses)) tool_call_responses = [] @@ -1118,11 +1023,7 @@ def _pop_and_merge_extra_body(data: RequestBody, optional_params: dict) -> None: for k, v in extra_body.items(): if k in _LITELLM_INTERNAL_EXTRA_BODY_KEYS: continue - if ( - k in data_dict - and isinstance(data_dict[k], dict) - and isinstance(v, dict) - ): + if k in data_dict and isinstance(data_dict[k], dict) and isinstance(v, dict): data_dict[k].update(v) else: data_dict[k] = v @@ -1132,9 +1033,7 @@ def _has_google_maps_tool(tools: Optional[Any]) -> bool: """Return True if any tool object in the list has a 'googleMaps' key.""" if not isinstance(tools, list): return False - return any( - isinstance(t, dict) and VertexToolName.GOOGLE_MAPS.value in t for t in tools - ) + return any(isinstance(t, dict) and VertexToolName.GOOGLE_MAPS.value in t for t in tools) def _rewrite_mime_type_to_response_format(generation_config: GenerationConfig) -> None: @@ -1195,17 +1094,13 @@ def _transform_request_body( Common transformation logic across sync + async Gemini /generateContent calls. """ # Separate system prompt from rest of message - supports_system_message = get_supports_system_message( - model=model, custom_llm_provider=custom_llm_provider - ) + supports_system_message = get_supports_system_message(model=model, custom_llm_provider=custom_llm_provider) system_instructions, messages = _transform_system_message( supports_system_message=supports_system_message, messages=messages ) # Checks for 'response_schema' support - if passed in if "response_schema" in optional_params: - supports_response_schema = get_supports_response_schema( - model=model, custom_llm_provider=custom_llm_provider - ) + supports_response_schema = get_supports_response_schema(model=model, custom_llm_provider=custom_llm_provider) if supports_response_schema is False: user_response_schema_message = response_schema_prompt( model=model, @@ -1235,12 +1130,8 @@ def _transform_request_body( ) tools: Optional[Tools] = optional_params.pop("tools", None) tool_choice: Optional[ToolConfig] = optional_params.pop("tool_choice", None) - include_server_side_tool_invocations: bool = optional_params.pop( - "include_server_side_tool_invocations", False - ) - safety_settings: Optional[List[SafetSettingsConfig]] = optional_params.pop( - "safety_settings", None - ) # type: ignore + include_server_side_tool_invocations: bool = optional_params.pop("include_server_side_tool_invocations", False) + safety_settings: Optional[List[SafetSettingsConfig]] = optional_params.pop("safety_settings", None) # type: ignore # Drop output_config as it's not supported by Vertex AI optional_params.pop("output_config", None) config_fields = GenerationConfig.__annotations__.keys() @@ -1248,15 +1139,9 @@ def _transform_request_body( # labels: optional explicit param and/or metadata.requester_metadata (OpenAI metadata) labels = pop_vertex_request_labels(optional_params, litellm_params) - filtered_params = { - k: v - for k, v in optional_params.items() - if _get_equivalent_key(k, set(config_fields)) - } + filtered_params = {k: v for k, v in optional_params.items() if _get_equivalent_key(k, set(config_fields))} - generation_config: Optional[GenerationConfig] = GenerationConfig( - **filtered_params - ) + generation_config: Optional[GenerationConfig] = GenerationConfig(**filtered_params) # For Gemini 2.x models, also add media_resolution to generation_config (global) # as a fallback, since some 2.x versions may not support per-part media_resolution. @@ -1264,20 +1149,14 @@ def _transform_request_body( if "gemini-2" in model: max_media_resolution = _extract_max_media_resolution_from_messages(messages) if max_media_resolution: - media_resolution_value = _convert_detail_to_media_resolution_enum( - max_media_resolution - ) + media_resolution_value = _convert_detail_to_media_resolution_enum(max_media_resolution) if media_resolution_value and generation_config is not None: - generation_config["mediaResolution"] = media_resolution_value[ - "level" - ] + generation_config["mediaResolution"] = media_resolution_value["level"] data = RequestBody(contents=content) # Vertex rejects system_instruction/tools/toolConfig alongside cachedContent. # Treat dropping these fields as a request mutation guarded by modify_params. - can_send_cache_incompatible_fields = ( - cached_content is None or litellm.modify_params is False - ) + can_send_cache_incompatible_fields = cached_content is None or litellm.modify_params is False if can_send_cache_incompatible_fields: if system_instructions is not None: data["system_instruction"] = system_instructions diff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py index 32bdb17840d4..678877c07215 100644 --- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py +++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py @@ -256,9 +256,7 @@ def get_json_schema_from_pydantic_object( if isinstance(response_format, dict): return response_format - if isinstance(response_format, type) and issubclass( - response_format, _BaseModel - ): + if isinstance(response_format, type) and issubclass(response_format, _BaseModel): schema = response_format.model_json_schema() return { "type": "json_schema", @@ -291,9 +289,7 @@ def _is_gemini_3_or_newer(model: str) -> bool: return False @staticmethod - def _forward_gemini_function_call_id( - model: str, custom_llm_provider: Optional[str] = None - ) -> bool: + def _forward_gemini_function_call_id(model: str, custom_llm_provider: Optional[str] = None) -> bool: """ Whether to include `id` on function_call / function_response parts. @@ -348,9 +344,7 @@ def get_supported_openai_params(self, model: str) -> List[str]: supported_params.append("thinking") return supported_params - def map_tool_choice_values( - self, model: str, tool_choice: Union[str, dict] - ) -> Optional[ToolConfig]: + def map_tool_choice_values(self, model: str, tool_choice: Union[str, dict]) -> Optional[ToolConfig]: if tool_choice == "none": return ToolConfig(functionCallingConfig=FunctionCallingConfig(mode="NONE")) elif tool_choice == "required": @@ -360,11 +354,7 @@ def map_tool_choice_values( elif isinstance(tool_choice, dict): # only supported for anthropic + mistral models - https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ToolChoice.html name = tool_choice.get("function", {}).get("name", "") - return ToolConfig( - functionCallingConfig=FunctionCallingConfig( - mode="ANY", allowed_function_names=[name] - ) - ) + return ToolConfig(functionCallingConfig=FunctionCallingConfig(mode="ANY", allowed_function_names=[name])) else: raise litellm.utils.UnsupportedParamsError( message="VertexAI doesn't support tool_choice={}. Supported tool_choice values=['auto', 'required', json object]. To drop it from the call, set `litellm.drop_params = True.".format( @@ -412,16 +402,12 @@ def _drop_search_tools_mixed_with_functions(cls, optional_params: dict) -> None: return search_tool_keys = cls._search_tool_keys() - has_function_declarations = any( - isinstance(tool, dict) and tool.get("function_declarations") - for tool in tools - ) + has_function_declarations = any(isinstance(tool, dict) and tool.get("function_declarations") for tool in tools) if not has_function_declarations: return has_search_tools = any( - isinstance(tool, dict) and any(key in tool for key in search_tool_keys) - for tool in tools + isinstance(tool, dict) and any(key in tool for key in search_tool_keys) for tool in tools ) if not has_search_tools: return @@ -434,11 +420,7 @@ def _drop_search_tools_mixed_with_functions(cls, optional_params: dict) -> None: "send a request without function calling tools." ) optional_params["tools"] = [ - tool - for tool in tools - if not ( - isinstance(tool, dict) and any(key in tool for key in search_tool_keys) - ) + tool for tool in tools if not (isinstance(tool, dict) and any(key in tool for key in search_tool_keys)) ] def _map_service_tier_param(self, value: str, optional_params: dict) -> None: @@ -482,19 +464,13 @@ def _transform_computer_use_config(self, computer_use_config: dict) -> dict: # Transform excluded_predefined_functions to camelCase if "excluded_predefined_functions" in computer_use_config: - transformed_config["excludedPredefinedFunctions"] = computer_use_config[ - "excluded_predefined_functions" - ] + transformed_config["excludedPredefinedFunctions"] = computer_use_config["excluded_predefined_functions"] elif "excludedPredefinedFunctions" in computer_use_config: - transformed_config["excludedPredefinedFunctions"] = computer_use_config[ - "excludedPredefinedFunctions" - ] + transformed_config["excludedPredefinedFunctions"] = computer_use_config["excludedPredefinedFunctions"] return transformed_config - def _extract_google_maps_retrieval_config( - self, google_maps_config: dict - ) -> Tuple[dict, Optional[dict]]: + def _extract_google_maps_retrieval_config(self, google_maps_config: dict) -> Tuple[dict, Optional[dict]]: """ Extract location configuration from googleMaps tool for Vertex AI toolConfig. @@ -527,9 +503,7 @@ def _extract_google_maps_retrieval_config( # Remove location fields from tool definition cleaned_config = { - k: v - for k, v in google_maps_config.items() - if k not in ["latitude", "longitude", "languageCode"] + k: v for k, v in google_maps_config.items() if k not in ["latitude", "longitude", "languageCode"] } return cleaned_config, retrieval_config @@ -546,9 +520,7 @@ def get_tool_value(self, tool: dict, tool_name: str) -> Optional[dict]: Optional[dict]: The tool value if found, None otherwise """ # Convert camelCase to underscore_case - underscore_name = "".join( - ["_" + c.lower() if c.isupper() else c for c in tool_name] - ).lstrip("_") + underscore_name = "".join(["_" + c.lower() if c.isupper() else c for c in tool_name]).lstrip("_") # Try both camelCase and underscore_case variants if tool.get(tool_name) is not None: @@ -592,14 +564,8 @@ def _resolve_search_tool_conflict( urlContext, ] ) - server_side_tool_invocations = optional_params.get( - "include_server_side_tool_invocations", False - ) - if ( - gtool_func_declarations - and has_search_tools - and not server_side_tool_invocations - ): + server_side_tool_invocations = optional_params.get("include_server_side_tool_invocations", False) + if gtool_func_declarations and has_search_tools and not server_side_tool_invocations: verbose_logger.warning( "Vertex AI does not support mixing function declarations with " "search tools (googleSearch, enterpriseWebSearch, urlContext, " @@ -644,9 +610,7 @@ def _map_function(self, value: List[dict], optional_params: dict) -> List[Tools] value = _remove_strict_from_schema(value) for tool in value: - openai_function_object: Optional[ChatCompletionToolParamFunctionChunk] = ( - None - ) + openai_function_object: Optional[ChatCompletionToolParamFunctionChunk] = None if "function" in tool: # tools list _openai_function_object = ChatCompletionToolParamFunctionChunk( # type: ignore **tool["function"] @@ -657,9 +621,7 @@ def _map_function(self, value: List[dict], optional_params: dict) -> List[Tools] and _openai_function_object["parameters"] is not None and isinstance(_openai_function_object["parameters"], dict) ): # OPENAI accepts JSON Schema, Google accepts OpenAPI schema. - _openai_function_object["parameters"] = _build_vertex_schema( - _openai_function_object["parameters"] - ) + _openai_function_object["parameters"] = _build_vertex_schema(_openai_function_object["parameters"]) openai_function_object = _openai_function_object @@ -675,68 +637,43 @@ def _map_function(self, value: List[dict], optional_params: dict) -> List[Tools] "web_search", "web_search_preview", ): - verbose_logger.info( - f"Gemini: Transforming OpenAI-style '{tool['type']}' tool to googleSearch" - ) + verbose_logger.info(f"Gemini: Transforming OpenAI-style '{tool['type']}' tool to googleSearch") tool = {VertexToolName.GOOGLE_SEARCH.value: {}} # Handle tools with 'type' field (OpenAI spec compliance) Ignore this field -> https://github.com/BerriAI/litellm/issues/14644#issuecomment-3342061838 elif "type" in tool: tool = {k: tool[k] for k in tool if k != "type"} tool_name = list(tool.keys())[0] if len(tool.keys()) == 1 else None if tool_name and ( - tool_name == "codeExecution" - or tool_name == VertexToolName.CODE_EXECUTION.value + tool_name == "codeExecution" or tool_name == VertexToolName.CODE_EXECUTION.value ): # code_execution maintained for backwards compatibility code_execution = self.get_tool_value(tool, "codeExecution") - elif tool_name and ( - tool_name == VertexToolName.GOOGLE_SEARCH.value - or tool_name == "google_search" - ): + elif tool_name and (tool_name == VertexToolName.GOOGLE_SEARCH.value or tool_name == "google_search"): googleSearch = self.get_tool_value(tool, tool_name) elif tool_name and ( - tool_name == VertexToolName.GOOGLE_SEARCH_RETRIEVAL.value - or tool_name == "google_search_retrieval" + tool_name == VertexToolName.GOOGLE_SEARCH_RETRIEVAL.value or tool_name == "google_search_retrieval" ): googleSearchRetrieval = self.get_tool_value(tool, tool_name) elif tool_name and ( - tool_name == VertexToolName.ENTERPRISE_WEB_SEARCH.value - or tool_name == "enterprise_web_search" + tool_name == VertexToolName.ENTERPRISE_WEB_SEARCH.value or tool_name == "enterprise_web_search" ): enterpriseWebSearch = self.get_tool_value(tool, tool_name) - elif tool_name and ( - tool_name == VertexToolName.URL_CONTEXT.value - or tool_name == "urlContext" - ): + elif tool_name and (tool_name == VertexToolName.URL_CONTEXT.value or tool_name == "urlContext"): urlContext = self.get_tool_value(tool, tool_name) - elif tool_name and ( - tool_name == VertexToolName.GOOGLE_MAPS.value - or tool_name == "google_maps" - ): - google_maps_value = self.get_tool_value( - tool, VertexToolName.GOOGLE_MAPS.value - ) + elif tool_name and (tool_name == VertexToolName.GOOGLE_MAPS.value or tool_name == "google_maps"): + google_maps_value = self.get_tool_value(tool, VertexToolName.GOOGLE_MAPS.value) # Extract and transform location configuration for toolConfig if google_maps_value is not None: ( googleMaps, google_maps_retrieval_config, - ) = self._extract_google_maps_retrieval_config( - google_maps_config=google_maps_value - ) - elif tool_name and ( - tool_name == VertexToolName.COMPUTER_USE.value - or tool_name == "computer_use" - ): - computer_use_value = self.get_tool_value( - tool, VertexToolName.COMPUTER_USE.value - ) + ) = self._extract_google_maps_retrieval_config(google_maps_config=google_maps_value) + elif tool_name and (tool_name == VertexToolName.COMPUTER_USE.value or tool_name == "computer_use"): + computer_use_value = self.get_tool_value(tool, VertexToolName.COMPUTER_USE.value) # Transform Computer Use configuration to Gemini API format if computer_use_value is not None: - computerUse = self._transform_computer_use_config( - computer_use_config=computer_use_value - ) + computerUse = self._transform_computer_use_config(computer_use_config=computer_use_value) else: # Empty config - Gemini will use defaults computerUse = {} @@ -792,15 +729,11 @@ def _map_function(self, value: List[dict], optional_params: dict) -> List[Tools] _tools_list.append(search_tool) if googleSearchRetrieval is not None: retrieval_tool = Tools() - retrieval_tool[VertexToolName.GOOGLE_SEARCH_RETRIEVAL.value] = ( - googleSearchRetrieval - ) + retrieval_tool[VertexToolName.GOOGLE_SEARCH_RETRIEVAL.value] = googleSearchRetrieval _tools_list.append(retrieval_tool) if enterpriseWebSearch is not None: enterprise_tool = Tools() - enterprise_tool[VertexToolName.ENTERPRISE_WEB_SEARCH.value] = ( - enterpriseWebSearch - ) + enterprise_tool[VertexToolName.ENTERPRISE_WEB_SEARCH.value] = enterpriseWebSearch _tools_list.append(enterprise_tool) if code_execution is not None: code_tool = Tools() @@ -823,9 +756,7 @@ def _map_function(self, value: List[dict], optional_params: dict) -> List[Tools] if google_maps_retrieval_config is not None: if "toolConfig" not in optional_params: optional_params["toolConfig"] = {} - optional_params["toolConfig"]["retrievalConfig"] = ( - google_maps_retrieval_config - ) + optional_params["toolConfig"]["retrievalConfig"] = google_maps_retrieval_config return _tools_list @@ -834,19 +765,13 @@ def _map_response_schema(self, value: dict) -> dict: if isinstance(old_schema, list): for item in old_schema: if isinstance(item, dict): - item = _build_vertex_schema( - parameters=item, add_property_ordering=True - ) + item = _build_vertex_schema(parameters=item, add_property_ordering=True) elif isinstance(old_schema, dict): - old_schema = _build_vertex_schema( - parameters=old_schema, add_property_ordering=True - ) + old_schema = _build_vertex_schema(parameters=old_schema, add_property_ordering=True) return old_schema - def apply_response_schema_transformation( - self, value: dict, optional_params: dict, model: str - ): + def apply_response_schema_transformation(self, value: dict, optional_params: dict, model: str): new_value = deepcopy(value) # remove 'strict' from json schema (not supported by Gemini) new_value = _remove_strict_from_schema(new_value) @@ -882,17 +807,13 @@ def apply_response_schema_transformation( # - Standard JSON Schema format (lowercase types) # - Supports additionalProperties # - No propertyOrdering needed - optional_params["response_json_schema"] = _build_json_schema( - deepcopy(schema) - ) + optional_params["response_json_schema"] = _build_json_schema(deepcopy(schema)) else: # Use responseSchema (default, backwards compatible) # - OpenAPI-style format (uppercase types) # - No additionalProperties support # - Requires propertyOrdering - optional_params["response_schema"] = self._map_response_schema( - value=schema - ) + optional_params["response_schema"] = self._map_response_schema(value=schema) @staticmethod def _map_reasoning_effort_to_thinking_budget( @@ -907,9 +828,7 @@ def _map_reasoning_effort_to_thinking_budget( elif model and "gemini-2.5-pro" in model.lower(): budget = DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_PRO elif model and "gemini-2.5-flash" in model.lower(): - budget = ( - DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH - ) + budget = DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET_GEMINI_2_5_FLASH else: budget = DEFAULT_REASONING_EFFORT_MINIMAL_THINKING_BUDGET @@ -962,9 +881,7 @@ def _map_reasoning_effort_to_thinking_level( # Check if this is gemini-3-flash which supports MINIMAL thinking level # Covers gemini-3-flash, gemini-3-flash-preview, gemini-3.1-flash, gemini-3.1-flash-lite-preview, # gemini-3.5-flash, and any future 3.x-flash variants. - is_gemini3flash = model and ( - "flash" in model.lower() and "gemini-3" in model.lower() - ) + is_gemini3flash = model and ("flash" in model.lower() and "gemini-3" in model.lower()) is_gemini31pro = model and ("gemini-3.1-pro-preview" in model.lower()) if reasoning_effort == "minimal": if is_gemini3flash: @@ -1058,20 +975,14 @@ def _map_thinking_param( params["includeThoughts"] = True # Follow provider defaults unless explicitly opted into legacy behavior. if litellm.enable_gemini_default_thinking_level_low is True: - is_gemini3flash = ( - "gemini-3" in model.lower() and "flash" in model.lower() - ) - params["thinkingLevel"] = ( - "minimal" if is_gemini3flash else "low" - ) + is_gemini3flash = "gemini-3" in model.lower() and "flash" in model.lower() + params["thinkingLevel"] = "minimal" if is_gemini3flash else "low" else: # Thinking disabled params["includeThoughts"] = False else: # For older Gemini models, use thinkingBudget - if thinking_enabled and not VertexGeminiConfig._is_thinking_budget_zero( - thinking_budget - ): + if thinking_enabled and not VertexGeminiConfig._is_thinking_budget_zero(thinking_budget): params["includeThoughts"] = True if thinking_budget is not None and isinstance(thinking_budget, int): params["thinkingBudget"] = thinking_budget @@ -1178,9 +1089,7 @@ def map_openai_params( model: str, drop_params: bool, ) -> Dict: - self._apply_include_server_side_tool_invocations( - non_default_params, optional_params - ) + self._apply_include_server_side_tool_invocations(non_default_params, optional_params) gemini_sampling_params_warned: bool = False for param, value in non_default_params.items(): if param == "temperature": @@ -1201,10 +1110,7 @@ def map_openai_params( gemini_sampling_params_warned = True optional_params["temperature"] = value elif param == "top_p": - if ( - VertexGeminiConfig._is_gemini_3_or_newer(model) - and not gemini_sampling_params_warned - ): + if VertexGeminiConfig._is_gemini_3_or_newer(model) and not gemini_sampling_params_warned: verbose_logger.warning( "DeprecationWarning: `temperature`, `top_p`, and `top_k` continue to " f"function for Gemini 3+ ({model}) but are planned for removal in a " @@ -1214,10 +1120,7 @@ def map_openai_params( gemini_sampling_params_warned = True optional_params["top_p"] = value elif param == "top_k": - if ( - VertexGeminiConfig._is_gemini_3_or_newer(model) - and not gemini_sampling_params_warned - ): + if VertexGeminiConfig._is_gemini_3_or_newer(model) and not gemini_sampling_params_warned: verbose_logger.warning( "DeprecationWarning: `temperature`, `top_p`, and `top_k` continue to " f"function for Gemini 3+ ({model}) but are planned for removal in a " @@ -1242,9 +1145,7 @@ def map_openai_params( elif param == "max_tokens" or param == "max_completion_tokens": optional_params["max_output_tokens"] = value elif param == "response_format" and isinstance(value, dict): # type: ignore - self.apply_response_schema_transformation( - value=value, optional_params=optional_params, model=model - ) + self.apply_response_schema_transformation(value=value, optional_params=optional_params, model=model) elif param == "frequency_penalty": if self._supports_penalty_parameters(model): optional_params["frequency_penalty"] = value @@ -1255,21 +1156,11 @@ def map_openai_params( optional_params["responseLogprobs"] = value elif param == "top_logprobs": optional_params["logprobs"] = value - elif ( - (param == "tools" or param == "functions") - and isinstance(value, list) - and value - ): + elif (param == "tools" or param == "functions") and isinstance(value, list) and value: # Pass optional_params so _map_function can add toolConfig if needed - mapped_tools = self._map_function( - value=value, optional_params=optional_params - ) - optional_params = self._add_tools_to_optional_params( - optional_params, mapped_tools - ) - elif param == "tool_choice" and ( - isinstance(value, str) or isinstance(value, dict) - ): + mapped_tools = self._map_function(value=value, optional_params=optional_params) + optional_params = self._add_tools_to_optional_params(optional_params, mapped_tools) + elif param == "tool_choice" and (isinstance(value, str) or isinstance(value, dict)): _tool_choice_value = self.map_tool_choice_values( model=model, tool_choice=value, # type: ignore @@ -1277,9 +1168,7 @@ def map_openai_params( if _tool_choice_value is not None: optional_params["tool_choice"] = _tool_choice_value elif param == "parallel_tool_calls": - tools_list = non_default_params.get( - "tools", non_default_params.get("functions") - ) + tools_list = non_default_params.get("tools", non_default_params.get("functions")) num_tools = len(tools_list) if isinstance(tools_list, list) else 0 # Gemini does not support parallel_tool_calls=False with multiple # tools. Drop the param instead of failing — Responses API clients @@ -1305,16 +1194,12 @@ def map_openai_params( param_description="thinking_budget", ) if VertexGeminiConfig._is_gemini_3_or_newer(model): - optional_params["thinkingConfig"] = ( - VertexGeminiConfig._map_reasoning_effort_to_thinking_level( - effort_value, model - ) + optional_params["thinkingConfig"] = VertexGeminiConfig._map_reasoning_effort_to_thinking_level( + effort_value, model ) else: - optional_params["thinkingConfig"] = ( - VertexGeminiConfig._map_reasoning_effort_to_thinking_budget( - effort_value, model - ) + optional_params["thinkingConfig"] = VertexGeminiConfig._map_reasoning_effort_to_thinking_budget( + effort_value, model ) elif param == "thinking": # Validate no conflict with thinking_level @@ -1323,20 +1208,16 @@ def map_openai_params( param_name="thinking", param_description="thinking_budget", ) - optional_params["thinkingConfig"] = ( - VertexGeminiConfig._map_thinking_param( - cast(AnthropicThinkingParam, value), - model=model, - ) + optional_params["thinkingConfig"] = VertexGeminiConfig._map_thinking_param( + cast(AnthropicThinkingParam, value), + model=model, ) elif param == "modalities" and isinstance(value, list): response_modalities = self.map_response_modalities(value) optional_params["responseModalities"] = response_modalities elif param == "web_search_options" and isinstance(value, dict): _tools = self._map_web_search_options(value) - optional_params = self._add_tools_to_optional_params( - optional_params, [_tools] - ) + optional_params = self._add_tools_to_optional_params(optional_params, [_tools]) elif param == "service_tier" and isinstance(value, str): self._map_service_tier_param(value, optional_params) elif param == "include_server_side_tool_invocations" and value is True: @@ -1479,11 +1360,7 @@ def get_finish_reason_mapping() -> Dict[str, OpenAIChatCompletionFinishReason]: """ from litellm.litellm_core_utils.core_helpers import _FINISH_REASON_MAP - return { - k: v - for k, v in _FINISH_REASON_MAP.items() - if k in VertexGeminiConfig._GEMINI_FINISH_REASON_KEYS - } + return {k: v for k, v in _FINISH_REASON_MAP.items() if k in VertexGeminiConfig._GEMINI_FINISH_REASON_KEYS} def translate_exception_str(self, exception_string: str): if ( @@ -1495,9 +1372,7 @@ def translate_exception_str(self, exception_string: str): ) return exception_string - def get_assistant_content_message( - self, parts: List[HttpxPartType] - ) -> Tuple[Optional[str], Optional[str]]: + def get_assistant_content_message(self, parts: List[HttpxPartType]) -> Tuple[Optional[str], Optional[str]]: content_str: Optional[str] = None reasoning_content_str: Optional[str] = None @@ -1509,9 +1384,7 @@ def get_assistant_content_message( if text_content.startswith("data:audio") and ";base64," in text_content: try: if is_base64_encoded(text_content): - media_type, _ = text_content.split("data:")[1].split( - ";base64," - ) + media_type, _ = text_content.split("data:")[1].split(";base64,") if media_type.startswith("audio/"): continue except (ValueError, IndexError): @@ -1540,9 +1413,7 @@ def get_assistant_content_message( return content_str, reasoning_content_str - def _extract_thinking_blocks_from_parts( - self, parts: List[HttpxPartType] - ) -> List[ChatCompletionThinkingBlock]: + def _extract_thinking_blocks_from_parts(self, parts: List[HttpxPartType]) -> List[ChatCompletionThinkingBlock]: """Extract thinking blocks from parts if present. Per Google's docs (https://ai.google.dev/gemini-api/docs/thinking): @@ -1565,9 +1436,7 @@ def _extract_thinking_blocks_from_parts( thinking_blocks.append(block) return thinking_blocks - def _extract_thought_signatures_from_parts( - self, parts: List[HttpxPartType] - ) -> Optional[List[str]]: + def _extract_thought_signatures_from_parts(self, parts: List[HttpxPartType]) -> Optional[List[str]]: """Extract thoughtSignature values from parts. Per Google's docs, thoughtSignature is returned for multi-turn context preservation @@ -1641,16 +1510,12 @@ def _extract_server_side_tool_invocations( # Any orphan responses (shouldn't happen, but be safe) for resp_id, resp_entry in tool_responses_by_id.items(): if "thought_signature" in resp_entry: - resp_entry["response_thought_signature"] = resp_entry[ - "thought_signature" - ] + resp_entry["response_thought_signature"] = resp_entry["thought_signature"] invocations.append(resp_entry) return invocations if invocations else None - def _extract_image_response_from_parts( - self, parts: List[HttpxPartType] - ) -> Optional[List[ImageURLListItem]]: + def _extract_image_response_from_parts(self, parts: List[HttpxPartType]) -> Optional[List[ImageURLListItem]]: """Extract image response from parts if present""" images: List[ImageURLListItem] = [] for part in parts: @@ -1670,9 +1535,7 @@ def _extract_image_response_from_parts( ) return images - def _extract_audio_response_from_parts( - self, parts: List[HttpxPartType] - ) -> Optional[ChatCompletionAudioResponse]: + def _extract_audio_response_from_parts(self, parts: List[HttpxPartType]) -> Optional[ChatCompletionAudioResponse]: """Extract audio response from parts if present""" for part in parts: if "text" in part: @@ -1681,9 +1544,7 @@ def _extract_audio_response_from_parts( if text_content.startswith("data:audio") and ";base64," in text_content: try: if is_base64_encoded(text_content): - media_type, audio_data = text_content.split("data:")[ - 1 - ].split(";base64,") + media_type, audio_data = text_content.split("data:")[1].split(";base64,") if media_type.startswith("audio/"): expires_at = int(time.time()) + (24 * 60 * 60) @@ -1706,9 +1567,7 @@ def _extract_audio_response_from_parts( expires_at = int(time.time()) + (24 * 60 * 60) transcript = "" # Gemini doesn't provide transcript - return ChatCompletionAudioResponse( - data=data, expires_at=expires_at, transcript=transcript - ) + return ChatCompletionAudioResponse(data=data, expires_at=expires_at, transcript=transcript) return None @@ -1728,9 +1587,7 @@ def _transform_parts( if "functionCall" in part: _function_chunk: ChatCompletionToolCallFunctionChunk = { "name": part["functionCall"]["name"], - "arguments": json.dumps( - part["functionCall"]["args"], ensure_ascii=False - ), + "arguments": json.dumps(part["functionCall"]["args"], ensure_ascii=False), } # Extract thought signature if present thought_signature = part.get("thoughtSignature") @@ -1744,9 +1601,7 @@ def _transform_parts( if thought_signature: if "provider_specific_fields" not in function_dict: function_dict["provider_specific_fields"] = {} - function_dict["provider_specific_fields"][ - "thought_signature" - ] = thought_signature + function_dict["provider_specific_fields"]["thought_signature"] = thought_signature function = cast(ChatCompletionToolCallFunctionChunk, function_dict) else: _tool_response_chunk: ChatCompletionToolCallChunk = { @@ -1765,10 +1620,8 @@ def _transform_parts( _tool_response_chunk["provider_specific_fields"] = { # type: ignore "thought_signature": thought_signature } - _tool_response_chunk["id"] = ( - _encode_tool_call_id_with_signature( - _tool_response_chunk["id"] or "", thought_signature - ) + _tool_response_chunk["id"] = _encode_tool_call_id_with_signature( + _tool_response_chunk["id"] or "", thought_signature ) _tools.append(_tool_response_chunk) cumulative_tool_call_idx += 1 @@ -1789,19 +1642,11 @@ def _transform_logprobs( logprobs_list: List[ChatCompletionTokenLogprob] = [] for index, candidate in enumerate(logprobs_result["chosenCandidates"]): top_logprobs: List[TopLogprob] = [] - if "topCandidates" in logprobs_result and index < len( - logprobs_result["topCandidates"] - ): - top_candidates_for_index = logprobs_result["topCandidates"][index][ - "candidates" - ] + if "topCandidates" in logprobs_result and index < len(logprobs_result["topCandidates"]): + top_candidates_for_index = logprobs_result["topCandidates"][index]["candidates"] for options in top_candidates_for_index: - top_logprobs.append( - TopLogprob( - token=options["token"], logprob=options["logProbability"] - ) - ) + top_logprobs.append(TopLogprob(token=options["token"], logprob=options["logProbability"])) logprobs_list.append( ChatCompletionTokenLogprob( token=candidate["token"], @@ -1836,12 +1681,8 @@ def _handle_blocked_response( ## GET USAGE ## usage = Usage( - prompt_tokens=completion_response["usageMetadata"].get( - "promptTokenCount", 0 - ), - completion_tokens=completion_response["usageMetadata"].get( - "candidatesTokenCount", 0 - ), + prompt_tokens=completion_response["usageMetadata"].get("promptTokenCount", 0), + completion_tokens=completion_response["usageMetadata"].get("candidatesTokenCount", 0), total_tokens=completion_response["usageMetadata"].get("totalTokenCount", 0), ) @@ -1874,12 +1715,8 @@ def _handle_content_policy_violation( ## GET USAGE ## usage = Usage( - prompt_tokens=completion_response["usageMetadata"].get( - "promptTokenCount", 0 - ), - completion_tokens=completion_response["usageMetadata"].get( - "candidatesTokenCount", 0 - ), + prompt_tokens=completion_response["usageMetadata"].get("promptTokenCount", 0), + completion_tokens=completion_response["usageMetadata"].get("candidatesTokenCount", 0), total_tokens=completion_response["usageMetadata"].get("totalTokenCount", 0), ) @@ -1907,17 +1744,10 @@ def is_candidate_token_count_inclusive(usage_metadata: UsageMetadata) -> bool: @staticmethod def _calculate_usage( - completion_response: Union[ - GenerateContentResponseBody, BidiGenerateContentServerMessage - ], + completion_response: Union[GenerateContentResponseBody, BidiGenerateContentServerMessage], ) -> Usage: - if ( - completion_response is not None - and "usageMetadata" not in completion_response - ): - raise ValueError( - f"usageMetadata not found in completion_response. Got={completion_response}" - ) + if completion_response is not None and "usageMetadata" not in completion_response: + raise ValueError(f"usageMetadata not found in completion_response. Got={completion_response}") cached_tokens: Optional[int] = None # Separate variables for prompt tokens by modality prompt_audio_tokens: Optional[int] = None @@ -1946,17 +1776,11 @@ def _get_token_count(detail: Mapping[str, Any]) -> int: modality = str(detail.get("modality", "")).upper() token_count = _get_token_count(detail) if modality == "TEXT": - response_tokens_details.text_tokens = ( - response_tokens_details.text_tokens or 0 - ) + token_count + response_tokens_details.text_tokens = (response_tokens_details.text_tokens or 0) + token_count elif modality == "AUDIO": - response_tokens_details.audio_tokens = ( - response_tokens_details.audio_tokens or 0 - ) + token_count + response_tokens_details.audio_tokens = (response_tokens_details.audio_tokens or 0) + token_count elif modality == "DOCUMENT": - response_tokens_details.text_tokens = ( - response_tokens_details.text_tokens or 0 - ) + token_count + response_tokens_details.text_tokens = (response_tokens_details.text_tokens or 0) + token_count ######################################################### @@ -1968,25 +1792,15 @@ def _get_token_count(detail: Mapping[str, Any]) -> int: modality = str(detail.get("modality", "")).upper() token_count = _get_token_count(detail) if modality == "TEXT": - response_tokens_details.text_tokens = ( - response_tokens_details.text_tokens or 0 - ) + token_count + response_tokens_details.text_tokens = (response_tokens_details.text_tokens or 0) + token_count elif modality == "AUDIO": - response_tokens_details.audio_tokens = ( - response_tokens_details.audio_tokens or 0 - ) + token_count + response_tokens_details.audio_tokens = (response_tokens_details.audio_tokens or 0) + token_count elif modality == "IMAGE": - response_tokens_details.image_tokens = ( - response_tokens_details.image_tokens or 0 - ) + token_count + response_tokens_details.image_tokens = (response_tokens_details.image_tokens or 0) + token_count elif modality == "VIDEO": - response_tokens_details.video_tokens = ( - response_tokens_details.video_tokens or 0 - ) + token_count + response_tokens_details.video_tokens = (response_tokens_details.video_tokens or 0) + token_count elif modality == "DOCUMENT": - response_tokens_details.text_tokens = ( - response_tokens_details.text_tokens or 0 - ) + token_count + response_tokens_details.text_tokens = (response_tokens_details.text_tokens or 0) + token_count # Calculate text_tokens if not explicitly provided in candidatesTokensDetails # candidatesTokenCount includes all modalities, so: text = total - (image + audio + video) @@ -1999,10 +1813,7 @@ def _get_token_count(detail: Mapping[str, Any]) -> int: completion_audio_tokens = response_tokens_details.audio_tokens or 0 completion_video_tokens = response_tokens_details.video_tokens or 0 calculated_text_tokens = ( - candidates_token_count - - completion_image_tokens - - completion_audio_tokens - - completion_video_tokens + candidates_token_count - completion_image_tokens - completion_audio_tokens - completion_video_tokens ) response_tokens_details.text_tokens = calculated_text_tokens ######################################################### @@ -2083,13 +1894,8 @@ def _get_token_count(detail: Mapping[str, Any]) -> int: video_tokens=prompt_video_tokens, ) - completion_tokens = response_tokens or completion_response["usageMetadata"].get( - "candidatesTokenCount", 0 - ) - if ( - not VertexGeminiConfig.is_candidate_token_count_inclusive(usage_metadata) - and reasoning_tokens - ): + completion_tokens = response_tokens or completion_response["usageMetadata"].get("candidatesTokenCount", 0) + if not VertexGeminiConfig.is_candidate_token_count_inclusive(usage_metadata) and reasoning_tokens: completion_tokens = reasoning_tokens + completion_tokens ## GET USAGE ## usage = Usage( @@ -2170,11 +1976,7 @@ def _check_prompt_level_content_filter( def _calculate_web_search_requests(grounding_metadata: List[dict]) -> Optional[int]: web_search_requests: Optional[int] = None - if ( - grounding_metadata - and isinstance(grounding_metadata, list) - and len(grounding_metadata) > 0 - ): + if grounding_metadata and isinstance(grounding_metadata, list) and len(grounding_metadata) > 0: for grounding_metadata_item in grounding_metadata: web_search_queries = grounding_metadata_item.get("webSearchQueries") if web_search_queries and web_search_requests: @@ -2199,9 +2001,7 @@ def _create_streaming_choice( from litellm.types.utils import Delta, StreamingChoices annotations = chat_completion_message.get("annotations") # type: ignore - provider_specific_fields = chat_completion_message.get( - "provider_specific_fields" - ) # type: ignore + provider_specific_fields = chat_completion_message.get("provider_specific_fields") # type: ignore # create a streaming choice object choice = StreamingChoices( finish_reason=VertexGeminiConfig._check_finish_reason( @@ -2290,14 +2090,10 @@ def _set_stream_metadata_on_response( ) -> None: setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata) # type: ignore if grounding_metadata: - model_response._hidden_params["vertex_ai_grounding_metadata"] = ( - grounding_metadata - ) + model_response._hidden_params["vertex_ai_grounding_metadata"] = grounding_metadata setattr(model_response, "vertex_ai_url_context_metadata", url_context_metadata) # type: ignore if url_context_metadata: - model_response._hidden_params["vertex_ai_url_context_metadata"] = ( - url_context_metadata - ) + model_response._hidden_params["vertex_ai_url_context_metadata"] = url_context_metadata setattr(model_response, "vertex_ai_safety_ratings", safety_ratings) # type: ignore setattr(model_response, "vertex_ai_safety_results", safety_ratings) # type: ignore if safety_ratings: @@ -2305,9 +2101,7 @@ def _set_stream_metadata_on_response( model_response._hidden_params["vertex_ai_safety_results"] = safety_ratings setattr(model_response, "vertex_ai_citation_metadata", citation_metadata) # type: ignore if citation_metadata: - model_response._hidden_params["vertex_ai_citation_metadata"] = ( - citation_metadata - ) + model_response._hidden_params["vertex_ai_citation_metadata"] = citation_metadata def apply_assembled_streaming_response_metadata( self, @@ -2440,51 +2234,35 @@ def _process_candidates( ( content, reasoning_content, - ) = VertexGeminiConfig().get_assistant_content_message( - parts=candidate["content"]["parts"] - ) + ) = VertexGeminiConfig().get_assistant_content_message(parts=candidate["content"]["parts"]) - audio_response = ( - VertexGeminiConfig()._extract_audio_response_from_parts( - parts=candidate["content"]["parts"] - ) + audio_response = VertexGeminiConfig()._extract_audio_response_from_parts( + parts=candidate["content"]["parts"] ) - image_response = ( - VertexGeminiConfig()._extract_image_response_from_parts( - parts=candidate["content"]["parts"] - ) + image_response = VertexGeminiConfig()._extract_image_response_from_parts( + parts=candidate["content"]["parts"] ) - thinking_blocks = ( - VertexGeminiConfig()._extract_thinking_blocks_from_parts( - parts=candidate["content"]["parts"] - ) + thinking_blocks = VertexGeminiConfig()._extract_thinking_blocks_from_parts( + parts=candidate["content"]["parts"] ) # Extract thoughtSignatures from parts (can exist without thought: true) - thought_signatures = ( - VertexGeminiConfig()._extract_thought_signatures_from_parts( - parts=candidate["content"]["parts"] - ) + thought_signatures = VertexGeminiConfig()._extract_thought_signatures_from_parts( + parts=candidate["content"]["parts"] ) # Extract server-side tool invocations (context circulation) - server_side_tool_invocations = ( - VertexGeminiConfig._extract_server_side_tool_invocations( - parts=candidate["content"]["parts"] - ) + server_side_tool_invocations = VertexGeminiConfig._extract_server_side_tool_invocations( + parts=candidate["content"]["parts"] ) if audio_response is not None: - cast(Dict[str, Any], chat_completion_message)["audio"] = ( - audio_response - ) + cast(Dict[str, Any], chat_completion_message)["audio"] = audio_response chat_completion_message["content"] = None # OpenAI spec if image_response is not None: # Handle image response - combine with text content into structured format - cast(Dict[str, Any], chat_completion_message)["images"] = ( - image_response - ) + cast(Dict[str, Any], chat_completion_message)["images"] = image_response if content is not None: chat_completion_message["content"] = content @@ -2492,11 +2270,9 @@ def _process_candidates( chat_completion_message["reasoning_content"] = reasoning_content if candidate_grounding_metadata: - annotations = ( - VertexGeminiConfig._convert_grounding_metadata_to_annotations( - grounding_metadata=candidate_grounding_metadata, - content_text=content, - ) + annotations = VertexGeminiConfig._convert_grounding_metadata_to_annotations( + grounding_metadata=candidate_grounding_metadata, + content_text=content, ) if annotations: chat_completion_message["annotations"] = annotations # type: ignore @@ -2526,10 +2302,7 @@ def _process_candidates( # Convert thinking_blocks to reasoning_content for streaming # This ensures reasoning_content is available in streaming responses - if ( - isinstance(model_response, ModelResponseStream) - and reasoning_content is None - ): + if isinstance(model_response, ModelResponseStream) and reasoning_content is None: reasoning_content_parts = [] for block in thinking_blocks: thinking_text = block.get("thinking") @@ -2544,17 +2317,15 @@ def _process_candidates( if thought_signatures is not None: if "provider_specific_fields" not in chat_completion_message: chat_completion_message["provider_specific_fields"] = {} - chat_completion_message["provider_specific_fields"][ - "thought_signatures" - ] = thought_signatures # type: ignore + chat_completion_message["provider_specific_fields"]["thought_signatures"] = thought_signatures # type: ignore # Store server-side tool invocations in provider_specific_fields if server_side_tool_invocations is not None: if "provider_specific_fields" not in chat_completion_message: chat_completion_message["provider_specific_fields"] = {} - chat_completion_message["provider_specific_fields"][ - "server_side_tool_invocations" - ] = server_side_tool_invocations # type: ignore + chat_completion_message["provider_specific_fields"]["server_side_tool_invocations"] = ( + server_side_tool_invocations # type: ignore + ) if isinstance(model_response, ModelResponseStream): choice = VertexGeminiConfig._create_streaming_choice( @@ -2647,10 +2418,7 @@ def _transform_google_generate_content_to_openai_model_response( model_response.model = model ## CHECK IF RESPONSE FLAGGED - if ( - "promptFeedback" in completion_response - and "blockReason" in completion_response["promptFeedback"] - ): + if "promptFeedback" in completion_response and "blockReason" in completion_response["promptFeedback"]: return self._handle_blocked_response( model_response=model_response, completion_response=completion_response, @@ -2658,13 +2426,8 @@ def _transform_google_generate_content_to_openai_model_response( _candidates = completion_response.get("candidates") if _candidates and len(_candidates) > 0: - content_policy_violations = ( - VertexGeminiConfig().get_flagged_finish_reasons() - ) - if ( - "finishReason" in _candidates[0] - and _candidates[0]["finishReason"] in content_policy_violations.keys() - ): + content_policy_violations = VertexGeminiConfig().get_flagged_finish_reasons() + if "finishReason" in _candidates[0] and _candidates[0]["finishReason"] in content_policy_violations.keys(): return self._handle_content_policy_violation( model_response=model_response, completion_response=completion_response, @@ -2686,38 +2449,24 @@ def _transform_google_generate_content_to_openai_model_response( safety_ratings, citation_metadata, _, # cumulative_tool_call_index not needed in non-streaming - ) = VertexGeminiConfig._process_candidates( - _candidates, model_response, logging_obj.optional_params - ) + ) = VertexGeminiConfig._process_candidates(_candidates, model_response, logging_obj.optional_params) - usage = VertexGeminiConfig._calculate_usage( - completion_response=completion_response - ) + usage = VertexGeminiConfig._calculate_usage(completion_response=completion_response) - web_search_requests = VertexGeminiConfig._calculate_web_search_requests( - grounding_metadata - ) + web_search_requests = VertexGeminiConfig._calculate_web_search_requests(grounding_metadata) if web_search_requests is not None: - cast( - PromptTokensDetailsWrapper, usage.prompt_tokens_details - ).web_search_requests = web_search_requests + cast(PromptTokensDetailsWrapper, usage.prompt_tokens_details).web_search_requests = web_search_requests setattr(model_response, "usage", usage) ## ADD METADATA TO RESPONSE ## setattr(model_response, "vertex_ai_grounding_metadata", grounding_metadata) - model_response._hidden_params["vertex_ai_grounding_metadata"] = ( - grounding_metadata - ) + model_response._hidden_params["vertex_ai_grounding_metadata"] = grounding_metadata - setattr( - model_response, "vertex_ai_url_context_metadata", url_context_metadata - ) + setattr(model_response, "vertex_ai_url_context_metadata", url_context_metadata) - model_response._hidden_params["vertex_ai_url_context_metadata"] = ( - url_context_metadata - ) + model_response._hidden_params["vertex_ai_url_context_metadata"] = url_context_metadata setattr(model_response, "vertex_ai_safety_results", safety_ratings) model_response._hidden_params["vertex_ai_safety_results"] = ( @@ -2731,13 +2480,9 @@ def _transform_google_generate_content_to_openai_model_response( ) ## ADD TRAFFIC TYPE ## - traffic_type = completion_response.get("usageMetadata", {}).get( - "trafficType" - ) + traffic_type = completion_response.get("usageMetadata", {}).get("trafficType") if traffic_type: - model_response._hidden_params.setdefault( - "provider_specific_fields", {} - )["traffic_type"] = traffic_type + model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type ## ADD SERVICE TIER ## if getattr(raw_response, "headers", None): @@ -2774,9 +2519,7 @@ def _transform_messages( def get_error_class( self, error_message: str, status_code: int, headers: Union[Dict, httpx.Headers] ) -> BaseLLMException: - return VertexAIError( - message=error_message, status_code=status_code, headers=headers - ) + return VertexAIError(message=error_message, status_code=status_code, headers=headers) def transform_request( self, @@ -2786,9 +2529,7 @@ def transform_request( litellm_params: Dict, headers: Dict, ) -> Dict: - raise NotImplementedError( - "Vertex AI has a custom implementation of transform_request. Needs sync + async." - ) + raise NotImplementedError("Vertex AI has a custom implementation of transform_request. Needs sync + async.") def validate_environment( self, @@ -2831,9 +2572,7 @@ async def make_call( ) try: - response = await client.post( - api_base, headers=headers, data=data, stream=True, logging_obj=logging_obj - ) + response = await client.post(api_base, headers=headers, data=data, stream=True, logging_obj=logging_obj) response.raise_for_status() except httpx.HTTPStatusError as e: exception_string = str(await e.response.aread()) @@ -2882,9 +2621,7 @@ def make_sync_call( if client is None: client = HTTPHandler() # Create a new client if none provided - response = client.post( - api_base, headers=headers, data=data, stream=True, logging_obj=logging_obj - ) + response = client.post(api_base, headers=headers, data=data, stream=True, logging_obj=logging_obj) if response.status_code != 200 and response.status_code != 201: raise VertexAIError( @@ -2941,9 +2678,7 @@ async def async_streaming( gemini_api_key: Optional[str] = None, extra_headers: Optional[dict] = None, ) -> CustomStreamWrapper: - should_use_v1beta1_features = self.is_using_v1beta1_features( - optional_params=optional_params - ) + should_use_v1beta1_features = self.is_using_v1beta1_features(optional_params=optional_params) _auth_header, vertex_project = await self._ensure_access_token_async( credentials=vertex_credentials, @@ -3000,11 +2735,7 @@ async def async_streaming( completion_stream=None, make_call=partial( make_call, - gemini_client=( - client - if client is not None and isinstance(client, AsyncHTTPHandler) - else None - ), + gemini_client=(client if client is not None and isinstance(client, AsyncHTTPHandler) else None), api_base=api_base, headers=headers, data=request_body_str, @@ -3043,9 +2774,7 @@ async def async_completion( gemini_api_key: Optional[str] = None, extra_headers: Optional[dict] = None, ) -> Union[ModelResponse, CustomStreamWrapper]: - should_use_v1beta1_features = self.is_using_v1beta1_features( - optional_params=optional_params - ) + should_use_v1beta1_features = self.is_using_v1beta1_features(optional_params=optional_params) _auth_header, vertex_project = await self._ensure_access_token_async( credentials=vertex_credentials, @@ -3090,9 +2819,7 @@ async def async_completion( if timeout: _async_client_params["timeout"] = timeout if client is None or not isinstance(client, AsyncHTTPHandler): - client = get_async_httpx_client( - params=_async_client_params, llm_provider=litellm.LlmProviders.VERTEX_AI - ) + client = get_async_httpx_client(params=_async_client_params, llm_provider=litellm.LlmProviders.VERTEX_AI) else: client = client # type: ignore ## LOGGING @@ -3231,9 +2958,7 @@ def completion( extra_headers=extra_headers, ) - should_use_v1beta1_features = self.is_using_v1beta1_features( - optional_params=optional_params - ) + should_use_v1beta1_features = self.is_using_v1beta1_features(optional_params=optional_params) _auth_header, vertex_project = self._ensure_access_token( credentials=vertex_credentials, @@ -3292,11 +3017,7 @@ def completion( completion_stream=None, make_call=partial( make_sync_call, - gemini_client=( - client - if client is not None and isinstance(client, HTTPHandler) - else None - ), + gemini_client=(client if client is not None and isinstance(client, HTTPHandler) else None), api_base=url, data=request_data_str, model=model, @@ -3323,9 +3044,7 @@ def completion( client = client try: - response = client.post( - url=url, headers=headers, json=data, logging_obj=logging_obj - ) # type: ignore + response = client.post(url=url, headers=headers, json=data, logging_obj=logging_obj) # type: ignore response.raise_for_status() except httpx.HTTPStatusError as err: error_code = err.response.status_code @@ -3428,11 +3147,7 @@ def _apply_stream_candidates( # to correctly set finish_reason="tool_calls" per the OpenAI spec. if not self.has_seen_tool_calls: for choice in model_response.choices: - if ( - hasattr(choice, "delta") - and choice.delta - and choice.delta.tool_calls - ): + if hasattr(choice, "delta") and choice.delta and choice.delta.tool_calls: self.has_seen_tool_calls = True break @@ -3452,9 +3167,7 @@ def _apply_stream_candidates( if self.has_seen_tool_calls: mapped_finish_reason = "tool_calls" else: - mapped_finish_reason = VertexGeminiConfig._check_finish_reason( - None, finish_reason_str - ) + mapped_finish_reason = VertexGeminiConfig._check_finish_reason(None, finish_reason_str) choice = StreamingChoices( finish_reason=mapped_finish_reason, index=candidate.get("index", 0), @@ -3502,19 +3215,13 @@ def _apply_stream_usage_metadata( completion_response=processed_chunk, ) - web_search_requests = VertexGeminiConfig._calculate_web_search_requests( - grounding_metadata - ) + web_search_requests = VertexGeminiConfig._calculate_web_search_requests(grounding_metadata) if web_search_requests is not None: - cast( - PromptTokensDetailsWrapper, usage.prompt_tokens_details - ).web_search_requests = web_search_requests + cast(PromptTokensDetailsWrapper, usage.prompt_tokens_details).web_search_requests = web_search_requests traffic_type = processed_chunk.get("usageMetadata", {}).get("trafficType") if traffic_type: - model_response._hidden_params.setdefault("provider_specific_fields", {})[ - "traffic_type" - ] = traffic_type + model_response._hidden_params.setdefault("provider_specific_fields", {})["traffic_type"] = traffic_type service_tier = self.response_headers.get("x-gemini-service-tier") if service_tier: @@ -3561,9 +3268,7 @@ def chunk_parser(self, chunk: dict) -> Optional["ModelResponseStream"]: citation_metadata, ) = self._apply_stream_candidates(_candidates, model_response) - usage = self._apply_stream_usage_metadata( - processed_chunk, model_response, grounding_metadata - ) + usage = self._apply_stream_usage_metadata(processed_chunk, model_response, grounding_metadata) setattr(model_response, "usage", usage) # type: ignore @@ -3595,9 +3300,7 @@ def handle_valid_json_chunk(self, chunk: str) -> Optional["ModelResponseStream"] return self.chunk_parser(chunk=json_chunk) - def handle_accumulated_json_chunk( - self, chunk: str - ) -> Optional["ModelResponseStream"]: + def handle_accumulated_json_chunk(self, chunk: str) -> Optional["ModelResponseStream"]: chunk = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(chunk) or "" message = chunk.replace("\n\n", "") @@ -3619,9 +3322,7 @@ def handle_accumulated_json_chunk( except json.JSONDecodeError: return None - def _common_chunk_parsing_logic( - self, chunk: str - ) -> Optional["ModelResponseStream"]: + def _common_chunk_parsing_logic(self, chunk: str) -> Optional["ModelResponseStream"]: try: chunk = litellm.CustomStreamWrapper._strip_sse_data_from_chunk(chunk) or "" if len(chunk) > 0: @@ -3688,16 +3389,12 @@ async def aclose(self) -> None: try: await iterator.aclose() except Exception as e: # noqa: BLE001 - verbose_logger.debug( - "ModelResponseIterator.aclose: error closing iterator: %s", e - ) + verbose_logger.debug("ModelResponseIterator.aclose: error closing iterator: %s", e) if self.response is not None: try: await self.response.aclose() except Exception as e: # noqa: BLE001 - verbose_logger.debug( - "ModelResponseIterator.aclose: error closing response: %s", e - ) + verbose_logger.debug("ModelResponseIterator.aclose: error closing response: %s", e) def close(self) -> None: iterator = getattr(self, "response_iterator", self.streaming_response) @@ -3705,13 +3402,9 @@ def close(self) -> None: try: iterator.close() except Exception as e: # noqa: BLE001 - verbose_logger.debug( - "ModelResponseIterator.close: error closing iterator: %s", e - ) + verbose_logger.debug("ModelResponseIterator.close: error closing iterator: %s", e) if self.response is not None: try: self.response.close() except Exception as e: # noqa: BLE001 - verbose_logger.debug( - "ModelResponseIterator.close: error closing response: %s", e - ) + verbose_logger.debug("ModelResponseIterator.close: error closing response: %s", e) diff --git a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py index 53f5fb464dfc..d989750a5f38 100644 --- a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py +++ b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_handler.py @@ -38,10 +38,7 @@ def _flatten_and_detect_file_refs( """Flatten nested input lists and detect file references.""" input_list = [input] if isinstance(input, str) else input flat_elements = [ - e - for item in input_list - for e in (item if isinstance(item, list) else [item]) - if isinstance(e, str) + e for item in input_list for e in (item if isinstance(item, list) else [item]) if isinstance(e, str) ] has_file_refs = any(_is_file_reference(e) for e in flat_elements) return flat_elements, has_file_refs @@ -73,9 +70,7 @@ def _resolve_file_references( response = sync_handler.get(url=url, headers=headers) if response.status_code != 200: - raise Exception( - f"Error fetching file {element}: {response.status_code} {response.text}" - ) + raise Exception(f"Error fetching file {element}: {response.status_code} {response.text}") file_data = response.json() resolved_files[element] = { @@ -112,9 +107,7 @@ async def _async_resolve_file_references( response = await async_handler.get(url=url, headers=headers) if response.status_code != 200: - raise Exception( - f"Error fetching file {element}: {response.status_code} {response.text}" - ) + raise Exception(f"Error fetching file {element}: {response.status_code} {response.text}") file_data = response.json() resolved_files[element] = { @@ -218,9 +211,7 @@ def batch_embeddings( if use_embed_content: resolved_files = {} if api_key: - resolved_files = self._resolve_file_references( - input=input, api_key=api_key, sync_handler=sync_handler - ) + resolved_files = self._resolve_file_references(input=input, api_key=api_key, sync_handler=sync_handler) request_data = transform_openai_input_gemini_embed_content( input=input, model=model, diff --git a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py index 27ca1bd92a4e..fd08fdf4c8c3 100644 --- a/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py +++ b/litellm/llms/vertex_ai/gemini_embeddings/batch_embed_content_transformation.py @@ -140,9 +140,7 @@ def _is_multimodal_input(input: GeminiEmbeddingInput) -> bool: for element in input: if isinstance(element, list): - if any( - _is_multimodal_element(sub) for sub in element if isinstance(sub, str) - ): + if any(_is_multimodal_element(sub) for sub in element if isinstance(sub, str)): return True elif isinstance(element, str) and _is_multimodal_element(element): return True @@ -242,13 +240,8 @@ def transform_openai_input_gemini_content( raise ValueError("Nested input list must not be empty") for sub in element: if not isinstance(sub, str): - raise ValueError( - f"Elements inside a nested input list must be strings, got {type(sub)}" - ) - parts = [ - _build_part_for_input(sub, resolved_files=resolved_files) - for sub in element - ] + raise ValueError(f"Elements inside a nested input list must be strings, got {type(sub)}") + parts = [_build_part_for_input(sub, resolved_files=resolved_files) for sub in element] else: parts = [_build_part_for_input(element, resolved_files=resolved_files)] request = EmbedContentRequest( @@ -322,11 +315,7 @@ def _parse_usage_metadata(raw_usage_metadata: object) -> Optional[UsageMetadata] def _flatten_input(input: GeminiEmbeddingInput) -> tuple[str, ...]: if isinstance(input, str): return (input,) - return tuple( - sub - for element in input - for sub in (element if isinstance(element, list) else [element]) - ) + return tuple(sub for element in input for sub in (element if isinstance(element, list) else [element])) def _is_image_element( @@ -354,17 +343,11 @@ def _count_input_images( input: GeminiEmbeddingInput, resolved_files: Mapping[str, Mapping[str, str]], ) -> int: - return sum( - 1 - for element in _flatten_input(input) - if _is_image_element(element, resolved_files) - ) + return sum(1 for element in _flatten_input(input) if _is_image_element(element, resolved_files)) def _tokens_for_modality(details: Sequence[PromptTokensDetails], modality: str) -> int: - return sum( - detail["tokenCount"] for detail in details if detail["modality"] == modality - ) + return sum(detail["tokenCount"] for detail in details if detail["modality"] == modality) def _fallback_usage(input: GeminiEmbeddingInput, model: str) -> Usage: @@ -388,28 +371,20 @@ def _usage_from_embed_content_response( prompt_tokens = usage_metadata.get("promptTokenCount", 0) total_tokens = usage_metadata.get("totalTokenCount") or prompt_tokens - details: Sequence[PromptTokensDetails] = ( - usage_metadata.get("promptTokensDetails") or () - ) + details: Sequence[PromptTokensDetails] = usage_metadata.get("promptTokensDetails") or () text_tokens = _tokens_for_modality(details, "TEXT") audio_tokens = _tokens_for_modality(details, "AUDIO") video_tokens = _tokens_for_modality(details, "VIDEO") image_count = _count_input_images(input, resolved_files) - video_length_seconds = ( - video_tokens / _VIDEO_TOKENS_PER_SECOND if video_tokens > 0 else 0.0 - ) - audio_length_seconds = ( - audio_tokens / _AUDIO_TOKENS_PER_SECOND if audio_tokens > 0 else 0.0 - ) + video_length_seconds = video_tokens / _VIDEO_TOKENS_PER_SECOND if video_tokens > 0 else 0.0 + audio_length_seconds = audio_tokens / _AUDIO_TOKENS_PER_SECOND if audio_tokens > 0 else 0.0 # generic_cost_per_token rewrites text_tokens to the full prompt minus # other modalities when both text_tokens and image_count are zero. For # video, that misallocates video tokens to text; a 1-token floor sidesteps # the rewrite and keeps billing on input_cost_per_video_per_second. - needs_video_text_floor = ( - video_length_seconds > 0 and text_tokens == 0 and image_count == 0 - ) + needs_video_text_floor = video_length_seconds > 0 and text_tokens == 0 and image_count == 0 resolved_text_tokens = 1 if needs_video_text_floor else text_tokens return Usage( @@ -447,9 +422,7 @@ def process_embed_content_response( EmbeddingResponse with single embedding """ if "embedding" not in response_json: - raise ValueError( - f"embedContent response missing 'embedding' field: {response_json}" - ) + raise ValueError(f"embedContent response missing 'embedding' field: {response_json}") embedding_data = response_json["embedding"] @@ -495,25 +468,17 @@ def process_response( text_elements: List[str] = [] for e in input_list: if isinstance(e, list): - text_elements.extend( - sub - for sub in e - if isinstance(sub, str) and not _is_multimodal_element(sub) - ) + text_elements.extend(sub for sub in e if isinstance(sub, str) and not _is_multimodal_element(sub)) elif isinstance(e, str) and not _is_multimodal_element(e): text_elements.append(e) if text_elements: - input_text = get_formatted_prompt( - data={"input": text_elements}, call_type="embedding" - ) + input_text = get_formatted_prompt(data={"input": text_elements}, call_type="embedding") prompt_tokens = token_counter(model=model, text=input_text) else: prompt_tokens = 0 else: input_text = get_formatted_prompt(data={"input": input}, call_type="embedding") prompt_tokens = token_counter(model=model, text=input_text) - model_response.usage = Usage( - prompt_tokens=prompt_tokens, total_tokens=prompt_tokens - ) + model_response.usage = Usage(prompt_tokens=prompt_tokens, total_tokens=prompt_tokens) return model_response diff --git a/litellm/llms/vertex_ai/image_edit/cost_calculator.py b/litellm/llms/vertex_ai/image_edit/cost_calculator.py index b346622a3360..6e951624081c 100644 --- a/litellm/llms/vertex_ai/image_edit/cost_calculator.py +++ b/litellm/llms/vertex_ai/image_edit/cost_calculator.py @@ -26,9 +26,7 @@ def cost_calculator( output_cost_per_image: float = model_info.get("output_cost_per_image") or 0.0 if not isinstance(image_response, ImageResponse): - raise ValueError( - f"image_response must be of type ImageResponse got type={type(image_response)}" - ) + raise ValueError(f"image_response must be of type ImageResponse got type={type(image_response)}") num_images = len(image_response.data or []) return output_cost_per_image * num_images diff --git a/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py index de7f234a861f..a2020149ef2c 100644 --- a/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py +++ b/litellm/llms/vertex_ai/image_edit/vertex_gemini_transformation.py @@ -48,11 +48,7 @@ def map_openai_params( drop_params: bool, ) -> Dict[str, Any]: supported_params = self.get_supported_openai_params(model) - filtered_params = { - key: value - for key, value in image_edit_optional_params.items() - if key in supported_params - } + filtered_params = {key: value for key, value in image_edit_optional_params.items() if key in supported_params} mapped_params: Dict[str, Any] = {} @@ -109,14 +105,8 @@ def validate_environment( # First check litellm_params (where vertex_ai_project/vertex_ai_credentials are passed) # then fall back to environment variables and other sources - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_credentials = ( - self.safe_get_vertex_ai_credentials(litellm_params) - or self._resolve_vertex_credentials() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -145,19 +135,11 @@ def get_complete_url( # First check litellm_params (where vertex_ai_project/vertex_ai_location are passed) # then fall back to environment variables and other sources - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_location = ( - self.safe_get_vertex_ai_location(litellm_params) - or self._resolve_vertex_location() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() if not vertex_project or not vertex_location: - raise ValueError( - "vertex_project and vertex_location are required for Vertex AI" - ) + raise ValueError("vertex_project and vertex_location are required for Vertex AI") base_url = get_vertex_base_url(vertex_location) @@ -192,9 +174,7 @@ def transform_image_edit_request( # type: ignore[override] # Add image-specific configuration image_config: Dict[str, Any] = {} if "aspectRatio" in image_edit_optional_request_params: - image_config["aspect_ratio"] = image_edit_optional_request_params[ - "aspectRatio" - ] + image_config["aspect_ratio"] = image_edit_optional_request_params["aspectRatio"] if image_config: generation_config["image_config"] = image_config @@ -203,9 +183,7 @@ def transform_image_edit_request( # type: ignore[override] payload: Any = json.dumps(request_body) empty_files = cast(RequestFiles, []) - return cast( - Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files) - ) + return cast(Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files)) def transform_image_edit_response( self, @@ -253,9 +231,7 @@ def _map_size_to_aspect_ratio(self, size: str) -> str: } return aspect_ratio_map.get(size, "1:1") - def _prepare_inline_image_parts( - self, image: Union[FileTypes, List[FileTypes]] - ) -> List[Dict[str, Any]]: + def _prepare_inline_image_parts(self, image: Union[FileTypes, List[FileTypes]]) -> List[Dict[str, Any]]: images: List[FileTypes] if isinstance(image, list): images = image diff --git a/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py b/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py index 3eb039614fd0..d9127a1929f6 100644 --- a/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py +++ b/litellm/llms/vertex_ai/image_edit/vertex_imagen_transformation.py @@ -49,11 +49,7 @@ def map_openai_params( drop_params: bool, ) -> Dict[str, Any]: supported_params = self.get_supported_openai_params(model) - filtered_params = { - key: value - for key, value in image_edit_optional_params.items() - if key in supported_params - } + filtered_params = {key: value for key, value in image_edit_optional_params.items() if key in supported_params} mapped_params: Dict[str, Any] = {} @@ -113,14 +109,8 @@ def validate_environment( if _api_base is not None: return headers - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_credentials = ( - self.safe_get_vertex_ai_credentials(litellm_params) - or self._resolve_vertex_credentials() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -137,19 +127,11 @@ def get_complete_url( """ Get the complete URL for Vertex AI Imagen predict API """ - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_location = ( - self.safe_get_vertex_ai_location(litellm_params) - or self._resolve_vertex_location() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() if not vertex_project or not vertex_location: - raise ValueError( - "vertex_project and vertex_location are required for Vertex AI" - ) + raise ValueError("vertex_project and vertex_location are required for Vertex AI") # Use the model name as provided, handling vertex_ai prefix model_name = model @@ -174,16 +156,10 @@ def transform_image_edit_request( # type: ignore[override] ) -> Tuple[Dict[str, Any], Optional[RequestFiles]]: # Prepare reference images in the correct Imagen format if image is None: - raise ValueError( - "Vertex AI Imagen image edit requires at least one reference image." - ) - reference_images = self._prepare_reference_images( - image, image_edit_optional_request_params - ) + raise ValueError("Vertex AI Imagen image edit requires at least one reference image.") + reference_images = self._prepare_reference_images(image, image_edit_optional_request_params) if not reference_images: - raise ValueError( - "Vertex AI Imagen image edit requires at least one reference image." - ) + raise ValueError("Vertex AI Imagen image edit requires at least one reference image.") if prompt is None: raise ValueError("Vertex AI Imagen image edit requires a prompt.") @@ -215,9 +191,7 @@ def transform_image_edit_request( # type: ignore[override] payload: Any = json.dumps(request_body) empty_files = cast(RequestFiles, []) - return cast( - Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files) - ) + return cast(Tuple[Dict[str, Any], Optional[RequestFiles]], (payload, empty_files)) def transform_image_edit_response( self, @@ -313,9 +287,7 @@ def _prepare_reference_images( return reference_images - def _read_all_bytes( - self, image: Any, depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH - ) -> bytes: + def _read_all_bytes(self, image: Any, depth: int = 0, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> bytes: if depth > max_depth: raise ValueError( f"Max recursion depth {max_depth} reached while reading image bytes for Vertex AI Imagen image edit." @@ -324,9 +296,7 @@ def _read_all_bytes( if isinstance(image, (list, tuple)): for item in image: if item is not None: - return self._read_all_bytes( - item, depth=depth + 1, max_depth=max_depth - ) + return self._read_all_bytes(item, depth=depth + 1, max_depth=max_depth) raise ValueError("Unsupported image type for Vertex AI Imagen image edit.") if isinstance(image, dict): @@ -338,13 +308,9 @@ def _read_all_bytes( return base64.b64decode(value) except Exception: continue - return self._read_all_bytes( - value, depth=depth + 1, max_depth=max_depth - ) + return self._read_all_bytes(value, depth=depth + 1, max_depth=max_depth) if "path" in image: - return self._read_all_bytes( - image["path"], depth=depth + 1, max_depth=max_depth - ) + return self._read_all_bytes(image["path"], depth=depth + 1, max_depth=max_depth) if isinstance(image, bytes): return image @@ -383,6 +349,4 @@ def _read_all_bytes( if isinstance(data, str): data = data.encode("utf-8") return data - raise ValueError( - f"Unsupported image type for Vertex AI Imagen image edit. Got type={type(image)}" - ) + raise ValueError(f"Unsupported image type for Vertex AI Imagen image edit. Got type={type(image)}") diff --git a/litellm/llms/vertex_ai/image_generation/image_generation_handler.py b/litellm/llms/vertex_ai/image_generation/image_generation_handler.py index e14cfe3be0b5..d265352ca0ac 100644 --- a/litellm/llms/vertex_ai/image_generation/image_generation_handler.py +++ b/litellm/llms/vertex_ai/image_generation/image_generation_handler.py @@ -131,9 +131,7 @@ def image_generation( should_use_v1beta1_features=False, mode="image_generation", ) - optional_params = optional_params or { - "sampleCount": 1 - } # default optional params + optional_params = optional_params or {"sampleCount": 1} # default optional params # Transform optional params to camelCase format optional_params = self.transform_optional_params(optional_params) @@ -165,9 +163,7 @@ def image_generation( raise Exception(f"Error: {response.status_code} {response.text}") json_response = response.json() - return self.process_image_generation_response( - json_response, model_response, model - ) + return self.process_image_generation_response(json_response, model_response, model) async def aimage_generation( self, @@ -271,9 +267,7 @@ async def aimage_generation( raise Exception(f"Error: {response.status_code} {response.text}") json_response = response.json() - return self.process_image_generation_response( - json_response, model_response, model - ) + return self.process_image_generation_response(json_response, model_response, model) def is_image_generation_response(self, json_response: Dict[str, Any]) -> bool: if "predictions" in json_response: diff --git a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py index 103c7b2a28a4..39503bd78ddd 100644 --- a/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py +++ b/litellm/llms/vertex_ai/image_generation/vertex_gemini_transformation.py @@ -153,19 +153,11 @@ def get_complete_url( # First check litellm_params (where vertex_ai_project/vertex_ai_location are passed) # then fall back to environment variables and other sources - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_location = ( - self.safe_get_vertex_ai_location(litellm_params) - or self._resolve_vertex_location() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() if not vertex_project or not vertex_location: - raise ValueError( - "vertex_project and vertex_location are required for Vertex AI" - ) + raise ValueError("vertex_project and vertex_location are required for Vertex AI") base_url = get_vertex_base_url(vertex_location) @@ -191,14 +183,8 @@ def validate_environment( # First check litellm_params (where vertex_ai_project/vertex_ai_credentials are passed) # then fall back to environment variables and other sources - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_credentials = ( - self.safe_get_vertex_ai_credentials(litellm_params) - or self._resolve_vertex_credentials() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, @@ -325,11 +311,7 @@ def transform_image_generation_response( ImageObject( b64_json=inline_data["data"], url=None, - provider_specific_fields=( - {"thought_signature": thought_sig} - if thought_sig - else None - ), + provider_specific_fields=({"thought_signature": thought_sig} if thought_sig else None), ) ) diff --git a/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py b/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py index 05ebd685d916..2cd3df010d6b 100644 --- a/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py +++ b/litellm/llms/vertex_ai/image_generation/vertex_imagen_transformation.py @@ -39,9 +39,7 @@ def __init__(self) -> None: BaseImageGenerationConfig.__init__(self) VertexLLM.__init__(self) - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: """ Imagen API supported parameters """ @@ -135,19 +133,11 @@ def get_complete_url( # First check litellm_params (where vertex_ai_project/vertex_ai_location are passed) # then fall back to environment variables and other sources - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_location = ( - self.safe_get_vertex_ai_location(litellm_params) - or self._resolve_vertex_location() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_location = self.safe_get_vertex_ai_location(litellm_params) or self._resolve_vertex_location() if not vertex_project or not vertex_location: - raise ValueError( - "vertex_project and vertex_location are required for Vertex AI" - ) + raise ValueError("vertex_project and vertex_location are required for Vertex AI") base_url = get_vertex_base_url(vertex_location) @@ -173,14 +163,8 @@ def validate_environment( # First check litellm_params (where vertex_ai_project/vertex_ai_credentials are passed) # then fall back to environment variables and other sources - vertex_project = ( - self.safe_get_vertex_ai_project(litellm_params) - or self._resolve_vertex_project() - ) - vertex_credentials = ( - self.safe_get_vertex_ai_credentials(litellm_params) - or self._resolve_vertex_credentials() - ) + vertex_project = self.safe_get_vertex_ai_project(litellm_params) or self._resolve_vertex_project() + vertex_credentials = self.safe_get_vertex_ai_credentials(litellm_params) or self._resolve_vertex_credentials() access_token, _ = self._ensure_access_token( credentials=vertex_credentials, project_id=vertex_project, diff --git a/litellm/llms/vertex_ai/multimodal_embeddings/transformation.py b/litellm/llms/vertex_ai/multimodal_embeddings/transformation.py index f1d121099f92..4bcfdee2d179 100644 --- a/litellm/llms/vertex_ai/multimodal_embeddings/transformation.py +++ b/litellm/llms/vertex_ai/multimodal_embeddings/transformation.py @@ -75,11 +75,7 @@ def _create_image_instance(self, input_str: str) -> InstanceImage: if self._is_gcs_uri(input_str): return InstanceImage(gcsUri=input_str) else: - return InstanceImage( - bytesBase64Encoded=( - input_str.split(",")[1] if "," in input_str else input_str - ) - ) + return InstanceImage(bytesBase64Encoded=(input_str.split(",")[1] if "," in input_str else input_str)) def _create_video_instance(self, input_str: str) -> InstanceVideo: """Create an InstanceVideo from a GCS URI.""" @@ -108,9 +104,7 @@ def _process_input_element(self, input_element: str) -> Instance: else: return Instance(text=input_element) - def _try_merge_text_with_media( - self, text_str: str, next_elem: Optional[str] - ) -> tuple[Instance, bool]: + def _try_merge_text_with_media(self, text_str: str, next_elem: Optional[str]) -> tuple[Instance, bool]: """ Try to merge a text element with a following media element into a single instance. @@ -133,9 +127,7 @@ def _try_merge_text_with_media( return instance_args, False - def process_openai_embedding_input( - self, _input: Union[list, str] - ) -> List[Instance]: + def process_openai_embedding_input(self, _input: Union[list, str]) -> List[Instance]: """ Process the input for multimodal embedding requests. @@ -160,9 +152,7 @@ def process_openai_embedding_input( i += 1 else: # Current element is text - try to merge with next media element - instance, consumed_next = self._try_merge_text_with_media( - text_str=current, next_elem=next_elem - ) + instance, consumed_next = self._try_merge_text_with_media(text_str=current, next_elem=next_elem) processed_instances.append(instance) i += 2 if consumed_next else 1 elif isinstance(current, dict): @@ -187,9 +177,7 @@ def transform_embedding_request( if "instances" in optional_params: request_data["instances"] = optional_params["instances"] elif isinstance(input, list): - vertex_instances: List[Instance] = self.process_openai_embedding_input( - _input=input - ) + vertex_instances: List[Instance] = self.process_openai_embedding_input(_input=input) request_data["instances"] = vertex_instances else: @@ -202,9 +190,7 @@ def transform_embedding_request( request_data["instances"] = [vertex_request_instance] if "outputDimensionality" in optional_params: - request_data["parameters"] = { - "dimension": optional_params["outputDimensionality"] - } + request_data["parameters"] = {"dimension": optional_params["outputDimensionality"]} return cast(dict, request_data) @@ -231,9 +217,7 @@ def transform_embedding_response( ) _predictions = _json_response["predictions"] vertex_predictions = MultimodalPredictions(predictions=_predictions) - model_response.data = self.transform_embedding_response_to_openai( - predictions=vertex_predictions - ) + model_response.data = self.transform_embedding_response_to_openai(predictions=vertex_predictions) model_response.model = model model_response.usage = self.calculate_usage( @@ -291,9 +275,7 @@ def calculate_usage( prompt_tokens_details=prompt_tokens_details, ) - def transform_embedding_response_to_openai( - self, predictions: MultimodalPredictions - ) -> List[Embedding]: + def transform_embedding_response_to_openai(self, predictions: MultimodalPredictions) -> List[Embedding]: openai_embeddings: List[Embedding] = [] if "predictions" in predictions: for idx, _prediction in enumerate(predictions["predictions"]): @@ -322,9 +304,5 @@ def transform_embedding_response_to_openai( openai_embeddings.append(openai_embedding_object) return openai_embeddings - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, Headers] - ) -> BaseLLMException: - return VertexAIError( - status_code=status_code, message=error_message, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, Headers]) -> BaseLLMException: + return VertexAIError(status_code=status_code, message=error_message, headers=headers) diff --git a/litellm/llms/vertex_ai/ocr/deepseek_transformation.py b/litellm/llms/vertex_ai/ocr/deepseek_transformation.py index a98311d04eb1..68836a64027e 100644 --- a/litellm/llms/vertex_ai/ocr/deepseek_transformation.py +++ b/litellm/llms/vertex_ai/ocr/deepseek_transformation.py @@ -66,12 +66,8 @@ def validate_environment( # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - vertex_project = VertexBase.safe_get_vertex_ai_project( - litellm_params=litellm_params - ) - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( - litellm_params=litellm_params - ) + vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=litellm_params) # Get access token from Vertex credentials access_token, project_id = self.vertex_base.get_access_token( @@ -110,12 +106,8 @@ def get_complete_url( # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - vertex_project = VertexBase.safe_get_vertex_ai_project( - litellm_params=litellm_params - ) - vertex_location = VertexBase.safe_get_vertex_ai_location( - litellm_params=litellm_params - ) + vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) + vertex_location = VertexBase.safe_get_vertex_ai_location(litellm_params=litellm_params) if vertex_project is None: raise ValueError( @@ -159,9 +151,7 @@ def transform_ocr_request( Returns: OCRRequestData with JSON data for the DeepSeek OCR endpoint """ - verbose_logger.debug( - "Vertex AI DeepSeek OCR transform_ocr_request (sync) called" - ) + verbose_logger.debug("Vertex AI DeepSeek OCR transform_ocr_request (sync) called") if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") @@ -176,9 +166,7 @@ def transform_ocr_request( elif doc_type == "document_url": document_url = document.get("document_url", "") else: - raise ValueError( - f"Unsupported document type: {doc_type}. Expected 'image_url' or 'document_url'" - ) + raise ValueError(f"Unsupported document type: {doc_type}. Expected 'image_url' or 'document_url'") # Build DeepSeek OCR message content content_item = {} @@ -317,17 +305,11 @@ def transform_ocr_response( "pages": [ { "index": 0, - "markdown": ( - content - if isinstance(content, str) - else json.dumps(content) - ), + "markdown": (content if isinstance(content, str) else json.dumps(content)), } ], "model": ocr_data.get("model", model), - "usage_info": ocr_data.get( - "usage_info", response_json.get("usage", {}) - ), + "usage_info": ocr_data.get("usage_info", response_json.get("usage", {})), } # Convert usage info if present @@ -352,11 +334,7 @@ def transform_ocr_response( if not pages: # Create a default page if none exist - pages = [ - OCRPage( - index=0, markdown=content if isinstance(content, str) else "" - ) - ] + pages = [OCRPage(index=0, markdown=content if isinstance(content, str) else "")] return OCRResponse( pages=pages, diff --git a/litellm/llms/vertex_ai/ocr/transformation.py b/litellm/llms/vertex_ai/ocr/transformation.py index a725762b3c5c..d67c5f2b0891 100644 --- a/litellm/llms/vertex_ai/ocr/transformation.py +++ b/litellm/llms/vertex_ai/ocr/transformation.py @@ -62,12 +62,8 @@ def validate_environment( # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - vertex_project = VertexBase.safe_get_vertex_ai_project( - litellm_params=litellm_params - ) - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( - litellm_params=litellm_params - ) + vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=litellm_params) # Get access token from Vertex credentials access_token, project_id = self.vertex_base.get_access_token( @@ -109,12 +105,8 @@ def get_complete_url( # Use safe_get_* methods that don't mutate litellm_params dict litellm_params = litellm_params or {} - vertex_project = VertexBase.safe_get_vertex_ai_project( - litellm_params=litellm_params - ) - vertex_location = VertexBase.safe_get_vertex_ai_location( - litellm_params=litellm_params - ) + vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=litellm_params) + vertex_location = VertexBase.safe_get_vertex_ai_location(litellm_params=litellm_params) if vertex_project is None: raise ValueError( @@ -148,17 +140,13 @@ def _convert_url_to_data_uri_sync(self, url: str) -> str: Returns: Base64 data URI string """ - verbose_logger.debug( - f"Vertex AI OCR: Converting URL to base64 data URI (sync): {url}" - ) + verbose_logger.debug(f"Vertex AI OCR: Converting URL to base64 data URI (sync): {url}") # Fetch and convert to base64 data URI # convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = convert_url_to_base64(url=url) - verbose_logger.debug( - f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})" - ) + verbose_logger.debug(f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})") return data_uri @@ -175,17 +163,13 @@ async def _convert_url_to_data_uri_async(self, url: str) -> str: Returns: Base64 data URI string """ - verbose_logger.debug( - f"Vertex AI OCR: Converting URL to base64 data URI (async): {url}" - ) + verbose_logger.debug(f"Vertex AI OCR: Converting URL to base64 data URI (async): {url}") # Fetch and convert to base64 data URI asynchronously # async_convert_url_to_base64 already returns a full data URI like "data:image/jpeg;base64,..." data_uri = await async_convert_url_to_base64(url=url) - verbose_logger.debug( - f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})" - ) + verbose_logger.debug(f"Vertex AI OCR: Converted URL to data URI (length: {len(data_uri)})") return data_uri @@ -226,18 +210,14 @@ def transform_ocr_request( document_url = document.get("document_url", "") # If it's not already a data URI, convert it if document_url and not document_url.startswith("data:"): - verbose_logger.debug( - "Vertex AI OCR: Converting document URL to base64 data URI (sync)" - ) + verbose_logger.debug("Vertex AI OCR: Converting document URL to base64 data URI (sync)") data_uri = self._convert_url_to_data_uri_sync(url=document_url) transformed_document["document_url"] = data_uri elif doc_type == "image_url": image_url = document.get("image_url", "") # If it's not already a data URI, convert it if image_url and not image_url.startswith("data:"): - verbose_logger.debug( - "Vertex AI OCR: Converting image URL to base64 data URI (sync)" - ) + verbose_logger.debug("Vertex AI OCR: Converting image URL to base64 data URI (sync)") data_uri = self._convert_url_to_data_uri_sync(url=image_url) transformed_document["image_url"] = data_uri @@ -274,9 +254,7 @@ async def async_transform_ocr_request( Returns: OCRRequestData with JSON data """ - verbose_logger.debug( - f"Vertex AI OCR async_transform_ocr_request - model: {model}" - ) + verbose_logger.debug(f"Vertex AI OCR async_transform_ocr_request - model: {model}") if not isinstance(document, dict): raise ValueError(f"Expected document dict, got {type(document)}") @@ -289,18 +267,14 @@ async def async_transform_ocr_request( document_url = document.get("document_url", "") # If it's not already a data URI, convert it if document_url and not document_url.startswith("data:"): - verbose_logger.debug( - "Vertex AI OCR: Converting document URL to base64 data URI (async)" - ) + verbose_logger.debug("Vertex AI OCR: Converting document URL to base64 data URI (async)") data_uri = await self._convert_url_to_data_uri_async(url=document_url) transformed_document["document_url"] = data_uri elif doc_type == "image_url": image_url = document.get("image_url", "") # If it's not already a data URI, convert it if image_url and not image_url.startswith("data:"): - verbose_logger.debug( - "Vertex AI OCR: Converting image URL to base64 data URI (async)" - ) + verbose_logger.debug("Vertex AI OCR: Converting image URL to base64 data URI (async)") data_uri = await self._convert_url_to_data_uri_async(url=image_url) transformed_document["image_url"] = data_uri diff --git a/litellm/llms/vertex_ai/rag_engine/ingestion.py b/litellm/llms/vertex_ai/rag_engine/ingestion.py index 2ec61667795f..d9e0035aa991 100644 --- a/litellm/llms/vertex_ai/rag_engine/ingestion.py +++ b/litellm/llms/vertex_ai/rag_engine/ingestion.py @@ -79,20 +79,14 @@ def __init__( ) # GCP config - self.vertex_project = self.vector_store_config.get( - "vertex_project" - ) or get_secret_str("VERTEXAI_PROJECT") + self.vertex_project = self.vector_store_config.get("vertex_project") or get_secret_str("VERTEXAI_PROJECT") self.vertex_location = ( - self.vector_store_config.get("vertex_location") - or get_secret_str("VERTEXAI_LOCATION") - or "us-central1" + self.vector_store_config.get("vertex_location") or get_secret_str("VERTEXAI_LOCATION") or "us-central1" ) self.vertex_credentials = self.vector_store_config.get("vertex_credentials") # GCS bucket for file uploads - self.gcs_bucket = self.vector_store_config.get("gcs_bucket") or os.environ.get( - "GCS_BUCKET_NAME" - ) + self.gcs_bucket = self.vector_store_config.get("gcs_bucket") or os.environ.get("GCS_BUCKET_NAME") if not self.gcs_bucket: raise ValueError( "gcs_bucket is required for Vertex AI RAG ingestion. " @@ -101,9 +95,7 @@ def __init__( # Import settings self.wait_for_import = self.vector_store_config.get("wait_for_import", True) - self.import_timeout = _get_int( - self.vector_store_config.get("import_timeout"), 600 - ) + self.import_timeout = _get_int(self.vector_store_config.get("import_timeout"), 600) # Validate required config if not self.vertex_project: @@ -141,8 +133,7 @@ async def _upload_file_to_gcs( file_tuple = (filename, file_content, content_type) verbose_logger.debug( - f"Uploading file to GCS via litellm.files.acreate_file: {filename} " - f"(bucket: {self.gcs_bucket})" + f"Uploading file to GCS via litellm.files.acreate_file: {filename} (bucket: {self.gcs_bucket})" ) # Upload to GCS using LiteLLM's file upload @@ -204,9 +195,7 @@ async def _import_file_to_corpus_via_sdk( transformation_config=transformation_config, timeout=self.import_timeout, ) - verbose_logger.info( - f"Import complete: {response.imported_rag_files_count} files imported" - ) + verbose_logger.info(f"Import complete: {response.imported_rag_files_count} files imported") else: # Async import - don't wait _ = rag.import_files_async( @@ -290,9 +279,7 @@ async def store( Tuple of (corpus_id, gcs_uri) """ if not file_content or not filename: - verbose_logger.warning( - "No file content or filename provided for Vertex AI ingestion" - ) + verbose_logger.warning("No file content or filename provided for Vertex AI ingestion") return _get_str_or_none(self.corpus_id), None # Step 1: Upload file to GCS diff --git a/litellm/llms/vertex_ai/rag_engine/transformation.py b/litellm/llms/vertex_ai/rag_engine/transformation.py index ed5154bbdff7..4aa2fcb49bef 100644 --- a/litellm/llms/vertex_ai/rag_engine/transformation.py +++ b/litellm/llms/vertex_ai/rag_engine/transformation.py @@ -39,7 +39,9 @@ def get_import_rag_files_url( Vertex AI RAG Engine primarily uses gRPC-based SDK. """ base_url = get_vertex_base_url(vertex_location) - return f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/ragCorpora/{corpus_id}:importRagFiles" + return ( + f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/ragCorpora/{corpus_id}:importRagFiles" + ) def get_retrieve_contexts_url( self, @@ -89,8 +91,7 @@ def transform_chunking_strategy_to_vertex_format( # Log if separators are provided (not supported by Vertex AI) if chunking_strategy.get("separators"): verbose_logger.warning( - "Vertex AI RAG Engine does not support custom separators. " - "The 'separators' parameter will be ignored." + "Vertex AI RAG Engine does not support custom separators. The 'separators' parameter will be ignored." ) return { @@ -115,9 +116,7 @@ def build_import_rag_files_request( Returns: Request payload dict for importRagFiles API """ - transformation_config = self.transform_chunking_strategy_to_vertex_format( - chunking_strategy - ) + transformation_config = self.transform_chunking_strategy_to_vertex_format(chunking_strategy) return { "import_rag_files_config": { @@ -136,9 +135,7 @@ def get_auth_headers( Uses the base class method to get credentials. """ - credentials = self.get_vertex_ai_credentials( - {"vertex_credentials": vertex_credentials} - ) + credentials = self.get_vertex_ai_credentials({"vertex_credentials": vertex_credentials}) project = vertex_project or self.get_vertex_ai_project({}) access_token, _ = self._ensure_access_token( diff --git a/litellm/llms/vertex_ai/realtime/transformation.py b/litellm/llms/vertex_ai/realtime/transformation.py index 9f339d3dc29e..beb8bc0be6fd 100644 --- a/litellm/llms/vertex_ai/realtime/transformation.py +++ b/litellm/llms/vertex_ai/realtime/transformation.py @@ -118,11 +118,7 @@ def session_configuration_request(self, model: str) -> str: from litellm.types.llms.vertex_ai import GeminiResponseModalities response_modalities: list[GeminiResponseModalities] = ["AUDIO"] - full_model_path = ( - f"projects/{self._project}" - f"/locations/{self._location}" - f"/publishers/google/models/{model}" - ) + full_model_path = f"projects/{self._project}/locations/{self._location}/publishers/google/models/{model}" setup_config: BidiGenerateContentSetup = { "model": full_model_path, "generationConfig": {"responseModalities": response_modalities}, @@ -146,11 +142,7 @@ def session_configuration_request(self, model: str) -> str: def _vertex_model_path(self, model: str) -> str: """Return the fully-qualified Vertex AI model resource path.""" - return ( - f"projects/{self._project}" - f"/locations/{self._location}" - f"/publishers/google/models/{model}" - ) + return f"projects/{self._project}/locations/{self._location}/publishers/google/models/{model}" def _build_vertex_ai_setup_config(self, model: str, session_params: dict) -> dict: """Build Vertex AI setup configuration with proper model path and defaults.""" @@ -161,9 +153,7 @@ def _build_vertex_ai_setup_config(self, model: str, session_params: dict) -> dic # settings would be silently dropped because ``map_openai_params`` only # recognises the flat OpenAI-beta key names. session_params = self._normalize_session_payload_for_mapping(session_params) - setup_config = self.map_openai_params( - optional_params={}, non_default_params=session_params - ) + setup_config = self.map_openai_params(optional_params={}, non_default_params=session_params) # Use full Vertex AI model path setup_config["model"] = self._vertex_model_path(model) @@ -184,13 +174,10 @@ def _build_vertex_ai_setup_config(self, model: str, session_params: dict) -> dic # that need that behaviour must accept that VAD is off. client_turn_detection = session_params.get("turn_detection") client_disabled_auto_response = ( - isinstance(client_turn_detection, dict) - and client_turn_detection.get("create_response") is False + isinstance(client_turn_detection, dict) and client_turn_detection.get("create_response") is False ) realtime_input_config = setup_config.setdefault("realtimeInputConfig", {}) - automatic_detection = realtime_input_config.setdefault( - "automaticActivityDetection", {} - ) + automatic_detection = realtime_input_config.setdefault("automaticActivityDetection", {}) if not client_disabled_auto_response: automatic_detection["disabled"] = False automatic_detection.setdefault("silenceDurationMs", 800) @@ -220,14 +207,10 @@ def transform_realtime_request( if msg_type == "session.update": if session_configuration_request is None: - setup_config = self._build_vertex_ai_setup_config( - model, json_message.get("session") or {} - ) + setup_config = self._build_vertex_ai_setup_config(model, json_message.get("session") or {}) gemini_setup_msg = json.dumps({"setup": setup_config}) - verbose_logger.debug( - "Vertex AI Realtime: Sending initial setup with tools to backend" - ) + verbose_logger.debug("Vertex AI Realtime: Sending initial setup with tools to backend") return [gemini_setup_msg] # A follow-up session.update can't be forwarded as a second setup @@ -235,13 +218,8 @@ def transform_realtime_request( # silencing the audio-transcription guardrail's create_response # disable, surface a warning so operators know the model will # auto-respond before the guardrail can gate it on Vertex AI. - client_turn_detection = GeminiRealtimeConfig._extract_turn_detection( - json_message.get("session") or {} - ) - if ( - isinstance(client_turn_detection, dict) - and client_turn_detection.get("create_response") is False - ): + client_turn_detection = GeminiRealtimeConfig._extract_turn_detection(json_message.get("session") or {}) + if isinstance(client_turn_detection, dict) and client_turn_detection.get("create_response") is False: verbose_logger.warning( "Vertex AI Realtime: Dropping subsequent session.update " "(turn_detection.create_response=False) — Vertex Live " @@ -250,11 +228,7 @@ def transform_realtime_request( "Vertex AI in non-deferred mode." ) else: - verbose_logger.debug( - "Vertex AI Realtime: Ignoring session.update (setup already sent)" - ) + verbose_logger.debug("Vertex AI Realtime: Ignoring session.update (setup already sent)") return [] - return super().transform_realtime_request( - message, model, session_configuration_request - ) + return super().transform_realtime_request(message, model, session_configuration_request) diff --git a/litellm/llms/vertex_ai/rerank/transformation.py b/litellm/llms/vertex_ai/rerank/transformation.py index 382a8498d40d..b9680af20cca 100644 --- a/litellm/llms/vertex_ai/rerank/transformation.py +++ b/litellm/llms/vertex_ai/rerank/transformation.py @@ -59,11 +59,7 @@ def get_complete_url( ) # Fallback to environment or litellm config - project_id = ( - vertex_project - or get_secret_str("VERTEXAI_PROJECT") - or litellm.vertex_project - ) + project_id = vertex_project or get_secret_str("VERTEXAI_PROJECT") or litellm.vertex_project if not project_id: raise ValueError( @@ -207,19 +203,13 @@ def transform_rerank_response( rerank_results = [] for result in results: rerank_results.append( - RerankResponseResult( - index=result["index"], relevance_score=result["relevance_score"] - ) + RerankResponseResult(index=result["index"], relevance_score=result["relevance_score"]) ) # Create meta object - meta = RerankResponseMeta( - billed_units=RerankBilledUnits(search_units=len(records)) - ) + meta = RerankResponseMeta(billed_units=RerankBilledUnits(search_units=len(records))) - return RerankResponse( - id=f"vertex_ai_rerank_{model}", results=rerank_results, meta=meta - ) + return RerankResponse(id=f"vertex_ai_rerank_{model}", results=rerank_results, meta=meta) def get_supported_cohere_rerank_params(self, model: str) -> list: return [ diff --git a/litellm/llms/vertex_ai/text_to_speech/text_to_speech_handler.py b/litellm/llms/vertex_ai/text_to_speech/text_to_speech_handler.py index b835ad7d8fac..e27df956c9d6 100644 --- a/litellm/llms/vertex_ai/text_to_speech/text_to_speech_handler.py +++ b/litellm/llms/vertex_ai/text_to_speech/text_to_speech_handler.py @@ -150,9 +150,7 @@ def audio_speech( json=request, # type: ignore ) if response.status_code != 200: - raise Exception( - f"Request failed with status code {response.status_code}, {response.text}" - ) + raise Exception(f"Request failed with status code {response.status_code}, {response.text}") ############ Process the response ############ _json_response = response.json() @@ -180,9 +178,7 @@ async def async_audio_speech( ) -> HttpxBinaryResponseContent: import base64 - async_handler = get_async_httpx_client( - llm_provider=litellm.LlmProviders.VERTEX_AI - ) + async_handler = get_async_httpx_client(llm_provider=litellm.LlmProviders.VERTEX_AI) response = await async_handler.post( url=url, @@ -191,9 +187,7 @@ async def async_audio_speech( ) if response.status_code != 200: - raise Exception( - f"Request did not return a 200 status code: {response.status_code}, {response.text}" - ) + raise Exception(f"Request did not return a 200 status code: {response.status_code}, {response.text}") _json_response = response.json() @@ -213,9 +207,7 @@ async def async_audio_speech( return http_binary_response -def validate_vertex_input( - input_data: VertexInput, kwargs: dict, optional_params: dict -) -> None: +def validate_vertex_input(input_data: VertexInput, kwargs: dict, optional_params: dict) -> None: # Remove None values if input_data.get("text") is None: input_data.pop("text", None) diff --git a/litellm/llms/vertex_ai/text_to_speech/transformation.py b/litellm/llms/vertex_ai/text_to_speech/transformation.py index be7bcfcadd7d..a003409f7a6f 100644 --- a/litellm/llms/vertex_ai/text_to_speech/transformation.py +++ b/litellm/llms/vertex_ai/text_to_speech/transformation.py @@ -330,9 +330,7 @@ def _validate_vertex_input( if not input_data: raise ValueError("Either 'text' or 'ssml' must be provided.") if "text" in input_data and "ssml" in input_data: - raise ValueError( - "Only one of 'text' or 'ssml' should be provided, not both." - ) + raise ValueError("Only one of 'text' or 'ssml' should be provided, not both.") return input_data @@ -357,9 +355,7 @@ def transform_text_to_speech_request( TextToSpeechRequestData: Contains dict_body and headers """ # Get Vertex AI credentials from litellm_params - vertex_credentials: Optional[VERTEX_CREDENTIALS_TYPES] = litellm_params.get( - "vertex_credentials" - ) + vertex_credentials: Optional[VERTEX_CREDENTIALS_TYPES] = litellm_params.get("vertex_credentials") vertex_project: Optional[str] = litellm_params.get("vertex_project") ####### Authenticate with Vertex AI ######## @@ -393,9 +389,7 @@ def transform_text_to_speech_request( # Check for voice dict stored in: # 1. litellm_params by dispatch method # 2. optional_params by map_openai_params - voice_dict = litellm_params.get("vertex_voice_dict") or optional_params.get( - "vertex_voice_dict" - ) + voice_dict = litellm_params.get("vertex_voice_dict") or optional_params.get("vertex_voice_dict") if voice_dict is not None and isinstance(voice_dict, dict): vertex_voice = VertexTextToSpeechVoice(**voice_dict) elif voice is not None and isinstance(voice, str): @@ -417,16 +411,12 @@ def transform_text_to_speech_request( ) # Build audio configuration - audio_encoding = optional_params.get( - "audioEncoding", self.DEFAULT_AUDIO_ENCODING - ) + audio_encoding = optional_params.get("audioEncoding", self.DEFAULT_AUDIO_ENCODING) speaking_rate = optional_params.get("speakingRate", self.DEFAULT_SPEAKING_RATE) # Check for full audioConfig in optional_params if "audioConfig" in optional_params: - vertex_audio_config = VertexTextToSpeechAudioConfig( - **optional_params["audioConfig"] - ) + vertex_audio_config = VertexTextToSpeechAudioConfig(**optional_params["audioConfig"]) else: vertex_audio_config = VertexTextToSpeechAudioConfig( audioEncoding=audio_encoding, diff --git a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py index d31e1f6c8f2d..47a81fc07bf9 100644 --- a/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py +++ b/litellm/llms/vertex_ai/vector_stores/rag_api/transformation.py @@ -35,9 +35,7 @@ class VertexVectorStoreConfig(BaseVectorStoreConfig, VertexBase): def __init__(self): super().__init__() - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: # Get credentials and project info vertex_credentials = self.get_vertex_ai_credentials(dict(litellm_params)) vertex_project = self.get_vertex_ai_project(dict(litellm_params)) @@ -62,9 +60,7 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [("POST", "/ragCorpora")], } - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate and set up authentication for Vertex AI RAG API """ @@ -183,9 +179,7 @@ def transform_search_vector_store_response( # Generate file_id from source URI or use display name as fallback file_id = source_uri if source_uri else source_display_name - filename = ( - source_display_name if source_display_name else "Unknown Document" - ) + filename = source_display_name if source_display_name else "Unknown Document" # Build attributes with available metadata attributes = {} @@ -233,9 +227,7 @@ def transform_create_vector_store_request( # Build the request body for Vertex AI RAG Corpus creation request_body: Dict[str, Any] = { - "display_name": vector_store_create_optional_params.get( - "name", "litellm-vector-store" - ), + "display_name": vector_store_create_optional_params.get("name", "litellm-vector-store"), "description": "Vector store created via LiteLLM", } @@ -246,9 +238,7 @@ def transform_create_vector_store_request( return url, request_body - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: """ Transform Vertex AI RAG Corpus creation response to standard vector store response """ @@ -257,9 +247,7 @@ def transform_create_vector_store_response( # Extract the corpus ID from the response name corpus_name = response_json.get("name", "") - corpus_id = ( - corpus_name.split("/")[-1] if "/" in corpus_name else corpus_name - ) + corpus_id = corpus_name.split("/")[-1] if "/" in corpus_name else corpus_name # Handle createTime conversion create_time = response_json.get("createTime", 0) diff --git a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py index 46dedb3d0a42..958839d4a486 100644 --- a/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py +++ b/litellm/llms/vertex_ai/vector_stores/search_api/transformation.py @@ -45,13 +45,9 @@ # via extra_body, derived from the TypedDicts so the type is the source of truth. # Engine/app mode is a superset (adds dataStoreSpecs, numResultsPerDataStore), # since an app fans out across multiple member data stores. -VERTEX_SEARCH_DATASTORE_EXTRA_BODY_FIELDS = frozenset( - VertexSearchDataStoreExtraBody.__annotations__ -) +VERTEX_SEARCH_DATASTORE_EXTRA_BODY_FIELDS = frozenset(VertexSearchDataStoreExtraBody.__annotations__) -VERTEX_SEARCH_ENGINE_EXTRA_BODY_FIELDS = frozenset( - VertexSearchEngineExtraBody.__annotations__ -) +VERTEX_SEARCH_ENGINE_EXTRA_BODY_FIELDS = frozenset(VertexSearchEngineExtraBody.__annotations__) class VertexSearchAPIVectorStoreConfig(BaseVectorStoreConfig, VertexBase): @@ -79,9 +75,7 @@ def get_supported_extra_body_fields(is_engine: bool = False) -> frozenset: return VERTEX_SEARCH_DATASTORE_EXTRA_BODY_FIELDS @classmethod - def _filter_extra_body( - cls, extra_body: Dict[str, Any], is_engine: bool = False - ) -> Dict[str, Any]: + def _filter_extra_body(cls, extra_body: Dict[str, Any], is_engine: bool = False) -> Dict[str, Any]: """ Validate ``extra_body`` against the supported-field allowlist for the active serving config (engine/app vs data store). @@ -94,9 +88,7 @@ def _filter_extra_body( data-store mode where they are meaningless. """ supported = cls.get_supported_extra_body_fields(is_engine=is_engine) - filtered = { - key: value for key, value in extra_body.items() if value is not None - } + filtered = {key: value for key, value in extra_body.items() if value is not None} target_selecting = set(filtered) & VERTEX_SEARCH_TARGET_SELECTING_FIELDS if target_selecting: @@ -124,9 +116,7 @@ def _filter_extra_body( return filtered - def get_auth_credentials( - self, litellm_params: dict - ) -> BaseVectorStoreAuthCredentials: + def get_auth_credentials(self, litellm_params: dict) -> BaseVectorStoreAuthCredentials: # Get credentials and project info vertex_credentials = self.get_vertex_ai_credentials(dict(litellm_params)) vertex_project = self.get_vertex_ai_project(dict(litellm_params)) @@ -151,9 +141,7 @@ def get_vector_store_endpoints_by_type(self) -> VectorStoreIndexEndpoints: "write": [], } - def validate_environment( - self, headers: dict, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate and set up authentication for Vertex AI RAG API """ @@ -181,12 +169,8 @@ def get_complete_url( vertex_location = self.get_vertex_ai_location(litellm_params) vertex_project = self.get_vertex_ai_project(litellm_params) - collection_id = ( - litellm_params.get("vertex_collection_id") or "default_collection" - ) - encoded_collection_id = encode_url_path_segment( - collection_id, field_name="vertex_collection_id" - ) + collection_id = litellm_params.get("vertex_collection_id") or "default_collection" + encoded_collection_id = encode_url_path_segment(collection_id, field_name="vertex_collection_id") base = ( f"https://discoveryengine.googleapis.com/v1/" f"projects/{vertex_project}/locations/{vertex_location}/" @@ -195,19 +179,13 @@ def get_complete_url( engine_id = litellm_params.get("vertex_engine_id") if engine_id: - encoded_engine_id = encode_url_path_segment( - engine_id, field_name="vertex_engine_id" - ) + encoded_engine_id = encode_url_path_segment(engine_id, field_name="vertex_engine_id") return f"{base}/engines/{encoded_engine_id}/servingConfigs/default_serving_config" datastore_id = litellm_params.get("vector_store_id") if not datastore_id: - raise ValueError( - "vector_store_id is required when vertex_engine_id is not set" - ) - encoded_datastore_id = encode_url_path_segment( - datastore_id, field_name="vector_store_id" - ) + raise ValueError("vector_store_id is required when vertex_engine_id is not set") + encoded_datastore_id = encode_url_path_segment(datastore_id, field_name="vector_store_id") return f"{base}/dataStores/{encoded_datastore_id}/servingConfigs/default_config" def transform_search_vector_store_request( @@ -249,13 +227,9 @@ def transform_search_vector_store_request( if max_num_results is not None: request_body["pageSize"] = max_num_results if isinstance(extra_body, dict): - request_body.update( - self._filter_extra_body(extra_body, is_engine=is_engine) - ) + request_body.update(self._filter_extra_body(extra_body, is_engine=is_engine)) - litellm_logging_obj.model_call_details["query"] = request_body.get( - "query", query - ) + litellm_logging_obj.model_call_details["query"] = request_body.get("query", query) return url, request_body @@ -299,10 +273,7 @@ def transform_search_vector_store_response( if snippets: # Combine all snippets into one text - text_parts = [ - snippet.get("snippet", snippet.get("htmlSnippet", "")) - for snippet in snippets - ] + text_parts = [snippet.get("snippet", snippet.get("htmlSnippet", "")) for snippet in snippets] text_content = " ".join(text_parts) # If no snippets, use title as fallback @@ -347,9 +318,7 @@ def transform_search_vector_store_response( # Note: Search API doesn't provide explicit scores in the response # You can use the position/rank as an implicit score - score = 1.0 / ( - float(search_results.__len__() + 1) - ) # Decreasing score based on position + score = 1.0 / (float(search_results.__len__() + 1)) # Decreasing score based on position result_obj = VectorStoreSearchResult( score=score, @@ -380,9 +349,7 @@ def transform_create_vector_store_request( ) -> Tuple[str, Dict]: raise NotImplementedError - def transform_create_vector_store_response( - self, response: httpx.Response - ) -> VectorStoreCreateResponse: + def transform_create_vector_store_response(self, response: httpx.Response) -> VectorStoreCreateResponse: raise NotImplementedError def calculate_vector_store_cost( diff --git a/litellm/llms/vertex_ai/vertex_ai_aws_wif.py b/litellm/llms/vertex_ai/vertex_ai_aws_wif.py index a03a4e37a21a..da95ac72c2f5 100644 --- a/litellm/llms/vertex_ai/vertex_ai_aws_wif.py +++ b/litellm/llms/vertex_ai/vertex_ai_aws_wif.py @@ -12,8 +12,7 @@ from typing import Dict GOOGLE_IMPORT_ERROR_MESSAGE = ( - "Google Cloud SDK not found. Install it with: pip install 'litellm[google]' " - "or pip install google-cloud-aiplatform" + "Google Cloud SDK not found. Install it with: pip install 'litellm[google]' or pip install google-cloud-aiplatform" ) # AWS params recognized in WIF credential JSON for explicit auth. @@ -107,9 +106,7 @@ def _get_aws_credentials(): token_url=json_obj.get("token_url"), credential_source=None, # Not using metadata endpoints aws_security_credentials_supplier=supplier, - service_account_impersonation_url=json_obj.get( - "service_account_impersonation_url" - ), + service_account_impersonation_url=json_obj.get("service_account_impersonation_url"), ) # Forward universe_domain if present (defaults to googleapis.com) if "universe_domain" in json_obj: diff --git a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py index c134dee7ad4c..33606013d5c3 100644 --- a/litellm/llms/vertex_ai/vertex_ai_non_gemini.py +++ b/litellm/llms/vertex_ai/vertex_ai_non_gemini.py @@ -17,13 +17,9 @@ class VertexAIError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url=" https://cloud.google.com/vertex-ai/" - ) + self.request = httpx.Request(method="POST", url=" https://cloud.google.com/vertex-ai/") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class TextStreamer: @@ -58,9 +54,7 @@ async def __anext__(self): raise StopAsyncIteration # once we run out of data to stream, we raise this error -def _get_client_cache_key( - model: str, vertex_project: Optional[str], vertex_location: Optional[str] -): +def _get_client_cache_key(model: str, vertex_project: Optional[str], vertex_location: Optional[str]): _cache_key = f"{model}-{vertex_project}-{vertex_location}" return _cache_key @@ -108,9 +102,7 @@ def completion( message="vertexai import failed please run `pip install google-cloud-aiplatform`. This is required for the 'vertex_ai/' route on LiteLLM", ) - if not ( - hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models") - ): + if not (hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models")): raise VertexAIError( status_code=400, message="""Upgrade vertex ai. Run `pip install "google-cloud-aiplatform>=1.38"`""", @@ -128,13 +120,9 @@ def completion( from vertexai.preview.language_models import ChatModel, CodeChatModel ## Load credentials with the correct quota project ref: https://github.com/googleapis/python-aiplatform/issues/2557#issuecomment-1709284744 - print_verbose( - f"VERTEX AI: vertex_project={vertex_project}; vertex_location={vertex_location}" - ) + print_verbose(f"VERTEX AI: vertex_project={vertex_project}; vertex_location={vertex_location}") - _cache_key = _get_client_cache_key( - model=model, vertex_project=vertex_project, vertex_location=vertex_location - ) + _cache_key = _get_client_cache_key(model=model, vertex_project=vertex_project, vertex_location=vertex_location) _vertex_llm_model_object = _get_client_from_cache(client_cache_key=_cache_key) # Load credentials - needed for both vertexai.init() and PredictionServiceClient @@ -176,18 +164,12 @@ def completion( raise ValueError("safety_settings must be a list") if len(safety_settings) > 0 and not isinstance(safety_settings[0], dict): raise ValueError("safety_settings must be a list of dicts") - safety_settings = [ - gapic_content_types.SafetySetting(x) for x in safety_settings - ] + safety_settings = [gapic_content_types.SafetySetting(x) for x in safety_settings] # vertexai does not use an API key, it looks for credentials.json in the environment prompt = " ".join( - [ - message.get("content") - for message in messages - if isinstance(message.get("content", None), str) - ] + [message.get("content") for message in messages if isinstance(message.get("content", None), str)] ) mode = "" @@ -195,14 +177,9 @@ def completion( request_str = "" response_obj = None instances = None - client_options = { - "api_endpoint": f"{vertex_location}-aiplatform.googleapis.com" - } + client_options = {"api_endpoint": f"{vertex_location}-aiplatform.googleapis.com"} fake_stream = False - if ( - model in litellm.vertex_language_models - or model in litellm.vertex_vision_models - ): + if model in litellm.vertex_language_models or model in litellm.vertex_vision_models: llm_model: Any = _vertex_llm_model_object or GenerativeModel(model) mode = "vision" request_str += f"llm_model = GenerativeModel({model})\n" @@ -211,15 +188,11 @@ def completion( mode = "chat" request_str += f"llm_model = ChatModel.from_pretrained({model})\n" elif model in litellm.vertex_text_models: - llm_model = _vertex_llm_model_object or TextGenerationModel.from_pretrained( - model - ) + llm_model = _vertex_llm_model_object or TextGenerationModel.from_pretrained(model) mode = "text" request_str += f"llm_model = TextGenerationModel.from_pretrained({model})\n" elif model in litellm.vertex_code_text_models: - llm_model = _vertex_llm_model_object or CodeGenerationModel.from_pretrained( - model - ) + llm_model = _vertex_llm_model_object or CodeGenerationModel.from_pretrained(model) mode = "text" request_str += f"llm_model = CodeGenerationModel.from_pretrained({model})\n" fake_stream = True @@ -280,9 +253,7 @@ def completion( completion_response = None - stream = optional_params.pop( - "stream", None - ) # See note above on handling streaming for vertex ai + stream = optional_params.pop("stream", None) # See note above on handling streaming for vertex ai if mode == "chat": chat = llm_model.start_chat() request_str += "chat = llm_model.start_chat()\n" @@ -291,13 +262,9 @@ def completion( # NOTE: VertexAI does not accept stream=True as a param and raises an error, # we handle this by removing 'stream' from optional params and sending the request # after we get the response we add optional_params["stream"] = True, since main.py needs to know it's a streaming response to then transform it for the OpenAI format - optional_params.pop( - "stream", None - ) # vertex ai raises an error when passing stream in optional params + optional_params.pop("stream", None) # vertex ai raises an error when passing stream in optional params - request_str += ( - f"chat.send_message_streaming({prompt}, **{optional_params})\n" - ) + request_str += f"chat.send_message_streaming({prompt}, **{optional_params})\n" ## LOGGING logging_obj.pre_call( input=prompt, @@ -325,9 +292,7 @@ def completion( completion_response = chat.send_message(prompt, **optional_params).text elif mode == "text": if fake_stream is not True and stream is True: - request_str += ( - f"llm_model.predict_streaming({prompt}, **{optional_params})\n" - ) + request_str += f"llm_model.predict_streaming({prompt}, **{optional_params})\n" ## LOGGING logging_obj.pre_call( input=prompt, @@ -358,9 +323,7 @@ def completion( """ if vertex_project is None or vertex_location is None: - raise ValueError( - "Vertex project and location are required for custom endpoint" - ) + raise ValueError("Vertex project and location are required for custom endpoint") ## LOGGING logging_obj.pre_call( @@ -376,21 +339,12 @@ def completion( credentials=creds, # type: ignore[arg-type] ) request_str += f"llm_model = aiplatform.gapic.PredictionServiceClient(client_options={client_options}, credentials=...)\n" - endpoint_path = llm_model.endpoint_path( - project=vertex_project, location=vertex_location, endpoint=model - ) - request_str += ( - f"llm_model.predict(endpoint={endpoint_path}, instances={instances})\n" - ) - response = llm_model.predict( - endpoint=endpoint_path, instances=instances - ).predictions + endpoint_path = llm_model.endpoint_path(project=vertex_project, location=vertex_location, endpoint=model) + request_str += f"llm_model.predict(endpoint={endpoint_path}, instances={instances})\n" + response = llm_model.predict(endpoint=endpoint_path, instances=instances).predictions completion_response = response[0] - if ( - isinstance(completion_response, str) - and "\nOutput:\n" in completion_response - ): + if isinstance(completion_response, str) and "\nOutput:\n" in completion_response: completion_response = completion_response.split("\nOutput:\n", 1)[1] if stream is True: response = TextStreamer(completion_response) @@ -416,19 +370,14 @@ def completion( response = llm_model.predict(instances=instances).predictions completion_response = response[0] - if ( - isinstance(completion_response, str) - and "\nOutput:\n" in completion_response - ): + if isinstance(completion_response, str) and "\nOutput:\n" in completion_response: completion_response = completion_response.split("\nOutput:\n", 1)[1] if stream is True: response = TextStreamer(completion_response) return response ## LOGGING - logging_obj.post_call( - input=prompt, api_key=None, original_response=completion_response - ) + logging_obj.post_call(input=prompt, api_key=None, original_response=completion_response) ## RESPONSE OBJECT if isinstance(completion_response, litellm.Message): @@ -456,16 +405,10 @@ def completion( response_obj.usage_metadata, "prompt_token_count" ): prompt_tokens = response_obj.usage_metadata.prompt_token_count - completion_tokens = ( - response_obj.usage_metadata.candidates_token_count - ) + completion_tokens = response_obj.usage_metadata.candidates_token_count else: prompt_tokens = len(encoding.encode(prompt)) - completion_tokens = len( - encoding.encode( - model_response["choices"][0]["message"].get("content", "") - ) - ) + completion_tokens = len(encoding.encode(model_response["choices"][0]["message"].get("content", ""))) usage = Usage( prompt_tokens=prompt_tokens, @@ -480,9 +423,7 @@ def completion( except Exception as e: if isinstance(e, VertexAIError): raise e - raise litellm.APIConnectionError( - message=str(e), llm_provider="vertex_ai", model=model - ) + raise litellm.APIConnectionError(message=str(e), llm_provider="vertex_ai", model=model) async def async_completion( @@ -545,9 +486,7 @@ async def async_completion( from google.cloud import aiplatform # type: ignore if vertex_project is None or vertex_location is None: - raise ValueError( - "Vertex project and location are required for custom endpoint" - ) + raise ValueError("Vertex project and location are required for custom endpoint") ## LOGGING logging_obj.pre_call( @@ -564,22 +503,15 @@ async def async_completion( credentials=vertex_credentials, ) request_str += f"llm_model = aiplatform.gapic.PredictionServiceAsyncClient(client_options={client_options}, credentials=...)\n" - endpoint_path = llm_model.endpoint_path( - project=vertex_project, location=vertex_location, endpoint=model - ) - request_str += ( - f"llm_model.predict(endpoint={endpoint_path}, instances={instances})\n" - ) + endpoint_path = llm_model.endpoint_path(project=vertex_project, location=vertex_location, endpoint=model) + request_str += f"llm_model.predict(endpoint={endpoint_path}, instances={instances})\n" response_obj = await llm_model.predict( endpoint=endpoint_path, instances=instances, ) response = response_obj.predictions completion_response = response[0] - if ( - isinstance(completion_response, str) - and "\nOutput:\n" in completion_response - ): + if isinstance(completion_response, str) and "\nOutput:\n" in completion_response: completion_response = completion_response.split("\nOutput:\n", 1)[1] elif mode == "private": @@ -590,16 +522,11 @@ async def async_completion( response = response_obj.predictions completion_response = response[0] - if ( - isinstance(completion_response, str) - and "\nOutput:\n" in completion_response - ): + if isinstance(completion_response, str) and "\nOutput:\n" in completion_response: completion_response = completion_response.split("\nOutput:\n", 1)[1] ## LOGGING - logging_obj.post_call( - input=prompt, api_key=None, original_response=completion_response - ) + logging_obj.post_call(input=prompt, api_key=None, original_response=completion_response) ## RESPONSE OBJECT if isinstance(completion_response, litellm.Message): @@ -625,18 +552,13 @@ async def async_completion( # this block attempts to get usage from response_obj if it exists, if not it uses the litellm token counter prompt_tokens, completion_tokens, _ = 0, 0, 0 if response_obj is not None and ( - hasattr(response_obj, "usage_metadata") - and hasattr(response_obj.usage_metadata, "prompt_token_count") + hasattr(response_obj, "usage_metadata") and hasattr(response_obj.usage_metadata, "prompt_token_count") ): prompt_tokens = response_obj.usage_metadata.prompt_token_count completion_tokens = response_obj.usage_metadata.candidates_token_count else: prompt_tokens = len(encoding.encode(prompt)) - completion_tokens = len( - encoding.encode( - model_response["choices"][0]["message"].get("content", "") - ) - ) + completion_tokens = len(encoding.encode(model_response["choices"][0]["message"].get("content", ""))) # set usage usage = Usage( @@ -675,12 +597,8 @@ async def async_streaming( response: Any = None if mode == "chat": chat = llm_model.start_chat() - optional_params.pop( - "stream", None - ) # vertex ai raises an error when passing stream in optional params - request_str += ( - f"chat.send_message_streaming_async({prompt}, **{optional_params})\n" - ) + optional_params.pop("stream", None) # vertex ai raises an error when passing stream in optional params + request_str += f"chat.send_message_streaming_async({prompt}, **{optional_params})\n" ## LOGGING logging_obj.pre_call( input=prompt, @@ -693,12 +611,8 @@ async def async_streaming( response = chat.send_message_streaming_async(prompt, **optional_params) elif mode == "text": - optional_params.pop( - "stream", None - ) # See note above on handling streaming for vertex ai - request_str += ( - f"llm_model.predict_streaming_async({prompt}, **{optional_params})\n" - ) + optional_params.pop("stream", None) # See note above on handling streaming for vertex ai + request_str += f"llm_model.predict_streaming_async({prompt}, **{optional_params})\n" ## LOGGING logging_obj.pre_call( input=prompt, @@ -713,9 +627,7 @@ async def async_streaming( from google.cloud import aiplatform # type: ignore if vertex_project is None or vertex_location is None: - raise ValueError( - "Vertex project and location are required for custom endpoint" - ) + raise ValueError("Vertex project and location are required for custom endpoint") stream = optional_params.pop("stream", None) @@ -733,12 +645,8 @@ async def async_streaming( credentials=vertex_credentials, ) request_str += f"llm_model = aiplatform.gapic.PredictionServiceAsyncClient(client_options={client_options}, credentials=...)\n" - endpoint_path = llm_model.endpoint_path( - project=vertex_project, location=vertex_location, endpoint=model - ) - request_str += ( - f"client.predict(endpoint={endpoint_path}, instances={instances})\n" - ) + endpoint_path = llm_model.endpoint_path(project=vertex_project, location=vertex_location, endpoint=model) + request_str += f"client.predict(endpoint={endpoint_path}, instances={instances})\n" response_obj = await llm_model.predict( endpoint=endpoint_path, instances=instances, @@ -746,10 +654,7 @@ async def async_streaming( response = response_obj.predictions completion_response = response[0] - if ( - isinstance(completion_response, str) - and "\nOutput:\n" in completion_response - ): + if isinstance(completion_response, str) and "\nOutput:\n" in completion_response: completion_response = completion_response.split("\nOutput:\n", 1)[1] if stream: response = TextStreamer(completion_response) @@ -765,10 +670,7 @@ async def async_streaming( ) response = response_obj.predictions completion_response = response[0] - if ( - isinstance(completion_response, str) - and "\nOutput:\n" in completion_response - ): + if isinstance(completion_response, str) and "\nOutput:\n" in completion_response: completion_response = completion_response.split("\nOutput:\n", 1)[1] if stream: response = TextStreamer(completion_response) diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/__init__.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/__init__.py index cc0ecc2e3c6e..a9c1e5819f26 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/__init__.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/__init__.py @@ -1,9 +1,7 @@ from litellm.llms.base_llm.chat.transformation import BaseConfig -def get_vertex_ai_partner_model_config( - model: str, vertex_publisher_or_api_spec: str -) -> BaseConfig: +def get_vertex_ai_partner_model_config(model: str, vertex_publisher_or_api_spec: str) -> BaseConfig: """Return config for handling response transformation for vertex ai partner models""" if vertex_publisher_or_api_spec == "anthropic": from .anthropic.transformation import VertexAIAnthropicConfig @@ -13,10 +11,7 @@ def get_vertex_ai_partner_model_config( from .ai21.transformation import VertexAIAi21Config return VertexAIAi21Config() - elif ( - vertex_publisher_or_api_spec == "openapi" - or vertex_publisher_or_api_spec == "mistralai" - ): + elif vertex_publisher_or_api_spec == "openapi" or vertex_publisher_or_api_spec == "mistralai": from .llama3.transformation import VertexAILlama3Config return VertexAILlama3Config() diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/ai21/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/ai21/transformation.py index 8ffc00cc9574..c8163708574d 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/ai21/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/ai21/transformation.py @@ -49,9 +49,7 @@ def map_openai_params( drop_params: bool, ): if "max_completion_tokens" in non_default_params: - non_default_params["max_tokens"] = non_default_params.pop( - "max_completion_tokens" - ) + non_default_params["max_tokens"] = non_default_params.pop("max_completion_tokens") return litellm.OpenAIConfig().map_openai_params( non_default_params=non_default_params, optional_params=optional_params, diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py index a633ef3298aa..8566496bf9c8 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/experimental_pass_through/transformation.py @@ -49,17 +49,15 @@ def validate_anthropic_messages_environment( ) headers["Authorization"] = f"Bearer {access_token}" - # Calculate api_base if not provided - if api_base is None: - api_base = self.get_complete_vertex_url( - custom_api_base=api_base, - vertex_location=vertex_ai_location, - vertex_project=vertex_ai_project, - project_id=project_id or "", - partner=VertexPartnerProvider.claude, - stream=optional_params.get("stream", False), - model=model, - ) + api_base = self.get_complete_vertex_url( + custom_api_base=api_base, + vertex_location=vertex_ai_location, + vertex_project=vertex_ai_project, + project_id=project_id or "", + partner=VertexPartnerProvider.claude, + stream=optional_params.get("stream", False), + model=model, + ) headers["content-type"] = "application/json" @@ -93,18 +91,12 @@ def validate_anthropic_messages_environment( # Add context management header if any other edits exist if has_other: - beta_values.add( - ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value - ) + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value) # Check for web search tool for tool in tools: - if isinstance(tool, dict) and tool.get("type", "").startswith( - ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value - ): - beta_values.add( - ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value - ) + if isinstance(tool, dict) and tool.get("type", "").startswith(ANTHROPIC_HOSTED_TOOLS.WEB_SEARCH.value): + beta_values.add(ANTHROPIC_BETA_HEADER_VALUES.WEB_SEARCH_2025_03_05.value) break # Check for tool search tools - Vertex AI uses different beta header @@ -127,9 +119,7 @@ def get_complete_url( stream: Optional[bool] = None, ) -> str: if api_base is None: - raise ValueError( - "api_base is required. Unable to determine the correct api_base for the request." - ) + raise ValueError("api_base is required. Unable to determine the correct api_base for the request.") return api_base # no transformation is needed - handled in validate_environment def transform_anthropic_messages_request( @@ -152,9 +142,7 @@ def transform_anthropic_messages_request( anthropic_messages_request["anthropic_version"] = "vertex-2023-10-16" - anthropic_messages_request.pop( - "model", None - ) # do not pass model in request body to vertex ai + anthropic_messages_request.pop("model", None) # do not pass model in request body to vertex ai sanitize_vertex_anthropic_output_params(anthropic_messages_request, model) diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py index ae8bdc554438..c8d91be359b7 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/anthropic/transformation.py @@ -17,13 +17,9 @@ class VertexAIError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url=" https://cloud.google.com/vertex-ai/" - ) + self.request = httpx.Request(method="POST", url=" https://cloud.google.com/vertex-ai/") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class VertexAIAnthropicConfig(AnthropicConfig): @@ -55,9 +51,7 @@ def custom_llm_provider(self) -> Optional[str]: def should_strip_billing_metadata(self) -> bool: return True - def _add_context_management_beta_headers( - self, beta_set: set, context_management: dict - ) -> None: + def _add_context_management_beta_headers(self, beta_set: set, context_management: dict) -> None: """ Add context_management beta headers to the beta_set. @@ -87,9 +81,7 @@ def _add_context_management_beta_headers( # Add context management header if any other edits exist if has_other: - beta_set.add( - ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value - ) + beta_set.add(ANTHROPIC_BETA_HEADER_VALUES.CONTEXT_MANAGEMENT_2025_06_27.value) def transform_request( self, @@ -124,9 +116,7 @@ def transform_request( beta_set = set(auto_betas) if tool_search_used: - beta_set.add( - "tool-search-tool-2025-10-19" - ) # Vertex requires this header for tool search + beta_set.add("tool-search-tool-2025-10-19") # Vertex requires this header for tool search # Add context_management beta headers (compact and/or context-management) context_management = optional_params.get("context_management") @@ -218,10 +208,7 @@ def is_supported_model(cls, model: str, custom_llm_provider: str) -> bool: """ Check if the model is supported by the VertexAI Anthropic API. """ - if ( - custom_llm_provider != "vertex_ai" - and custom_llm_provider != "vertex_ai_beta" - ): + if custom_llm_provider != "vertex_ai" and custom_llm_provider != "vertex_ai_beta": return False if "claude" in model.lower(): return True diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py index 3a3ab2e24658..d3edf2e98483 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/count_tokens/handler.py @@ -130,9 +130,7 @@ async def handle_count_tokens_request( vertex_project = self.get_vertex_ai_project(litellm_params) # Check for count_tokens specific location override - vertex_count_tokens_location = litellm_params.get( - "vertex_count_tokens_location" - ) + vertex_count_tokens_location = litellm_params.get("vertex_count_tokens_location") vertex_location_raw = self.get_vertex_ai_location(litellm_params) # Determine final location with precedence: @@ -185,9 +183,7 @@ async def handle_count_tokens_request( # Check for errors if response.status_code != 200: error_text = response.text - raise ValueError( - f"Token counting request failed with status {response.status_code}: {error_text}" - ) + raise ValueError(f"Token counting request failed with status {response.status_code}: {error_text}") # Parse response result = response.json() diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py index 47c388f0a542..13cb09dc22ca 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/gpt_oss/transformation.py @@ -28,9 +28,7 @@ def get_supported_openai_params(self, model: str) -> list: "functions", ] base_gpt_series_params = [ - param - for param in base_gpt_series_params - if param not in TOOL_CALLING_PARAMS_TO_REMOVE + param for param in base_gpt_series_params if param not in TOOL_CALLING_PARAMS_TO_REMOVE ] return base_gpt_series_params diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py index 3031f159d871..411a2a1cb0dd 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py @@ -78,9 +78,7 @@ def map_openai_params( drop_params: bool, ): if "max_completion_tokens" in non_default_params: - non_default_params["max_tokens"] = non_default_params.pop( - "max_completion_tokens" - ) + non_default_params["max_tokens"] = non_default_params.pop("max_completion_tokens") return super().map_openai_params( non_default_params=non_default_params, optional_params=optional_params, @@ -128,9 +126,7 @@ def transform_response( except Exception as e: response_headers = getattr(raw_response, "headers", None) raise VertexAIError( - message="Unable to get json response - {}, Original Response: {}".format( - str(e), raw_response.text - ), + message="Unable to get json response - {}, Original Response: {}".format(str(e), raw_response.text), status_code=raw_response.status_code, headers=response_headers, ) @@ -202,9 +198,7 @@ def chunk_parser(self, chunk: dict) -> ModelResponseStream: elif delta.role is None: delta.role = "assistant" # If the first chunk has empty content, ensure it's still emitted - if ( - delta.content == "" or delta.content is None - ) and delta.provider_specific_fields is None: + if (delta.content == "" or delta.content is None) and delta.provider_specific_fields is None: delta.provider_specific_fields = {} self.sent_role = True return result diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py index 78669f1e7894..097928508a53 100644 --- a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py +++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py @@ -20,13 +20,9 @@ class VertexAIError(Exception): def __init__(self, status_code, message): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url=" https://cloud.google.com/vertex-ai/" - ) + self.request = httpx.Request(method="POST", url=" https://cloud.google.com/vertex-ai/") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs class PartnerModelPrefixes(str, Enum): @@ -125,9 +121,7 @@ def completion( message=f"""vertexai import failed please run `pip install -U "google-cloud-aiplatform>=1.38"`. Got error: {e}""", ) - if not ( - hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models") - ): + if not (hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models")): raise VertexAIError( status_code=400, message="""Upgrade vertex ai. Run `pip install "google-cloud-aiplatform>=1.38"`""", @@ -174,9 +168,7 @@ def completion( if "codestral" in model and litellm_params.get("text_completion") is True: optional_params["model"] = model - text_completion_model_response = litellm.TextCompletionResponse( - stream=stream - ) + text_completion_model_response = litellm.TextCompletionResponse(stream=stream) return codestral_fim_completions.completion( model=model, messages=messages, diff --git a/litellm/llms/vertex_ai/vertex_embeddings/bge.py b/litellm/llms/vertex_ai/vertex_embeddings/bge.py index e3f25b425ff9..6525d3342f5a 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/bge.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/bge.py @@ -57,9 +57,7 @@ def is_bge_model(model: str) -> bool: return model_lower.startswith("bge/") or "bge" in model_lower @staticmethod - def transform_request( - input: Union[list, str], optional_params: dict, model: str - ) -> VertexEmbeddingRequest: + def transform_request(input: Union[list, str], optional_params: dict, model: str) -> VertexEmbeddingRequest: """ Transforms an OpenAI request to a Vertex BGE embedding request. @@ -82,9 +80,7 @@ def transform_request( input = [input] for text in input: - embedding_input = VertexBGEConfig._create_embedding_input( - prompt=text, task_type=task_type, title=title - ) + embedding_input = VertexBGEConfig._create_embedding_input(prompt=text, task_type=task_type, title=title) vertex_text_embedding_input_list.append(embedding_input) vertex_request["instances"] = vertex_text_embedding_input_list @@ -119,9 +115,7 @@ def _create_embedding_input( return text_embedding_input @staticmethod - def transform_response( - response: dict, model: str, model_response: EmbeddingResponse - ) -> EmbeddingResponse: + def transform_response(response: dict, model: str, model_response: EmbeddingResponse) -> EmbeddingResponse: """ Transforms a Vertex BGE embedding response to OpenAI format. @@ -151,9 +145,7 @@ def transform_response( _predictions = response["predictions"] if not isinstance(_predictions, list): - raise ValueError( - f"Expected 'predictions' to be a list, got {type(_predictions)}" - ) + raise ValueError(f"Expected 'predictions' to be a list, got {type(_predictions)}") embedding_response = [] # BGE models don't return token counts, so we estimate or set to 0 @@ -161,9 +153,7 @@ def transform_response( for idx, embedding_values in enumerate(_predictions): if not isinstance(embedding_values, list): - raise ValueError( - f"Expected embedding at index {idx} to be a list, got {type(embedding_values)}" - ) + raise ValueError(f"Expected embedding at index {idx} to be a list, got {type(embedding_values)}") embedding_response.append( { @@ -176,8 +166,6 @@ def transform_response( model_response.object = "list" model_response.data = embedding_response model_response.model = model - usage = Usage( - prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens - ) + usage = Usage(prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens) setattr(model_response, "usage", usage) return model_response diff --git a/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py b/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py index 729cc9c3ead9..0e7afd5da3fc 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/embedding_handler.py @@ -65,9 +65,7 @@ def embedding( litellm_params=litellm_params, ) - should_use_v1beta1_features = self.is_using_v1beta1_features( - optional_params=optional_params - ) + should_use_v1beta1_features = self.is_using_v1beta1_features(optional_params=optional_params) _auth_header, vertex_project = self._ensure_access_token( credentials=vertex_credentials, @@ -92,11 +90,13 @@ def embedding( use_psc_endpoint_format=use_psc_endpoint_format, ) headers = self.set_headers(auth_header=auth_header, extra_headers=extra_headers) - vertex_request: VertexEmbeddingRequest = litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( - input=input, - optional_params=optional_params, - model=model, - litellm_params=litellm_params, + vertex_request: VertexEmbeddingRequest = ( + litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( + input=input, + optional_params=optional_params, + model=model, + litellm_params=litellm_params, + ) ) _client_params = {} @@ -128,14 +128,10 @@ def embedding( _json_response = response.json() ## LOGGING POST-CALL - logging_obj.post_call( - input=input, api_key=None, original_response=_json_response - ) + logging_obj.post_call(input=input, api_key=None, original_response=_json_response) - model_response = ( - litellm.vertexAITextEmbeddingConfig.transform_vertex_response_to_openai( - response=_json_response, model=model, model_response=model_response - ) + model_response = litellm.vertexAITextEmbeddingConfig.transform_vertex_response_to_openai( + response=_json_response, model=model, model_response=model_response ) return model_response @@ -164,9 +160,7 @@ async def async_embedding( """ Async embedding implementation """ - should_use_v1beta1_features = self.is_using_v1beta1_features( - optional_params=optional_params - ) + should_use_v1beta1_features = self.is_using_v1beta1_features(optional_params=optional_params) _auth_header, vertex_project = await self._ensure_access_token_async( credentials=vertex_credentials, project_id=vertex_project, @@ -190,20 +184,20 @@ async def async_embedding( use_psc_endpoint_format=use_psc_endpoint_format, ) headers = self.set_headers(auth_header=auth_header, extra_headers=extra_headers) - vertex_request: VertexEmbeddingRequest = litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( - input=input, - optional_params=optional_params, - model=model, - litellm_params=litellm_params, + vertex_request: VertexEmbeddingRequest = ( + litellm.vertexAITextEmbeddingConfig.transform_openai_request_to_vertex_embedding_request( + input=input, + optional_params=optional_params, + model=model, + litellm_params=litellm_params, + ) ) _async_client_params = {} if timeout: _async_client_params["timeout"] = timeout if client is None or not isinstance(client, AsyncHTTPHandler): - client = get_async_httpx_client( - params=_async_client_params, llm_provider=litellm.LlmProviders.VERTEX_AI - ) + client = get_async_httpx_client(params=_async_client_params, llm_provider=litellm.LlmProviders.VERTEX_AI) else: client = client # type: ignore ## LOGGING @@ -228,14 +222,10 @@ async def async_embedding( _json_response = response.json() ## LOGGING POST-CALL - logging_obj.post_call( - input=input, api_key=None, original_response=_json_response - ) + logging_obj.post_call(input=input, api_key=None, original_response=_json_response) - model_response = ( - litellm.vertexAITextEmbeddingConfig.transform_vertex_response_to_openai( - response=_json_response, model=model, model_response=model_response - ) + model_response = litellm.vertexAITextEmbeddingConfig.transform_vertex_response_to_openai( + response=_json_response, model=model, model_response=model_response ) return model_response diff --git a/litellm/llms/vertex_ai/vertex_embeddings/transformation.py b/litellm/llms/vertex_ai/vertex_embeddings/transformation.py index 24396628dbd4..6b7e6c036c0f 100644 --- a/litellm/llms/vertex_ai/vertex_embeddings/transformation.py +++ b/litellm/llms/vertex_ai/vertex_embeddings/transformation.py @@ -75,9 +75,7 @@ def get_config(cls): def get_supported_openai_params(self): return ["dimensions"] - def map_openai_params( - self, non_default_params: dict, optional_params: dict, kwargs: dict - ): + def map_openai_params(self, non_default_params: dict, optional_params: dict, kwargs: dict): for param, value in non_default_params.items(): if param == "dimensions": optional_params["outputDimensionality"] = value @@ -116,10 +114,8 @@ def transform_openai_request_to_vertex_embedding_request( labels = pop_vertex_request_labels(optional_params, litellm_params) if model.isdigit(): - vertex_request = ( - self._transform_openai_request_to_fine_tuned_embedding_request( - input, optional_params, model - ) + vertex_request = self._transform_openai_request_to_fine_tuned_embedding_request( + input, optional_params, model ) if labels: vertex_request["labels"] = labels @@ -141,9 +137,7 @@ def transform_openai_request_to_vertex_embedding_request( input = [input] # Convert single string to list for uniform processing for text in input: - embedding_input = self.create_embedding_input( - content=text, task_type=task_type, title=title - ) + embedding_input = self.create_embedding_input(content=text, task_type=task_type, title=title) vertex_text_embedding_input_list.append(embedding_input) vertex_request["instances"] = vertex_text_embedding_input_list @@ -188,14 +182,9 @@ def _transform_openai_request_to_fine_tuned_embedding_request( vertex_text_embedding_input_list.append(embedding_input) vertex_request["instances"] = vertex_text_embedding_input_list - vertex_request["parameters"] = TextEmbeddingFineTunedParameters( - **optional_params - ) + vertex_request["parameters"] = TextEmbeddingFineTunedParameters(**optional_params) # Remove 'shared_session' from parameters if present - if ( - vertex_request["parameters"] is not None - and "shared_session" in vertex_request["parameters"] - ): + if vertex_request["parameters"] is not None and "shared_session" in vertex_request["parameters"]: del vertex_request["parameters"]["shared_session"] # type: ignore[typeddict-item] return vertex_request @@ -233,17 +222,13 @@ def transform_vertex_response_to_openai( Transforms a vertex embedding response to an openai response. """ if model.isdigit(): - return self._transform_vertex_response_to_openai_for_fine_tuned_models( - response, model, model_response - ) + return self._transform_vertex_response_to_openai_for_fine_tuned_models(response, model, model_response) # Import here to avoid circular import issues with litellm.__init__ from litellm.llms.vertex_ai.vertex_embeddings.bge import VertexBGEConfig if VertexBGEConfig.is_bge_model(model): - return VertexBGEConfig.transform_response( - response=response, model=model, model_response=model_response - ) + return VertexBGEConfig.transform_response(response=response, model=model, model_response=model_response) _predictions = response["predictions"] @@ -263,9 +248,7 @@ def transform_vertex_response_to_openai( model_response.object = "list" model_response.data = embedding_response model_response.model = model - usage = Usage( - prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens - ) + usage = Usage(prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens) setattr(model_response, "usage", usage) return model_response @@ -286,17 +269,13 @@ def _transform_vertex_response_to_openai_for_fine_tuned_models( { "object": "embedding", "index": idx, - "embedding": embedding_values[ - 0 - ], # The embedding values are nested one level deeper + "embedding": embedding_values[0], # The embedding values are nested one level deeper } ) model_response.object = "list" model_response.data = embedding_response model_response.model = model - usage = Usage( - prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens - ) + usage = Usage(prompt_tokens=input_tokens, completion_tokens=0, total_tokens=input_tokens) setattr(model_response, "usage", usage) return model_response diff --git a/litellm/llms/vertex_ai/vertex_gemma_models/main.py b/litellm/llms/vertex_ai/vertex_gemma_models/main.py index b6bf2f73b723..9622a93c0d80 100644 --- a/litellm/llms/vertex_ai/vertex_gemma_models/main.py +++ b/litellm/llms/vertex_ai/vertex_gemma_models/main.py @@ -71,9 +71,7 @@ def completion( message=f"""vertexai import failed please run `pip install -U "google-cloud-aiplatform>=1.38"`. Got error: {e}""", ) - if not ( - hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models") - ): + if not (hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models")): raise VertexAIError( status_code=400, message="""Upgrade vertex ai. Run `pip install "google-cloud-aiplatform>=1.38"`""", diff --git a/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py b/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py index 35cd54d65f6b..567c8c6a3ee9 100644 --- a/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py +++ b/litellm/llms/vertex_ai/vertex_gemma_models/transformation.py @@ -87,9 +87,7 @@ def transform_request( # Remove params not needed/supported by Vertex Gemma openai_request.pop("model", None) - openai_request.pop( - "stream", None - ) # Streaming not supported, will be faked client-side + openai_request.pop("stream", None) # Streaming not supported, will be faked client-side openai_request.pop("stream_options", None) # Stream options not supported # Vertex Gemma's chatCompletions wrapper does not understand # `context_management` (an Anthropic/Responses API concept). Strip it @@ -264,9 +262,7 @@ def _sync_completion( ) # Return fake stream iterator if streaming was requested - return self._handle_fake_stream_response( - model_response=model_response, stream=stream - ) + return self._handle_fake_stream_response(model_response=model_response, stream=stream) async def _async_completion( self, @@ -359,6 +355,4 @@ async def _async_completion( ) # Return fake stream iterator if streaming was requested - return self._handle_fake_stream_response( - model_response=model_response, stream=stream - ) + return self._handle_fake_stream_response(model_response=model_response, stream=stream) diff --git a/litellm/llms/vertex_ai/vertex_llm_base.py b/litellm/llms/vertex_ai/vertex_llm_base.py index 18a9c98c3150..d57d7bf17df9 100644 --- a/litellm/llms/vertex_ai/vertex_llm_base.py +++ b/litellm/llms/vertex_ai/vertex_llm_base.py @@ -26,8 +26,7 @@ ) GOOGLE_IMPORT_ERROR_MESSAGE = ( - "Google Cloud SDK not found. Install it with: pip install 'litellm[google]' " - "or pip install google-cloud-aiplatform" + "Google Cloud SDK not found. Install it with: pip install 'litellm[google]' or pip install google-cloud-aiplatform" ) if TYPE_CHECKING: @@ -73,9 +72,7 @@ def get_vertex_region(self, vertex_region: Optional[str], model: str) -> str: # Try to get supported_regions directly from model_cost # Check both with and without vertex_ai/ prefix - model_key = ( - f"vertex_ai/{model}" if not model.startswith("vertex_ai/") else model - ) + model_key = f"vertex_ai/{model}" if not model.startswith("vertex_ai/") else model model_info = litellm.model_cost.get(model_key, {}) supported_regions = model_info.get("supported_regions") @@ -86,8 +83,7 @@ def get_vertex_region(self, vertex_region: Optional[str], model: str) -> str: # If user specified a region not supported by this model, override it if vertex_region not in supported_regions: verbose_logger.warning( - "Vertex AI model '%s' does not support region '%s' " - "(supported: %s). Routing to '%s'.", + "Vertex AI model '%s' does not support region '%s' (supported: %s). Routing to '%s'.", model, vertex_region, supported_regions, @@ -128,18 +124,14 @@ def load_auth( elif isinstance(credentials, dict): json_obj = credentials else: - raise ValueError( - "Invalid credentials type: {}".format(type(credentials)) - ) + raise ValueError("Invalid credentials type: {}".format(type(credentials))) # Check if the JSON object contains Workload Identity Federation configuration if "type" in json_obj and json_obj["type"] == "external_account": # If environment_id key contains "aws" value it corresponds to an AWS config file credential_source = json_obj.get("credential_source", {}) environment_id = ( - credential_source.get("environment_id", "") - if isinstance(credential_source, dict) - else "" + credential_source.get("environment_id", "") if isinstance(credential_source, dict) else "" ) if isinstance(environment_id, str) and "aws" in environment_id: # Check if explicit AWS params are in the JSON (bypasses metadata) @@ -159,10 +151,7 @@ def load_auth( json_obj, scopes=["https://www.googleapis.com/auth/cloud-platform"], ) - elif ( - isinstance(credential_source, dict) - and "executable" in credential_source - ): + elif isinstance(credential_source, dict) and "executable" in credential_source: creds = self._credentials_from_pluggable( json_obj, scopes=["https://www.googleapis.com/auth/cloud-platform"], @@ -179,7 +168,9 @@ def load_auth( scopes=["https://www.googleapis.com/auth/cloud-platform"], ) if project_id is None: - project_id = creds.quota_project_id # authorized user credentials don't have a project_id, only quota_project_id + project_id = ( + creds.quota_project_id + ) # authorized user credentials don't have a project_id, only quota_project_id else: creds = self._credentials_from_service_account( json_obj, @@ -201,9 +192,7 @@ def load_auth( raise ValueError("Could not resolve project_id") if not isinstance(project_id, str): - raise TypeError( - f"Expected project_id to be a str but got {type(project_id)}" - ) + raise TypeError(f"Expected project_id to be a str but got {type(project_id)}") return creds, project_id @@ -247,9 +236,7 @@ def _credentials_from_authorized_user(self, json_obj, scopes): except ImportError: raise ImportError(GOOGLE_IMPORT_ERROR_MESSAGE) - return google.oauth2.credentials.Credentials.from_authorized_user_info( - json_obj, scopes=scopes - ) + return google.oauth2.credentials.Credentials.from_authorized_user_info(json_obj, scopes=scopes) def _credentials_from_service_account(self, json_obj, scopes): try: @@ -257,9 +244,7 @@ def _credentials_from_service_account(self, json_obj, scopes): except ImportError: raise ImportError(GOOGLE_IMPORT_ERROR_MESSAGE) - return google.oauth2.service_account.Credentials.from_service_account_info( - json_obj, scopes=scopes - ) + return google.oauth2.service_account.Credentials.from_service_account_info(json_obj, scopes=scopes) def _credentials_from_default_auth(self, scopes): try: @@ -272,14 +257,10 @@ def _credentials_from_default_auth(self, scopes): def get_default_vertex_location(self) -> str: return "us-central1" - def get_api_base( - self, api_base: Optional[str], vertex_location: Optional[str] - ) -> str: + def get_api_base(self, api_base: Optional[str], vertex_location: Optional[str]) -> str: if api_base: return api_base - return get_vertex_base_url( - vertex_location or self.get_default_vertex_location() - ) + return get_vertex_base_url(vertex_location or self.get_default_vertex_location()) @staticmethod def create_vertex_url( @@ -324,9 +305,7 @@ def get_complete_vertex_url( ) -> str: # Use get_vertex_region to handle global-only models resolved_location = self.get_vertex_region(vertex_location, model) - api_base = self.get_api_base( - api_base=custom_api_base, vertex_location=resolved_location - ) + api_base = self.get_api_base(api_base=custom_api_base, vertex_location=resolved_location) default_api_base = VertexBase.create_vertex_url( vertex_location=resolved_location, vertex_project=vertex_project or project_id, @@ -383,17 +362,13 @@ def _acquire_async_refresh_lock(self, credential_cache_key: tuple) -> asyncio.Lo caller is done with the lock so the entry can be pruned when no other coroutine is holding or waiting on it. """ - lock = self._async_refresh_locks.setdefault( - credential_cache_key, asyncio.Lock() - ) + lock = self._async_refresh_locks.setdefault(credential_cache_key, asyncio.Lock()) self._async_refresh_lock_refcounts[credential_cache_key] = ( self._async_refresh_lock_refcounts.get(credential_cache_key, 0) + 1 ) return lock - def _release_async_refresh_lock( - self, credential_cache_key: tuple, lock: asyncio.Lock - ) -> None: + def _release_async_refresh_lock(self, credential_cache_key: tuple, lock: asyncio.Lock) -> None: """Decrement the refcount and drop the lock entry when it reaches zero. Must be called only after the caller has released ``lock`` (i.e. once @@ -459,9 +434,7 @@ def _try_get_usable_cached_token( return None return creds.token, resolved_project, token_state, creds, cached_project_id - def _unpack_cached_credentials( - self, credential_cache_key: tuple - ) -> Tuple[Any, Optional[str]]: + def _unpack_cached_credentials(self, credential_cache_key: tuple) -> Tuple[Any, Optional[str]]: """ Return (credentials, project_id) from the cache, or (None, None) if not cached. Handles both tuple and legacy cache formats. @@ -471,9 +444,7 @@ def _unpack_cached_credentials( cached_entry = self._credentials_project_mapping[credential_cache_key] if isinstance(cached_entry, tuple): return cached_entry - return cached_entry, cached_entry.quota_project_id or getattr( - cached_entry, "project_id", None - ) + return cached_entry, cached_entry.quota_project_id or getattr(cached_entry, "project_id", None) def _get_token_state(self, credentials: Any) -> "TokenState": """ @@ -550,9 +521,7 @@ async def _background_refresh_credentials( exc_info=True, ) - async def _await_in_flight_background_refresh( - self, credential_cache_key: tuple - ) -> None: + async def _await_in_flight_background_refresh(self, credential_cache_key: tuple) -> None: """Wait for an in-flight background refresh to finish, if any. google-auth's ``Credentials.refresh()`` is not safe to invoke @@ -588,9 +557,7 @@ def _schedule_background_refresh( return self._background_refresh_tasks.pop(credential_cache_key, None) task = asyncio.create_task( - self._background_refresh_credentials( - credentials, credential_cache_key, credential_project_id - ) + self._background_refresh_credentials(credentials, credential_cache_key, credential_project_id) ) def _drop_background_refresh_task(_fut: asyncio.Future[Any]) -> None: @@ -664,9 +631,7 @@ def _check_custom_proxy( if custom_llm_provider == "gemini": # For Gemini (Google AI Studio), construct the full path like other providers if model is None: - raise ValueError( - "Model parameter is required for Gemini custom API base URLs" - ) + raise ValueError("Model parameter is required for Gemini custom API base URLs") url = "{}/models/{}:{}".format(api_base, model, endpoint) if gemini_api_key is None: raise ValueError( @@ -795,8 +760,7 @@ def _handle_reauthentication( The original error if reauthentication fails """ verbose_logger.debug( - f"Handling reauthentication for project_id: {project_id}. " - f"Clearing cache and retrying once." + f"Handling reauthentication for project_id: {project_id}. Clearing cache and retrying once." ) # Clear the cached credentials @@ -829,8 +793,7 @@ async def _handle_reauthentication_async( Async reauthentication retry that stays within the per-key async lock. """ verbose_logger.debug( - f"Handling async reauthentication for project_id: {project_id}. " - f"Clearing cache and retrying once." + f"Handling async reauthentication for project_id: {project_id}. Clearing cache and retrying once." ) self._credentials_project_mapping.pop(credential_cache_key, None) @@ -846,11 +809,7 @@ async def _handle_reauthentication_async( ) if project_id is None and isinstance(credential_project_id, str): project_id = credential_project_id - cache_credentials = ( - json.dumps(credentials) - if isinstance(credentials, dict) - else credentials - ) + cache_credentials = json.dumps(credentials) if isinstance(credentials, dict) else credentials resolved_cache_key = (cache_credentials, project_id) # Always overwrite — any pre-existing entry at the resolved key # references the OLD credentials object we just replaced, and @@ -903,20 +862,14 @@ def get_access_token( """ # Convert dict credentials to string for caching - cache_credentials = ( - json.dumps(credentials) if isinstance(credentials, dict) else credentials - ) + cache_credentials = json.dumps(credentials) if isinstance(credentials, dict) else credentials credential_cache_key = (cache_credentials, project_id) _credentials: Optional[GoogleCredentialsObject] = None - verbose_logger.debug( - f"Checking cached credentials for project_id: {project_id}" - ) + verbose_logger.debug(f"Checking cached credentials for project_id: {project_id}") if credential_cache_key in self._credentials_project_mapping: - verbose_logger.debug( - f"Cached credentials found for project_id: {project_id}." - ) + verbose_logger.debug(f"Cached credentials found for project_id: {project_id}.") # Retrieve both credentials and cached project_id cached_entry = self._credentials_project_mapping[credential_cache_key] verbose_logger.debug("cached_entry: %s", cached_entry) @@ -925,9 +878,7 @@ def get_access_token( else: # Backward compatibility with old cache format _credentials = cached_entry - credential_project_id = _credentials.quota_project_id or getattr( - _credentials, "project_id", None - ) + credential_project_id = _credentials.quota_project_id or getattr(_credentials, "project_id", None) verbose_logger.debug( "Using cached credentials for project_id: %s", credential_project_id, @@ -939,9 +890,7 @@ def get_access_token( ) try: - _credentials, credential_project_id = self.load_auth( - credentials=credentials, project_id=project_id - ) + _credentials, credential_project_id = self.load_auth(credentials=credentials, project_id=project_id) except Exception as e: verbose_logger.exception( f"Failed to load vertex credentials. Check to see if credentials containing partial/invalid information. Error: {str(e)}" @@ -962,11 +911,7 @@ def get_access_token( ## VALIDATE CREDENTIALS verbose_logger.debug("Validating credentials") - if ( - project_id is None - and credential_project_id is not None - and isinstance(credential_project_id, str) - ): + if project_id is None and credential_project_id is not None and isinstance(credential_project_id, str): project_id = credential_project_id # Update cache with resolved project_id for future lookups resolved_cache_key = (cache_credentials, project_id) @@ -1030,9 +975,7 @@ async def get_access_token_async( """ from google.auth.credentials import TokenState - cache_credentials = ( - json.dumps(credentials) if isinstance(credentials, dict) else credentials - ) + cache_credentials = json.dumps(credentials) if isinstance(credentials, dict) else credentials credential_cache_key = (cache_credentials, project_id) # === FAST PATH (no lock) === @@ -1043,13 +986,9 @@ async def get_access_token_async( # callers on the lock just to schedule that refresh. usable = self._try_get_usable_cached_token(credential_cache_key, project_id) if usable is not None: - cached_token, resolved_project, token_state, creds, cached_project_id = ( - usable - ) + cached_token, resolved_project, token_state, creds, cached_project_id = usable if token_state == TokenState.STALE: - self._schedule_background_refresh( - creds, credential_cache_key, cached_project_id - ) + self._schedule_background_refresh(creds, credential_cache_key, cached_project_id) return cached_token, resolved_project # === SLOW PATH (per-key lock) === @@ -1061,18 +1000,14 @@ async def get_access_token_async( if cached is not None: return cached - _credentials, credential_project_id = self._unpack_cached_credentials( - credential_cache_key - ) + _credentials, credential_project_id = self._unpack_cached_credentials(credential_cache_key) # Load credentials if not cached if _credentials is None: ( _credentials, credential_project_id, - ) = await self._load_and_cache_credentials( - credentials, project_id, credential_cache_key - ) + ) = await self._load_and_cache_credentials(credentials, project_id, credential_cache_key) # Resolve project_id from credentials if not provided if project_id is None and isinstance(credential_project_id, str): @@ -1117,9 +1052,7 @@ async def get_access_token_async( # on the same credentials object, and the background task # runs outside this lock. await self._await_in_flight_background_refresh(credential_cache_key) - cached = self._try_get_cached_token( - credential_cache_key, project_id - ) + cached = self._try_get_cached_token(credential_cache_key, project_id) if cached is not None: return cached @@ -1133,9 +1066,7 @@ async def get_access_token_async( ) except Exception as e: if "Reauthentication is needed" in str(e): - verbose_logger.debug( - "Reauthentication needed, clearing cache and retrying" - ) + verbose_logger.debug("Reauthentication needed, clearing cache and retrying") return await self._handle_reauthentication_async( credentials=credentials, project_id=project_id, @@ -1145,9 +1076,7 @@ async def get_access_token_async( raise # Final validation - if _credentials.token is None or not isinstance( - _credentials.token, str - ): + if _credentials.token is None or not isinstance(_credentials.token, str): raise ValueError( "Could not resolve credentials token. Got None or non-string token (type={})".format( type(_credentials.token).__name__ @@ -1179,9 +1108,7 @@ async def _ensure_access_token_async( project_id=project_id, ) - def set_headers( - self, auth_header: Optional[str], extra_headers: Optional[dict] - ) -> dict: + def set_headers(self, auth_header: Optional[str], extra_headers: Optional[dict]) -> dict: headers = { "Content-Type": "application/json", } diff --git a/litellm/llms/vertex_ai/vertex_model_garden/main.py b/litellm/llms/vertex_ai/vertex_model_garden/main.py index f54b8d935005..bd9d95e6d047 100644 --- a/litellm/llms/vertex_ai/vertex_model_garden/main.py +++ b/litellm/llms/vertex_ai/vertex_model_garden/main.py @@ -48,10 +48,7 @@ def create_vertex_url( """Return the api base for vertex model garden (without /chat/completions).""" base_url = get_vertex_base_url(vertex_location) if _vertex_model_garden_model_id_in_json_body(model): - return ( - f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}" - "/endpoints/openapi" - ) + return f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/endpoints/openapi" return f"{base_url}/v1beta1/projects/{vertex_project}/locations/{vertex_location}/endpoints/{model}" @@ -95,9 +92,7 @@ def completion( message=f"""vertexai import failed please run `pip install -U "google-cloud-aiplatform>=1.38"`. Got error: {e}""", ) - if not ( - hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models") - ): + if not (hasattr(vertexai, "preview") or hasattr(vertexai.preview, "language_models")): raise VertexAIError( status_code=400, message="""Upgrade vertex ai. Run `pip install "google-cloud-aiplatform>=1.38"`""", diff --git a/litellm/llms/vertex_ai/videos/transformation.py b/litellm/llms/vertex_ai/videos/transformation.py index b84966354b89..98af8ca30ea3 100644 --- a/litellm/llms/vertex_ai/videos/transformation.py +++ b/litellm/llms/vertex_ai/videos/transformation.py @@ -49,9 +49,7 @@ def _build_vertex_video_usage_from_request_data( return usage_data parameters = request_data.get("parameters", {}) - duration = ( - parameters.get("durationSeconds") or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS - ) + duration = parameters.get("durationSeconds") or DEFAULT_GOOGLE_VIDEO_DURATION_SECONDS if duration is not None: try: usage_data["duration_seconds"] = float(duration) @@ -203,16 +201,10 @@ def validate_environment( # Extract Vertex AI parameters using safe helpers from VertexBase # Use safe_get_* methods that don't mutate litellm_params dict # Ensure litellm_params is a dict for type checking - params_dict: Dict[str, Any] = ( - cast(Dict[str, Any], litellm_params) if litellm_params is not None else {} - ) + params_dict: Dict[str, Any] = cast(Dict[str, Any], litellm_params) if litellm_params is not None else {} - vertex_project = VertexBase.safe_get_vertex_ai_project( - litellm_params=params_dict - ) - vertex_credentials = VertexBase.safe_get_vertex_ai_credentials( - litellm_params=params_dict - ) + vertex_project = VertexBase.safe_get_vertex_ai_project(litellm_params=params_dict) + vertex_credentials = VertexBase.safe_get_vertex_ai_credentials(litellm_params=params_dict) # Get access token from Vertex credentials access_token, project_id = self.get_access_token( @@ -261,7 +253,9 @@ def get_complete_url( else: base_url = get_vertex_base_url(vertex_location) - url = f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/google/models/{model_name}" + url = ( + f"{base_url}/v1/projects/{vertex_project}/locations/{vertex_location}/publishers/google/models/{model_name}" + ) return url @@ -376,15 +370,11 @@ def transform_video_create_response( raise ValueError(f"No operation name in Veo response: {response_data}") if custom_llm_provider: - video_id = encode_video_id_with_provider( - operation_name, custom_llm_provider, model - ) + video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, model) else: video_id = operation_name - video_obj = VideoObject( - id=video_id, object="video", status="processing", model=model - ) + video_obj = VideoObject(id=video_id, object="video", status="processing", model=model) video_obj.usage = _build_vertex_video_usage_from_request_data(request_data) return video_obj @@ -461,9 +451,7 @@ def transform_video_status_retrieve_response( model = self.extract_model_from_operation_name(operation_name) if custom_llm_provider: - video_id = encode_video_id_with_provider( - operation_name, custom_llm_provider, model - ) + video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, model) else: video_id = operation_name @@ -471,9 +459,7 @@ def transform_video_status_retrieve_response( create_time_str = response_data.get("metadata", {}).get("createTime") if create_time_str: try: - created_at = _convert_vertex_datetime_to_openai_datetime( - create_time_str - ) + created_at = _convert_vertex_datetime_to_openai_datetime(create_time_str) except Exception: created_at = int(time.time()) else: @@ -515,9 +501,7 @@ def transform_video_content_request( Since we need to make an HTTP call here, we'll use the same fetchPredictOperation approach as status retrieval. """ - return self.transform_video_status_retrieve_request( - video_id, api_base, litellm_params, headers - ) + return self.transform_video_status_retrieve_request(video_id, api_base, litellm_params, headers) def transform_video_content_response( self, @@ -533,8 +517,7 @@ def transform_video_content_response( if not response_data.get("done", False): raise ValueError( - "Video generation is not complete yet. " - "Please check status with video_status() before downloading." + "Video generation is not complete yet. Please check status with video_status() before downloading." ) try: @@ -571,8 +554,7 @@ def transform_video_remix_request( Video remix is not supported by Veo API. """ raise NotImplementedError( - "Video remix is not supported by Vertex AI Veo. " - "Please use video_generation() to create new videos." + "Video remix is not supported by Vertex AI Veo. Please use video_generation() to create new videos." ) def transform_video_remix_response( @@ -622,8 +604,7 @@ def transform_video_delete_request( Video delete is not supported by Veo API. """ raise NotImplementedError( - "Video delete is not supported by Vertex AI Veo. " - "Videos are automatically cleaned up by Google." + "Video delete is not supported by Vertex AI Veo. Videos are automatically cleaned up by Google." ) def transform_video_delete_response( @@ -634,21 +615,13 @@ def transform_video_delete_response( """Video delete is not supported.""" raise NotImplementedError("Video delete is not supported by Vertex AI Veo.") - def transform_video_create_character_request( - self, name, video, api_base, litellm_params, headers - ): - raise NotImplementedError( - "video create character is not supported for Vertex AI" - ) + def transform_video_create_character_request(self, name, video, api_base, litellm_params, headers): + raise NotImplementedError("video create character is not supported for Vertex AI") def transform_video_create_character_response(self, raw_response, logging_obj): - raise NotImplementedError( - "video create character is not supported for Vertex AI" - ) + raise NotImplementedError("video create character is not supported for Vertex AI") - def transform_video_get_character_request( - self, character_id, api_base, litellm_params, headers - ): + def transform_video_get_character_request(self, character_id, api_base, litellm_params, headers): raise NotImplementedError("video get character is not supported for Vertex AI") def transform_video_get_character_response(self, raw_response, logging_obj): @@ -692,10 +665,7 @@ def transform_video_edit_request( ) if not prefetched_source_data.get("done", False): - raise ValueError( - "Source video generation is not complete yet. " - "Check the video status before editing." - ) + raise ValueError("Source video generation is not complete yet. Check the video status before editing.") videos = prefetched_source_data.get("response", {}).get("videos", []) if not videos: @@ -709,9 +679,7 @@ def transform_video_edit_request( video_input["bytesBase64Encoded"] = source_video["bytesBase64Encoded"] video_input["mimeType"] = source_video.get("mimeType", "video/mp4") else: - raise ValueError( - "Source video has neither gcsUri nor bytesBase64Encoded. Cannot edit." - ) + raise ValueError("Source video has neither gcsUri nor bytesBase64Encoded. Cannot edit.") operation_name = extract_original_video_id(video_id) model = self.extract_model_from_operation_name(operation_name) or "" @@ -757,9 +725,7 @@ def transform_video_edit_response( model = self.extract_model_from_operation_name(operation_name) or "" if custom_llm_provider: - video_id = encode_video_id_with_provider( - operation_name, custom_llm_provider, model - ) + video_id = encode_video_id_with_provider(operation_name, custom_llm_provider, model) else: video_id = operation_name @@ -784,9 +750,7 @@ def transform_video_extension_request( ): raise NotImplementedError("video extension is not supported for Vertex AI") - def transform_video_extension_response( - self, raw_response, logging_obj, custom_llm_provider=None - ): + def transform_video_extension_response(self, raw_response, logging_obj, custom_llm_provider=None): raise NotImplementedError("video extension is not supported for Vertex AI") def get_error_class( diff --git a/litellm/llms/vllm/common_utils.py b/litellm/llms/vllm/common_utils.py index e2ed0daafe4b..1d6b8d7897ee 100644 --- a/litellm/llms/vllm/common_utils.py +++ b/litellm/llms/vllm/common_utils.py @@ -60,9 +60,7 @@ def get_api_key(api_key: Optional[str] = None) -> Optional[str]: def get_base_model(model: str) -> Optional[str]: return model - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: api_base = VLLMModelInfo.get_api_base(api_base) api_key = VLLMModelInfo.get_api_key(api_key) endpoint = "/v1/models" @@ -85,6 +83,4 @@ def get_models( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return VLLMError( - status_code=status_code, message=error_message, headers=headers - ) + return VLLMError(status_code=status_code, message=error_message, headers=headers) diff --git a/litellm/llms/vllm/completion/handler.py b/litellm/llms/vllm/completion/handler.py index 1f13082917f6..cb352b599f91 100644 --- a/litellm/llms/vllm/completion/handler.py +++ b/litellm/llms/vllm/completion/handler.py @@ -18,9 +18,7 @@ def __init__(self, status_code, message): self.message = message self.request = httpx.Request(method="POST", url="http://0.0.0.0:8000") self.response = httpx.Response(status_code=status_code, request=self.request) - super().__init__( - self.message - ) # Call the base class constructor with the parameters it needs + super().__init__(self.message) # Call the base class constructor with the parameters it needs # check if vllm is installed @@ -76,9 +74,7 @@ def completion( if llm: outputs = llm.generate(prompt, sampling_params) else: - raise VLLMError( - status_code=0, message="Need to pass in a model name to initialize vllm" - ) + raise VLLMError(status_code=0, message="Need to pass in a model name to initialize vllm") ## COMPLETION CALL if "stream" in optional_params and optional_params["stream"] is True: @@ -110,9 +106,7 @@ def completion( return model_response -def batch_completions( - model: str, messages: list, optional_params=None, custom_prompt_dict={} -): +def batch_completions(model: str, messages: list, optional_params=None, custom_prompt_dict={}): """ Example usage: import litellm @@ -164,9 +158,7 @@ def batch_completions( if llm: outputs = llm.generate(prompts, sampling_params) else: - raise VLLMError( - status_code=0, message="Need to pass in a model name to initialize vllm" - ) + raise VLLMError(status_code=0, message="Need to pass in a model name to initialize vllm") final_outputs = [] for output in outputs: diff --git a/litellm/llms/volcengine/chat/transformation.py b/litellm/llms/volcengine/chat/transformation.py index d60f54615fa6..c6dbbdbce60c 100644 --- a/litellm/llms/volcengine/chat/transformation.py +++ b/litellm/llms/volcengine/chat/transformation.py @@ -96,13 +96,10 @@ def map_openai_params( if ( thinking_value is not None and isinstance(thinking_value, dict) - and thinking_value.get("type", None) - in ["enabled", "disabled", "auto"] # legal values, see docs + and thinking_value.get("type", None) in ["enabled", "disabled", "auto"] # legal values, see docs ): # Add thinking parameter to extra_body for all legal cases - optional_params.setdefault("extra_body", {})["thinking"] = ( - thinking_value - ) + optional_params.setdefault("extra_body", {})["thinking"] = thinking_value else: # Skip adding thinking parameter when it's not set or has invalid value pass diff --git a/litellm/llms/volcengine/common_utils.py b/litellm/llms/volcengine/common_utils.py index 0c8d3daebdc7..be6390864379 100644 --- a/litellm/llms/volcengine/common_utils.py +++ b/litellm/llms/volcengine/common_utils.py @@ -14,15 +14,11 @@ class VolcEngineError(BaseLLMException): Custom exception class for Volcengine provider errors. """ - def __init__( - self, status_code: int, message: str, headers: Optional[httpx.Headers] = None - ): + def __init__(self, status_code: int, message: str, headers: Optional[httpx.Headers] = None): self.status_code = status_code self.message = message self.headers = headers or httpx.Headers() - super().__init__( - status_code=status_code, message=message, headers=dict(self.headers) - ) + super().__init__(status_code=status_code, message=message, headers=dict(self.headers)) def get_volcengine_base_url(api_base: Optional[str] = None) -> str: diff --git a/litellm/llms/volcengine/responses/transformation.py b/litellm/llms/volcengine/responses/transformation.py index 99e0a958ef1a..569501519696 100644 --- a/litellm/llms/volcengine/responses/transformation.py +++ b/litellm/llms/volcengine/responses/transformation.py @@ -92,20 +92,14 @@ def get_supported_openai_params(self, model: str) -> list: def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> VolcEngineError: - typed_headers: httpx.Headers = ( - headers - if isinstance(headers, httpx.Headers) - else httpx.Headers(headers or {}) - ) + typed_headers: httpx.Headers = headers if isinstance(headers, httpx.Headers) else httpx.Headers(headers or {}) return VolcEngineError( status_code=status_code, message=error_message, headers=typed_headers, ) - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Build auth headers for Volcengine Responses API. """ @@ -122,9 +116,7 @@ def validate_environment( ) if api_key is None: - raise ValueError( - "Volcengine API key is required. Set ARK_API_KEY / VOLCENGINE_API_KEY or pass api_key." - ) + raise ValueError("Volcengine API key is required. Set ARK_API_KEY / VOLCENGINE_API_KEY or pass api_key.") return get_volcengine_headers(api_key=api_key, extra_headers=headers) @@ -173,9 +165,7 @@ def map_openai_params( # Volcengine docs do not list parallel_tool_calls; drop it to avoid backend errors. if "parallel_tool_calls" in params: - verbose_logger.debug( - "Volcengine Responses API: dropping unsupported 'parallel_tool_calls' param." - ) + verbose_logger.debug("Volcengine Responses API: dropping unsupported 'parallel_tool_calls' param.") params.pop("parallel_tool_calls", None) return params @@ -195,11 +185,7 @@ def transform_responses_api_request( """ allowed = set(self._SUPPORTED_OPTIONAL_PARAMS) - sanitized_optional = { - k: v - for k, v in response_api_optional_request_params.items() - if k in allowed - } + sanitized_optional = {k: v for k, v in response_api_optional_request_params.items() if k in allowed} # Ensure metadata never reaches provider sanitized_optional.pop("metadata", None) sanitized_optional.pop("parallel_tool_calls", None) @@ -207,11 +193,7 @@ def transform_responses_api_request( # If extra_body is provided, filter its keys against the same allowlist to avoid # leaking unsupported params to the provider. if isinstance(sanitized_optional.get("extra_body"), dict): - filtered_body = { - k: v - for k, v in sanitized_optional["extra_body"].items() - if k in allowed - } + filtered_body = {k: v for k, v in sanitized_optional["extra_body"].items() if k in allowed} if filtered_body: sanitized_optional["extra_body"] = filtered_body else: @@ -247,9 +229,7 @@ def transform_streaming_response( chunk = patched_chunk event_type = str(chunk.get("type")) if isinstance(chunk, dict) else None - event_pydantic_model = OpenAIResponsesAPIConfig.get_event_model_class( - event_type=event_type - ) + event_pydantic_model = OpenAIResponsesAPIConfig.get_event_model_class(event_type=event_type) patched_chunk = self._fill_missing_fields(chunk, event_pydantic_model) @@ -268,13 +248,9 @@ def transform_response_api_response( ) raw_response_json = raw_response.json() if "created_at" in raw_response_json: - raw_response_json["created_at"] = _safe_convert_created_field( - raw_response_json["created_at"] - ) + raw_response_json["created_at"] = _safe_convert_created_field(raw_response_json["created_at"]) except Exception: - raise VolcEngineError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VolcEngineError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) @@ -282,9 +258,7 @@ def transform_response_api_response( try: response = ResponsesAPIResponse(**raw_response_json) except Exception: - verbose_logger.debug( - "Volcengine Responses API: falling back to model_construct for response parsing." - ) + verbose_logger.debug("Volcengine Responses API: falling back to model_construct for response parsing.") response = ResponsesAPIResponse.model_construct(**raw_response_json) response._hidden_params["additional_headers"] = processed_headers @@ -301,9 +275,7 @@ def transform_delete_response_api_request( litellm_params: GenericLiteLLMParams, headers: dict, ) -> Tuple[str, Dict]: - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}" data: Dict = {} return url, data @@ -316,9 +288,7 @@ def transform_delete_response_api_response( try: raw_response_json = raw_response.json() except Exception: - raise VolcEngineError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VolcEngineError(message=raw_response.text, status_code=raw_response.status_code) try: return DeleteResponseResult(**raw_response_json) except Exception: @@ -337,9 +307,7 @@ def transform_get_response_api_request( litellm_params: GenericLiteLLMParams, headers: dict, ) -> Tuple[str, Dict]: - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}" data: Dict = {} return url, data @@ -352,9 +320,7 @@ def transform_get_response_api_response( try: raw_response_json = raw_response.json() except Exception: - raise VolcEngineError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VolcEngineError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) @@ -379,9 +345,7 @@ def transform_list_input_items_request( limit: int = 20, order: Literal["asc", "desc"] = "desc", ) -> Tuple[str, Dict]: - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}/input_items" params: Dict[str, Any] = {} if after is not None: @@ -404,9 +368,7 @@ def transform_list_input_items_response( try: return raw_response.json() except Exception: - raise VolcEngineError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VolcEngineError(message=raw_response.text, status_code=raw_response.status_code) ######################################################### ########## CANCEL RESPONSE API TRANSFORMATION ########## @@ -418,9 +380,7 @@ def transform_cancel_response_api_request( litellm_params: GenericLiteLLMParams, headers: dict, ) -> Tuple[str, Dict]: - encoded_response_id = encode_url_path_segment( - response_id, field_name="response_id" - ) + encoded_response_id = encode_url_path_segment(response_id, field_name="response_id") url = f"{api_base}/{encoded_response_id}/cancel" data: Dict = {} return url, data @@ -433,9 +393,7 @@ def transform_cancel_response_api_response( try: raw_response_json = raw_response.json() except Exception: - raise VolcEngineError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VolcEngineError(message=raw_response.text, status_code=raw_response.status_code) raw_response_headers = dict(raw_response.headers) processed_headers = process_response_headers(raw_response_headers) @@ -471,29 +429,19 @@ def _fill_missing_fields(chunk: Any, event_model: Any) -> Dict[str, Any]: for name, field in fields_map.items(): if name in patched: - patched[name] = VolcEngineResponsesAPIConfig._maybe_fill_nested( - patched[name], field.annotation - ) + patched[name] = VolcEngineResponsesAPIConfig._maybe_fill_nested(patched[name], field.annotation) continue # Explicit default or factory - if ( - field.default is not pyd_fields.PydanticUndefined - and field.default is not None - ): + if field.default is not pyd_fields.PydanticUndefined and field.default is not None: patched[name] = field.default continue - if ( - field.default_factory is not None - and field.default_factory is not pyd_fields.PydanticUndefined - ): + if field.default_factory is not None and field.default_factory is not pyd_fields.PydanticUndefined: patched[name] = field.default_factory() continue # Heuristic defaults for missing required fields - patched[name] = VolcEngineResponsesAPIConfig._default_for_annotation( - field.annotation - ) + patched[name] = VolcEngineResponsesAPIConfig._default_for_annotation(field.annotation) return patched @@ -533,10 +481,7 @@ def _maybe_fill_nested(value: Any, annotation: Any) -> Any: # Attempt to fill list elements if we know the element annotation elem_ann: Any = args[0] if args else None if elem_ann is not None: - return [ - VolcEngineResponsesAPIConfig._maybe_fill_nested(v, elem_ann) - for v in value - ] + return [VolcEngineResponsesAPIConfig._maybe_fill_nested(v, elem_ann) for v in value] return value diff --git a/litellm/llms/voyage/embedding/transformation.py b/litellm/llms/voyage/embedding/transformation.py index 91811e03927d..7193fd2f10a0 100644 --- a/litellm/llms/voyage/embedding/transformation.py +++ b/litellm/llms/voyage/embedding/transformation.py @@ -19,9 +19,7 @@ def __init__( ): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.voyageai.com/v1/embeddings" - ) + self.request = httpx.Request(method="POST", url="https://api.voyageai.com/v1/embeddings") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( status_code=status_code, @@ -124,9 +122,7 @@ def transform_embedding_response( try: raw_response_json = raw_response.json() except Exception: - raise VoyageError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VoyageError(message=raw_response.text, status_code=raw_response.status_code) # model_response.usage model_response.model = raw_response_json.get("model") @@ -143,6 +139,4 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return VoyageError( - message=error_message, status_code=status_code, headers=headers - ) + return VoyageError(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/voyage/embedding/transformation_contextual.py b/litellm/llms/voyage/embedding/transformation_contextual.py index 1f5ca99f47d9..d7cca3c87a85 100644 --- a/litellm/llms/voyage/embedding/transformation_contextual.py +++ b/litellm/llms/voyage/embedding/transformation_contextual.py @@ -24,9 +24,7 @@ def __init__( ): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.voyageai.com/v1/contextualizedembeddings" - ) + self.request = httpx.Request(method="POST", url="https://api.voyageai.com/v1/contextualizedembeddings") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( status_code=status_code, @@ -126,9 +124,7 @@ def transform_embedding_response( try: raw_response_json = raw_response.json() except Exception: - raise VoyageError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VoyageError(message=raw_response.text, status_code=raw_response.status_code) # model_response.usage model_response.model = raw_response_json.get("model") @@ -145,9 +141,7 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return VoyageError( - message=error_message, status_code=status_code, headers=headers - ) + return VoyageError(message=error_message, status_code=status_code, headers=headers) @staticmethod def is_contextualized_embeddings(model: str) -> bool: diff --git a/litellm/llms/voyage/embedding/transformation_multimodal.py b/litellm/llms/voyage/embedding/transformation_multimodal.py index 55e221b065bd..916037054ef6 100644 --- a/litellm/llms/voyage/embedding/transformation_multimodal.py +++ b/litellm/llms/voyage/embedding/transformation_multimodal.py @@ -27,9 +27,7 @@ def __init__( ): self.status_code = status_code self.message = message - self.request = httpx.Request( - method="POST", url="https://api.voyageai.com/v1/multimodalembeddings" - ) + self.request = httpx.Request(method="POST", url="https://api.voyageai.com/v1/multimodalembeddings") self.response = httpx.Response(status_code=status_code, request=self.request) super().__init__( status_code=status_code, @@ -124,10 +122,7 @@ def _normalize_input_item(self, item: Any) -> Dict[str, Any]: content = item.get("content") or [] return { **item, - "content": [ - self._normalize_content_item(content_item) - for content_item in content - ], + "content": [self._normalize_content_item(content_item) for content_item in content], } return item @@ -159,9 +154,7 @@ def transform_embedding_response( try: raw_response_json = raw_response.json() except Exception: - raise VoyageMultimodalEmbeddingError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VoyageMultimodalEmbeddingError(message=raw_response.text, status_code=raw_response.status_code) model_response.model = raw_response_json.get("model") model_response.data = raw_response_json.get("data") @@ -178,6 +171,4 @@ def transform_embedding_response( def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: - return VoyageMultimodalEmbeddingError( - message=error_message, status_code=status_code, headers=headers - ) + return VoyageMultimodalEmbeddingError(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/voyage/rerank/transformation.py b/litellm/llms/voyage/rerank/transformation.py index 05991d4cc8ce..e426e39962b6 100644 --- a/litellm/llms/voyage/rerank/transformation.py +++ b/litellm/llms/voyage/rerank/transformation.py @@ -88,9 +88,7 @@ def transform_rerank_response( litellm_params: Dict = {}, ) -> RerankResponse: if raw_response.status_code != 200: - raise VoyageError( - message=raw_response.text, status_code=raw_response.status_code - ) + raise VoyageError(message=raw_response.text, status_code=raw_response.status_code) logging_obj.post_call(original_response=raw_response.text) @@ -141,13 +139,9 @@ def validate_environment( optional_params: dict | None = None, ) -> Dict: if api_key is None: - api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str( - "VOYAGE_AI_API_KEY" - ) + api_key = get_secret_str("VOYAGE_API_KEY") or get_secret_str("VOYAGE_AI_API_KEY") if api_key is None: - raise ValueError( - "Voyage AI API key is required. Set via `api_key` parameter or `VOYAGE_API_KEY` env var." - ) + raise ValueError("Voyage AI API key is required. Set via `api_key` parameter or `VOYAGE_API_KEY` env var.") return { "Authorization": f"Bearer {api_key}", "content-type": "application/json", @@ -172,9 +166,5 @@ def calculate_rerank_cost( return 0.0, 0.0 return model_info["input_cost_per_token"] * total_tokens, 0.0 - def get_error_class( - self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] - ): - return VoyageError( - message=error_message, status_code=status_code, headers=headers - ) + def get_error_class(self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]): + return VoyageError(message=error_message, status_code=status_code, headers=headers) diff --git a/litellm/llms/watsonx/audio_transcription/transformation.py b/litellm/llms/watsonx/audio_transcription/transformation.py index 5944705258e8..6d28790b8d12 100644 --- a/litellm/llms/watsonx/audio_transcription/transformation.py +++ b/litellm/llms/watsonx/audio_transcription/transformation.py @@ -25,9 +25,7 @@ from ..common_utils import IBMWatsonXMixin -class IBMWatsonXAudioTranscriptionConfig( - IBMWatsonXMixin, OpenAIWhisperAudioTranscriptionConfig -): +class IBMWatsonXAudioTranscriptionConfig(IBMWatsonXMixin, OpenAIWhisperAudioTranscriptionConfig): """ IBM WatsonX Audio Transcription Config @@ -65,9 +63,7 @@ def validate_environment( result.pop("Content-Type", None) return result - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIAudioTranscriptionOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIAudioTranscriptionOptionalParams]: """ Get the supported OpenAI params for WatsonX audio transcription. """ @@ -98,9 +94,7 @@ def transform_audio_transcription_request( """ # Use common utility to process the audio file processed_audio = process_audio_file(audio_file) - project_id = optional_params.get("project_id") or optional_params.get( - "watsonx_project" - ) + project_id = optional_params.get("project_id") or optional_params.get("watsonx_project") space_id = optional_params.get("space_id") # api_params = _get_api_params(params=optional_params, model=model) @@ -157,10 +151,7 @@ def get_complete_url( url = f"{url}/ml/v1/audio/transcriptions" # Add version parameter (only version in query string, not project_id) - api_version = ( - optional_params.get("api_version", None) - or litellm.WATSONX_DEFAULT_API_VERSION - ) + api_version = optional_params.get("api_version", None) or litellm.WATSONX_DEFAULT_API_VERSION url = f"{url}?version={api_version}" return url @@ -178,9 +169,7 @@ def transform_audio_transcription_response( try: raw_response_json = raw_response.json() except Exception as e: - raise ValueError( - f"Error transforming response to json: {str(e)}\nResponse: {raw_response.text}" - ) + raise ValueError(f"Error transforming response to json: {str(e)}\nResponse: {raw_response.text}") # Extract only valid fields for TranscriptionResponse.__init__() # TranscriptionResponse only accepts 'text' and 'usage' in __init__() diff --git a/litellm/llms/watsonx/chat/transformation.py b/litellm/llms/watsonx/chat/transformation.py index 157493a4ce89..8c938e8dc4d8 100644 --- a/litellm/llms/watsonx/chat/transformation.py +++ b/litellm/llms/watsonx/chat/transformation.py @@ -69,17 +69,13 @@ def map_openai_params( optional_params["tool_choice_option"] = _tool_choice elif _tool_choice is not None: optional_params["tool_choice"] = _tool_choice - return super().map_openai_params( - non_default_params, optional_params, model, drop_params - ) + return super().map_openai_params(non_default_params, optional_params, model, drop_params) def _get_openai_compatible_provider_info( self, api_base: Optional[str], api_key: Optional[str] ) -> Tuple[Optional[str], Optional[str]]: api_base = api_base or get_secret_str("HOSTED_VLLM_API_BASE") # type: ignore - dynamic_api_key = ( - api_key or get_secret_str("HOSTED_VLLM_API_KEY") or "" - ) # vllm does not require an api key + dynamic_api_key = api_key or get_secret_str("HOSTED_VLLM_API_KEY") or "" # vllm does not require an api key return api_base, dynamic_api_key def get_complete_url( @@ -95,29 +91,19 @@ def get_complete_url( if model.startswith("deployment/"): deployment_id = "/".join(model.split("/")[1:]) endpoint = ( - WatsonXAIEndpoint.DEPLOYMENT_CHAT_STREAM.value - if stream - else WatsonXAIEndpoint.DEPLOYMENT_CHAT.value + WatsonXAIEndpoint.DEPLOYMENT_CHAT_STREAM.value if stream else WatsonXAIEndpoint.DEPLOYMENT_CHAT.value ) endpoint = endpoint.format(deployment_id=deployment_id) else: - endpoint = ( - WatsonXAIEndpoint.CHAT_STREAM.value - if stream - else WatsonXAIEndpoint.CHAT.value - ) + endpoint = WatsonXAIEndpoint.CHAT_STREAM.value if stream else WatsonXAIEndpoint.CHAT.value url = url.rstrip("/") + endpoint ## add api version - url = self._add_api_version_to_url( - url=url, api_version=optional_params.pop("api_version", None) - ) + url = self._add_api_version_to_url(url=url, api_version=optional_params.pop("api_version", None)) return url @staticmethod - def _apply_prompt_template_core( - model: str, messages: List[Dict[str, str]], hf_template_fn - ) -> Optional[str]: + def _apply_prompt_template_core(model: str, messages: List[Dict[str, str]], hf_template_fn) -> Optional[str]: """Core logic for applying prompt templates""" from litellm.litellm_core_utils.prompt_templates.factory import ( custom_prompt, @@ -169,9 +155,7 @@ def _apply_prompt_template_core( return None @staticmethod - async def aapply_prompt_template( - model: str, messages: List[Dict[str, str]] - ) -> Optional[str]: + async def aapply_prompt_template(model: str, messages: List[Dict[str, str]]) -> Optional[str]: """Apply prompt template (async version)""" import litellm from litellm.litellm_core_utils.prompt_templates.factory import ( @@ -208,9 +192,7 @@ async def aapply_prompt_template( # Log the exception for debugging but don't raise it # The caller will fall back to default prompt factory try: - verbose_logger.debug( - f"Failed to apply HuggingFace template for model {hf_model}: {e}" - ) + verbose_logger.debug(f"Failed to apply HuggingFace template for model {hf_model}: {e}") except Exception: # If logging fails, silently continue - don't break the flow pass @@ -237,9 +219,7 @@ async def aapply_prompt_template( return None @staticmethod - def apply_prompt_template( - model: str, messages: List[Dict[str, str]] - ) -> Optional[str]: + def apply_prompt_template(model: str, messages: List[Dict[str, str]]) -> Optional[str]: """Apply prompt template (sync version)""" from litellm.litellm_core_utils.prompt_templates.factory import ( hf_chat_template, diff --git a/litellm/llms/watsonx/common_utils.py b/litellm/llms/watsonx/common_utils.py index 2aead929c8d2..d1b065dbc6d1 100644 --- a/litellm/llms/watsonx/common_utils.py +++ b/litellm/llms/watsonx/common_utils.py @@ -26,9 +26,7 @@ def __init__( def get_watsonx_iam_url(): - return ( - get_secret_str("WATSONX_IAM_URL") or "https://iam.cloud.ibm.com/identity/token" - ) + return get_secret_str("WATSONX_IAM_URL") or "https://iam.cloud.ibm.com/identity/token" def generate_iam_token(api_key=None, **params) -> str: @@ -58,9 +56,7 @@ def generate_iam_token(api_key=None, **params) -> str: headers, data, ) - response = litellm.module_level_client.post( - url=iam_token_url, data=data, headers=headers - ) + response = litellm.module_level_client.post(url=iam_token_url, data=data, headers=headers) response.raise_for_status() json_data = response.json() @@ -99,16 +95,10 @@ def _get_api_params(params: dict, model: Optional[str] = None) -> WatsonXAPIPara # Load auth variables from environment variables if project_id is None: project_id = ( - get_secret_str("WATSONX_PROJECT_ID") - or get_secret_str("WX_PROJECT_ID") - or get_secret_str("PROJECT_ID") + get_secret_str("WATSONX_PROJECT_ID") or get_secret_str("WX_PROJECT_ID") or get_secret_str("PROJECT_ID") ) if region_name is None: - region_name = ( - get_secret_str("WATSONX_REGION") - or get_secret_str("WX_REGION") - or get_secret_str("REGION") - ) + region_name = get_secret_str("WATSONX_REGION") or get_secret_str("WX_REGION") or get_secret_str("REGION") if space_id is None: space_id = ( get_secret_str("WATSONX_DEPLOYMENT_SPACE_ID") @@ -117,12 +107,7 @@ def _get_api_params(params: dict, model: Optional[str] = None) -> WatsonXAPIPara or get_secret_str("SPACE_ID") ) - if ( - project_id is None - and space_id is None - and model is not None - and not model.startswith("deployment/") - ): + if project_id is None and space_id is None and model is not None and not model.startswith("deployment/"): raise WatsonXAIError( status_code=401, message="Error: Watsonx project_id and space_id not set. Set WX_PROJECT_ID or WX_SPACE_ID in environment variables or pass in as a parameter.", @@ -150,9 +135,7 @@ async def _aconvert_watsonx_messages_core( model_prompt_dict = custom_prompt_dict[model] return ptf.custom_prompt( messages=messages, - role_dict=model_prompt_dict.get( - "role_dict", model_prompt_dict.get("roles") - ), + role_dict=model_prompt_dict.get("role_dict", model_prompt_dict.get("roles")), initial_prompt_value=model_prompt_dict.get("initial_prompt_value", ""), final_prompt_value=model_prompt_dict.get("final_prompt_value", ""), bos_token=model_prompt_dict.get("bos_token", ""), @@ -166,9 +149,7 @@ async def _aconvert_watsonx_messages_core( if result: return result # Fallback to default - return ptf.prompt_factory( - model=model, messages=messages, custom_llm_provider="watsonx" - ) # type: ignore + return ptf.prompt_factory(model=model, messages=messages, custom_llm_provider="watsonx") # type: ignore def _convert_watsonx_messages_core( @@ -186,9 +167,7 @@ def _convert_watsonx_messages_core( model_prompt_dict = custom_prompt_dict[model] return ptf.custom_prompt( messages=messages, - role_dict=model_prompt_dict.get( - "role_dict", model_prompt_dict.get("roles") - ), + role_dict=model_prompt_dict.get("role_dict", model_prompt_dict.get("roles")), initial_prompt_value=model_prompt_dict.get("initial_prompt_value", ""), final_prompt_value=model_prompt_dict.get("final_prompt_value", ""), bos_token=model_prompt_dict.get("bos_token", ""), @@ -202,9 +181,7 @@ def _convert_watsonx_messages_core( if result: return result # Fallback to default - return ptf.prompt_factory( - model=model, messages=messages, custom_llm_provider="watsonx" - ) # type: ignore + return ptf.prompt_factory(model=model, messages=messages, custom_llm_provider="watsonx") # type: ignore async def aconvert_watsonx_messages_to_prompt( @@ -268,8 +245,7 @@ def validate_environment( ) zen_api_key = cast( Optional[str], - optional_params.pop("zen_api_key", None) - or get_secret_str("WATSONX_ZENAPIKEY"), + optional_params.pop("zen_api_key", None) or get_secret_str("WATSONX_ZENAPIKEY"), ) if token: headers["Authorization"] = f"Bearer {token}" @@ -306,9 +282,7 @@ def _add_api_version_to_url(self, url: str, api_version: Optional[str]) -> str: def get_error_class( self, error_message: str, status_code: int, headers: Union[Dict, httpx.Headers] ) -> BaseLLMException: - return WatsonXAIError( - status_code=status_code, message=error_message, headers=headers - ) + return WatsonXAIError(status_code=status_code, message=error_message, headers=headers) @staticmethod def get_watsonx_credentials( @@ -337,18 +311,14 @@ def get_watsonx_credentials( wx_credentials = optional_params.pop( "wx_credentials", - optional_params.pop( - "watsonx_credentials", None - ), # follow {provider}_credentials, same as vertex ai + optional_params.pop("watsonx_credentials", None), # follow {provider}_credentials, same as vertex ai ) token: Optional[str] = None if wx_credentials is not None: api_base = wx_credentials.get("url", api_base) - api_key = wx_credentials.get( - "apikey", wx_credentials.get("api_key", api_key) - ) + api_key = wx_credentials.get("apikey", wx_credentials.get("api_key", api_key)) token = wx_credentials.get( "token", wx_credentials.get( @@ -365,9 +335,7 @@ def get_watsonx_credentials( status_code=401, message="Error: Watsonx API base not set. Set WATSONX_API_BASE in environment variables or pass in as parameter - 'api_base='.", ) - return WatsonXCredentials( - api_key=api_key, api_base=api_base, token=cast(Optional[str], token) - ) + return WatsonXCredentials(api_key=api_key, api_base=api_base, token=cast(Optional[str], token)) def _prepare_payload(self, model: str, api_params: WatsonXAPIParams) -> dict: payload: dict = {} diff --git a/litellm/llms/watsonx/completion/transformation.py b/litellm/llms/watsonx/completion/transformation.py index 8f418567371b..190e2f7e93dd 100644 --- a/litellm/llms/watsonx/completion/transformation.py +++ b/litellm/llms/watsonx/completion/transformation.py @@ -228,16 +228,12 @@ def get_us_regions(self) -> List[str]: "us-south", ] - def _build_request_payload( - self, model: str, prompt: str, optional_params: Dict - ) -> Dict: + def _build_request_payload(self, model: str, prompt: str, optional_params: Dict) -> Dict: """Shared logic to build request payload""" extra_body_params = optional_params.pop("extra_body", {}) optional_params.update(extra_body_params) watsonx_api_params = _get_api_params(params=optional_params, model=model) - watsonx_auth_payload = self._prepare_payload( - model=model, api_params=watsonx_api_params - ) + watsonx_auth_payload = self._prepare_payload(model=model, api_params=watsonx_api_params) return { "input": prompt, @@ -263,9 +259,7 @@ async def atransform_request( prompt = await aconvert_watsonx_messages_to_prompt( model=model, messages=messages, provider=provider, custom_prompt_dict={} ) - return self._build_request_payload( - model=model, prompt=prompt, optional_params=optional_params - ) + return self._build_request_payload(model=model, prompt=prompt, optional_params=optional_params) def transform_request( self, @@ -280,9 +274,7 @@ def transform_request( prompt = convert_watsonx_messages_to_prompt( model=model, messages=messages, provider=provider, custom_prompt_dict={} ) - return self._build_request_payload( - model=model, prompt=prompt, optional_params=optional_params - ) + return self._build_request_payload(model=model, prompt=prompt, optional_params=optional_params) def transform_response( self, @@ -318,17 +310,13 @@ def transform_response( prompt_tokens = json_resp["results"][0]["input_token_count"] completion_tokens = json_resp["results"][0]["generated_token_count"] model_response.choices[0].message.content = generated_text # type: ignore - model_response.choices[0].finish_reason = map_finish_reason( - json_resp["results"][0]["stop_reason"] - ) + model_response.choices[0].finish_reason = map_finish_reason(json_resp["results"][0]["stop_reason"]) if json_resp.get("created_at"): try: created_datetime = datetime.fromisoformat(json_resp["created_at"]) except ValueError: # datetime.fromisoformat cannot handle 'Z' in Python 3.10 - created_datetime = datetime.fromisoformat( - f"{json_resp['created_at'].rstrip('Z')}+00:00" - ) + created_datetime = datetime.fromisoformat(f"{json_resp['created_at'].rstrip('Z')}+00:00") model_response.created = int(created_datetime.timestamp()) else: model_response.created = int(time.time()) @@ -360,17 +348,11 @@ def get_complete_url( ) endpoint = endpoint.format(deployment_id=deployment_id) else: - endpoint = ( - WatsonXAIEndpoint.TEXT_GENERATION_STREAM - if stream - else WatsonXAIEndpoint.TEXT_GENERATION - ) + endpoint = WatsonXAIEndpoint.TEXT_GENERATION_STREAM if stream else WatsonXAIEndpoint.TEXT_GENERATION url = url.rstrip("/") + endpoint ## add api version - url = self._add_api_version_to_url( - url=url, api_version=optional_params.pop("api_version", None) - ) + url = self._add_api_version_to_url(url=url, api_version=optional_params.pop("api_version", None)) return url def get_model_response_iterator( diff --git a/litellm/llms/watsonx/embed/transformation.py b/litellm/llms/watsonx/embed/transformation.py index ae873d63fe92..a841ba9d3add 100644 --- a/litellm/llms/watsonx/embed/transformation.py +++ b/litellm/llms/watsonx/embed/transformation.py @@ -47,9 +47,7 @@ def transform_embedding_request( inputs: list[str] = [input] elif isinstance(input, list): if len(input) > 0 and isinstance(input[0], (list, int)): - raise ValueError( - "WatsonX embeddings require a string or list of strings" - ) + raise ValueError("WatsonX embeddings require a string or list of strings") inputs = input else: inputs = [input] @@ -77,9 +75,7 @@ def get_complete_url( url = url.rstrip("/") + endpoint ## add api version - url = self._add_api_version_to_url( - url=url, api_version=optional_params.pop("api_version", None) - ) + url = self._add_api_version_to_url(url=url, api_version=optional_params.pop("api_version", None)) return url def transform_embedding_response( diff --git a/litellm/llms/watsonx/passthrough/transformation.py b/litellm/llms/watsonx/passthrough/transformation.py index 9162eef0e034..a89c72dbe10e 100644 --- a/litellm/llms/watsonx/passthrough/transformation.py +++ b/litellm/llms/watsonx/passthrough/transformation.py @@ -54,16 +54,14 @@ def get_api_key( ) -> Optional[str]: return ( api_key - or IBMWatsonXMixin.get_watsonx_credentials( - optional_params=dict(), api_base=None, api_key=api_key - )["api_key"] + or IBMWatsonXMixin.get_watsonx_credentials(optional_params=dict(), api_base=None, api_key=api_key)[ + "api_key" + ] ) @staticmethod def get_base_model(model: str) -> Optional[str]: return model - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: return super().get_models(api_key, api_base) diff --git a/litellm/llms/watsonx/rerank/transformation.py b/litellm/llms/watsonx/rerank/transformation.py index 790606c7e6d5..25b593f1c0a5 100644 --- a/litellm/llms/watsonx/rerank/transformation.py +++ b/litellm/llms/watsonx/rerank/transformation.py @@ -42,9 +42,7 @@ def get_complete_url( params = optional_params or {} - complete_url = self._add_api_version_to_url( - url=url, api_version=(params.get("api_version", None)) - ) + complete_url = self._add_api_version_to_url(url=url, api_version=(params.get("api_version", None))) return complete_url def get_supported_cohere_rerank_params(self, model: str) -> list: @@ -78,8 +76,7 @@ def validate_environment( # type: ignore[override] ) zen_api_key = cast( str | None, - optional_params.pop("zen_api_key", None) - or get_secret_str("WATSONX_ZENAPIKEY"), + optional_params.pop("zen_api_key", None) or get_secret_str("WATSONX_ZENAPIKEY"), ) if token: headers["Authorization"] = f"Bearer {token}" @@ -115,21 +112,13 @@ def map_cohere_rerank_params( if k == "query" and v is not None: optional_rerank_params["query"] = v elif k == "documents" and v is not None: - optional_rerank_params["inputs"] = [ - {"text": el} if isinstance(el, str) else el for el in v - ] + optional_rerank_params["inputs"] = [{"text": el} if isinstance(el, str) else el for el in v] elif k == "top_n" and v is not None: - optional_rerank_params.setdefault("parameters", {}).setdefault( - "return_options", {} - )["top_n"] = v + optional_rerank_params.setdefault("parameters", {}).setdefault("return_options", {})["top_n"] = v elif k == "return_documents" and v is not None and isinstance(v, bool): - optional_rerank_params.setdefault("parameters", {}).setdefault( - "return_options", {} - )["inputs"] = v + optional_rerank_params.setdefault("parameters", {}).setdefault("return_options", {})["inputs"] = v elif k == "max_tokens_per_doc" and v is not None: - optional_rerank_params.setdefault("parameters", {})[ - "truncate_input_tokens" - ] = v + optional_rerank_params.setdefault("parameters", {})["truncate_input_tokens"] = v # IBM watsonx.ai require one of below parameters elif k == "project_id" and v is not None: @@ -200,11 +189,7 @@ def transform_rerank_response( transformed_results.append(transformed_result) - response_id = ( - raw_response_json.get("id") - or raw_response_json.get("model_id") - or str(uuid.uuid4()) - ) + response_id = raw_response_json.get("id") or raw_response_json.get("model_id") or str(uuid.uuid4()) # Extract usage information _tokens = RerankTokens( diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py index 87b5757ef352..0e689549421d 100644 --- a/litellm/llms/xai/chat/transformation.py +++ b/litellm/llms/xai/chat/transformation.py @@ -58,9 +58,7 @@ def validate_environment( dynamic_api_key = XAIModelInfo.get_api_key(api_key) if should_use_xai_oauth(litellm_params) and not dynamic_api_key: try: - headers["Authorization"] = ( - f"Bearer {XAIOAuthAuthenticator().get_access_token()}" - ) + headers["Authorization"] = f"Bearer {XAIOAuthAuthenticator().get_access_token()}" except XAIOAuthError as exc: raise AuthenticationError( model=model, @@ -142,9 +140,7 @@ def get_supported_openai_params(self, model: str) -> list: # reasoning check ######################################################### try: - if litellm.supports_reasoning( - model=model, custom_llm_provider=self.custom_llm_provider - ): + if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider): base_openai_params.append("reasoning_effort") except Exception as e: verbose_logger.debug(f"Error checking if model supports reasoning: {e}") @@ -222,9 +218,7 @@ def transform_request( Filter out 'name' from messages """ messages = strip_name_from_messages(messages) - return super().transform_request( - model, messages, optional_params, litellm_params, headers - ) + return super().transform_request(model, messages, optional_params, litellm_params, headers) @staticmethod def _fix_choice_finish_reason_for_tool_calls(choice: Choices) -> None: @@ -234,11 +228,7 @@ def _fix_choice_finish_reason_for_tool_calls(choice: Choices) -> None: XAI API returns empty string for finish_reason when using tools, so we need to set it to "tool_calls" when tool_calls are present. """ - if ( - choice.finish_reason == "" - and choice.message.tool_calls - and len(choice.message.tool_calls) > 0 - ): + if choice.finish_reason == "" and choice.message.tool_calls and len(choice.message.tool_calls) > 0: choice.finish_reason = "tool_calls" def transform_response( @@ -345,9 +335,7 @@ def _fold_reasoning_tokens_into_completion( return details = getattr(usage, "completion_tokens_details", None) - reasoning_tokens = ( - int(getattr(details, "reasoning_tokens", 0) or 0) if details else 0 - ) + reasoning_tokens = int(getattr(details, "reasoning_tokens", 0) or 0) if details else 0 if reasoning_tokens <= 0: return @@ -364,9 +352,7 @@ def _fold_reasoning_tokens_into_completion( usage.completion_tokens = completion_tokens + reasoning_tokens - def _enhance_usage_with_xai_web_search_fields( - self, model_response: ModelResponse, raw_response_json: dict - ) -> None: + def _enhance_usage_with_xai_web_search_fields(self, model_response: ModelResponse, raw_response_json: dict) -> None: """ Extract num_sources_used from X.AI response and map it to web_search_requests. """ diff --git a/litellm/llms/xai/common_utils.py b/litellm/llms/xai/common_utils.py index adc857894c51..0e499e33ed12 100644 --- a/litellm/llms/xai/common_utils.py +++ b/litellm/llms/xai/common_utils.py @@ -59,12 +59,7 @@ def get_api_key( the provider-specific litellm.xai_key takes precedence over fallbacks. """ if legacy_generic_before_env: - return ( - api_key - or litellm.xai_key - or litellm.api_key - or get_secret_str("XAI_API_KEY") - ) + return api_key or litellm.xai_key or litellm.api_key or get_secret_str("XAI_API_KEY") return api_key or litellm.xai_key or get_secret_str("XAI_API_KEY") @@ -72,9 +67,7 @@ def get_api_key( def get_base_model(model: str) -> Optional[str]: return model.replace("xai/", "") - def get_models( - self, api_key: Optional[str] = None, api_base: Optional[str] = None - ) -> List[str]: + def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = None) -> List[str]: api_base = self.get_api_base(api_base) api_key = self.get_api_key(api_key) if api_base is None or api_key is None: diff --git a/litellm/llms/xai/cost_calculator.py b/litellm/llms/xai/cost_calculator.py index 8edfd0c27ad5..284400b08242 100644 --- a/litellm/llms/xai/cost_calculator.py +++ b/litellm/llms/xai/cost_calculator.py @@ -34,16 +34,10 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: total_tokens = int(getattr(usage, "total_tokens", 0) or 0) reasoning_tokens = 0 if hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details: - reasoning_tokens = int( - getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0 - ) + reasoning_tokens = int(getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0) already_normalised = total_tokens == prompt_tokens + completion_tokens - total_completion_tokens = ( - completion_tokens - if already_normalised - else completion_tokens + reasoning_tokens - ) + total_completion_tokens = completion_tokens if already_normalised else completion_tokens + reasoning_tokens modified_usage = Usage( prompt_tokens=usage.prompt_tokens, @@ -53,9 +47,7 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]: completion_tokens_details=None, ) - prompt_cost, completion_cost = generic_cost_per_token( - model=model, usage=modified_usage, custom_llm_provider="xai" - ) + prompt_cost, completion_cost = generic_cost_per_token(model=model, usage=modified_usage, custom_llm_provider="xai") return prompt_cost, completion_cost diff --git a/litellm/llms/xai/oauth.py b/litellm/llms/xai/oauth.py index 30c717b7ca06..064e0ff77d64 100644 --- a/litellm/llms/xai/oauth.py +++ b/litellm/llms/xai/oauth.py @@ -62,9 +62,7 @@ def do_GET(self) -> None: self.send_response(400) self.send_header("Content-Type", "text/html; charset=utf-8") self.end_headers() - self.wfile.write( - b"

xAI authorization state mismatch.

" - ) + self.wfile.write(b"

xAI authorization state mismatch.

") return self.send_response(200) @@ -87,30 +85,18 @@ class _CallbackServer(HTTPServer): class XAIOAuthAuthenticator: - def __init__( - self, http_client: Optional[Union[httpx.Client, HTTPHandler]] = None - ) -> None: - self.token_dir = get_secret_str("XAI_OAUTH_TOKEN_DIR") or os.path.expanduser( - "~/.config/litellm/xai_oauth" - ) - self.auth_file = os.path.join( - self.token_dir, get_secret_str("XAI_OAUTH_AUTH_FILE") or "auth.json" - ) + def __init__(self, http_client: Optional[Union[httpx.Client, HTTPHandler]] = None) -> None: + self.token_dir = get_secret_str("XAI_OAUTH_TOKEN_DIR") or os.path.expanduser("~/.config/litellm/xai_oauth") + self.auth_file = os.path.join(self.token_dir, get_secret_str("XAI_OAUTH_AUTH_FILE") or "auth.json") self.http_client = http_client def get_api_base(self) -> str: - return ( - get_secret_str("XAI_OAUTH_API_BASE") - or get_secret_str("XAI_API_BASE") - or XAI_API_BASE - ) + return get_secret_str("XAI_OAUTH_API_BASE") or get_secret_str("XAI_API_BASE") or XAI_API_BASE def get_access_token(self) -> str: auth_data = self._read_auth_file() if not auth_data: - raise XAIOAuthLoginRequiredError( - "xAI OAuth login required. Run `litellm xai-oauth login`." - ) + raise XAIOAuthLoginRequiredError("xAI OAuth login required. Run `litellm xai-oauth login`.") access_token = auth_data.get("access_token") if access_token and not self._is_expired(auth_data): @@ -118,9 +104,7 @@ def get_access_token(self) -> str: refresh_token = auth_data.get("refresh_token") if not refresh_token: - raise XAIOAuthLoginRequiredError( - "xAI OAuth refresh token missing. Run `litellm xai-oauth login`." - ) + raise XAIOAuthLoginRequiredError("xAI OAuth refresh token missing. Run `litellm xai-oauth login`.") with _XAI_OAUTH_REFRESH_LOCK: locked_auth_data = self._read_auth_file() or auth_data @@ -156,9 +140,7 @@ def login(self, force: bool = False, no_browser: bool = False) -> Dict[str, Any] ) if no_browser or not webbrowser.open(authorize_url): - sys.stdout.write( - f"Open this URL to authenticate with xAI:\n{authorize_url}\n" - ) + sys.stdout.write(f"Open this URL to authenticate with xAI:\n{authorize_url}\n") sys.stdout.flush() result = self._wait_for_callback(server) @@ -245,9 +227,7 @@ def _is_expired(self, auth_data: Dict[str, Any]) -> bool: def _discover(self) -> Dict[str, str]: try: - response = self._client().get( - XAI_OAUTH_DISCOVERY_URL, headers={"Accept": "application/json"} - ) + response = self._client().get(XAI_OAUTH_DISCOVERY_URL, headers={"Accept": "application/json"}) response.raise_for_status() except httpx.HTTPStatusError as exc: raise XAIOAuthError( @@ -256,17 +236,13 @@ def _discover(self) -> Dict[str, str]: try: data = response.json() except ValueError as exc: - raise XAIOAuthError( - "xAI OAuth discovery response was not valid JSON" - ) from exc + raise XAIOAuthError("xAI OAuth discovery response was not valid JSON") from exc authorization_endpoint = data.get("authorization_endpoint") token_endpoint = data.get("token_endpoint") if not authorization_endpoint or not token_endpoint: raise XAIOAuthError("xAI OAuth discovery missing endpoints") return { - "authorization_endpoint": self._validate_xai_endpoint( - authorization_endpoint - ), + "authorization_endpoint": self._validate_xai_endpoint(authorization_endpoint), "token_endpoint": self._validate_xai_endpoint(token_endpoint), } @@ -274,29 +250,19 @@ def _validate_xai_endpoint(self, url: str) -> str: parsed = urlparse(url) host = (parsed.hostname or "").lower() if parsed.scheme != "https" or (host != "x.ai" and not host.endswith(".x.ai")): - raise XAIOAuthError( - f"xAI OAuth discovery returned unexpected endpoint: {url}" - ) + raise XAIOAuthError(f"xAI OAuth discovery returned unexpected endpoint: {url}") return url def _pkce_pair(self) -> Tuple[str, str]: - verifier = ( - base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode() - ) - challenge = ( - base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) - .rstrip(b"=") - .decode() - ) + verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode() + challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() return verifier, challenge def _start_callback_server(self, state: str) -> Tuple[_CallbackServer, str]: last_error: Optional[OSError] = None for port in (XAI_OAUTH_REDIRECT_PORT, 0): try: - server = _CallbackServer( - (XAI_OAUTH_REDIRECT_HOST, port), _CallbackHandler - ) + server = _CallbackServer((XAI_OAUTH_REDIRECT_HOST, port), _CallbackHandler) server.expected_state = state server.callback_result = None actual_port = server.server_address[1] @@ -338,9 +304,7 @@ def _wait_for_callback(self, server: _CallbackServer) -> Dict[str, Optional[str] server.server_close() raise XAIOAuthError("Timed out waiting for xAI OAuth callback") - def _exchange_token( - self, token_endpoint: str, data: Dict[str, str] - ) -> Dict[str, Any]: + def _exchange_token(self, token_endpoint: str, data: Dict[str, str]) -> Dict[str, Any]: try: response = self._client().post( token_endpoint, @@ -396,9 +360,7 @@ def _refresh_tokens(self, auth_data: Dict[str, Any]) -> Dict[str, Any]: token_endpoint = self._validate_xai_endpoint(token_endpoint) refresh_token = auth_data.get("refresh_token") if not refresh_token: - raise XAIOAuthLoginRequiredError( - "xAI OAuth refresh token missing. Run `litellm xai-oauth login`." - ) + raise XAIOAuthLoginRequiredError("xAI OAuth refresh token missing. Run `litellm xai-oauth login`.") token_payload = self._exchange_token( token_endpoint, diff --git a/litellm/llms/xai/realtime/transformation.py b/litellm/llms/xai/realtime/transformation.py index f7981dc547a4..6d8a8948f068 100644 --- a/litellm/llms/xai/realtime/transformation.py +++ b/litellm/llms/xai/realtime/transformation.py @@ -105,10 +105,7 @@ def _default_server_vad_create_response(session: dict) -> None: @staticmethod def _ensure_server_vad_create_response(turn_detection: dict) -> None: - if ( - turn_detection.get("type") == "server_vad" - and "create_response" not in turn_detection - ): + if turn_detection.get("type") == "server_vad" and "create_response" not in turn_detection: turn_detection["create_response"] = True # --------------------------------------------------------------------------- @@ -128,9 +125,7 @@ def _remember_content_part(self, event: dict) -> None: if isinstance(part, dict): self._content_part_by_key[self._content_part_key(event)] = part - def _update_content_part_field( - self, event: dict, *, part_type: str, field: str, value: object - ) -> None: + def _update_content_part_field(self, event: dict, *, part_type: str, field: str, value: object) -> None: if value is None: return key = self._content_part_key(event) @@ -164,9 +159,7 @@ def _normalize_content_part_events(self, event: dict) -> dict: return event if event_type == "response.output_text.done": - self._update_content_part_field( - event, part_type="text", field="text", value=event.get("text") - ) + self._update_content_part_field(event, part_type="text", field="text", value=event.get("text")) return event if event_type == "response.output_audio_transcript.done": @@ -250,9 +243,7 @@ def _default_ga_usage() -> dict[str, Any]: } @staticmethod - def _normalize_usage( - usage: object, *, empty_as_null: bool - ) -> Optional[dict[str, Any]]: + def _normalize_usage(usage: object, *, empty_as_null: bool) -> Optional[dict[str, Any]]: """Coerce a usage object into the full OpenAI GA shape. ``empty_as_null=True`` for ``response.created`` (usage optional). diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py index f81e860a8ce2..2773444bce98 100644 --- a/litellm/llms/xai/responses/transformation.py +++ b/litellm/llms/xai/responses/transformation.py @@ -51,9 +51,7 @@ def get_supported_openai_params(self, model: str) -> list: return supported_params - def _transform_web_search_tool( - self, tool: Dict[str, Any] - ) -> Union[XAIWebSearchTool, Dict[str, Any]]: + def _transform_web_search_tool(self, tool: Dict[str, Any]) -> Union[XAIWebSearchTool, Dict[str, Any]]: """ Transform web_search tool to XAI format. @@ -92,9 +90,7 @@ def _transform_web_search_tool( return xai_tool - def _transform_x_search_tool( - self, tool: Dict[str, Any] - ) -> Union[XAIXSearchTool, Dict[str, Any]]: + def _transform_x_search_tool(self, tool: Dict[str, Any]) -> Union[XAIXSearchTool, Dict[str, Any]]: """ Transform x_search tool to XAI format. @@ -154,15 +150,11 @@ def map_openai_params( # Drop instructions parameter (not supported by XAI) if "instructions" in params: - verbose_logger.debug( - "XAI Responses API does not support 'instructions' parameter. Dropping it." - ) + verbose_logger.debug("XAI Responses API does not support 'instructions' parameter. Dropping it.") params.pop("instructions") if "metadata" in params: - verbose_logger.debug( - "XAI Responses API does not support 'metadata' parameter. Dropping it." - ) + verbose_logger.debug("XAI Responses API does not support 'metadata' parameter. Dropping it.") params.pop("metadata") # Transform tools @@ -179,23 +171,17 @@ def map_openai_params( if tool_type == "code_interpreter": # XAI supports code_interpreter but doesn't use the container field - verbose_logger.debug( - "XAI: Transforming code_interpreter tool, removing container field" - ) + verbose_logger.debug("XAI: Transforming code_interpreter tool, removing container field") transformed_tools.append({"type": "code_interpreter"}) elif tool_type == "web_search": # Transform web_search to XAI format - verbose_logger.debug( - "XAI: Transforming web_search tool to XAI format" - ) + verbose_logger.debug("XAI: Transforming web_search tool to XAI format") transformed_tools.append(self._transform_web_search_tool(tool)) elif tool_type == "x_search": # Transform x_search to XAI format - verbose_logger.debug( - "XAI: Transforming x_search tool to XAI format" - ) + verbose_logger.debug("XAI: Transforming x_search tool to XAI format") transformed_tools.append(self._transform_x_search_tool(tool)) else: @@ -208,18 +194,14 @@ def map_openai_params( return params - def validate_environment( - self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams] - ) -> dict: + def validate_environment(self, headers: dict, model: str, litellm_params: Optional[GenericLiteLLMParams]) -> dict: """ Validate environment and set up headers for XAI API. Uses the shared xAI key resolver with Responses API legacy precedence. """ litellm_params = litellm_params or GenericLiteLLMParams() - api_key = XAIModelInfo.get_api_key( - litellm_params.api_key, legacy_generic_before_env=True - ) + api_key = XAIModelInfo.get_api_key(litellm_params.api_key, legacy_generic_before_env=True) if not api_key: from litellm.llms.xai.oauth import ( @@ -264,18 +246,11 @@ def get_complete_url( """ from litellm.llms.xai.oauth import XAIOAuthAuthenticator, should_use_xai_oauth - api_key = XAIModelInfo.get_api_key( - litellm_params.get("api_key"), legacy_generic_before_env=True - ) + api_key = XAIModelInfo.get_api_key(litellm_params.get("api_key"), legacy_generic_before_env=True) if should_use_xai_oauth(litellm_params) and not api_key: api_base = XAIOAuthAuthenticator().get_api_base() else: - api_base = ( - api_base - or litellm.api_base - or get_secret_str("XAI_API_BASE") - or XAI_API_BASE - ) + api_base = api_base or litellm.api_base or get_secret_str("XAI_API_BASE") or XAI_API_BASE # Remove trailing slashes api_base = api_base.rstrip("/") diff --git a/litellm/llms/xinference/image_generation/transformation.py b/litellm/llms/xinference/image_generation/transformation.py index 6ff70d0642dc..0d2d890ddf40 100644 --- a/litellm/llms/xinference/image_generation/transformation.py +++ b/litellm/llms/xinference/image_generation/transformation.py @@ -13,9 +13,7 @@ class XInferenceImageGenerationConfig(BaseImageGenerationConfig): https://inference.readthedocs.io/en/v1.1.1/reference/generated/xinference.client.handlers.ImageModelHandle.text_to_image.html#xinference.client.handlers.ImageModelHandle.text_to_image """ - def get_supported_openai_params( - self, model: str - ) -> List[OpenAIImageGenerationOptionalParams]: + def get_supported_openai_params(self, model: str) -> List[OpenAIImageGenerationOptionalParams]: return ["n", "response_format", "size", "response_format"] def map_openai_params( diff --git a/litellm/llms/you_com/search/transformation.py b/litellm/llms/you_com/search/transformation.py index 0c7916e4c05d..0cd825c3ab88 100644 --- a/litellm/llms/you_com/search/transformation.py +++ b/litellm/llms/you_com/search/transformation.py @@ -108,9 +108,7 @@ def get_complete_url( api_base = api_base.rstrip("/") - if not api_base.endswith("/v1/search") and not api_base.endswith( - "/v1/agents/search" - ): + if not api_base.endswith("/v1/search") and not api_base.endswith("/v1/agents/search"): api_base = f"{api_base}/v1/search" return api_base @@ -150,10 +148,7 @@ def transform_search_request( result_data = dict(request_data) for param, value in optional_params.items(): - if ( - param not in self.get_supported_perplexity_optional_params() - and param not in result_data - ): + if param not in self.get_supported_perplexity_optional_params() and param not in result_data: result_data[param] = value return result_data diff --git a/litellm/llms/zai/chat/transformation.py b/litellm/llms/zai/chat/transformation.py index c932dcd2e032..fb1d67df357f 100644 --- a/litellm/llms/zai/chat/transformation.py +++ b/litellm/llms/zai/chat/transformation.py @@ -48,9 +48,7 @@ def get_supported_openai_params(self, model: str) -> list: import litellm try: - if litellm.supports_reasoning( - model=model, custom_llm_provider=self.custom_llm_provider - ): + if litellm.supports_reasoning(model=model, custom_llm_provider=self.custom_llm_provider): base_params.append("thinking") except Exception: pass diff --git a/litellm/main.py b/litellm/main.py index cdea7dbd684a..18d2c367f8d3 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -374,9 +374,7 @@ def create(self, messages, model=None, **kwargs): self.params[k] = v model = model or self.params.get("model") if self.router_obj is not None: - response = self.router_obj.completion( - model=model, messages=messages, **self.params - ) + response = self.router_obj.completion(model=model, messages=messages, **self.params) else: response = completion(model=model, messages=messages, **self.params) return response @@ -392,9 +390,7 @@ async def create(self, messages, model=None, **kwargs): self.params[k] = v model = model or self.params.get("model") if self.router_obj is not None: - response = await self.router_obj.acompletion( - model=model, messages=messages, **self.params - ) + response = await self.router_obj.acompletion(model=model, messages=messages, **self.params) else: response = await acompletion(model=model, messages=messages, **self.params) return response @@ -433,9 +429,7 @@ async def acompletion( logprobs: Optional[bool] = None, top_logprobs: Optional[int] = None, deployment_id=None, - reasoning_effort: Optional[ - Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"] - ] = None, + reasoning_effort: Optional[Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"]] = None, verbosity: Optional[Literal["low", "medium", "high"]] = None, safety_identifier: Optional[str] = None, service_tier: Optional[str] = None, @@ -547,13 +541,9 @@ async def acompletion( # Log shared session usage if shared_session is not None: - verbose_logger.debug( - f"🔄 SHARED SESSION: acompletion called with shared_session (ID: {id(shared_session)})" - ) + verbose_logger.debug(f"🔄 SHARED SESSION: acompletion called with shared_session (ID: {id(shared_session)})") else: - verbose_logger.debug( - "🔄 NO SHARED SESSION: acompletion called without shared_session" - ) + verbose_logger.debug("🔄 NO SHARED SESSION: acompletion called without shared_session") # Adjusted to use explicit arguments instead of *args and **kwargs completion_kwargs = { @@ -609,9 +599,7 @@ async def acompletion( fallbacks = fallbacks or litellm.model_fallbacks if fallbacks is not None: - response = await async_completion_with_fallbacks( - **completion_kwargs, kwargs={"fallbacks": fallbacks, **kwargs} - ) + response = await async_completion_with_fallbacks(**completion_kwargs, kwargs={"fallbacks": fallbacks, **kwargs}) if response is None: raise Exception( "No response from fallbacks. Got none. Turn on `litellm.set_verbose=True` to see more details." @@ -641,9 +629,7 @@ async def acompletion( func_with_context = partial(ctx.run, func) init_response = await loop.run_in_executor(None, func_with_context) - if isinstance(init_response, dict) or isinstance( - init_response, ModelResponse - ): ## CACHING SCENARIO + if isinstance(init_response, dict) or isinstance(init_response, ModelResponse): ## CACHING SCENARIO if isinstance(init_response, dict): response = ModelResponse(**init_response) response = init_response @@ -738,45 +724,29 @@ def _handle_mock_potential_exceptions( raise litellm.MockException( status_code=getattr(mock_response, "status_code", 500), # type: ignore message=getattr(mock_response, "text", str(mock_response)), - llm_provider=getattr( - mock_response, "llm_provider", custom_llm_provider or "openai" - ), # type: ignore + llm_provider=getattr(mock_response, "llm_provider", custom_llm_provider or "openai"), # type: ignore model=model, # type: ignore request=httpx.Request(method="POST", url="https://api.openai.com/v1/"), ) elif isinstance(mock_response, str) and mock_response == "litellm.RateLimitError": raise litellm.RateLimitError( message="this is a mock rate limit error", - llm_provider=getattr( - mock_response, "llm_provider", custom_llm_provider or "openai" - ), # type: ignore + llm_provider=getattr(mock_response, "llm_provider", custom_llm_provider or "openai"), # type: ignore model=model, ) - elif ( - isinstance(mock_response, str) - and mock_response == "litellm.ContextWindowExceededError" - ): + elif isinstance(mock_response, str) and mock_response == "litellm.ContextWindowExceededError": raise litellm.ContextWindowExceededError( message="this is a mock context window exceeded error", - llm_provider=getattr( - mock_response, "llm_provider", custom_llm_provider or "openai" - ), # type: ignore + llm_provider=getattr(mock_response, "llm_provider", custom_llm_provider or "openai"), # type: ignore model=model, ) - elif ( - isinstance(mock_response, str) - and mock_response == "litellm.InternalServerError" - ): + elif isinstance(mock_response, str) and mock_response == "litellm.InternalServerError": raise litellm.InternalServerError( message="this is a mock internal server error", - llm_provider=getattr( - mock_response, "llm_provider", custom_llm_provider or "openai" - ), # type: ignore + llm_provider=getattr(mock_response, "llm_provider", custom_llm_provider or "openai"), # type: ignore model=model, ) - elif isinstance(mock_response, str) and mock_response.startswith( - "Exception: content_filter_policy" - ): + elif isinstance(mock_response, str) and mock_response.startswith("Exception: content_filter_policy"): raise litellm.MockException( status_code=400, message=mock_response, @@ -892,9 +862,7 @@ def mock_completion( mock_response = cast( Union[str, dict, ModelResponse, ModelResponseStream], mock_response ) # after this point, mock_response is a string, dict, ModelResponse, or ModelResponseStream - if isinstance(mock_response, str) and mock_response.startswith( - "Exception: mock_streaming_error" - ): + if isinstance(mock_response, str) and mock_response.startswith("Exception: mock_streaming_error"): mock_response = litellm.MockException( message="This is a mock error raised mid-stream", llm_provider="anthropic", @@ -948,9 +916,7 @@ def mock_completion( for i in range(n): _choice = litellm.utils.Choices( index=i, - message=litellm.utils.Message( - content=mock_response, role="assistant" - ), + message=litellm.utils.Message(content=mock_response, role="assistant"), ) _all_choices.append(_choice) model_response.choices = _all_choices # type: ignore @@ -959,8 +925,7 @@ def mock_completion( if mock_tool_calls: model_response.choices[0].message.tool_calls = [ # type: ignore - ChatCompletionMessageToolCall(**tool_call) - for tool_call in mock_tool_calls + ChatCompletionMessageToolCall(**tool_call) for tool_call in mock_tool_calls ] setattr( @@ -969,8 +934,7 @@ def mock_completion( Usage( prompt_tokens=DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT, completion_tokens=DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT, - total_tokens=DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT - + DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT, + total_tokens=DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT + DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT, ), ) @@ -1016,9 +980,7 @@ def responses_api_bridge_check( try: model_info = cast( dict, - _get_model_info_helper( - model=model, custom_llm_provider=custom_llm_provider - ), + _get_model_info_helper(model=model, custom_llm_provider=custom_llm_provider), ) if model_info.get("mode") is None and model.startswith("responses/"): model = model.replace("responses/", "") @@ -1032,9 +994,7 @@ def responses_api_bridge_check( except Exception as e: verbose_logger.debug("Error getting model info: {}".format(e)) - if model.startswith( - "responses/" - ): # handle azure models - `azure/responses/` + if model.startswith("responses/"): # handle azure models - `azure/responses/` model = model.replace("responses/", "") mode = "responses" model_info["mode"] = mode @@ -1052,10 +1012,7 @@ def responses_api_bridge_check( and OpenAIGPT5Config.is_model_gpt_5_model(model) and not OpenAIGPT5Config.is_model_gpt_5_search_model(model) and reasoning_effort is not None - and ( - reasoning_summary is not None - or (OpenAIGPT5Config.is_model_gpt_5_4_plus_model(model) and tools) - ) + and (reasoning_summary is not None or (OpenAIGPT5Config.is_model_gpt_5_4_plus_model(model) and tools)) ): model_info["mode"] = "responses" model = model.replace("responses/", "") @@ -1063,16 +1020,10 @@ def responses_api_bridge_check( return model_info, model -def _should_allow_input_examples( - custom_llm_provider: Optional[str], model: str -) -> bool: +def _should_allow_input_examples(custom_llm_provider: Optional[str], model: str) -> bool: if custom_llm_provider == "anthropic": return True - if ( - custom_llm_provider == "azure_ai" - or custom_llm_provider == "bedrock" - or custom_llm_provider == "vertex_ai" - ): + if custom_llm_provider == "azure_ai" or custom_llm_provider == "bedrock" or custom_llm_provider == "vertex_ai": return "claude" in model.lower() return False @@ -1149,10 +1100,7 @@ def _complete_azure(ctx: _CompletionDispatchContext) -> _CompletionDispatchResul timeout = ctx.timeout dynamic_params = False - if client is not None and ( - isinstance(client, openai.AzureOpenAI) - or isinstance(client, openai.AsyncAzureOpenAI) - ): + if client is not None and (isinstance(client, openai.AzureOpenAI) or isinstance(client, openai.AsyncAzureOpenAI)): dynamic_params = _check_dynamic_azure_params( azure_client_params={"api_version": api_version}, azure_client=client, @@ -1163,10 +1111,7 @@ def _complete_azure(ctx: _CompletionDispatchContext) -> _CompletionDispatchResul api_base = api_base or litellm.api_base or get_secret("AZURE_API_BASE") api_version = ( - api_version - or litellm.api_version - or get_secret_str("AZURE_API_VERSION") - or litellm.AZURE_DEFAULT_API_VERSION + api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") or litellm.AZURE_DEFAULT_API_VERSION ) api_key = ( @@ -1177,9 +1122,9 @@ def _complete_azure(ctx: _CompletionDispatchContext) -> _CompletionDispatchResul or get_secret_str("AZURE_API_KEY") ) - azure_ad_token = optional_params.get("extra_body", {}).pop( - "azure_ad_token", None - ) or get_secret_str("AZURE_AD_TOKEN") + azure_ad_token = optional_params.get("extra_body", {}).pop("azure_ad_token", None) or get_secret_str( + "AZURE_AD_TOKEN" + ) azure_ad_token_provider = litellm_params.get("azure_ad_token_provider", None) @@ -1293,9 +1238,7 @@ def _complete_azure_text(ctx: _CompletionDispatchContext) -> _CompletionDispatch "api_base is required for Azure OpenAI LLM provider. Either set it dynamically or set the AZURE_API_BASE environment variable." ) - api_version = ( - api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") - ) + api_version = api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") api_key = ( api_key @@ -1305,9 +1248,9 @@ def _complete_azure_text(ctx: _CompletionDispatchContext) -> _CompletionDispatch or get_secret_str("AZURE_API_KEY") ) - azure_ad_token = optional_params.get("extra_body", {}).pop( - "azure_ad_token", None - ) or get_secret_str("AZURE_AD_TOKEN") + azure_ad_token = optional_params.get("extra_body", {}).pop("azure_ad_token", None) or get_secret_str( + "AZURE_AD_TOKEN" + ) azure_ad_token_provider = litellm_params.get("azure_ad_token_provider", None) @@ -1443,8 +1386,7 @@ def _complete_azure_ai(ctx: _CompletionDispatchContext) -> _CompletionDispatchRe api_base = AzureFoundryModelInfo.get_api_base(api_base) if api_base is None: raise ValueError( - "Azure AI Agents requests require an api_base. " - "Set `api_base` or the AZURE_AI_API_BASE env var." + "Azure AI Agents requests require an api_base. Set `api_base` or the AZURE_AI_API_BASE env var." ) api_key = AzureFoundryModelInfo.get_api_key(api_key) @@ -1469,8 +1411,7 @@ def _complete_azure_ai(ctx: _CompletionDispatchContext) -> _CompletionDispatchRe api_base = AzureFoundryModelInfo.get_api_base(api_base) if api_base is None: raise ValueError( - "Azure Anthropic requests require an api_base. " - "Set `api_base` or the AZURE_AI_API_BASE env var." + "Azure Anthropic requests require an api_base. Set `api_base` or the AZURE_AI_API_BASE env var." ) api_key = AzureFoundryModelInfo.get_api_key(api_key) @@ -1601,9 +1542,7 @@ def _complete_text_completion_openai( openai.api_version = None # set API KEY - api_key = ( - api_key or litellm.api_key or litellm.openai_key or get_secret("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret("OPENAI_API_KEY") headers = headers or litellm.headers @@ -1636,16 +1575,10 @@ def _complete_text_completion_openai( timeout=timeout, # type: ignore ) - if ( - optional_params.get("stream", False) is False - and acompletion is False - and text_completion is False - ): + if optional_params.get("stream", False) is False and acompletion is False and text_completion is False: # convert to chat completion response - _response = ( - litellm.OpenAITextCompletionConfig().convert_to_chat_model_response_object( - response_object=_response, model_response_object=model_response - ) + _response = litellm.OpenAITextCompletionConfig().convert_to_chat_model_response_object( + response_object=_response, model_response_object=model_response ) if optional_params.get("stream", False) or acompletion is True: @@ -2217,19 +2150,9 @@ def _complete_cometapi(ctx: _CompletionDispatchContext) -> _CompletionDispatchRe stream = ctx.stream timeout = ctx.timeout - api_key = ( - api_key - or litellm.cometapi_key - or get_secret_str("COMETAPI_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.cometapi_key or get_secret_str("COMETAPI_KEY") or litellm.api_key - api_base = ( - api_base - or litellm.api_base - or get_secret_str("COMETAPI_API_BASE") - or "https://api.cometapi.com/v1" - ) + api_base = api_base or litellm.api_base or get_secret_str("COMETAPI_API_BASE") or "https://api.cometapi.com/v1" ## COMPLETION CALL response = base_llm_http_handler.completion( @@ -2278,12 +2201,7 @@ def _complete_minimax(ctx: _CompletionDispatchContext) -> _CompletionDispatchRes api_key = api_key or get_secret_str("MINIMAX_API_KEY") or litellm.api_key - api_base = ( - api_base - or litellm.api_base - or get_secret_str("MINIMAX_API_BASE") - or "https://api.minimax.io/v1" - ) + api_base = api_base or litellm.api_base or get_secret_str("MINIMAX_API_BASE") or "https://api.minimax.io/v1" response = base_llm_http_handler.completion( model=model, @@ -2419,9 +2337,7 @@ def _complete_custom_openai( if extra_headers is not None: optional_params["extra_headers"] = extra_headers - if ( - litellm.enable_preview_features and metadata is not None - ): # [PREVIEW] allow metadata to be passed to OPENAI + if litellm.enable_preview_features and metadata is not None: # [PREVIEW] allow metadata to be passed to OPENAI openai_metadata = get_requester_metadata(metadata) if openai_metadata is not None: optional_params["metadata"] = openai_metadata @@ -2435,9 +2351,7 @@ def _complete_custom_openai( optional_params[k] = v ## COMPLETION CALL - use_base_llm_http_handler = get_secret_bool( - "EXPERIMENTAL_OPENAI_BASE_LLM_HTTP_HANDLER" - ) + use_base_llm_http_handler = get_secret_bool("EXPERIMENTAL_OPENAI_BASE_LLM_HTTP_HANDLER") try: if use_base_llm_http_handler: @@ -2522,12 +2436,7 @@ def _complete_mistral(ctx: _CompletionDispatchContext) -> _CompletionDispatchRes timeout = ctx.timeout api_key = api_key or litellm.api_key or get_secret("MISTRAL_API_KEY") - api_base = ( - api_base - or litellm.api_base - or get_secret("MISTRAL_API_BASE") - or "https://api.mistral.ai/v1" - ) + api_base = api_base or litellm.api_base or get_secret("MISTRAL_API_BASE") or "https://api.mistral.ai/v1" return base_llm_http_handler.completion( model=model, @@ -2572,12 +2481,7 @@ def _complete_replicate(ctx: _CompletionDispatchContext) -> _CompletionDispatchR or get_secret("REPLICATE_API_TOKEN") ) - api_base = ( - api_base - or litellm.api_base - or get_secret("REPLICATE_API_BASE") - or "https://api.replicate.com/v1" - ) + api_base = api_base or litellm.api_base or get_secret("REPLICATE_API_BASE") or "https://api.replicate.com/v1" custom_prompt_dict = custom_prompt_dict or litellm.custom_prompt_dict @@ -2627,12 +2531,7 @@ def _complete_anthropic_text( stream = ctx.stream timeout = ctx.timeout - api_key = ( - api_key - or litellm.anthropic_key - or litellm.api_key - or os.environ.get("ANTHROPIC_API_KEY") - ) + api_key = api_key or litellm.anthropic_key or litellm.api_key or os.environ.get("ANTHROPIC_API_KEY") custom_prompt_dict = custom_prompt_dict or litellm.custom_prompt_dict api_base = cast( Optional[str], @@ -2645,16 +2544,10 @@ def _complete_anthropic_text( # Check if we should disable automatic URL suffix appending disable_url_suffix = get_secret_bool("LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX") - if ( - api_base is not None - and not disable_url_suffix - and not api_base.endswith("/v1/complete") - ): + if api_base is not None and not disable_url_suffix and not api_base.endswith("/v1/complete"): api_base += "/v1/complete" elif disable_url_suffix: - verbose_logger.debug( - "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX is set, skipping /v1/complete suffix" - ) + verbose_logger.debug("LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX is set, skipping /v1/complete suffix") return base_llm_http_handler.completion( model=model, @@ -2692,12 +2585,7 @@ def _complete_anthropic(ctx: _CompletionDispatchContext) -> _CompletionDispatchR optional_params = ctx.optional_params timeout = ctx.timeout - api_key = ( - api_key - or litellm.anthropic_key - or litellm.api_key - or os.environ.get("ANTHROPIC_API_KEY") - ) + api_key = api_key or litellm.anthropic_key or litellm.api_key or os.environ.get("ANTHROPIC_API_KEY") custom_prompt_dict = custom_prompt_dict or litellm.custom_prompt_dict # call /messages # default route for all anthropic models @@ -2712,16 +2600,10 @@ def _complete_anthropic(ctx: _CompletionDispatchContext) -> _CompletionDispatchR # Check if we should disable automatic URL suffix appending disable_url_suffix = get_secret_bool("LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX") - if ( - api_base is not None - and not disable_url_suffix - and not api_base.endswith("/v1/messages") - ): + if api_base is not None and not disable_url_suffix and not api_base.endswith("/v1/messages"): api_base += "/v1/messages" elif disable_url_suffix: - verbose_logger.debug( - "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX is set, skipping /v1/messages suffix" - ) + verbose_logger.debug("LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX is set, skipping /v1/messages suffix") response = anthropic_chat_completions.completion( model=model, @@ -2764,19 +2646,9 @@ def _complete_nlp_cloud(ctx: _CompletionDispatchContext) -> _CompletionDispatchR model_response = ctx.model_response optional_params = ctx.optional_params - nlp_cloud_key = ( - api_key - or litellm.nlp_cloud_key - or get_secret("NLP_CLOUD_API_KEY") - or litellm.api_key - ) + nlp_cloud_key = api_key or litellm.nlp_cloud_key or get_secret("NLP_CLOUD_API_KEY") or litellm.api_key - api_base = ( - api_base - or litellm.api_base - or get_secret("NLP_CLOUD_API_BASE") - or "https://api.nlpcloud.io/v1/gpu/" - ) + api_base = api_base or litellm.api_base or get_secret("NLP_CLOUD_API_BASE") or "https://api.nlpcloud.io/v1/gpu/" response = nlp_cloud_chat_completion( model=model, @@ -2832,10 +2704,7 @@ def _complete_aleph_alpha(ctx: _CompletionDispatchContext) -> _CompletionDispatc ) api_base = ( - api_base - or litellm.api_base - or get_secret("ALEPH_ALPHA_API_BASE") - or "https://api.aleph-alpha.com/complete" + api_base or litellm.api_base or get_secret("ALEPH_ALPHA_API_BASE") or "https://api.aleph-alpha.com/complete" ) model_response = aleph_alpha.completion( @@ -2893,22 +2762,12 @@ def _complete_cohere_chat(ctx: _CompletionDispatchContext) -> _CompletionDispatc verbose_logger.debug(f"Cohere route: {cohere_route}") # Set API base based on route if cohere_route == "v2": - api_base = ( - api_base - or litellm.api_base - or get_secret_str("COHERE_API_BASE") - or "https://api.cohere.com/v2/chat" - ) + api_base = api_base or litellm.api_base or get_secret_str("COHERE_API_BASE") or "https://api.cohere.com/v2/chat" # Remove v2/ prefix from model name for the actual API call if "v2/" in model: model = model.replace("v2/", "") else: - api_base = ( - api_base - or litellm.api_base - or get_secret_str("COHERE_API_BASE") - or "https://api.cohere.ai/v1/chat" - ) + api_base = api_base or litellm.api_base or get_secret_str("COHERE_API_BASE") or "https://api.cohere.ai/v1/chat" headers = headers or litellm.headers or {} if headers is None: @@ -2951,19 +2810,9 @@ def _complete_maritalk(ctx: _CompletionDispatchContext) -> _CompletionDispatchRe model_response = ctx.model_response optional_params = ctx.optional_params - maritalk_key = ( - api_key - or litellm.maritalk_key - or get_secret("MARITALK_API_KEY") - or litellm.api_key - ) + maritalk_key = api_key or litellm.maritalk_key or get_secret("MARITALK_API_KEY") or litellm.api_key - api_base = ( - api_base - or litellm.api_base - or get_secret("MARITALK_API_BASE") - or "https://chat.maritaca.ai/api" - ) + api_base = api_base or litellm.api_base or get_secret("MARITALK_API_BASE") or "https://chat.maritaca.ai/api" return openai_like_chat_completion.completion( model=model, @@ -2996,17 +2845,9 @@ def _complete_amazon_nova(ctx: _CompletionDispatchContext) -> _CompletionDispatc optional_params = ctx.optional_params timeout = ctx.timeout - api_key = ( - api_key - or litellm.amazon_nova_api_key - or get_secret_str("AMAZON_NOVA_API_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.amazon_nova_api_key or get_secret_str("AMAZON_NOVA_API_KEY") or litellm.api_key api_base = ( - api_base - or litellm.api_base - or get_secret_str("AMAZON_NOVA_API_BASE") - or "https://api.nova.amazon.com/v1" + api_base or litellm.api_base or get_secret_str("AMAZON_NOVA_API_BASE") or "https://api.nova.amazon.com/v1" ) return openai_like_chat_completion.completion( model=model, @@ -3305,12 +3146,7 @@ def _complete_openrouter(ctx: _CompletionDispatchContext) -> _CompletionDispatch stream = ctx.stream timeout = ctx.timeout - api_base = ( - api_base - or litellm.api_base - or get_secret_str("OPENROUTER_API_BASE") - or "https://openrouter.ai/api/v1" - ) + api_base = api_base or litellm.api_base or get_secret_str("OPENROUTER_API_BASE") or "https://openrouter.ai/api/v1" api_key = ( api_key @@ -3366,9 +3202,7 @@ def _complete_openrouter(ctx: _CompletionDispatchContext) -> _CompletionDispatch client=client, ) ## LOGGING - logging.post_call( - input=messages, api_key=openai.api_key, original_response=response - ) + logging.post_call(input=messages, api_key=openai.api_key, original_response=response) return response @@ -3446,9 +3280,7 @@ def _complete_vercel_ai_gateway( client=client, ) ## LOGGING - logging.post_call( - input=messages, api_key=openai.api_key, original_response=response - ) + logging.post_call(input=messages, api_key=openai.api_key, original_response=response) return response @@ -3696,11 +3528,7 @@ def _complete_vertex_ai(ctx: _CompletionDispatchContext) -> _CompletionDispatchR acompletion=acompletion, ) - if ( - "stream" in optional_params - and optional_params["stream"] is True - and acompletion is False - ): + if "stream" in optional_params and optional_params["stream"] is True and acompletion is False: return CustomStreamWrapper( model_response, model, @@ -3744,12 +3572,7 @@ def _complete_predibase(ctx: _CompletionDispatchContext) -> _CompletionDispatchR or get_secret("PREDIBASE_API_BASE") ) - api_key = ( - api_key - or litellm.api_key - or litellm.predibase_key - or get_secret("PREDIBASE_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.predibase_key or get_secret("PREDIBASE_API_KEY") _model_response = predibase_chat_completions.completion( model=model, @@ -3769,11 +3592,7 @@ def _complete_predibase(ctx: _CompletionDispatchContext) -> _CompletionDispatchR timeout=timeout, ) - if ( - "stream" in optional_params - and optional_params["stream"] is True - and acompletion is False - ): + if "stream" in optional_params and optional_params["stream"] is True and acompletion is False: return _model_response return _model_response @@ -3823,11 +3642,7 @@ def _complete_text_completion_codestral( timeout=timeout, ) - if ( - "stream" in optional_params - and optional_params["stream"] is True - and acompletion is False - ): + if "stream" in optional_params and optional_params["stream"] is True and acompletion is False: return _model_response # pyright: ignore[reportReturnType] # provider SDK return type is broader than the dispatch contract return _model_response # pyright: ignore[reportReturnType] # provider SDK return type is broader than the dispatch contract @@ -3850,16 +3665,8 @@ def _complete_text_completion_inception( text_completion = ctx.text_completion timeout = ctx.timeout - passed_api_base = ( - api_base - or optional_params.pop("api_base", None) - or optional_params.pop("base_url", None) - ) - api_base = ( - passed_api_base - or get_secret_str("INCEPTION_API_BASE") - or "https://api.inceptionlabs.ai/v1" - ) + passed_api_base = api_base or optional_params.pop("api_base", None) or optional_params.pop("base_url", None) + api_base = passed_api_base or get_secret_str("INCEPTION_API_BASE") or "https://api.inceptionlabs.ai/v1" # FIM is served at `/v1/fim/completions`; the OpenAI client appends # `/completions`, so point it at the `/v1/fim` base. api_base = api_base.rstrip("/") @@ -3870,9 +3677,7 @@ def _complete_text_completion_inception( # api_base; only resolve it for the default/server base, or when the # caller passes their own key. if passed_api_base is None or api_key: - api_key = ( - api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") - ) + api_key = api_key or litellm.inception_key or get_secret_str("INCEPTION_API_KEY") _response = openai_text_completions.completion( model=model, @@ -3891,15 +3696,9 @@ def _complete_text_completion_inception( timeout=timeout, # type: ignore ) - if ( - optional_params.get("stream", False) is False - and acompletion is False - and text_completion is False - ): - _response = ( - litellm.OpenAITextCompletionConfig().convert_to_chat_model_response_object( - response_object=_response, model_response_object=model_response - ) + if optional_params.get("stream", False) is False and acompletion is False and text_completion is False: + _response = litellm.OpenAITextCompletionConfig().convert_to_chat_model_response_object( + response_object=_response, model_response_object=model_response ) if optional_params.get("stream", False) or acompletion is True: @@ -4012,10 +3811,7 @@ def _complete_bedrock(ctx: _CompletionDispatchContext) -> _CompletionDispatchRes optional_params["aws_secret_access_key"] = creds.secret_key if creds.token: optional_params["aws_session_token"] = creds.token - if ( - "aws_region_name" not in optional_params - or optional_params["aws_region_name"] is None - ): + if "aws_region_name" not in optional_params or optional_params["aws_region_name"] is None: optional_params["aws_region_name"] = aws_bedrock_client.meta.region_name bedrock_route = BedrockModelInfo.get_bedrock_route(model) @@ -4181,9 +3977,7 @@ def _complete_watsonx_text( wx_credentials = optional_params.pop( "wx_credentials", - optional_params.pop( - "watsonx_credentials", None - ), # follow {provider}_credentials, same as vertex ai + optional_params.pop("watsonx_credentials", None), # follow {provider}_credentials, same as vertex ai ) token: Optional[str] = None @@ -4273,12 +4067,7 @@ def _complete_ollama(ctx: _CompletionDispatchContext) -> _CompletionDispatchResu stream = ctx.stream timeout = ctx.timeout - api_base = ( - litellm.api_base - or api_base - or get_secret("OLLAMA_API_BASE") - or "http://localhost:11434" - ) + api_base = litellm.api_base or api_base or get_secret("OLLAMA_API_BASE") or "http://localhost:11434" if api_key is not None and "Authorization" not in headers: headers["Authorization"] = f"Bearer {api_key}" @@ -4318,19 +4107,9 @@ def _complete_ollama_chat(ctx: _CompletionDispatchContext) -> _CompletionDispatc stream = ctx.stream timeout = ctx.timeout - api_base = ( - litellm.api_base - or api_base - or get_secret("OLLAMA_API_BASE") - or "http://localhost:11434" - ) + api_base = litellm.api_base or api_base or get_secret("OLLAMA_API_BASE") or "http://localhost:11434" - api_key = ( - api_key - or litellm.ollama_key - or os.environ.get("OLLAMA_API_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.ollama_key or os.environ.get("OLLAMA_API_KEY") or litellm.api_key if api_key is not None and "Authorization" not in headers: headers["Authorization"] = f"Bearer {api_key}" @@ -4406,12 +4185,7 @@ def _complete_cloudflare(ctx: _CompletionDispatchContext) -> _CompletionDispatch stream = ctx.stream timeout = ctx.timeout - api_key = ( - api_key - or litellm.cloudflare_api_key - or litellm.api_key - or get_secret("CLOUDFLARE_API_KEY") - ) + api_key = api_key or litellm.cloudflare_api_key or litellm.api_key or get_secret("CLOUDFLARE_API_KEY") api_base = api_base or litellm.api_base or get_secret("CLOUDFLARE_API_BASE") custom_prompt_dict = custom_prompt_dict or litellm.custom_prompt_dict @@ -4578,12 +4352,7 @@ def _complete_bytez(ctx: _CompletionDispatchContext) -> _CompletionDispatchResul stream = ctx.stream timeout = ctx.timeout - api_key = ( - api_key - or litellm.bytez_key - or get_secret_str("BYTEZ_API_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.bytez_key or get_secret_str("BYTEZ_API_KEY") or litellm.api_key response = base_llm_http_handler.completion( model=model, @@ -4625,12 +4394,7 @@ def _complete_lemonade(ctx: _CompletionDispatchContext) -> _CompletionDispatchRe stream = ctx.stream timeout = ctx.timeout - api_key = ( - api_key - or litellm.lemonade_key - or get_secret_str("LEMONADE_API_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.lemonade_key or get_secret_str("LEMONADE_API_KEY") or litellm.api_key response = base_llm_http_handler.completion( model=model, @@ -4672,12 +4436,7 @@ def _complete_ovhcloud(ctx: _CompletionDispatchContext) -> _CompletionDispatchRe stream = ctx.stream timeout = ctx.timeout - api_key = ( - api_key - or litellm.ovhcloud_key - or get_secret_str("OVHCLOUD_API_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.ovhcloud_key or get_secret_str("OVHCLOUD_API_KEY") or litellm.api_key api_base = ( api_base @@ -4723,9 +4482,7 @@ def _complete_custom(ctx: _CompletionDispatchContext) -> _CompletionDispatchResu url = litellm.api_base or api_base or "" if url is None or url == "": - raise ValueError( - "api_base not set. Set api_base or litellm.api_base for custom endpoints" - ) + raise ValueError("api_base not set. Set api_base or litellm.api_base for custom endpoints") """ assume input to custom LLM api bases follow this format: @@ -4808,14 +4565,10 @@ def _complete_custom_providers( custom_handler = item["custom_handler"] if custom_handler is None: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) ## ROUTE LLM CALL ## - handler_fn = custom_chat_llm_router( - async_fn=acompletion, stream=stream, custom_llm=custom_handler - ) + handler_fn = custom_chat_llm_router(async_fn=acompletion, stream=stream, custom_llm=custom_handler) headers = headers or litellm.headers or {} @@ -4970,9 +4723,7 @@ def completion( # type: ignore logit_bias: Optional[dict] = None, user: Optional[str] = None, # openai v1.0+ new params - reasoning_effort: Optional[ - Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"] - ] = None, + reasoning_effort: Optional[Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"]] = None, verbosity: Optional[Literal["low", "medium", "high"]] = None, response_format: Optional[Union[dict, Type[BaseModel]]] = None, seed: Optional[int] = None, @@ -5081,9 +4832,7 @@ def completion( # type: ignore # Check if MCP tools are present (following responses pattern) # Cast tools to Optional[Iterable[ToolParam]] for type checking tools_for_mcp = cast(Optional[Iterable[ToolParam]], tools) - if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway( - tools=tools_for_mcp - ): + if LiteLLM_Proxy_MCP_Handler._should_use_litellm_mcp_gateway(tools=tools_for_mcp): return acompletion_with_mcp( # pyright: ignore[reportReturnType] # MCP path returns a coroutine that acompletion() awaits; completion()'s sync return type omits it model=model, messages=messages, @@ -5142,17 +4891,11 @@ def completion( # type: ignore model_info = kwargs.get("model_info", None) proxy_server_request = kwargs.get("proxy_server_request", None) fallbacks = kwargs.get("fallbacks", None) - provider_specific_header = cast( - Optional[ProviderSpecificHeader], kwargs.get("provider_specific_header", None) - ) + provider_specific_header = cast(Optional[ProviderSpecificHeader], kwargs.get("provider_specific_header", None)) headers = kwargs.get("headers", None) or extra_headers - ensure_alternating_roles: Optional[bool] = kwargs.get( - "ensure_alternating_roles", None - ) - user_continue_message: Optional[ChatCompletionUserMessage] = kwargs.get( - "user_continue_message", None - ) + ensure_alternating_roles: Optional[bool] = kwargs.get("ensure_alternating_roles", None) + user_continue_message: Optional[ChatCompletionUserMessage] = kwargs.get("user_continue_message", None) assistant_continue_message: Optional[ChatCompletionAssistantMessage] = kwargs.get( "assistant_continue_message", None ) @@ -5194,9 +4937,7 @@ def completion( # type: ignore model_info.get("base_model") if isinstance(model_info, dict) else None ) ### DISABLE FLAGS ### - disable_add_transform_inline_image_block = kwargs.get( - "disable_add_transform_inline_image_block", None - ) + disable_add_transform_inline_image_block = kwargs.get("disable_add_transform_inline_image_block", None) ### TEXT COMPLETION CALLS ### text_completion = kwargs.get("text_completion", False) atext_completion = kwargs.get("atext_completion", False) @@ -5260,9 +5001,7 @@ def completion( # type: ignore **args ) if model_list is not None: - deployments = [ - m["litellm_params"] for m in model_list if m["model_name"] == model - ] + deployments = [m["litellm_params"] for m in model_list if m["model_name"] == model] return litellm.batch_completion_models( # pyright: ignore[reportReturnType] # batch path returns a list of responses, outside completion()'s single-response return type deployments=deployments, **args ) @@ -5279,18 +5018,14 @@ def completion( # type: ignore if deployment_id is not None: # azure llms model = deployment_id custom_llm_provider = "azure" - _supplemental_provider_params = { - k: kwargs[k] for k in OPTIONAL_KWARGS_KEYS if k in kwargs - } + _supplemental_provider_params = {k: kwargs[k] for k in OPTIONAL_KWARGS_KEYS if k in kwargs} model, custom_llm_provider, dynamic_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=( - GenericLiteLLMParams(**_supplemental_provider_params) - if _supplemental_provider_params - else None + GenericLiteLLMParams(**_supplemental_provider_params) if _supplemental_provider_params else None ), ) @@ -5301,9 +5036,7 @@ def completion( # type: ignore web_search_options=web_search_options, ) - if not _should_allow_input_examples( - custom_llm_provider=custom_llm_provider, model=model - ): + if not _should_allow_input_examples(custom_llm_provider=custom_llm_provider, model=model): tools = _drop_input_examples_from_tools(tools=tools) if provider_specific_header is not None: @@ -5344,13 +5077,7 @@ def completion( # type: ignore ) ### BUILD CUSTOM PROMPT TEMPLATE -- IF GIVEN ### custom_prompt_dict = {} # type: ignore - if ( - initial_prompt_value - or roles - or final_prompt_value - or bos_token - or eos_token - ): + if initial_prompt_value or roles or final_prompt_value or bos_token or eos_token: custom_prompt_dict = {model: {}} if initial_prompt_value: custom_prompt_dict[model]["initial_prompt_value"] = initial_prompt_value @@ -5373,9 +5100,7 @@ def completion( # type: ignore ) provider_config: Optional[BaseConfig] = None - if custom_llm_provider is not None and custom_llm_provider in [ - provider.value for provider in LlmProviders - ]: + if custom_llm_provider is not None and custom_llm_provider in [provider.value for provider in LlmProviders]: provider_config = ProviderConfigManager.get_provider_chat_config( model=model, provider=LlmProviders(custom_llm_provider), @@ -5383,9 +5108,7 @@ def completion( # type: ignore ) if provider_config is not None: - messages = provider_config.translate_developer_role_to_system_role( - messages=messages - ) + messages = provider_config.translate_developer_role_to_system_role(messages=messages) if ( supports_system_message is not None @@ -5441,9 +5164,7 @@ def completion( # type: ignore "allowed_openai_params": kwargs.get("allowed_openai_params"), "base_model": base_model, } - optional_params = get_optional_params( - **optional_param_args, **non_default_params - ) + optional_params = get_optional_params(**optional_param_args, **non_default_params) processed_non_default_params = pre_process_non_default_params( model=model, passed_params=optional_param_args, @@ -5455,16 +5176,11 @@ def completion( # type: ignore provider_config=provider_config, ) - if ( - litellm.add_function_to_prompt - and optional_params.get("functions_unsupported_model", None) + if litellm.add_function_to_prompt and optional_params.get( + "functions_unsupported_model", None ): # if user opts to add it to prompt, when API doesn't support function calling - functions_unsupported_model = optional_params.pop( - "functions_unsupported_model" - ) - messages = function_call_prompt( - messages=messages, functions=functions_unsupported_model - ) + functions_unsupported_model = optional_params.pop("functions_unsupported_model") + messages = function_call_prompt(messages=messages, functions=functions_unsupported_model) # For logging - save the values of the litellm-specific params passed in litellm_params = get_litellm_params( @@ -5502,9 +5218,7 @@ def completion( # type: ignore prompt_id=prompt_id, prompt_variables=prompt_variables, ssl_verify=ssl_verify, - merge_reasoning_content_in_choices=kwargs.get( - "merge_reasoning_content_in_choices", None - ), + merge_reasoning_content_in_choices=kwargs.get("merge_reasoning_content_in_choices", None), use_litellm_proxy=kwargs.get("use_litellm_proxy", False), api_version=api_version, azure_ad_token=kwargs.get("azure_ad_token"), @@ -5567,15 +5281,10 @@ def completion( # type: ignore # detection when the deployment name differs from the model name. _azure_detection_model = base_model or model - if ( - responses_api_model_info.get("mode") == "responses" - and not skip_responses_api_bridge - ): + if responses_api_model_info.get("mode") == "responses" and not skip_responses_api_bridge: from litellm.completion_extras import responses_api_bridge - optional_params, rs_val = ( - strip_reasoning_summary_aliases_from_optional_params(optional_params) - ) + optional_params, rs_val = strip_reasoning_summary_aliases_from_optional_params(optional_params) if isinstance(reasoning_effort, dict) and "summary" in reasoning_effort: optional_params["reasoning_effort"] = reasoning_effort @@ -5608,18 +5317,11 @@ def completion( # type: ignore encoding=_get_encoding(), stream=stream, ) - elif ( - custom_llm_provider == "openai" - and OpenAIGPT5Config.is_model_gpt_5_model(model) - ) or ( + elif (custom_llm_provider == "openai" and OpenAIGPT5Config.is_model_gpt_5_model(model)) or ( custom_llm_provider == "azure" - and litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model( - _azure_detection_model - ) + and litellm.AzureOpenAIGPT5Config.is_model_gpt_5_model(_azure_detection_model) ): - optional_params, _ = strip_reasoning_summary_aliases_from_optional_params( - optional_params - ) + optional_params, _ = strip_reasoning_summary_aliases_from_optional_params(optional_params) _dispatch_ctx = _CompletionDispatchContext( _azure_detection_model=_azure_detection_model, @@ -5671,8 +5373,7 @@ def completion( # type: ignore custom_llm_provider == "text-completion-openai" or "ft:babbage-002" in model or "ft:davinci-002" in model # support for finetuned completion models - or custom_llm_provider - in litellm.openai_text_completion_compatible_providers + or custom_llm_provider in litellm.openai_text_completion_compatible_providers and kwargs.get("text_completion") is True ): response = _complete_text_completion_openai(_dispatch_ctx) @@ -5728,9 +5429,7 @@ def completion( # type: ignore or custom_llm_provider == "wandb" or custom_llm_provider == "clarifai" or custom_llm_provider in litellm.openai_compatible_providers - or JSONProviderRegistry.exists( - custom_llm_provider - ) # JSON-configured providers + or JSONProviderRegistry.exists(custom_llm_provider) # JSON-configured providers or "ft:gpt-3.5-turbo" in model # finetune gpt-3.5-turbo ): # allow user to make an openai call with a custom base # note: if a user sets a custom base - we should ensure this works @@ -5739,18 +5438,10 @@ def completion( # type: ignore elif custom_llm_provider == "mistral": response = _complete_mistral(_dispatch_ctx) - elif ( - "replicate" in model - or custom_llm_provider == "replicate" - or model in litellm.replicate_models - ): + elif "replicate" in model or custom_llm_provider == "replicate" or model in litellm.replicate_models: # Setting the relevant API KEY for replicate, replicate defaults to using os.environ.get("REPLICATE_API_TOKEN") response = _complete_replicate(_dispatch_ctx) - elif ( - "clarifai" in model - or custom_llm_provider == "clarifai" - or model in litellm.clarifai_models - ): + elif "clarifai" in model or custom_llm_provider == "clarifai" or model in litellm.clarifai_models: pass # Deprecated - handled in the openai compatible provider section above elif custom_llm_provider == "anthropic_text": response = _complete_anthropic_text(_dispatch_ctx) @@ -5853,9 +5544,7 @@ def completion( # type: ignore elif custom_llm_provider == "custom": response = _complete_custom(_dispatch_ctx) - elif ( - custom_llm_provider in litellm._custom_providers - ): # Assume custom LLM provider + elif custom_llm_provider in litellm._custom_providers: # Assume custom LLM provider # Get the Custom Handler response = _complete_custom_providers(_dispatch_ctx) @@ -5868,9 +5557,7 @@ def completion( # type: ignore response = _complete_langflow(_dispatch_ctx) else: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) return response except Exception as e: ## Map to OpenAI Exception @@ -5890,9 +5577,7 @@ def completion_with_retries(*args, **kwargs): try: import tenacity except Exception as e: - raise Exception( - f"tenacity import failed please run `pip install tenacity`. Error{e}" - ) + raise Exception(f"tenacity import failed please run `pip install tenacity`. Error{e}") num_retries = kwargs.pop("num_retries", 3) # reset retries in .completion() @@ -5909,9 +5594,7 @@ def completion_with_retries(*args, **kwargs): reraise=True, ) else: - retryer = tenacity.Retrying( - stop=tenacity.stop_after_attempt(num_retries), reraise=True - ) + retryer = tenacity.Retrying(stop=tenacity.stop_after_attempt(num_retries), reraise=True) return retryer(original_function, *args, **kwargs) @@ -5923,9 +5606,7 @@ async def acompletion_with_retries(*args, **kwargs): try: import tenacity except Exception as e: - raise Exception( - f"tenacity import failed please run `pip install tenacity`. Error{e}" - ) + raise Exception(f"tenacity import failed please run `pip install tenacity`. Error{e}") num_retries = kwargs.pop("num_retries", 3) kwargs["max_retries"] = 0 @@ -5939,9 +5620,7 @@ async def acompletion_with_retries(*args, **kwargs): reraise=True, ) else: - retryer = tenacity.AsyncRetrying( - stop=tenacity.stop_after_attempt(num_retries), reraise=True - ) + retryer = tenacity.AsyncRetrying(stop=tenacity.stop_after_attempt(num_retries), reraise=True) return await retryer(original_function, *args, **kwargs) @@ -5952,9 +5631,7 @@ def responses_with_retries(*args, **kwargs): try: import tenacity except Exception as e: - raise Exception( - f"tenacity import failed please run `pip install tenacity`. Error{e}" - ) + raise Exception(f"tenacity import failed please run `pip install tenacity`. Error{e}") from litellm.responses.main import responses @@ -5973,9 +5650,7 @@ def responses_with_retries(*args, **kwargs): reraise=True, ) else: - retryer = tenacity.Retrying( - stop=tenacity.stop_after_attempt(num_retries), reraise=True - ) + retryer = tenacity.Retrying(stop=tenacity.stop_after_attempt(num_retries), reraise=True) return retryer(original_function, *args, **kwargs) @@ -5986,9 +5661,7 @@ async def aresponses_with_retries(*args, **kwargs): try: import tenacity except Exception as e: - raise Exception( - f"tenacity import failed please run `pip install tenacity`. Error{e}" - ) + raise Exception(f"tenacity import failed please run `pip install tenacity`. Error{e}") from litellm.responses.main import aresponses @@ -6004,9 +5677,7 @@ async def aresponses_with_retries(*args, **kwargs): reraise=True, ) else: - retryer = tenacity.AsyncRetrying( - stop=tenacity.stop_after_attempt(num_retries), reraise=True - ) + retryer = tenacity.AsyncRetrying(stop=tenacity.stop_after_attempt(num_retries), reraise=True) return await retryer(original_function, *args, **kwargs) @@ -6052,17 +5723,11 @@ async def aembedding(*args, **kwargs) -> EmbeddingResponse: response = init_response elif asyncio.iscoroutine(init_response): response = await init_response # type: ignore - if ( - response is not None - and isinstance(response, EmbeddingResponse) - and hasattr(response, "_hidden_params") - ): + if response is not None and isinstance(response, EmbeddingResponse) and hasattr(response, "_hidden_params"): response._hidden_params["custom_llm_provider"] = custom_llm_provider if response is None: - raise ValueError( - "Unable to get Embedding Response. Please pass a valid llm_provider." - ) + raise ValueError("Unable to get Embedding Response. Please pass a valid llm_provider.") return response except Exception as e: custom_llm_provider = custom_llm_provider or "openai" @@ -6236,9 +5901,7 @@ def embedding( if dynamic_api_key is not None: api_key = dynamic_api_key - allowed_openai_params: Optional[List[str]] = kwargs.get( - "allowed_openai_params", None - ) + allowed_openai_params: Optional[List[str]] = kwargs.get("allowed_openai_params", None) optional_params = get_optional_params_embeddings( model=model, user=user, @@ -6250,9 +5913,7 @@ def embedding( ) ### REGISTER CUSTOM MODEL PRICING -- IF GIVEN ### - if ( - input_cost_per_token is not None and output_cost_per_token is not None - ) or input_cost_per_second is not None: + if (input_cost_per_token is not None and output_cost_per_token is not None) or input_cost_per_second is not None: litellm.register_model( { f"{custom_llm_provider}/{model}": _build_custom_pricing_entry( @@ -6277,9 +5938,7 @@ def embedding( if mock_response is not None: return mock_embedding(model=model, mock_response=mock_response) try: - response: Optional[ - Union[EmbeddingResponse, Coroutine[Any, Any, EmbeddingResponse]] - ] = None + response: Optional[Union[EmbeddingResponse, Coroutine[Any, Any, EmbeddingResponse]]] = None if azure is True or custom_llm_provider == "azure": # azure configs @@ -6293,21 +5952,12 @@ def embedding( or litellm.AZURE_DEFAULT_API_VERSION ) - azure_ad_token = optional_params.pop( - "azure_ad_token", None - ) or get_secret_str("AZURE_AD_TOKEN") + azure_ad_token = optional_params.pop("azure_ad_token", None) or get_secret_str("AZURE_AD_TOKEN") - api_key = ( - api_key - or litellm.api_key - or litellm.azure_key - or get_secret_str("AZURE_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.azure_key or get_secret_str("AZURE_API_KEY") if api_base is None: - raise ValueError( - "No API Base provided for Azure OpenAI LLM provider. Set 'AZURE_API_BASE' in .env" - ) + raise ValueError("No API Base provided for Azure OpenAI LLM provider. Set 'AZURE_API_BASE' in .env") ## EMBEDDING CALL response = azure_chat_completions.embedding( @@ -6349,10 +5999,7 @@ def embedding( or custom_llm_provider == "together_ai" or custom_llm_provider == "nvidia_nim" or custom_llm_provider == "litellm_proxy" - or ( - model in litellm.open_ai_embedding_models - and custom_llm_provider is None - ) + or (model in litellm.open_ai_embedding_models and custom_llm_provider is None) ): api_base = ( api_base @@ -6367,12 +6014,7 @@ def embedding( or None # default - https://github.com/openai/openai-python/blob/284c1799070c723c6a553337134148a7ab088dd8/openai/util.py#L105 ) # set API KEY - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") if headers is not None and headers != {}: optional_params["extra_headers"] = headers @@ -6384,9 +6026,7 @@ def embedding( if env_fmt is not None and env_fmt.strip().lower() == "none": optional_params.pop("encoding_format", None) else: - _default_fmt = ( - optional_params.get("encoding_format") or env_fmt or "float" - ) + _default_fmt = optional_params.get("encoding_format") or env_fmt or "float" if _default_fmt.strip().lower() == "none": optional_params.pop("encoding_format", None) else: @@ -6413,12 +6053,7 @@ def embedding( api_base = api_base or litellm.api_base or get_secret("DATABRICKS_API_BASE") # type: ignore # set API KEY - api_key = ( - api_key - or litellm.api_key - or litellm.databricks_key - or get_secret("DATABRICKS_API_KEY") - ) # type: ignore + api_key = api_key or litellm.api_key or litellm.databricks_key or get_secret("DATABRICKS_API_KEY") # type: ignore ## EMBEDDING CALL response = databricks_embedding.embedding( @@ -6434,9 +6069,7 @@ def embedding( aembedding=aembedding, ) elif custom_llm_provider == "hosted_vllm": - api_base = ( - api_base or litellm.api_base or get_secret_str("HOSTED_VLLM_API_BASE") - ) + api_base = api_base or litellm.api_base or get_secret_str("HOSTED_VLLM_API_BASE") # set API KEY if api_key is None: @@ -6462,18 +6095,11 @@ def embedding( or custom_llm_provider == "llamafile" or custom_llm_provider == "lm_studio" ): - api_base = ( - api_base or litellm.api_base or get_secret_str("OPENAI_LIKE_API_BASE") - ) + api_base = api_base or litellm.api_base or get_secret_str("OPENAI_LIKE_API_BASE") # set API KEY if api_key is None: - api_key = ( - api_key - or litellm.api_key - or litellm.openai_like_key - or get_secret_str("OPENAI_LIKE_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_like_key or get_secret_str("OPENAI_LIKE_API_KEY") if headers is not None and headers != {}: optional_params["extra_headers"] = headers @@ -6540,10 +6166,7 @@ def embedding( ) elif custom_llm_provider == "openrouter": api_base = ( - api_base - or litellm.api_base - or get_secret_str("OPENROUTER_API_BASE") - or "https://openrouter.ai/api/v1" + api_base or litellm.api_base or get_secret_str("OPENROUTER_API_BASE") or "https://openrouter.ai/api/v1" ) api_key = ( @@ -6614,12 +6237,7 @@ def embedding( headers=headers, ) elif custom_llm_provider == "huggingface": - api_key = ( - api_key - or litellm.huggingface_key - or get_secret("HUGGINGFACE_API_KEY") - or litellm.api_key - ) # type: ignore + api_key = api_key or litellm.huggingface_key or get_secret("HUGGINGFACE_API_KEY") or litellm.api_key # type: ignore response = huggingface_embed.embedding( model=model, input=input, @@ -6657,9 +6275,7 @@ def embedding( ) elif custom_llm_provider == "triton": if api_base is None: - raise ValueError( - "api_base is required for triton. Please pass `api_base`" - ) + raise ValueError("api_base is required for triton. Please pass `api_base`") response = base_llm_http_handler.embedding( model=model, input=input, @@ -6721,16 +6337,11 @@ def embedding( ) api_base = ( - api_base - or litellm.api_base - or get_secret_str("VERTEXAI_API_BASE") - or get_secret_str("VERTEX_API_BASE") + api_base or litellm.api_base or get_secret_str("VERTEXAI_API_BASE") or get_secret_str("VERTEX_API_BASE") ) try: - model_info = get_model_info( - model=model, custom_llm_provider="vertex_ai" - ) + model_info = get_model_info(model=model, custom_llm_provider="vertex_ai") uses_embed_content = model_info.get("uses_embed_content", False) except Exception: uses_embed_content = False @@ -6757,8 +6368,7 @@ def embedding( elif ( "image" in optional_params or "video" in optional_params - or model - in vertex_multimodal_embedding.SUPPORTED_MULTIMODAL_EMBEDDING_MODELS + or model in vertex_multimodal_embedding.SUPPORTED_MULTIMODAL_EMBEDDING_MODELS ): response = vertex_multimodal_embedding.multimodal_embedding( model=model, @@ -6809,12 +6419,7 @@ def embedding( api_key=api_key, ) elif custom_llm_provider == "ollama": - api_base = ( - litellm.api_base - or api_base - or get_secret_str("OLLAMA_API_BASE") - or "http://localhost:11434" - ) # type: ignore + api_base = litellm.api_base or api_base or get_secret_str("OLLAMA_API_BASE") or "http://localhost:11434" # type: ignore if isinstance(input, str): input = [input] @@ -6824,11 +6429,7 @@ def embedding( model=model, # type: ignore llm_provider="ollama", # type: ignore ) - ollama_embeddings_fn = ( - ollama.ollama_aembeddings - if aembedding is True - else ollama.ollama_embeddings - ) + ollama_embeddings_fn = ollama.ollama_aembeddings if aembedding is True else ollama.ollama_embeddings response = ollama_embeddings_fn( # type: ignore api_base=api_base, model=model, @@ -6863,9 +6464,7 @@ def embedding( aembedding=aembedding, ) elif custom_llm_provider == "fireworks_ai": - api_key = ( - api_key or litellm.api_key or get_secret_str("FIREWORKS_AI_API_KEY") - ) + api_key = api_key or litellm.api_key or get_secret_str("FIREWORKS_AI_API_KEY") response = openai_chat_completions.embedding( model=model, input=input, @@ -6880,12 +6479,7 @@ def embedding( ) elif custom_llm_provider == "nebius": api_key = api_key or litellm.api_key or get_secret_str("NEBIUS_API_KEY") - api_base = ( - api_base - or litellm.api_base - or get_secret_str("NEBIUS_API_BASE") - or "api.studio.nebius.ai/v1" - ) + api_base = api_base or litellm.api_base or get_secret_str("NEBIUS_API_BASE") or "api.studio.nebius.ai/v1" response = openai_chat_completions.embedding( model=model, @@ -6902,10 +6496,7 @@ def embedding( elif custom_llm_provider == "wandb": api_key = api_key or litellm.api_key or get_secret_str("WANDB_API_KEY") api_base = ( - api_base - or litellm.api_base - or get_secret_str("WANDB_API_BASE") - or "https://api.inference.wandb.ai/v1" + api_base or litellm.api_base or get_secret_str("WANDB_API_BASE") or "https://api.inference.wandb.ai/v1" ) response = openai_chat_completions.embedding( @@ -6923,10 +6514,7 @@ def embedding( elif custom_llm_provider == "sambanova": api_key = api_key or litellm.api_key or get_secret_str("SAMBANOVA_API_KEY") api_base = ( - api_base - or litellm.api_base - or get_secret_str("SAMBANOVA_API_BASE") - or "https://api.sambanova.ai/v1" + api_base or litellm.api_base or get_secret_str("SAMBANOVA_API_BASE") or "https://api.sambanova.ai/v1" ) response = base_llm_http_handler.embedding( model=model, @@ -6999,16 +6587,10 @@ def embedding( ) elif custom_llm_provider == "xinference": api_key = ( - api_key - or litellm.api_key - or get_secret_str("XINFERENCE_API_KEY") - or "stub-xinference-key" + api_key or litellm.api_key or get_secret_str("XINFERENCE_API_KEY") or "stub-xinference-key" ) # xinference does not need an api key, pass a stub key if user did not set one api_base = ( - api_base - or litellm.api_base - or get_secret_str("XINFERENCE_API_BASE") - or "http://127.0.0.1:9997/v1" + api_base or litellm.api_base or get_secret_str("XINFERENCE_API_BASE") or "http://127.0.0.1:9997/v1" ) response = openai_chat_completions.embedding( model=model, @@ -7085,10 +6667,7 @@ def embedding( ) elif custom_llm_provider == "volcengine": volcengine_key = ( - api_key - or litellm.api_key - or get_secret_str("ARK_API_KEY") - or get_secret_str("VOLCENGINE_API_KEY") + api_key or litellm.api_key or get_secret_str("ARK_API_KEY") or get_secret_str("VOLCENGINE_API_KEY") ) if volcengine_key is None: raise ValueError( @@ -7114,9 +6693,7 @@ def embedding( headers=headers, ) elif custom_llm_provider == "dashscope": - dashscope_key = ( - api_key or litellm.api_key or get_secret_str("DASHSCOPE_API_KEY") - ) + dashscope_key = api_key or litellm.api_key or get_secret_str("DASHSCOPE_API_KEY") if dashscope_key is None: raise ValueError( "Missing API key for DashScope. Set DASHSCOPE_API_KEY environment variable or pass api_key parameter." @@ -7163,17 +6740,9 @@ def embedding( litellm_params={}, ) elif custom_llm_provider == "cometapi": - api_key = ( - api_key - or litellm.cometapi_key - or get_secret_str("COMETAPI_KEY") - or litellm.api_key - ) + api_key = api_key or litellm.cometapi_key or get_secret_str("COMETAPI_KEY") or litellm.api_key api_base = ( - api_base - or litellm.api_base - or get_secret_str("COMETAPI_API_BASE") - or "https://api.cometapi.com/v1" + api_base or litellm.api_base or get_secret_str("COMETAPI_API_BASE") or "https://api.cometapi.com/v1" ) response = base_llm_http_handler.embedding( model=model, @@ -7196,15 +6765,9 @@ def embedding( custom_handler = item["custom_handler"] if custom_handler is None: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) - handler_fn = ( - custom_handler.embedding - if not aembedding - else custom_handler.aembedding - ) + handler_fn = custom_handler.embedding if not aembedding else custom_handler.aembedding response = handler_fn( model=model, @@ -7272,20 +6835,12 @@ def embedding( litellm_params={}, ) else: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) - if ( - response is not None - and hasattr(response, "_hidden_params") - and isinstance(response, EmbeddingResponse) - ): + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) + if response is not None and hasattr(response, "_hidden_params") and isinstance(response, EmbeddingResponse): response._hidden_params["custom_llm_provider"] = custom_llm_provider if response is None: - raise LiteLLMUnknownProvider( - model=model, custom_llm_provider=custom_llm_provider - ) + raise LiteLLMUnknownProvider(model=model, custom_llm_provider=custom_llm_provider) return response except Exception as e: ## LOGGING @@ -7305,9 +6860,7 @@ def embedding( ###### Text Completion ################ @client -async def atext_completion( - *args, **kwargs -) -> Union[TextCompletionResponse, TextCompletionStreamWrapper]: +async def atext_completion(*args, **kwargs) -> Union[TextCompletionResponse, TextCompletionStreamWrapper]: """ Implemented to handle async streaming for the text completion endpoint """ @@ -7325,9 +6878,7 @@ async def atext_completion( func_with_context = partial(ctx.run, func) init_response = await loop.run_in_executor(None, func_with_context) - if isinstance(init_response, dict) or isinstance( - init_response, TextCompletionResponse - ): ## CACHING SCENARIO + if isinstance(init_response, dict) or isinstance(init_response, TextCompletionResponse): ## CACHING SCENARIO if isinstance(init_response, dict): response = TextCompletionResponse(**init_response) else: @@ -7384,27 +6935,13 @@ def text_completion( str, List[Union[str, List[Union[str, List[int]]]]] ], # Required: The prompt(s) to generate completions for. model: Optional[str] = None, # Optional: either `model` or `engine` can be set - best_of: Optional[ - int - ] = None, # Optional: Generates best_of completions server-side. - echo: Optional[ - bool - ] = None, # Optional: Echo back the prompt in addition to the completion. - frequency_penalty: Optional[ - float - ] = None, # Optional: Penalize new tokens based on their existing frequency. - logit_bias: Optional[ - Dict[int, int] - ] = None, # Optional: Modify the likelihood of specified tokens. - logprobs: Optional[ - int - ] = None, # Optional: Include the log probabilities on the most likely tokens. - max_tokens: Optional[ - int - ] = None, # Optional: The maximum number of tokens to generate in the completion. - n: Optional[ - int - ] = None, # Optional: How many completions to generate for each prompt. + best_of: Optional[int] = None, # Optional: Generates best_of completions server-side. + echo: Optional[bool] = None, # Optional: Echo back the prompt in addition to the completion. + frequency_penalty: Optional[float] = None, # Optional: Penalize new tokens based on their existing frequency. + logit_bias: Optional[Dict[int, int]] = None, # Optional: Modify the likelihood of specified tokens. + logprobs: Optional[int] = None, # Optional: Include the log probabilities on the most likely tokens. + max_tokens: Optional[int] = None, # Optional: The maximum number of tokens to generate in the completion. + n: Optional[int] = None, # Optional: How many completions to generate for each prompt. presence_penalty: Optional[ float ] = None, # Optional: Penalize new tokens based on whether they appear in the text so far. @@ -7413,14 +6950,10 @@ def text_completion( ] = None, # Optional: Sequences where the API will stop generating further tokens. stream: Optional[bool] = None, # Optional: Whether to stream back partial progress. stream_options: Optional[dict] = None, - suffix: Optional[ - str - ] = None, # Optional: The suffix that comes after a completion of inserted text. + suffix: Optional[str] = None, # Optional: The suffix that comes after a completion of inserted text. temperature: Optional[float] = None, # Optional: Sampling temperature to use. top_p: Optional[float] = None, # Optional: Nucleus sampling parameter. - user: Optional[ - str - ] = None, # Optional: A unique identifier representing your end-user. + user: Optional[str] = None, # Optional: A unique identifier representing your end-user. # set api_base, api_version, api_key api_base: Optional[str] = None, api_version: Optional[str] = None, @@ -7554,9 +7087,7 @@ def process_prompt(i, individual_prompt): executor.submit(process_prompt, i, individual_prompt) for i, individual_prompt in enumerate(prompt) ] - for i, future in enumerate( - concurrent.futures.as_completed(completed_futures) - ): + for i, future in enumerate(concurrent.futures.as_completed(completed_futures)): responses[i] = future.result() text_completion_response.choices = responses # type: ignore @@ -7614,11 +7145,7 @@ def process_prompt(i, individual_prompt): ) if kwargs.get("acompletion", False) is True: return response - if ( - stream is True - or kwargs.get("stream", False) is True - or isinstance(response, CustomStreamWrapper) - ): + if stream is True or kwargs.get("stream", False) is True or isinstance(response, CustomStreamWrapper): response = TextCompletionStreamWrapper( completion_stream=response, model=model, @@ -7633,11 +7160,9 @@ def process_prompt(i, individual_prompt): if isinstance(response, TextCompletionResponse): return response - text_completion_response = ( - litellm.utils.LiteLLMResponseObjectHandler.convert_chat_to_text_completion( - response=response, - text_completion_response=text_completion_response, - ) + text_completion_response = litellm.utils.LiteLLMResponseObjectHandler.convert_chat_to_text_completion( + response=response, + text_completion_response=text_completion_response, ) return text_completion_response @@ -7667,21 +7192,13 @@ async def aadapter_completion( new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs) - response: Union[ModelResponse, CustomStreamWrapper] = await acompletion( - **new_kwargs - ) # type: ignore - translated_response: Optional[ - Union[BaseModel, AdapterCompletionStreamWrapper] - ] = None + response: Union[ModelResponse, CustomStreamWrapper] = await acompletion(**new_kwargs) # type: ignore + translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = None if isinstance(response, ModelResponse): - translated_response = translation_obj.translate_completion_output_params( - response=response - ) + translated_response = translation_obj.translate_completion_output_params(response=response) if isinstance(response, CustomStreamWrapper): - translated_response = ( - translation_obj.translate_completion_output_params_streaming( - completion_stream=response - ) + translated_response = translation_obj.translate_completion_output_params_streaming( + completion_stream=response ) return translated_response @@ -7696,16 +7213,12 @@ async def aadapter_generate_content( coro = cast( Coroutine[Any, Any, Union[Dict[str, Any], AsyncIterator[bytes]]], - GenerateContentToCompletionHandler.generate_content_handler( - **kwargs, _is_async=True - ), + GenerateContentToCompletionHandler.generate_content_handler(**kwargs, _is_async=True), ) return await coro -def adapter_completion( - *, adapter_id: str, **kwargs -) -> Optional[Union[BaseModel, AdapterCompletionStreamWrapper]]: +def adapter_completion(*, adapter_id: str, **kwargs) -> Optional[Union[BaseModel, AdapterCompletionStreamWrapper]]: translation_obj: Optional[CustomLogger] = None for item in litellm.adapters: if item["id"] == adapter_id: @@ -7721,19 +7234,11 @@ def adapter_completion( new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs) response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore - translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = ( - None - ) + translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = None if isinstance(response, ModelResponse): - translated_response = translation_obj.translate_completion_output_params( - response=response - ) + translated_response = translation_obj.translate_completion_output_params(response=response) elif isinstance(response, CustomStreamWrapper) or inspect.isgenerator(response): - translated_response = ( - translation_obj.translate_completion_output_params_streaming( - completion_stream=response - ) - ) + translated_response = translation_obj.translate_completion_output_params_streaming(completion_stream=response) return translated_response @@ -7745,12 +7250,7 @@ def moderation( input: str, model: Optional[str] = None, api_key: Optional[str] = None, **kwargs ) -> OpenAIModerationResponse: # only supports open ai for now - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") # Extract api_base from kwargs api_base = kwargs.get("api_base", None) @@ -7784,16 +7284,9 @@ async def amoderation( from openai import AsyncOpenAI # only supports open ai for now - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret_str("OPENAI_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret_str("OPENAI_API_KEY") optional_params = GenericLiteLLMParams(**kwargs) - litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get( - "litellm_logging_obj", None - ) + litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get("litellm_logging_obj", None) _dynamic_api_base = None try: ( @@ -7870,9 +7363,7 @@ async def atranscription(*args, **kwargs) -> TranscriptionResponse: ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) - _, custom_llm_provider, _, _ = get_llm_provider( - model=model, api_base=kwargs.get("api_base", None) - ) + _, custom_llm_provider, _, _ = get_llm_provider(model=model, api_base=kwargs.get("api_base", None)) # Await normally init_response = await loop.run_in_executor(None, func_with_context) @@ -7894,18 +7385,12 @@ async def atranscription(*args, **kwargs) -> TranscriptionResponse: # exposing it in the response body. Adding duration to the response # tricks the OpenAI SDK's "best match deserialization" into thinking # a plain Transcription is a TranscriptionVerbose/Diarized type. - if ( - response is not None - and not isinstance(response, Coroutine) - and file is not None - ): + if response is not None and not isinstance(response, Coroutine) and file is not None: existing_duration = getattr(response, "duration", None) if existing_duration is None: calculated_duration = calculate_request_duration(file) if calculated_duration is not None: - response._hidden_params["audio_transcription_duration"] = ( - calculated_duration - ) + response._hidden_params["audio_transcription_duration"] = calculated_duration return response except Exception as e: @@ -7926,9 +7411,7 @@ def transcription( ## OPTIONAL OPENAI PARAMS ## language: Optional[str] = None, prompt: Optional[str] = None, - response_format: Optional[ - Literal["json", "text", "srt", "verbose_json", "vtt"] - ] = None, + response_format: Optional[Literal["json", "text", "srt", "verbose_json", "vtt"]] = None, timestamp_granularities: Optional[List[Literal["word", "segment"]]] = None, temperature: Optional[int] = None, # openai defaults this to 0 ## LITELLM PARAMS ## @@ -8012,9 +7495,7 @@ def transcription( custom_llm_provider=custom_llm_provider, ) - response: Optional[ - Union[TranscriptionResponse, Coroutine[Any, Any, TranscriptionResponse]] - ] = None + response: Optional[Union[TranscriptionResponse, Coroutine[Any, Any, TranscriptionResponse]]] = None provider_config = ProviderConfigManager.get_provider_audio_transcription_config( model=model, @@ -8025,20 +7506,11 @@ def transcription( # azure configs api_base = api_base or litellm.api_base or get_secret_str("AZURE_API_BASE") - api_version = ( - api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") - ) + api_version = api_version or litellm.api_version or get_secret_str("AZURE_API_VERSION") - azure_ad_token = kwargs.pop("azure_ad_token", None) or get_secret_str( - "AZURE_AD_TOKEN" - ) + azure_ad_token = kwargs.pop("azure_ad_token", None) or get_secret_str("AZURE_AD_TOKEN") - api_key = ( - api_key - or litellm.api_key - or litellm.azure_key - or get_secret_str("AZURE_API_KEY") - ) + api_key = api_key or litellm.api_key or litellm.azure_key or get_secret_str("AZURE_API_KEY") optional_params["extra_headers"] = extra_headers @@ -8058,9 +7530,7 @@ def transcription( max_retries=max_retries, litellm_params=litellm_params_dict, ) - elif custom_llm_provider == "openai" or ( - custom_llm_provider in litellm.openai_compatible_providers - ): + elif custom_llm_provider == "openai" or (custom_llm_provider in litellm.openai_compatible_providers): api_base = ( api_base or litellm.api_base @@ -8075,12 +7545,7 @@ def transcription( ) # set API KEY - api_key = ( - api_key - or litellm.api_key - or litellm.openai_key - or get_secret("OPENAI_API_KEY") - ) # type: ignore + api_key = api_key or litellm.api_key or litellm.openai_key or get_secret("OPENAI_API_KEY") # type: ignore response = openai_audio_transcriptions.audio_transcriptions( model=model, audio_file=file, @@ -8112,9 +7577,7 @@ def transcription( api_base=api_base, api_key=api_key, provider_config=( - provider_config - if isinstance(provider_config, NvidiaRivaAudioTranscriptionConfig) - else None + provider_config if isinstance(provider_config, NvidiaRivaAudioTranscriptionConfig) else None ), ) elif custom_llm_provider == "soniox": @@ -8131,11 +7594,7 @@ def transcription( atranscription=atranscription, client=( client - if client is not None - and ( - isinstance(client, HTTPHandler) - or isinstance(client, AsyncHTTPHandler) - ) + if client is not None and (isinstance(client, HTTPHandler) or isinstance(client, AsyncHTTPHandler)) else None ), timeout=timeout, @@ -8156,11 +7615,7 @@ def transcription( atranscription=atranscription, client=( client - if client is not None - and ( - isinstance(client, HTTPHandler) - or isinstance(client, AsyncHTTPHandler) - ) + if client is not None and (isinstance(client, HTTPHandler) or isinstance(client, AsyncHTTPHandler)) else None ), timeout=timeout, @@ -8181,9 +7636,7 @@ def transcription( if existing_duration is None: calculated_duration = calculate_request_duration(file) if calculated_duration is not None: - response._hidden_params["audio_transcription_duration"] = ( - calculated_duration - ) + response._hidden_params["audio_transcription_duration"] = calculated_duration if response is None: raise ValueError("Unmapped provider passed in. Unable to get the response.") @@ -8208,9 +7661,7 @@ async def aspeech(*args, **kwargs) -> HttpxBinaryResponseContent: ctx = contextvars.copy_context() func_with_context = partial(ctx.run, func) - _, custom_llm_provider, _, _ = get_llm_provider( - model=model, api_base=kwargs.get("api_base", None) - ) + _, custom_llm_provider, _, _ = get_llm_provider(model=model, api_base=kwargs.get("api_base", None)) # Await normally init_response = await loop.run_in_executor(None, func_with_context) @@ -8280,11 +7731,9 @@ def speech( litellm_params_dict = get_litellm_params(**kwargs) # Get provider-specific text-to-speech config and map parameters - text_to_speech_provider_config = ( - ProviderConfigManager.get_provider_text_to_speech_config( - model=model, - provider=litellm.LlmProviders(custom_llm_provider), - ) + text_to_speech_provider_config = ProviderConfigManager.get_provider_text_to_speech_config( + model=model, + provider=litellm.LlmProviders(custom_llm_provider), ) # Map OpenAI params to provider-specific params if config exists @@ -8297,9 +7746,7 @@ def speech( kwargs=kwargs, ) - logging_obj: LiteLLMLoggingObj = cast( - LiteLLMLoggingObj, kwargs.get("litellm_logging_obj") - ) + logging_obj: LiteLLMLoggingObj = cast(LiteLLMLoggingObj, kwargs.get("litellm_logging_obj")) logging_obj.update_environment_variables( model=model, user=user, @@ -8320,10 +7767,7 @@ def speech( Coroutine[Any, Any, HttpxBinaryResponseContent], None, ] = None - if ( - custom_llm_provider == "openai" - or custom_llm_provider in litellm.openai_compatible_providers - ): + if custom_llm_provider == "openai" or custom_llm_provider in litellm.openai_compatible_providers: if voice is None or not (isinstance(voice, str)): raise litellm.BadRequestError( message="'voice' is required to be passed as a string for OpenAI TTS", @@ -8392,9 +7836,7 @@ def speech( ) # Cast to specific Azure config type to access dispatch method - azure_config = cast( - AzureAVATextToSpeechConfig, text_to_speech_provider_config - ) + azure_config = cast(AzureAVATextToSpeechConfig, text_to_speech_provider_config) response = azure_config.dispatch_text_to_speech( # type: ignore model=model, @@ -8421,9 +7863,7 @@ def speech( ) api_base = api_base or litellm.api_base or get_secret("AZURE_API_BASE") # type: ignore - api_version = ( - api_version or litellm.api_version or get_secret("AZURE_API_VERSION") - ) # type: ignore + api_version = api_version or litellm.api_version or get_secret("AZURE_API_VERSION") # type: ignore api_key = ( api_key @@ -8466,9 +7906,7 @@ def speech( if text_to_speech_provider_config is None: text_to_speech_provider_config = ElevenLabsTextToSpeechConfig() - elevenlabs_config = cast( - ElevenLabsTextToSpeechConfig, text_to_speech_provider_config - ) + elevenlabs_config = cast(ElevenLabsTextToSpeechConfig, text_to_speech_provider_config) voice_id = voice if isinstance(voice, str) else None if voice_id is None or not voice_id.strip(): @@ -8479,17 +7917,11 @@ def speech( ) voice_id = voice_id.strip() - query_params = kwargs.pop( - ElevenLabsTextToSpeechConfig.ELEVENLABS_QUERY_PARAMS_KEY, None - ) + query_params = kwargs.pop(ElevenLabsTextToSpeechConfig.ELEVENLABS_QUERY_PARAMS_KEY, None) if isinstance(query_params, dict): - litellm_params_dict[ - ElevenLabsTextToSpeechConfig.ELEVENLABS_QUERY_PARAMS_KEY - ] = query_params + litellm_params_dict[ElevenLabsTextToSpeechConfig.ELEVENLABS_QUERY_PARAMS_KEY] = query_params - litellm_params_dict[ElevenLabsTextToSpeechConfig.ELEVENLABS_VOICE_ID_KEY] = ( - voice_id - ) + litellm_params_dict[ElevenLabsTextToSpeechConfig.ELEVENLABS_VOICE_ID_KEY] = voice_id if api_base is not None: litellm_params_dict["api_base"] = api_base @@ -8594,9 +8026,7 @@ def speech( ) # Cast to specific RunwayML config type to access dispatch method - runwayml_config = cast( - RunwayMLTextToSpeechConfig, text_to_speech_provider_config - ) + runwayml_config = cast(RunwayMLTextToSpeechConfig, text_to_speech_provider_config) response = runwayml_config.dispatch_text_to_speech( # type: ignore model=model, @@ -8661,9 +8091,7 @@ def speech( text_to_speech_provider_config = AWSPollyTextToSpeechConfig() # Cast to specific AWS Polly config type to access dispatch method - aws_polly_config = cast( - AWSPollyTextToSpeechConfig, text_to_speech_provider_config - ) + aws_polly_config = cast(AWSPollyTextToSpeechConfig, text_to_speech_provider_config) response = aws_polly_config.dispatch_text_to_speech( model=model, @@ -8730,10 +8158,8 @@ async def ahealth_check( log_raw_request_response=True, ) model_params["litellm_logging_obj"] = litellm_logging_obj - model_params = ( - HealthCheckHelpers._update_model_params_with_health_check_tracking_information( - model_params=model_params - ) + model_params = HealthCheckHelpers._update_model_params_with_health_check_tracking_information( + model_params=model_params ) ######################################################### try: @@ -8757,9 +8183,7 @@ async def ahealth_check( if model in litellm.model_cost and mode is None: mode = litellm.model_cost[model].get("mode") - model_params["cache"] = { - "no-cache": True - } # don't used cached responses for making health check calls + model_params["cache"] = {"no-cache": True} # don't used cached responses for making health check calls mode = mode or "chat" if "*" in model: return await HealthCheckHelpers.ahealth_check_wildcard_models( @@ -8780,14 +8204,10 @@ async def ahealth_check( if mode in mode_handlers: _response = await mode_handlers[mode]() # Only process headers for chat mode - _response_headers: dict = ( - getattr(_response, "_hidden_params", {}).get("headers", {}) or {} - ) + _response_headers: dict = getattr(_response, "_hidden_params", {}).get("headers", {}) or {} return _create_health_check_response(_response_headers) else: - raise Exception( - f"Mode {mode} not supported. See modes here: https://docs.litellm.ai/docs/proxy/health" - ) + raise Exception(f"Mode {mode} not supported. See modes here: https://docs.litellm.ai/docs/proxy/health") except Exception as e: stack_trace = _redact_string(traceback.format_exc()) if isinstance(stack_trace, str): @@ -8801,9 +8221,7 @@ async def ahealth_check( error_to_return = str(e) + "\nstack trace: " + stack_trace - raw_request_typed_dict = litellm_logging_obj.model_call_details.get( - "raw_request_typed_dict" - ) + raw_request_typed_dict = litellm_logging_obj.model_call_details.get("raw_request_typed_dict") return { "error": error_to_return, @@ -8834,9 +8252,7 @@ def config_completion(**kwargs): ) -def stream_chunk_builder_text_completion( - chunks: list, messages: Optional[List] = None -) -> TextCompletionResponse: +def stream_chunk_builder_text_completion(chunks: list, messages: Optional[List] = None) -> TextCompletionResponse: id = chunks[0]["id"] object = chunks[0]["object"] created = chunks[0]["created"] @@ -8869,11 +8285,7 @@ def stream_chunk_builder_text_completion( for chunk in chunks: choices = chunk["choices"] for choice in choices: - if ( - choice is not None - and hasattr(choice, "text") - and choice.get("text") is not None - ): + if choice is not None and hasattr(choice, "text") and choice.get("text") is not None: _choice = choice.get("text") content_list.append(_choice) @@ -8889,9 +8301,7 @@ def stream_chunk_builder_text_completion( pass # # Update usage information if needed try: - response["usage"]["prompt_tokens"] = token_counter( - model=model, messages=messages - ) + response["usage"]["prompt_tokens"] = token_counter(model=model, messages=messages) except Exception: # don't allow this failing to block a complete streaming response from being returned print_verbose("token_counter failed, assuming prompt tokens is 0") response["usage"]["prompt_tokens"] = 0 @@ -8900,9 +8310,7 @@ def stream_chunk_builder_text_completion( text=combined_content, count_response_tokens=True, # count_response_tokens is a Flag to tell token counter this is a response, No need to add extra tokens we do for input messages ) - response["usage"]["total_tokens"] = ( - response["usage"]["prompt_tokens"] + response["usage"]["completion_tokens"] - ) + response["usage"]["total_tokens"] = response["usage"]["prompt_tokens"] + response["usage"]["completion_tokens"] return TextCompletionResponse(**response) @@ -8935,9 +8343,7 @@ def stream_chunk_builder( if first_chunk_with_choices is not None and isinstance( first_chunk_with_choices["choices"][0], litellm.utils.TextChoices ): # route to the text completion logic - return stream_chunk_builder_text_completion( - chunks=chunks, messages=messages - ) + return stream_chunk_builder_text_completion(chunks=chunks, messages=messages) model = chunks[0]["model"] # Initialize the response dictionary @@ -8952,11 +8358,7 @@ def stream_chunk_builder( continue choice = chunk["choices"][0] - delta_obj = ( - choice.get("delta", {}) - if isinstance(choice, dict) - else getattr(choice, "delta", {}) - ) + delta_obj = choice.get("delta", {}) if isinstance(choice, dict) else getattr(choice, "delta", {}) if isinstance(delta_obj, dict): delta = delta_obj elif hasattr(delta_obj, "model_dump"): @@ -8983,9 +8385,7 @@ def stream_chunk_builder( if is_simple_text_stream: if simple_content_parts: - response["choices"][0]["message"]["content"] = "".join( - simple_content_parts - ) + response["choices"][0]["message"]["content"] = "".join(simple_content_parts) completion_output = get_content_from_model_response(response) usage = processor.calculate_usage( chunks=chunks, @@ -9003,9 +8403,9 @@ def stream_chunk_builder( else: hidden = getattr(chunk, "_hidden_params", None) if isinstance(hidden, dict) and "provider_specific_fields" in hidden: - response._hidden_params.setdefault( - "provider_specific_fields", {} - ).update(hidden["provider_specific_fields"]) + response._hidden_params.setdefault("provider_specific_fields", {}).update( + hidden["provider_specific_fields"] + ) break if litellm.include_cost_in_streaming_usage and logging_obj is not None: @@ -9014,9 +8414,7 @@ def stream_chunk_builder( "cost", logging_obj._response_cost_calculator(result=response), ) - processor.apply_provider_assembled_streaming_metadata( - response, chunks, logging_obj - ) + processor.apply_provider_assembled_streaming_metadata(response, chunks, logging_obj) return response tool_call_chunks = [ @@ -9044,9 +8442,7 @@ def stream_chunk_builder( if len(function_call_chunks) > 0: _choice = cast(Choices, response.choices[0]) _choice.message.content = None - _choice.message.function_call = ( - processor.get_combined_function_call_content(function_call_chunks) - ) + _choice.message.function_call = processor.get_combined_function_call_content(function_call_chunks) content_chunks = [ chunk @@ -9057,9 +8453,7 @@ def stream_chunk_builder( ] if len(content_chunks) > 0: - response["choices"][0]["message"]["content"] = ( - processor.get_combined_content(content_chunks) - ) + response["choices"][0]["message"]["content"] = processor.get_combined_content(content_chunks) thinking_blocks = [ chunk @@ -9070,8 +8464,8 @@ def stream_chunk_builder( ] if len(thinking_blocks) > 0: - response["choices"][0]["message"]["thinking_blocks"] = ( - processor.get_combined_thinking_content(thinking_blocks) + response["choices"][0]["message"]["thinking_blocks"] = processor.get_combined_thinking_content( + thinking_blocks ) reasoning_chunks = [ @@ -9083,8 +8477,8 @@ def stream_chunk_builder( ] if len(reasoning_chunks) > 0: - response["choices"][0]["message"]["reasoning_content"] = ( - processor.get_combined_reasoning_content(reasoning_chunks) + response["choices"][0]["message"]["reasoning_content"] = processor.get_combined_reasoning_content( + reasoning_chunks ) annotation_chunks = [ @@ -9151,9 +8545,7 @@ def stream_chunk_builder( for key, value in fields.items(): if key not in combined_provider_fields: combined_provider_fields[key] = value - elif isinstance(value, list) and isinstance( - combined_provider_fields[key], list - ): + elif isinstance(value, list) and isinstance(combined_provider_fields[key], list): # For lists like web_search_results, take the last (most complete) one combined_provider_fields[key] = value else: @@ -9185,27 +8577,19 @@ def stream_chunk_builder( else: hidden = getattr(chunk, "_hidden_params", None) if isinstance(hidden, dict) and "provider_specific_fields" in hidden: - response._hidden_params.setdefault( - "provider_specific_fields", {} - ).update(hidden["provider_specific_fields"]) + response._hidden_params.setdefault("provider_specific_fields", {}).update( + hidden["provider_specific_fields"] + ) break # Add cost to usage object if include_cost_in_streaming_usage is True if litellm.include_cost_in_streaming_usage and logging_obj is not None: - setattr( - usage, "cost", logging_obj._response_cost_calculator(result=response) - ) + setattr(usage, "cost", logging_obj._response_cost_calculator(result=response)) - processor.apply_provider_assembled_streaming_metadata( - response, chunks, logging_obj - ) + processor.apply_provider_assembled_streaming_metadata(response, chunks, logging_obj) return response except Exception as e: - verbose_logger.exception( - "litellm.main.py::stream_chunk_builder() - Exception occurred - {}".format( - str(e) - ) - ) + verbose_logger.exception("litellm.main.py::stream_chunk_builder() - Exception occurred - {}".format(str(e))) raise litellm.APIError( status_code=500, message="Error building chunks for logging/streaming usage calculation", @@ -9276,17 +8660,12 @@ async def acount_tokens( # Try to get provider-specific token counter try: llm_provider_enum = LlmProviders(custom_llm_provider) - provider_model_info = ProviderConfigManager.get_provider_model_info( - model=model, provider=llm_provider_enum - ) + provider_model_info = ProviderConfigManager.get_provider_model_info(model=model, provider=llm_provider_enum) if provider_model_info is not None: token_counter_instance = provider_model_info.get_token_counter() - if ( - token_counter_instance is not None - and token_counter_instance.should_use_token_counting_api( - custom_llm_provider - ) + if token_counter_instance is not None and token_counter_instance.should_use_token_counting_api( + custom_llm_provider ): result = await token_counter_instance.count_tokens( model_to_use=resolved_model, @@ -9300,9 +8679,7 @@ async def acount_tokens( if result is not None and not result.error: return result except Exception as e: - verbose_logger.debug( - f"Provider token counting failed for model={model}, falling back to local: {e}" - ) + verbose_logger.debug(f"Provider token counting failed for model={model}, falling back to local: {e}") # Fallback to local tiktoken-based token counting fallback_messages = messages or [] diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 6a65977e9095..b60c6e71867c 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -549,12 +549,9 @@ "input_cost_per_query": 0.001, "input_cost_per_token": 0.0, "litellm_provider": "bedrock", - "max_document_chunks_per_query": 100, "max_input_tokens": 32000, "max_output_tokens": 32000, - "max_query_tokens": 32000, "max_tokens": 32000, - "max_tokens_per_document_chunk": 512, "mode": "rerank", "output_cost_per_token": 0.0 }, @@ -607,27 +604,18 @@ "amazon.titan-image-generator-v1": { "input_cost_per_image": 0.0, "output_cost_per_image": 0.008, - "output_cost_per_image_premium_image": 0.01, - "output_cost_per_image_above_512_and_512_pixels": 0.01, - "output_cost_per_image_above_512_and_512_pixels_and_premium_image": 0.012, "litellm_provider": "bedrock", "mode": "image_generation" }, "amazon.titan-image-generator-v2": { "input_cost_per_image": 0.0, "output_cost_per_image": 0.008, - "output_cost_per_image_premium_image": 0.01, - "output_cost_per_image_above_1024_and_1024_pixels": 0.01, - "output_cost_per_image_above_1024_and_1024_pixels_and_premium_image": 0.012, "litellm_provider": "bedrock", "mode": "image_generation" }, "amazon.titan-image-generator-v2:0": { "input_cost_per_image": 0.0, "output_cost_per_image": 0.008, - "output_cost_per_image_premium_image": 0.01, - "output_cost_per_image_above_1024_and_1024_pixels": 0.01, - "output_cost_per_image_above_1024_and_1024_pixels_and_premium_image": 0.012, "litellm_provider": "bedrock", "mode": "image_generation" }, @@ -1021,6 +1009,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1051,6 +1040,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1081,6 +1071,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1111,6 +1102,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1141,6 +1133,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1171,6 +1164,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1218,6 +1212,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1250,6 +1245,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1282,6 +1278,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1314,6 +1311,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1642,6 +1640,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -1653,7 +1652,6 @@ "supports_tool_choice": true, "supports_vision": true, "supports_xhigh_reasoning_effort": true, - "tool_use_system_prompt_tokens": 346, "supports_native_structured_output": true, "supports_max_reasoning_effort": true, "supports_minimal_reasoning_effort": true @@ -1674,6 +1672,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -1703,6 +1702,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -1732,6 +1732,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -1761,6 +1762,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -1790,6 +1792,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -1819,6 +1822,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -2338,6 +2342,7 @@ "cache_creation_input_token_cost": 6.25e-06, "cache_creation_input_token_cost_above_1hr": 1e-05, "cache_read_input_token_cost": 5e-07, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -2366,6 +2371,7 @@ "cache_creation_input_token_cost": 6.25e-06, "cache_creation_input_token_cost_above_1hr": 1e-05, "cache_read_input_token_cost": 5e-07, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -2492,6 +2498,7 @@ "max_tokens": 64000, "mode": "chat", "output_cost_per_token": 1.5e-05, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -2590,7 +2597,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -2637,7 +2643,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -2684,7 +2689,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -2731,7 +2735,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -2777,7 +2780,6 @@ "supports_response_schema": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -2823,7 +2825,6 @@ "supports_response_schema": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -2870,7 +2871,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -2917,7 +2917,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -2964,7 +2963,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -3011,7 +3009,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -4575,7 +4572,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_none_reasoning_effort": true, "supports_minimal_reasoning_effort": true @@ -5223,7 +5219,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "azure/gpt-5.2-chat": { @@ -5356,7 +5351,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "azure/gpt-5.3-codex": { @@ -5490,7 +5484,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "azure/gpt-5.4-2026-03-05": { @@ -5532,7 +5525,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "azure/gpt-5.4-pro": { @@ -5644,7 +5636,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -5690,7 +5681,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -5798,7 +5788,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -5834,7 +5823,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -5870,7 +5858,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -5906,14 +5893,12 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, "supports_xhigh_reasoning_effort": false }, "azure/gpt-image-1": { - "cache_read_input_image_token_cost": 2.5e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_image_token": 1e-05, "input_cost_per_token": 5e-06, @@ -6025,7 +6010,6 @@ ] }, "azure/gpt-image-1-mini": { - "cache_read_input_image_token_cost": 2.5e-07, "cache_read_input_token_cost": 2e-07, "input_cost_per_image_token": 2.5e-06, "input_cost_per_token": 2e-06, @@ -6038,7 +6022,6 @@ ] }, "azure/gpt-image-1.5": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "input_cost_per_image_token": 8e-06, @@ -6051,7 +6034,6 @@ ] }, "azure/gpt-image-1.5-2025-12-16": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "input_cost_per_image_token": 8e-06, @@ -6064,7 +6046,6 @@ ] }, "azure/gpt-image-2": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "input_cost_per_image_token": 8e-06, @@ -6080,7 +6061,6 @@ "supports_pdf_input": true }, "azure/gpt-image-2-2026-04-21": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "input_cost_per_image_token": 8e-06, @@ -7574,7 +7554,6 @@ "litellm_provider": "azure_ai", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -7585,7 +7564,6 @@ "litellm_provider": "azure_ai", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -7596,7 +7574,6 @@ "litellm_provider": "azure_ai", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -7607,7 +7584,6 @@ "litellm_provider": "azure_ai", "max_input_tokens": 32768, "max_output_tokens": 32768, - "max_query_tokens": 4096, "max_tokens": 32768, "mode": "rerank", "output_cost_per_token": 0.0, @@ -7619,7 +7595,6 @@ "litellm_provider": "azure_ai", "max_input_tokens": 32768, "max_output_tokens": 32768, - "max_query_tokens": 4096, "max_tokens": 32768, "mode": "rerank", "output_cost_per_token": 0.0, @@ -11108,12 +11083,9 @@ "input_cost_per_query": 0.002, "input_cost_per_token": 0.0, "litellm_provider": "bedrock", - "max_document_chunks_per_query": 100, "max_input_tokens": 32000, "max_output_tokens": 32000, - "max_query_tokens": 32000, "max_tokens": 32000, - "max_tokens_per_document_chunk": 512, "mode": "rerank", "output_cost_per_token": 0.0 }, @@ -15908,15 +15880,9 @@ "input_cost_per_audio_token": 7e-07, "input_cost_per_token": 1e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 4e-07, "source": "https://ai.google.dev/pricing#2_0flash", @@ -15953,15 +15919,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 1.5e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 6e-07, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", @@ -15996,14 +15956,8 @@ "input_cost_per_audio_token": 7.5e-08, "input_cost_per_token": 7.5e-08, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 50, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 3e-07, "source": "https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-2.0-flash", @@ -16037,14 +15991,8 @@ "input_cost_per_audio_token": 7.5e-08, "input_cost_per_token": 7.5e-08, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 50, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 3e-07, "source": "https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models#gemini-2.0-flash", @@ -16077,15 +16025,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -16121,7 +16063,6 @@ "search_context_size_medium": 0.035, "search_context_size_high": 0.035 }, - "supports_service_tier": true, "supports_image_size": false }, "gemini-2.5-flash-image": { @@ -16129,15 +16070,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 32768, "max_output_tokens": 32768, "max_tokens": 32768, - "max_pdf_size_mb": 30, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "image_generation", "output_cost_per_image": 0.039, "output_cost_per_image_token": 3e-05, @@ -16172,7 +16107,6 @@ "supports_vision": true, "supports_web_search": false, "tpm": 8000000, - "supports_service_tier": true, "supports_image_size": false }, "gemini-3-pro-image-preview": { @@ -16213,8 +16147,7 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "gemini-3.1-flash-image-preview": { "input_cost_per_image": 0.00056, @@ -16256,19 +16189,12 @@ }, "gemini-3.1-flash-lite-preview": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -16289,8 +16215,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -16309,14 +16233,11 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "gemini-3.1-flash-lite": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_batches": 1.25e-08, "cache_read_input_token_cost_flex": 1.25e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "cache_read_input_token_cost_priority": 4.5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, @@ -16324,15 +16245,9 @@ "input_cost_per_token_flex": 1.25e-07, "input_cost_per_token_priority": 4.5e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -16356,8 +16271,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -16376,8 +16289,7 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "deep-research-pro-preview-12-2025": { "input_cost_per_image": 0.0011, @@ -16418,15 +16330,9 @@ "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -16462,7 +16368,6 @@ "search_context_size_medium": 0.035, "search_context_size_high": 0.035 }, - "supports_service_tier": true, "supports_image_size": false }, "gemini-2.5-flash-lite-preview-09-2025": { @@ -16470,15 +16375,9 @@ "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -16521,15 +16420,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -16572,15 +16465,9 @@ "input_cost_per_audio_token": 3e-06, "input_cost_per_token": 3e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "realtime", "output_cost_per_audio_token": 1.2e-05, "output_cost_per_token": 2e-06, @@ -16622,15 +16509,9 @@ "input_cost_per_audio_token": 3e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "realtime", "output_cost_per_audio_token": 1.2e-05, "output_cost_per_token": 2e-06, @@ -16675,15 +16556,9 @@ "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 1e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -16728,15 +16603,9 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "output_cost_per_token_above_200k_tokens": 1.5e-05, @@ -16769,8 +16638,7 @@ "search_context_size_low": 0.035, "search_context_size_medium": 0.035, "search_context_size_high": 0.035 - }, - "supports_service_tier": true + } }, "gemini-3-pro-preview": { "deprecation_date": "2026-03-26", @@ -16781,15 +16649,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -16827,7 +16689,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -16843,15 +16704,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -16891,7 +16746,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -16907,15 +16761,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -16964,15 +16812,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "vertex_ai", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -17010,7 +16852,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -17023,15 +16864,9 @@ "input_cost_per_token": 5e-07, "input_cost_per_audio_token": 1e-06, "litellm_provider": "vertex_ai", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 3e-06, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", @@ -17065,7 +16900,6 @@ "input_cost_per_audio_token_priority": 1.8e-06, "output_cost_per_token_priority": 5.4e-06, "cache_read_input_token_cost_priority": 9e-08, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -17078,15 +16912,9 @@ "input_cost_per_token": 1.5e-06, "input_cost_per_audio_token": 1e-06, "litellm_provider": "vertex_ai", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 9e-06, "output_cost_per_token": 9e-06, @@ -17123,7 +16951,6 @@ "input_cost_per_audio_token_priority": 1.8e-06, "output_cost_per_token_priority": 1.62e-05, "cache_read_input_token_cost_priority": 2.7e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -17139,15 +16966,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "vertex_ai", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -17187,7 +17008,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -17203,15 +17023,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "vertex_ai", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -17251,7 +17065,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -17266,15 +17079,9 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "output_cost_per_token_above_200k_tokens": 1.5e-05, @@ -17384,7 +17191,6 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "vertex_ai-language-models", - "max_images_per_prompt": 3000, "max_input_tokens": 128000, "max_output_tokens": 64000, "max_tokens": 64000, @@ -17552,15 +17358,9 @@ "input_cost_per_audio_token": 7e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 4e-07, "rpm": 10000, @@ -17598,15 +17398,9 @@ "input_cost_per_audio_token": 7e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 4e-07, "rpm": 10000, @@ -17642,14 +17436,8 @@ "input_cost_per_audio_token": 7.5e-08, "input_cost_per_token": 7.5e-08, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 50, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 3e-07, "rpm": 4000, @@ -17683,15 +17471,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -17729,7 +17511,6 @@ "search_context_size_medium": 0.035, "search_context_size_high": 0.035 }, - "supports_service_tier": true, "supports_image_size": false }, "gemini/gemini-2.5-flash-image": { @@ -17737,16 +17518,10 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, "supports_reasoning": false, - "max_images_per_prompt": 3000, "max_input_tokens": 32768, "max_output_tokens": 32768, "max_tokens": 32768, - "max_pdf_size_mb": 30, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "image_generation", "output_cost_per_image": 0.039, "output_cost_per_image_token": 3e-05, @@ -17786,7 +17561,6 @@ "search_context_size_medium": 0.035, "search_context_size_high": 0.035 }, - "supports_service_tier": true, "supports_image_size": false }, "gemini/gemini-3-pro-image-preview": { @@ -17829,8 +17603,7 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "gemini/gemini-3.1-flash-image-preview": { "input_cost_per_token": 2.5e-07, @@ -17842,7 +17615,6 @@ "mode": "image_generation", "output_cost_per_image": 0.045, "output_cost_per_image_token": 6e-05, - "output_cost_per_image_token_batches": 3e-05, "output_cost_per_token": 1.5e-06, "output_cost_per_token_batches": 7.5e-07, "rpm": 1000, @@ -17920,15 +17692,9 @@ "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -17966,7 +17732,6 @@ "search_context_size_medium": 0.035, "search_context_size_high": 0.035 }, - "supports_service_tier": true, "supports_image_size": false }, "gemini/gemini-2.5-flash-lite-preview-09-2025": { @@ -17974,15 +17739,9 @@ "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -18027,15 +17786,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -18080,15 +17833,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -18132,15 +17879,9 @@ "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -18185,15 +17926,9 @@ "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -18253,15 +17988,9 @@ "input_cost_per_token_priority": 1.25e-06, "input_cost_per_token_above_200k_tokens_priority": 2.5e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "output_cost_per_token_above_200k_tokens": 1.5e-05, @@ -18269,7 +17998,6 @@ "output_cost_per_token_above_200k_tokens_priority": 1.5e-05, "rpm": 2000, "source": "https://cloud.google.com/vertex-ai/generative-ai/pricing", - "supports_service_tier": true, "supported_endpoints": [ "/v1/chat/completions", "/v1/completions" @@ -18305,7 +18033,6 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "gemini", - "max_images_per_prompt": 3000, "max_input_tokens": 128000, "max_output_tokens": 64000, "max_tokens": 64000, @@ -18340,15 +18067,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -18387,7 +18108,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18397,19 +18117,12 @@ }, "gemini/gemini-3.1-flash-lite-preview": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -18431,8 +18144,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -18452,14 +18163,11 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "gemini/gemini-3.1-flash-lite": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_batches": 1.25e-08, "cache_read_input_token_cost_flex": 1.25e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "cache_read_input_token_cost_priority": 4.5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, @@ -18467,15 +18175,9 @@ "input_cost_per_token_flex": 1.25e-07, "input_cost_per_token_priority": 4.5e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -18500,8 +18202,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -18521,23 +18221,16 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "gemini/gemini-3-flash-preview": { "cache_read_input_token_cost": 5e-08, "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 5e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 3e-06, "output_cost_per_token": 3e-06, @@ -18575,7 +18268,6 @@ "input_cost_per_audio_token_priority": 1.8e-06, "output_cost_per_token_priority": 5.4e-06, "cache_read_input_token_cost_priority": 9e-08, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18588,15 +18280,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 1.5e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 9e-06, "output_cost_per_token": 9e-06, @@ -18636,7 +18322,6 @@ "input_cost_per_audio_token_priority": 1.8e-06, "output_cost_per_token_priority": 1.62e-05, "cache_read_input_token_cost_priority": 2.7e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18651,15 +18336,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -18700,7 +18379,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18715,15 +18393,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -18764,7 +18436,6 @@ "output_cost_per_token_above_200k_tokens_priority": 3.24e-05, "cache_read_input_token_cost_priority": 3.6e-07, "cache_read_input_token_cost_above_200k_tokens_priority": 7.2e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18777,15 +18448,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 5e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 3e-06, "output_cost_per_token": 3e-06, @@ -18821,7 +18486,6 @@ "input_cost_per_audio_token_priority": 1.8e-06, "output_cost_per_token_priority": 5.4e-06, "cache_read_input_token_cost_priority": 9e-08, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18834,15 +18498,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 1.5e-06, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 9e-06, "output_cost_per_token": 9e-06, @@ -18880,7 +18538,6 @@ "input_cost_per_audio_token_priority": 1.8e-06, "output_cost_per_token_priority": 1.62e-05, "cache_read_input_token_cost_priority": 2.7e-07, - "supports_service_tier": true, "search_context_cost_per_query": { "search_context_size_low": 0.014, "search_context_size_medium": 0.014, @@ -18895,15 +18552,9 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "output_cost_per_token_above_200k_tokens": 1.5e-05, @@ -18934,15 +18585,9 @@ "input_cost_per_token": 0, "input_cost_per_token_above_128k_tokens": 0, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "metadata": { "notes": "Rate limits not documented for gemini-exp-1114. Assuming same as gemini-1.5-pro.", "supports_tool_choice": true @@ -18963,15 +18608,9 @@ "input_cost_per_token": 0, "input_cost_per_token_above_128k_tokens": 0, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 2097152, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "metadata": { "notes": "Rate limits not documented for gemini-exp-1206. Assuming same as gemini-1.5-pro.", "supports_tool_choice": true @@ -19279,6 +18918,7 @@ "supported_endpoints": [ "/v1/chat/completions" ], + "supports_adaptive_thinking": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_vision": true @@ -20407,7 +20047,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -20442,7 +20081,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -20480,7 +20118,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -20515,7 +20152,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -20553,7 +20189,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4.1-nano-2025-04-14": { @@ -20587,7 +20222,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4o": { @@ -20611,7 +20245,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4o-2024-05-13": { @@ -20652,7 +20285,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4o-2024-11-20": { @@ -20673,7 +20305,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4o-audio-preview": { @@ -20961,7 +20592,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4o-mini-2024-07-18": { @@ -20987,7 +20617,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-4o-mini-audio-preview": { @@ -21251,7 +20880,6 @@ ] }, "gpt-image-1.5": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "litellm_provider": "openai", @@ -21266,7 +20894,6 @@ "supports_pdf_input": true }, "gpt-image-1.5-2025-12-16": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "litellm_provider": "openai", @@ -21281,7 +20908,6 @@ "supports_pdf_input": true }, "gpt-image-2": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "litellm_provider": "openai", @@ -21297,7 +20923,6 @@ "supports_pdf_input": true }, "gpt-image-2-2026-04-21": { - "cache_read_input_image_token_cost": 2e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_token": 5e-06, "litellm_provider": "openai", @@ -21678,7 +21303,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -21718,7 +21342,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -21758,7 +21381,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -21838,7 +21460,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -21879,7 +21500,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22073,7 +21693,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22123,7 +21742,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22168,7 +21786,6 @@ "supports_response_schema": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -22214,7 +21831,6 @@ "supports_response_schema": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -22265,7 +21881,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_none_reasoning_effort": true, "supports_xhigh_reasoning_effort": true, @@ -22314,7 +21929,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true }, "gpt-5.4-pro": { @@ -22355,7 +21969,6 @@ "supports_response_schema": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -22400,7 +22013,6 @@ "supports_response_schema": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -22410,7 +22022,6 @@ "gpt-5.4-mini": { "cache_read_input_token_cost": 7.5e-08, "cache_read_input_token_cost_flex": 3.75e-08, - "cache_read_input_token_cost_batches": 3.75e-08, "cache_read_input_token_cost_priority": 1.5e-07, "input_cost_per_token": 7.5e-07, "input_cost_per_token_flex": 3.75e-07, @@ -22448,7 +22059,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22458,7 +22068,6 @@ "gpt-5.4-mini-2026-03-17": { "cache_read_input_token_cost": 7.5e-08, "cache_read_input_token_cost_flex": 3.75e-08, - "cache_read_input_token_cost_batches": 3.75e-08, "cache_read_input_token_cost_priority": 1.5e-07, "input_cost_per_token": 7.5e-07, "input_cost_per_token_flex": 3.75e-07, @@ -22496,7 +22105,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22506,7 +22114,6 @@ "gpt-5.4-nano": { "cache_read_input_token_cost": 2e-08, "cache_read_input_token_cost_flex": 1e-08, - "cache_read_input_token_cost_batches": 1e-08, "input_cost_per_token": 2e-07, "input_cost_per_token_flex": 1e-07, "input_cost_per_token_batches": 1e-07, @@ -22541,7 +22148,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22551,7 +22157,6 @@ "gpt-5.4-nano-2026-03-17": { "cache_read_input_token_cost": 2e-08, "cache_read_input_token_cost_flex": 1e-08, - "cache_read_input_token_cost_batches": 1e-08, "input_cost_per_token": 2e-07, "input_cost_per_token_flex": 1e-07, "input_cost_per_token_batches": 1e-07, @@ -22586,7 +22191,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": true, @@ -22701,7 +22305,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -23030,7 +22633,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -23073,7 +22675,6 @@ "supports_response_schema": true, "supports_system_messages": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true, "supports_none_reasoning_effort": false, @@ -23160,7 +22761,6 @@ "supports_minimal_reasoning_effort": true }, "gpt-image-1": { - "cache_read_input_image_token_cost": 2.5e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_image_token": 1e-05, "input_cost_per_token": 5e-06, @@ -23173,7 +22773,6 @@ ] }, "gpt-image-1-mini": { - "cache_read_input_image_token_cost": 2.5e-07, "cache_read_input_token_cost": 2e-07, "input_cost_per_image_token": 2.5e-06, "input_cost_per_token": 2e-06, @@ -24240,7 +23839,6 @@ "jina-reranker-v2-base-multilingual": { "input_cost_per_token": 1.8e-08, "litellm_provider": "jina_ai", - "max_document_chunks_per_query": 2048, "max_input_tokens": 1024, "max_output_tokens": 1024, "max_tokens": 1024, @@ -27225,7 +26823,6 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -27258,7 +26855,6 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -27448,7 +27044,6 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -27468,7 +27063,6 @@ "supports_reasoning": true, "supports_response_schema": true, "supports_tool_choice": true, - "supports_service_tier": true, "supports_vision": true, "supports_web_search": true }, @@ -28554,6 +28148,7 @@ "output_cost_per_token": 1.5e-05, "output_cost_per_token_above_200k_tokens": 2.25e-05, "source": "https://openrouter.ai/anthropic/claude-sonnet-4.6", + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -28592,6 +28187,7 @@ "max_tokens": 128000, "mode": "chat", "output_cost_per_token": 2.5e-05, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -28652,6 +28248,7 @@ "max_tokens": 128000, "mode": "chat", "output_cost_per_token": 2.5e-05, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -28777,15 +28374,9 @@ "input_cost_per_audio_token": 7e-07, "input_cost_per_token": 1e-07, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 4e-07, "supports_audio_output": true, @@ -28799,15 +28390,9 @@ "input_cost_per_audio_token": 7e-07, "input_cost_per_token": 3e-07, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 2.5e-06, "supports_audio_output": true, @@ -28822,15 +28407,9 @@ "input_cost_per_audio_token": 7e-07, "input_cost_per_token": 1.25e-06, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 30, "max_tokens": 8192, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "supports_audio_output": true, @@ -28848,15 +28427,9 @@ "input_cost_per_token_above_200k_tokens": 4e-06, "input_cost_per_token_batches": 1e-06, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1.2e-05, "output_cost_per_token_above_200k_tokens": 1.8e-05, @@ -28892,15 +28465,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 5e-07, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 3e-06, "output_cost_per_token": 3e-06, @@ -28936,19 +28503,12 @@ }, "openrouter/google/gemini-3.1-flash-lite-preview": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -28970,8 +28530,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -28988,19 +28546,12 @@ }, "openrouter/google/gemini-3.1-flash-lite": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, "litellm_provider": "openrouter", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -29022,8 +28573,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -30577,28 +30126,24 @@ "litellm_provider": "perplexity", "mode": "responses", "supports_web_search": true, - "supports_preset": true, "supports_function_calling": true }, "perplexity/preset/pro-search": { "litellm_provider": "perplexity", "mode": "responses", "supports_web_search": true, - "supports_preset": true, "supports_function_calling": true }, "perplexity/preset/deep-research": { "litellm_provider": "perplexity", "mode": "responses", "supports_web_search": true, - "supports_preset": true, "supports_function_calling": true }, "perplexity/preset/advanced-deep-research": { "litellm_provider": "perplexity", "mode": "responses", "supports_web_search": true, - "supports_preset": true, "supports_function_calling": true }, "perplexity/openai/gpt-5.2": { @@ -30625,6 +30170,7 @@ "perplexity/anthropic/claude-opus-4-6": { "litellm_provider": "perplexity", "mode": "responses", + "supports_adaptive_thinking": true, "supports_web_search": true, "supports_reasoning": false, "supports_function_calling": true, @@ -30633,6 +30179,7 @@ "perplexity/anthropic/claude-opus-4-7": { "litellm_provider": "perplexity", "mode": "responses", + "supports_adaptive_thinking": true, "supports_web_search": true, "supports_reasoning": false, "supports_function_calling": true, @@ -31318,7 +30865,6 @@ "litellm_provider": "cohere", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -31329,7 +30875,6 @@ "litellm_provider": "cohere", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -31340,7 +30885,6 @@ "litellm_provider": "cohere", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -31351,7 +30895,6 @@ "litellm_provider": "cohere", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -31362,7 +30905,6 @@ "litellm_provider": "cohere", "max_input_tokens": 4096, "max_output_tokens": 4096, - "max_query_tokens": 2048, "max_tokens": 4096, "mode": "rerank", "output_cost_per_token": 0.0 @@ -32333,7 +31875,6 @@ }, "text-embedding-preview-0409": { "input_cost_per_token": 6.25e-09, - "input_cost_per_token_batch_requests": 5e-09, "litellm_provider": "vertex_ai-embedding-models", "max_input_tokens": 3072, "max_tokens": 3072, @@ -33882,6 +33423,7 @@ "max_tokens": 64000, "mode": "chat", "output_cost_per_token": 2.5e-05, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -35115,6 +34657,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -35143,6 +34686,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -35171,6 +34715,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -35200,6 +34745,7 @@ "search_context_size_low": 0.01, "search_context_size_medium": 0.01 }, + "supports_adaptive_thinking": true, "supports_assistant_prefill": false, "supports_computer_use": true, "supports_function_calling": true, @@ -35371,6 +34917,7 @@ "max_tokens": 64000, "mode": "chat", "output_cost_per_token": 1.5e-05, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, @@ -35640,15 +35187,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 32768, "max_output_tokens": 32768, "max_tokens": 32768, - "max_pdf_size_mb": 30, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "image_generation", "output_cost_per_image": 0.039, "output_cost_per_image_token": 3e-05, @@ -35715,19 +35256,12 @@ }, "vertex_ai/gemini-3.1-flash-lite-preview": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -35748,8 +35282,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -35772,9 +35304,7 @@ }, "vertex_ai/gemini-3.1-flash-lite": { "cache_read_input_token_cost": 2.5e-08, - "cache_read_input_token_cost_batches": 1.25e-08, "cache_read_input_token_cost_flex": 1.25e-08, - "cache_read_input_token_cost_per_audio_token": 5e-08, "cache_read_input_token_cost_priority": 4.5e-08, "input_cost_per_audio_token": 5e-07, "input_cost_per_token": 2.5e-07, @@ -35782,15 +35312,9 @@ "input_cost_per_token_flex": 1.25e-07, "input_cost_per_token_priority": 4.5e-07, "litellm_provider": "vertex_ai-language-models", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65536, - "max_pdf_size_mb": 30, "max_tokens": 65536, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 1.5e-06, "output_cost_per_token": 1.5e-06, @@ -35814,8 +35338,6 @@ ], "supports_audio_input": true, "supports_audio_output": false, - "supports_code_execution": true, - "supports_file_search": true, "supports_function_calling": true, "supports_parallel_function_calling": true, "supports_pdf_input": true, @@ -35834,8 +35356,7 @@ "search_context_size_medium": 0.014, "search_context_size_high": 0.014 }, - "web_search_billing_unit": "per_query", - "supports_service_tier": true + "web_search_billing_unit": "per_query" }, "vertex_ai/deep-research-pro-preview-12-2025": { "input_cost_per_image": 0.0011, @@ -36602,7 +36123,6 @@ "litellm_provider": "voyage", "max_input_tokens": 16000, "max_output_tokens": 16000, - "max_query_tokens": 16000, "max_tokens": 16000, "mode": "rerank", "output_cost_per_token": 0.0 @@ -36612,7 +36132,6 @@ "litellm_provider": "voyage", "max_input_tokens": 8000, "max_output_tokens": 8000, - "max_query_tokens": 8000, "max_tokens": 8000, "mode": "rerank", "output_cost_per_token": 0.0 @@ -36622,7 +36141,6 @@ "litellm_provider": "voyage", "max_input_tokens": 32000, "max_output_tokens": 32000, - "max_query_tokens": 32000, "max_tokens": 32000, "mode": "rerank", "output_cost_per_token": 0.0 @@ -36632,7 +36150,6 @@ "litellm_provider": "voyage", "max_input_tokens": 32000, "max_output_tokens": 32000, - "max_query_tokens": 32000, "max_tokens": 32000, "mode": "rerank", "output_cost_per_token": 0.0 @@ -38128,10 +37645,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "720x1280", - "1280x720" ] }, "openai/sora-2-pro": { @@ -38145,10 +37658,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "720x1280", - "1280x720" ] }, "openai/sora-2-pro-high-res": { @@ -38162,10 +37671,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "1024x1792", - "1792x1024" ] }, "azure/sora-2": { @@ -38178,10 +37683,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "720x1280", - "1280x720" ] }, "azure/sora-2-pro": { @@ -38194,10 +37695,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "720x1280", - "1280x720" ] }, "azure/sora-2-pro-high-res": { @@ -38210,10 +37707,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "1024x1792", - "1792x1024" ] }, "runwayml/gen4_turbo": { @@ -38228,10 +37721,6 @@ "supported_output_modalities": [ "video" ], - "supported_resolutions": [ - "1280x720", - "720x1280" - ], "metadata": { "comment": "5 credits per second @ $0.01 per credit = $0.05 per second" } @@ -38248,10 +37737,6 @@ "supported_output_modalities": [ "video" ], - "supported_resolutions": [ - "1280x720", - "720x1280" - ], "metadata": { "comment": "15 credits per second @ $0.01 per credit = $0.15 per second" } @@ -38268,10 +37753,6 @@ "supported_output_modalities": [ "video" ], - "supported_resolutions": [ - "1280x720", - "720x1280" - ], "metadata": { "comment": "5 credits per second @ $0.01 per credit = $0.05 per second" } @@ -38289,10 +37770,6 @@ "supported_output_modalities": [ "image" ], - "supported_resolutions": [ - "1280x720", - "1920x1080" - ], "metadata": { "comment": "5 credits per 720p image or 8 credits per 1080p image @ $0.01 per credit. Using 5 credits ($0.05) as base cost" } @@ -38310,10 +37787,6 @@ "supported_output_modalities": [ "image" ], - "supported_resolutions": [ - "1280x720", - "1920x1080" - ], "metadata": { "comment": "2 credits per image (any resolution) @ $0.01 per credit = $0.02 per image" } @@ -42289,10 +41762,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "720x1280", - "1280x720" ] }, "sora-2-pro": { @@ -42306,10 +41775,6 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "720x1280", - "1280x720" ] }, "sora-2-pro-high-res": { @@ -42323,14 +41788,9 @@ ], "supported_output_modalities": [ "video" - ], - "supported_resolutions": [ - "1024x1792", - "1792x1024" ] }, "chatgpt-image-latest": { - "cache_read_input_image_token_cost": 2.5e-06, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_image_token": 1e-05, "input_cost_per_token": 5e-06, @@ -42345,7 +41805,6 @@ "gemini-2.0-flash-exp-image-generation": { "input_cost_per_token": 0.0, "litellm_provider": "gemini", - "max_images_per_prompt": 3000, "max_input_tokens": 32768, "max_output_tokens": 32768, "max_tokens": 32768, @@ -42366,7 +41825,6 @@ "gemini/gemini-2.0-flash-exp-image-generation": { "input_cost_per_token": 0.0, "litellm_provider": "gemini", - "max_images_per_prompt": 3000, "max_input_tokens": 32768, "max_output_tokens": 32768, "max_tokens": 32768, @@ -42392,14 +41850,8 @@ "input_cost_per_audio_token": 7.5e-08, "input_cost_per_token": 7.5e-08, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 8192, - "max_pdf_size_mb": 50, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 3e-07, "rpm": 4000, @@ -42667,15 +42119,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -42719,15 +42165,9 @@ "input_cost_per_audio_token": 3e-07, "input_cost_per_token": 1e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 4e-07, "output_cost_per_token": 4e-07, @@ -42772,15 +42212,9 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "output_cost_per_token_above_200k_tokens": 1.5e-05, @@ -42823,15 +42257,9 @@ "input_cost_per_token": 1.25e-06, "input_cost_per_token_above_200k_tokens": 2.5e-06, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_token": 1e-05, "output_cost_per_token_above_200k_tokens": 1.5e-05, @@ -42873,15 +42301,9 @@ "input_cost_per_audio_token": 1e-06, "input_cost_per_token": 3e-07, "litellm_provider": "gemini", - "max_audio_length_hours": 8.4, - "max_audio_per_prompt": 1, - "max_images_per_prompt": 3000, "max_input_tokens": 1048576, "max_output_tokens": 65535, - "max_pdf_size_mb": 30, "max_tokens": 65535, - "max_video_length": 1, - "max_videos_per_prompt": 10, "mode": "chat", "output_cost_per_reasoning_token": 2.5e-06, "output_cost_per_token": 2.5e-06, @@ -42931,6 +42353,7 @@ "max_tokens": 64000, "mode": "chat", "output_cost_per_token": 1.5e-05, + "supports_adaptive_thinking": true, "supports_assistant_prefill": true, "supports_computer_use": true, "supports_function_calling": true, diff --git a/litellm/models/budget.py b/litellm/models/budget.py index e7dfe2f8fbc8..8c35aebd208c 100644 --- a/litellm/models/budget.py +++ b/litellm/models/budget.py @@ -29,9 +29,7 @@ class LiteLLM_BudgetTable(LiteLLMPydanticObjectBase): rpm_limit: Optional[int] = None model_max_budget: Optional[dict] = None budget_duration: Optional[str] = None - allowed_models: Optional[List[str]] = ( - None # per-member model scope; empty = inherit team models - ) + allowed_models: Optional[List[str]] = None # per-member model scope; empty = inherit team models model_config = ConfigDict(protected_namespaces=()) diff --git a/litellm/models/team.py b/litellm/models/team.py index aa0798955f21..f11c21a078e2 100644 --- a/litellm/models/team.py +++ b/litellm/models/team.py @@ -118,10 +118,7 @@ def set_model_info(cls, values): if isinstance(values, BaseModel): values = values.model_dump() - if ( - isinstance(values.get("members_with_roles"), dict) - and not values["members_with_roles"] - ): + if isinstance(values.get("members_with_roles"), dict) and not values["members_with_roles"]: values["members_with_roles"] = [] for field in dict_fields: diff --git a/litellm/models/team_membership.py b/litellm/models/team_membership.py index d0a1308ce7c6..e79b64977d47 100644 --- a/litellm/models/team_membership.py +++ b/litellm/models/team_membership.py @@ -17,9 +17,7 @@ class LiteLLM_TeamMembership(LiteLLMPydanticObjectBase): budget_id: Optional[str] = None spend: Optional[float] = 0.0 total_spend: Optional[float] = 0.0 - litellm_budget_table: Optional[ - Union[LiteLLM_BudgetTableFull, LiteLLM_BudgetTable] - ] = None + litellm_budget_table: Optional[Union[LiteLLM_BudgetTableFull, LiteLLM_BudgetTable]] = None def safe_get_team_member_rpm_limit(self) -> Optional[int]: if self.litellm_budget_table is not None: diff --git a/litellm/ocr/main.py b/litellm/ocr/main.py index 93b3a892659a..5716155361d0 100644 --- a/litellm/ocr/main.py +++ b/litellm/ocr/main.py @@ -72,9 +72,7 @@ def _prepare_ocr_request( litellm_call_id = cast(str | None, kwargs.get("litellm_call_id", None)) if not isinstance(document, dict): - raise ValueError( - f"document must be a dict with 'type' and URL/file field, got {type(document)}" - ) + raise ValueError(f"document must be a dict with 'type' and URL/file field, got {type(document)}") doc_type = document.get("type") @@ -83,10 +81,7 @@ def _prepare_ocr_request( 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'" - ) + raise ValueError(f"Invalid document type: {doc_type}. Must be 'document_url', 'image_url', or 'file'") ( model, @@ -226,9 +221,7 @@ def _prepare_rust_ocr_call( litellm_params=prepared_request.litellm_params, ) rust_api_base = _rust_bridge_api_base(prepared_request, resolve_api_key) - rust_optional_params = _rust_bridge_optional_params( - prepared_request, resolve_api_key - ) + rust_optional_params = _rust_bridge_optional_params(prepared_request, resolve_api_key) prepared_request.litellm_logging_obj.pre_call( input="OCR document processing", api_key=resolved_api_key, @@ -392,9 +385,7 @@ async def aocr( ) model = prepared.model custom_llm_provider = prepared.custom_llm_provider - completion_kwargs.update( - {"model": model, "custom_llm_provider": custom_llm_provider} - ) + completion_kwargs.update({"model": model, "custom_llm_provider": custom_llm_provider}) if _rust_ocr_supported(prepared) and rust_ocr_bridge.rust_ocr_enabled(): from litellm.secret_managers.main import get_secret_str @@ -404,9 +395,7 @@ async def aocr( resolve_api_key=get_secret_str, ) if rust_response is None: - verbose_logger.debug( - "Async Rust OCR bridge unavailable; falling back to Python path" - ) + verbose_logger.debug("Async Rust OCR bridge unavailable; falling back to Python path") else: return rust_response @@ -429,9 +418,7 @@ async def aocr( response = await response if response is None: - raise ValueError( - f"Got an unexpected None response from the OCR API: {response}" - ) + raise ValueError(f"Got an unexpected None response from the OCR API: {response}") return response except Exception as e: @@ -539,8 +526,7 @@ def convert_file_document_to_url_document(document: dict[str, Any]) -> dict[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." + f"Unsupported file input type: {type(file_input)}. Expected pathlib.Path, bytes, or a file-like object." ) if not file_bytes: @@ -667,9 +653,7 @@ def ocr( ) model = prepared.model custom_llm_provider = prepared.custom_llm_provider - completion_kwargs.update( - {"model": model, "custom_llm_provider": custom_llm_provider} - ) + completion_kwargs.update({"model": model, "custom_llm_provider": custom_llm_provider}) if _rust_ocr_supported(prepared) and rust_ocr_bridge.rust_ocr_enabled(): from litellm.secret_managers.main import get_secret_str @@ -679,9 +663,7 @@ def ocr( resolve_api_key=get_secret_str, ) if rust_response is None: - verbose_logger.debug( - "Rust OCR bridge unavailable; falling back to Python path" - ) + verbose_logger.debug("Rust OCR bridge unavailable; falling back to Python path") else: return rust_response diff --git a/litellm/passthrough/main.py b/litellm/passthrough/main.py index b1d4864cea7a..663675130621 100644 --- a/litellm/passthrough/main.py +++ b/litellm/passthrough/main.py @@ -264,9 +264,7 @@ def llm_passthrough_route( # [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) - ) + encoded_url_str = CommonUtils.encode_bedrock_runtime_modelid_arn(str(updated_url)) updated_url = httpx.URL(encoded_url_str) # Add or update query parameters @@ -345,9 +343,7 @@ def llm_passthrough_route( ) else: # Sync path - client.client.send returns Response directly - response: httpx.Response = client.client.send( - request=request, stream=is_streaming_request - ) # type: ignore + response: httpx.Response = client.client.send(request=request, stream=is_streaming_request) # type: ignore response.raise_for_status() if ( diff --git a/litellm/passthrough/timeout_utils.py b/litellm/passthrough/timeout_utils.py index a423db2aa913..84ec89b7e2a1 100644 --- a/litellm/passthrough/timeout_utils.py +++ b/litellm/passthrough/timeout_utils.py @@ -21,9 +21,7 @@ def resolve_pass_through_request_timeout( try: proxy_server = sys.modules.get("litellm.proxy.proxy_server") if proxy_server is not None: - global_timeout = getattr(proxy_server, "general_settings", {}).get( - "pass_through_request_timeout" - ) + global_timeout = getattr(proxy_server, "general_settings", {}).get("pass_through_request_timeout") if global_timeout is not None: return float(global_timeout) except Exception: diff --git a/litellm/passthrough/utils.py b/litellm/passthrough/utils.py index 9484922833ad..706beb7dc5e5 100644 --- a/litellm/passthrough/utils.py +++ b/litellm/passthrough/utils.py @@ -36,9 +36,7 @@ def get_merged_query_parameters( 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() - } + 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 = {} @@ -84,12 +82,9 @@ def forward_headers_from_request( 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() + 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 + 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", diff --git a/litellm/proxy/_experimental/mcp_server/auth/token_exchange.py b/litellm/proxy/_experimental/mcp_server/auth/token_exchange.py index 97a16ad3e159..aa42074f2c7c 100644 --- a/litellm/proxy/_experimental/mcp_server/auth/token_exchange.py +++ b/litellm/proxy/_experimental/mcp_server/auth/token_exchange.py @@ -49,9 +49,7 @@ def __init__(self) -> None: ) # WeakValueDictionary so locks are GC'd once no coroutine holds a reference, # preventing unbounded growth with many rotating user tokens. - self._locks: weakref.WeakValueDictionary[str, asyncio.Lock] = ( - weakref.WeakValueDictionary() - ) + self._locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary() def _get_lock(self, cache_key: str) -> asyncio.Lock: lock = self._locks.get(cache_key) @@ -118,8 +116,7 @@ async def _do_exchange( data: Dict[str, str] = { "grant_type": TOKEN_EXCHANGE_GRANT_TYPE, "subject_token": subject_token, - "subject_token_type": server.subject_token_type - or DEFAULT_SUBJECT_TOKEN_TYPE, + "subject_token_type": server.subject_token_type or DEFAULT_SUBJECT_TOKEN_TYPE, "client_id": server.client_id, "client_secret": server.client_secret, } @@ -146,8 +143,7 @@ async def _do_exchange( exc.response.status_code, ) raise ValueError( - f"Token exchange for MCP server '{server.server_id}' " - f"failed with status {exc.response.status_code}" + f"Token exchange for MCP server '{server.server_id}' failed with status {exc.response.status_code}" ) from exc body = response.json() @@ -159,18 +155,11 @@ async def _do_exchange( access_token = body.get("access_token") if not access_token: - raise ValueError( - f"Token exchange response for MCP server '{server.server_id}' " - f"missing 'access_token'" - ) + raise ValueError(f"Token exchange response for MCP server '{server.server_id}' missing 'access_token'") raw_expires_in = body.get("expires_in") try: - expires_in = ( - int(raw_expires_in) - if raw_expires_in is not None - else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL - ) + expires_in = int(raw_expires_in) if raw_expires_in is not None else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL except (TypeError, ValueError): expires_in = MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py index b7ac6a8c3258..2520c7e82a17 100644 --- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py +++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py @@ -7,7 +7,6 @@ from starlette.types import Scope from litellm._logging import verbose_logger -from litellm.constants import DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL from litellm.proxy._types import ( LiteLLM_TeamTable, ProxyException, @@ -17,15 +16,14 @@ ) from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.auth.user_api_key_auth import user_api_key_auth +from litellm.proxy.common_utils.user_api_key_cache import get_management_object_ttl from litellm.repositories.table_repositories import ( AgentsRepository, MCPServerRepository, ) -def _parse_mcp_server_names_from_path( - path: str, mcp_servers_header: Optional[List[str]] = None -) -> Optional[List[str]]: +def _parse_mcp_server_names_from_path(path: str, mcp_servers_header: Optional[List[str]] = None) -> Optional[List[str]]: """Resolve the single MCP server name a cold-start passthrough bypass may target. Delegates parsing to :meth:`MCPRequestHandler._extract_target_server_names_from_path` so the @@ -59,9 +57,7 @@ def _parse_mcp_server_names_from_path( return servers -def _is_mcp_passthrough_cold_start( - mcp_servers: Optional[List[str]], client_ip: Optional[str] -) -> bool: +def _is_mcp_passthrough_cold_start(mcp_servers: Optional[List[str]], client_ip: Optional[str]) -> bool: """True only when EVERY targeted server is a pass-through server with no auth headers — the cold-start OAuth discovery case per RFC 9728 / MCP Authorization spec. Lets the route handler's 401 emitter produce the @@ -79,9 +75,7 @@ def _is_mcp_passthrough_cold_start( ) for name in mcp_servers: - server = global_mcp_server_manager.get_mcp_server_by_name( - name, client_ip=client_ip - ) + server = global_mcp_server_manager.get_mcp_server_by_name(name, client_ip=client_ip) if server is None or not getattr(server, "is_oauth_passthrough", False): return False return True @@ -161,44 +155,31 @@ async def process_mcp_request( headers = MCPRequestHandler._safe_get_headers_from_scope(scope) # Check if there is an explicit LiteLLM API key (primary header) - has_explicit_litellm_key = ( - headers.get(MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_PRIMARY) - is not None - ) + has_explicit_litellm_key = headers.get(MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_PRIMARY) is not None - litellm_api_key = ( - MCPRequestHandler.get_litellm_api_key_from_headers(headers) or "" - ) + litellm_api_key = MCPRequestHandler.get_litellm_api_key_from_headers(headers) or "" # Get the old mcp_auth_header for backward compatibility mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(headers) # Get the new server-specific auth headers - mcp_server_auth_headers = ( - MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers) - ) + mcp_server_auth_headers = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers) # Get the oauth2 headers oauth2_headers = MCPRequestHandler._get_oauth2_headers_from_headers(headers) # Parse MCP servers from header - mcp_servers_header = headers.get( - MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME - ) + mcp_servers_header = headers.get(MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME) verbose_logger.debug(f"Raw MCP servers header: {mcp_servers_header}") mcp_servers = None if mcp_servers_header is not None: try: - mcp_servers = [ - s.strip() for s in mcp_servers_header.split(",") if s.strip() - ] + mcp_servers = [s.strip() for s in mcp_servers_header.split(",") if s.strip()] verbose_logger.debug(f"Parsed MCP servers: {mcp_servers}") except Exception as e: verbose_logger.debug(f"Error parsing mcp_servers header: {e}") mcp_servers = None - if mcp_servers_header == "" or ( - mcp_servers is not None and len(mcp_servers) == 0 - ): + if mcp_servers_header == "" or (mcp_servers is not None and len(mcp_servers) == 0): mcp_servers = [] # Create a proper Request object with mock body method to avoid ASGI receive channel issues request = Request(scope=scope) @@ -220,9 +201,7 @@ async def mock_body(): # An explicit x-litellm-api-key is always a LiteLLM credential, even # for a delegated server, so validate it: identity / spend / rate # limits resolve and any stored upstream token can be forwarded. - validated_user_api_key_auth = await user_api_key_auth( - api_key=litellm_api_key, request=request - ) + validated_user_api_key_auth = await user_api_key_auth(api_key=litellm_api_key, request=request) elif MCPRequestHandler._target_servers_delegate_auth_to_upstream( path=request_route, mcp_servers=mcp_servers, @@ -247,17 +226,13 @@ async def mock_body(): # so a recognized-but-forbidden key still fails closed. client_ip = IPAddressUtils.get_mcp_client_ip(request) try: - validated_user_api_key_auth = await user_api_key_auth( - api_key=litellm_api_key, request=request - ) + validated_user_api_key_auth = await user_api_key_auth(api_key=litellm_api_key, request=request) except (HTTPException, ProxyException) as e: # ProxyException.code is normalized to str (possibly "None"), so # compare both int and str forms rather than coercing. status = e.status_code if isinstance(e, HTTPException) else e.code is_unauthenticated = status in (401, "401") - mcp_servers_from_path = _parse_mcp_server_names_from_path( - request_route, mcp_servers - ) + mcp_servers_from_path = _parse_mcp_server_names_from_path(request_route, mcp_servers) if ( is_unauthenticated and mcp_servers_from_path is not None @@ -265,30 +240,23 @@ async def mock_body(): mcp_auth_header, mcp_server_auth_headers, ) - and _is_mcp_passthrough_cold_start( - mcp_servers_from_path, client_ip=client_ip - ) + and _is_mcp_passthrough_cold_start(mcp_servers_from_path, client_ip=client_ip) ): verbose_logger.debug( - "MCP pass-through return: forwarding Authorization as " - "upstream OAuth token for delegated auth" + "MCP pass-through return: forwarding Authorization as upstream OAuth token for delegated auth" ) validated_user_api_key_auth = UserAPIKeyAuth() else: raise else: try: - validated_user_api_key_auth = await user_api_key_auth( - api_key=litellm_api_key, request=request - ) + validated_user_api_key_auth = await user_api_key_auth(api_key=litellm_api_key, request=request) except (HTTPException, ProxyException) as exc: # Cold-start MCP OAuth discovery: RFC 9728 / MCP Authorization spec # require unauthenticated requests to protected resources to receive # 401 + WWW-Authenticate. Defer to _raise_preemptive_401_for_unauthenticated_servers # for pass-through servers instead of surfacing a generic admission error. - mcp_servers_from_path = _parse_mcp_server_names_from_path( - request_route, mcp_servers - ) + mcp_servers_from_path = _parse_mcp_server_names_from_path(request_route, mcp_servers) client_ip = IPAddressUtils.get_mcp_client_ip(request) if ( mcp_servers_from_path is not None @@ -297,13 +265,9 @@ async def mock_body(): mcp_server_auth_headers, ) and _is_litellm_auth_admission_error(exc) - and _is_mcp_passthrough_cold_start( - mcp_servers_from_path, client_ip=client_ip - ) + and _is_mcp_passthrough_cold_start(mcp_servers_from_path, client_ip=client_ip) ): - verbose_logger.debug( - "MCP pass-through cold start: deferring admission to route 401 emitter" - ) + verbose_logger.debug("MCP pass-through cold start: deferring admission to route 401 emitter") validated_user_api_key_auth = UserAPIKeyAuth() else: raise @@ -370,9 +334,7 @@ def _extract_target_server_names_from_path(path: str) -> List[str]: return [s.strip() for s in servers_part.split(",") if s.strip()] # Single-server case — server name may contain at most one slash. - single_server_match = re.match( - r"^([^/]+(?:/[^/]+)?)(?:/.*)?$", servers_and_path - ) + single_server_match = re.match(r"^([^/]+(?:/[^/]+)?)(?:/.*)?$", servers_and_path) if single_server_match: return [single_server_match.group(1)] return [servers_and_path] @@ -402,16 +364,12 @@ def _target_servers_delegate_auth_to_upstream( # (``extract_mcp_auth_context``) or an attacker could set # ``x-mcp-servers`` to a delegate-enabled server while the URL path # targets a non-delegate server, skipping LiteLLM auth for it. - target_names = MCPRequestHandler._resolve_target_server_names( - path=path, mcp_servers_header=mcp_servers - ) + target_names = MCPRequestHandler._resolve_target_server_names(path=path, mcp_servers_header=mcp_servers) if not target_names: return False for name in target_names: - server = global_mcp_server_manager.get_mcp_server_by_name( - name, client_ip=client_ip - ) + server = global_mcp_server_manager.get_mcp_server_by_name(name, client_ip=client_ip) if server is None or server.auth_type != MCPAuth.oauth2: return False # `is True` is intentional: opt-in must be an explicit boolean @@ -428,9 +386,7 @@ def _target_servers_delegate_auth_to_upstream( return True @staticmethod - def _resolve_target_server_names( - path: str, mcp_servers_header: Optional[List[str]] - ) -> List[str]: + def _resolve_target_server_names(path: str, mcp_servers_header: Optional[List[str]]) -> List[str]: """ Resolve the target MCP server names exactly as downstream routing does (``server.py::extract_mcp_auth_context``). @@ -464,9 +420,7 @@ def _get_mcp_auth_header_from_headers(headers: Headers) -> Optional[str]: DEPRECATED: This method is deprecated in favor of server-specific auth headers using the format x-mcp-{{server_alias}}-{{header_name}} instead. """ - mcp_client_side_auth_header_name: str = ( - MCPRequestHandler._get_mcp_client_side_auth_header_name() - ) + mcp_client_side_auth_header_name: str = MCPRequestHandler._get_mcp_client_side_auth_header_name() auth_header = headers.get(mcp_client_side_auth_header_name) if auth_header: verbose_logger.warning( @@ -498,10 +452,8 @@ def _get_mcp_server_auth_headers_from_headers( if header_name.lower().startswith(prefix): # Skip the access groups header as it's not a server auth header if ( - header_name.lower() - == MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME.lower() - or header_name.lower() - == MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME.lower() + header_name.lower() == MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME.lower() + or header_name.lower() == MCPRequestHandler.LITELLM_MCP_SERVERS_HEADER_NAME.lower() ): continue @@ -521,9 +473,7 @@ def _get_mcp_server_auth_headers_from_headers( if server_alias not in server_auth_headers: server_auth_headers[server_alias] = {} - server_auth_headers[server_alias][auth_header_name] = ( - header_value - ) + server_auth_headers[server_alias][auth_header_name] = header_value verbose_logger.debug( f"Found server auth header: {server_alias} -> {auth_header_name}: {header_value[:10]}..." ) @@ -553,18 +503,14 @@ def _get_mcp_client_side_auth_header_name() -> str: from litellm.proxy.proxy_server import general_settings from litellm.secret_managers.main import get_secret_str - MCP_CLIENT_SIDE_AUTH_HEADER_NAME: str = ( - MCPRequestHandler.LITELLM_MCP_AUTH_HEADER_NAME - ) + MCP_CLIENT_SIDE_AUTH_HEADER_NAME: str = MCPRequestHandler.LITELLM_MCP_AUTH_HEADER_NAME if get_secret_str("LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME") is not None: MCP_CLIENT_SIDE_AUTH_HEADER_NAME = ( - get_secret_str("LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME") - or MCP_CLIENT_SIDE_AUTH_HEADER_NAME + get_secret_str("LITELLM_MCP_CLIENT_SIDE_AUTH_HEADER_NAME") or MCP_CLIENT_SIDE_AUTH_HEADER_NAME ) elif general_settings.get("mcp_client_side_auth_header_name") is not None: MCP_CLIENT_SIDE_AUTH_HEADER_NAME = ( - general_settings.get("mcp_client_side_auth_header_name") - or MCP_CLIENT_SIDE_AUTH_HEADER_NAME + general_settings.get("mcp_client_side_auth_header_name") or MCP_CLIENT_SIDE_AUTH_HEADER_NAME ) return MCP_CLIENT_SIDE_AUTH_HEADER_NAME @@ -584,9 +530,7 @@ def get_litellm_api_key_from_headers(headers: Headers) -> Optional[str]: if api_key: return api_key - auth_header = headers.get( - MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_SECONDARY - ) + auth_header = headers.get(MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_SECONDARY) if auth_header: return auth_header @@ -605,10 +549,7 @@ def _safe_get_headers_from_scope(scope: Scope) -> Headers: # ASGI headers are list of [name: bytes, value: bytes] pairs raw_headers = scope.get("headers", []) # Convert bytes to strings and create dict for Headers constructor - headers_dict = { - name.decode("latin-1"): value.decode("latin-1") - for name, value in raw_headers - } + headers_dict = {name.decode("latin-1"): value.decode("latin-1") for name, value in raw_headers} return Headers(headers_dict) except (UnicodeDecodeError, AttributeError, TypeError) as e: verbose_logger.exception(f"Error getting headers from scope: {e}") @@ -640,31 +581,16 @@ async def get_allowed_mcp_servers( try: # Get allowed servers from key and team - allowed_mcp_servers_for_key = ( - await MCPRequestHandler._get_allowed_mcp_servers_for_key( - user_api_key_auth - ) - ) + allowed_mcp_servers_for_key = await MCPRequestHandler._get_allowed_mcp_servers_for_key(user_api_key_auth) # The key explicitly opted out of every MCP server. This overrides # team inheritance and additive grants (mirrors no-default-models). - if ( - SpecialMCPServerNames.no_mcp_servers.value - in allowed_mcp_servers_for_key - ): + if SpecialMCPServerNames.no_mcp_servers.value in allowed_mcp_servers_for_key: return [] - allowed_mcp_servers_for_team = ( - await MCPRequestHandler._get_allowed_mcp_servers_for_team( - user_api_key_auth - ) - ) + allowed_mcp_servers_for_team = await MCPRequestHandler._get_allowed_mcp_servers_for_team(user_api_key_auth) - key_access_group_grants = ( - await MCPRequestHandler._get_key_access_group_mcp_server_extras( - user_api_key_auth - ) - ) + key_access_group_grants = await MCPRequestHandler._get_key_access_group_mcp_server_extras(user_api_key_auth) ######################################################### # Calculate key/team allowed servers using inheritance and intersection logic @@ -684,11 +610,7 @@ async def get_allowed_mcp_servers( # team is a ceiling rather than a default, so the key must # grant servers explicitly (or via an access group) to reach # any — it inherits none. - base = ( - set() - if general_settings.get("require_key_mcp_access_defined", False) - else team_set - ) + base = set() if general_settings.get("require_key_mcp_access_defined", False) else team_set else: base = key_set & team_set # both restrict → intersect @@ -701,10 +623,8 @@ async def get_allowed_mcp_servers( # Check end_user permissions if end_user_id is set ######################################################### if user_api_key_auth and user_api_key_auth.end_user_id: - allowed_mcp_servers_for_end_user = ( - await MCPRequestHandler._get_allowed_mcp_servers_for_end_user( - user_api_key_auth - ) + allowed_mcp_servers_for_end_user = await MCPRequestHandler._get_allowed_mcp_servers_for_end_user( + user_api_key_auth ) # If end_user has explicit MCP server permissions, apply intersection @@ -735,19 +655,13 @@ async def get_allowed_mcp_servers( # Check agent permissions if agent_id is set on the key ######################################################### if user_api_key_auth and user_api_key_auth.agent_id: - allowed_mcp_servers_for_agent = ( - await MCPRequestHandler._get_allowed_mcp_servers_for_agent( - user_api_key_auth - ) + allowed_mcp_servers_for_agent = await MCPRequestHandler._get_allowed_mcp_servers_for_agent( + user_api_key_auth ) if len(allowed_mcp_servers_for_agent) > 0: has_lower_level_mcp_restrictions = True # Intersect: agent can only use servers allowed by BOTH key/team AND agent config - allowed_mcp_servers = [ - s - for s in allowed_mcp_servers - if s in allowed_mcp_servers_for_agent - ] + allowed_mcp_servers = [s for s in allowed_mcp_servers if s in allowed_mcp_servers_for_agent] verbose_logger.debug( f"Applied agent intersection filter. Final allowed servers: {allowed_mcp_servers}" ) @@ -756,25 +670,17 @@ async def get_allowed_mcp_servers( # Apply org-level ceiling if org_id is set ######################################################### if user_api_key_auth and user_api_key_auth.org_id: - allowed_mcp_servers_for_org = ( - await MCPRequestHandler._get_allowed_mcp_servers_for_org( - user_api_key_auth - ) + allowed_mcp_servers_for_org = await MCPRequestHandler._get_allowed_mcp_servers_for_org( + user_api_key_auth ) if len(allowed_mcp_servers_for_org) > 0: if has_lower_level_mcp_restrictions: # Lower-level restrictions exist, so org can only cap them. - allowed_mcp_servers = [ - s - for s in allowed_mcp_servers - if s in allowed_mcp_servers_for_org - ] + allowed_mcp_servers = [s for s in allowed_mcp_servers if s in allowed_mcp_servers_for_org] else: # No lower-level restrictions → org list becomes the ceiling allowed_mcp_servers = allowed_mcp_servers_for_org - verbose_logger.debug( - f"Applied org ceiling filter. Final allowed servers: {allowed_mcp_servers}" - ) + verbose_logger.debug(f"Applied org ceiling filter. Final allowed servers: {allowed_mcp_servers}") return list(set(allowed_mcp_servers)) except Exception as e: @@ -854,12 +760,8 @@ async def get_allowed_tools_for_server( try: # Get key and team object permissions (already loaded in main auth flow) - key_obj_perm = MCPRequestHandler._get_key_object_permission( - user_api_key_auth - ) - team_obj_perm = await MCPRequestHandler._get_team_object_permission( - user_api_key_auth - ) + key_obj_perm = MCPRequestHandler._get_key_object_permission(user_api_key_auth) + team_obj_perm = await MCPRequestHandler._get_team_object_permission(user_api_key_auth) # Extract tool permissions for this server. Dict keys may be # server_ids OR names/aliases; normalize to server_id-keyed form @@ -870,16 +772,12 @@ async def get_allowed_tools_for_server( ) key_tools = ( - global_mcp_server_manager.expand_tool_permissions( - key_obj_perm.mcp_tool_permissions - ).get(server_id) + global_mcp_server_manager.expand_tool_permissions(key_obj_perm.mcp_tool_permissions).get(server_id) if key_obj_perm else None ) team_tools = ( - global_mcp_server_manager.expand_tool_permissions( - team_obj_perm.mcp_tool_permissions - ).get(server_id) + global_mcp_server_manager.expand_tool_permissions(team_obj_perm.mcp_tool_permissions).get(server_id) if team_obj_perm else None ) @@ -899,15 +797,11 @@ async def get_allowed_tools_for_server( # Intersect with agent's tool permissions if agent_id is set if user_api_key_auth.agent_id: # Pre-fetch agent object_permission once to avoid duplicate DB query - agent_obj_perm = await MCPRequestHandler._get_agent_object_permission( - user_api_key_auth - ) - agent_tools = ( - await MCPRequestHandler._get_agent_tool_permissions_for_server( - server_id=server_id, - user_api_key_auth=user_api_key_auth, - agent_object_permission=agent_obj_perm, - ) + agent_obj_perm = await MCPRequestHandler._get_agent_object_permission(user_api_key_auth) + agent_tools = await MCPRequestHandler._get_agent_tool_permissions_for_server( + server_id=server_id, + user_api_key_auth=user_api_key_auth, + agent_object_permission=agent_obj_perm, ) if agent_tools is not None: if allowed_tools is not None: @@ -919,13 +813,9 @@ async def get_allowed_tools_for_server( if user_api_key_auth.org_id: # _get_org_object_permission uses user_api_key_cache, so this is not a # fresh DB round-trip when get_allowed_mcp_servers was already called. - org_obj_perm = await MCPRequestHandler._get_org_object_permission( - user_api_key_auth - ) + org_obj_perm = await MCPRequestHandler._get_org_object_permission(user_api_key_auth) org_tools = ( - global_mcp_server_manager.expand_tool_permissions( - org_obj_perm.mcp_tool_permissions - ).get(server_id) + global_mcp_server_manager.expand_tool_permissions(org_obj_perm.mcp_tool_permissions).get(server_id) if org_obj_perm and org_obj_perm.mcp_tool_permissions else None ) @@ -1027,9 +917,7 @@ async def _get_key_access_group_mcp_server_extras( # Permission entries may be server_ids OR names/aliases — expand to ids. return global_mcp_server_manager.expand_permission_list(raw_server_ids) except Exception as e: - verbose_logger.warning( - f"Failed to get key access group MCP server grants: {str(e)}" - ) + verbose_logger.warning(f"Failed to get key access group MCP server grants: {str(e)}") return [] @staticmethod @@ -1061,14 +949,8 @@ async def _get_allowed_mcp_servers_for_key( ) # Get key object permission (already loaded in main auth flow, or fetch from DB) - key_object_permission = MCPRequestHandler._get_key_object_permission( - user_api_key_auth - ) - if ( - key_object_permission is None - and user_api_key_auth.object_permission_id - and prisma_client is not None - ): + key_object_permission = MCPRequestHandler._get_key_object_permission(user_api_key_auth) + if key_object_permission is None and user_api_key_auth.object_permission_id and prisma_client is not None: key_object_permission = await get_object_permission( object_permission_id=user_api_key_auth.object_permission_id, prisma_client=prisma_client, @@ -1081,9 +963,7 @@ async def _get_allowed_mcp_servers_for_key( # Sentinel opt-out: surface it unexpanded so the caller can short-circuit # to zero servers instead of inheriting the team. - if SpecialMCPServerNames.no_mcp_servers.value in ( - key_object_permission.mcp_servers or [] - ): + if SpecialMCPServerNames.no_mcp_servers.value in (key_object_permission.mcp_servers or []): return [SpecialMCPServerNames.no_mcp_servers.value] # Permission entries may be server_ids OR names/aliases — expand to ids. @@ -1092,26 +972,20 @@ async def _get_allowed_mcp_servers_for_key( ) # Get MCP servers from access groups - access_group_servers = ( - await MCPRequestHandler._get_mcp_servers_from_access_groups( - key_object_permission.mcp_access_groups or [] - ) + access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups( + key_object_permission.mcp_access_groups or [] ) # servers referenced in tool permissions should also be accessible tool_perm_servers = list( - global_mcp_server_manager.expand_tool_permissions( - key_object_permission.mcp_tool_permissions - ).keys() + global_mcp_server_manager.expand_tool_permissions(key_object_permission.mcp_tool_permissions).keys() ) # Combine all lists all_servers = direct_mcp_servers + access_group_servers + tool_perm_servers return list(set(all_servers)) except Exception as e: - verbose_logger.warning( - f"Failed to get allowed MCP servers for key: {str(e)}" - ) + verbose_logger.warning(f"Failed to get allowed MCP servers for key: {str(e)}") return [] @staticmethod @@ -1143,11 +1017,7 @@ async def _get_allowed_mcp_servers_for_team( user_api_key_cache, ) - if ( - user_api_key_auth is None - or not user_api_key_auth.team_id - or prisma_client is None - ): + if user_api_key_auth is None or not user_api_key_auth.team_id or prisma_client is None: return [] team_obj: Optional[LiteLLM_TeamTable] = await get_team_object( @@ -1171,33 +1041,22 @@ async def _get_allowed_mcp_servers_for_team( if object_permissions is None: return list(set(team_access_group_servers)) - direct_mcp_servers = global_mcp_server_manager.expand_permission_list( - object_permissions.mcp_servers or [] - ) + direct_mcp_servers = global_mcp_server_manager.expand_permission_list(object_permissions.mcp_servers or []) - legacy_access_group_servers = ( - await MCPRequestHandler._get_mcp_servers_from_access_groups( - object_permissions.mcp_access_groups or [] - ) + legacy_access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups( + object_permissions.mcp_access_groups or [] ) tool_perm_servers = list( - global_mcp_server_manager.expand_tool_permissions( - object_permissions.mcp_tool_permissions - ).keys() + global_mcp_server_manager.expand_tool_permissions(object_permissions.mcp_tool_permissions).keys() ) all_servers = ( - direct_mcp_servers - + legacy_access_group_servers - + tool_perm_servers - + team_access_group_servers + direct_mcp_servers + legacy_access_group_servers + tool_perm_servers + team_access_group_servers ) return list(set(all_servers)) except Exception as e: - verbose_logger.warning( - f"Failed to get allowed MCP servers for team: {str(e)}" - ) + verbose_logger.warning(f"Failed to get allowed MCP servers for team: {str(e)}") return [] @staticmethod @@ -1257,9 +1116,7 @@ async def _get_allowed_mcp_servers_for_org( An empty result means the org places no restriction (allow-all from this level). """ try: - object_permissions = await MCPRequestHandler._get_org_object_permission( - user_api_key_auth - ) + object_permissions = await MCPRequestHandler._get_org_object_permission(user_api_key_auth) if object_permissions is None: return [] @@ -1269,28 +1126,20 @@ async def _get_allowed_mcp_servers_for_org( ) # Expand names/aliases to canonical server IDs (consistent with key/team/end-user path) - direct_mcp_servers = global_mcp_server_manager.expand_permission_list( - object_permissions.mcp_servers or [] - ) + direct_mcp_servers = global_mcp_server_manager.expand_permission_list(object_permissions.mcp_servers or []) - access_group_servers = ( - await MCPRequestHandler._get_mcp_servers_from_access_groups( - object_permissions.mcp_access_groups or [] - ) + access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups( + object_permissions.mcp_access_groups or [] ) tool_perm_servers = list( - global_mcp_server_manager.expand_tool_permissions( - object_permissions.mcp_tool_permissions - ).keys() + global_mcp_server_manager.expand_tool_permissions(object_permissions.mcp_tool_permissions).keys() ) all_servers = direct_mcp_servers + access_group_servers + tool_perm_servers return list(set(all_servers)) except Exception as e: - verbose_logger.warning( - f"Failed to get allowed MCP servers for org: {str(e)}" - ) + verbose_logger.warning(f"Failed to get allowed MCP servers for org: {str(e)}") return [] @staticmethod @@ -1340,10 +1189,8 @@ async def _get_allowed_mcp_servers_for_end_user( ) # Get MCP servers from access groups - access_group_servers = ( - await MCPRequestHandler._get_mcp_servers_from_access_groups( - end_user_obj.object_permission.mcp_access_groups or [] - ) + access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups( + end_user_obj.object_permission.mcp_access_groups or [] ) # servers referenced in tool permissions should also be accessible @@ -1357,9 +1204,7 @@ async def _get_allowed_mcp_servers_for_end_user( all_servers = direct_mcp_servers + access_group_servers + tool_perm_servers return list(set(all_servers)) except Exception as e: - verbose_logger.warning( - f"Failed to get allowed MCP servers for end_user: {str(e)}" - ) + verbose_logger.warning(f"Failed to get allowed MCP servers for end_user: {str(e)}") return [] # Sentinel stored in cache when an agent has no object_permission, so we @@ -1394,9 +1239,7 @@ async def _get_agent_object_permission( cache_key = f"agent_object_permission_id:{agent_id}" try: - object_permission_id: Optional[ - str - ] = await user_api_key_cache.async_get_cache(key=cache_key) + object_permission_id: Optional[str] = await user_api_key_cache.async_get_cache(key=cache_key) if object_permission_id == MCPRequestHandler._AGENT_NO_PERMISSION_SENTINEL: return None @@ -1406,15 +1249,12 @@ async def _get_agent_object_permission( where={"agent_id": agent_id}, ) object_permission_id = ( - getattr(agent_row, "object_permission_id", None) - if agent_row is not None - else None + getattr(agent_row, "object_permission_id", None) if agent_row is not None else None ) await user_api_key_cache.async_set_cache( key=cache_key, - value=object_permission_id - or MCPRequestHandler._AGENT_NO_PERMISSION_SENTINEL, - ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL, + value=object_permission_id or MCPRequestHandler._AGENT_NO_PERMISSION_SENTINEL, + ttl=get_management_object_ttl(user_api_key_cache), ) if not object_permission_id: return None @@ -1452,9 +1292,7 @@ async def _get_allowed_mcp_servers_for_agent( try: obj_perm = agent_object_permission if obj_perm is None: - obj_perm = await MCPRequestHandler._get_agent_object_permission( - user_api_key_auth - ) + obj_perm = await MCPRequestHandler._get_agent_object_permission(user_api_key_auth) if obj_perm is None: return [] @@ -1470,21 +1308,13 @@ async def _get_allowed_mcp_servers_for_agent( global_mcp_server_manager, ) - expanded_direct_servers = global_mcp_server_manager.expand_permission_list( - list(direct_mcp_servers) - ) + expanded_direct_servers = global_mcp_server_manager.expand_permission_list(list(direct_mcp_servers)) - access_group_servers = ( - await MCPRequestHandler._get_mcp_servers_from_access_groups( - mcp_access_groups - ) - ) + access_group_servers = await MCPRequestHandler._get_mcp_servers_from_access_groups(mcp_access_groups) all_servers = expanded_direct_servers + access_group_servers return list(set(all_servers)) except Exception as e: - verbose_logger.warning( - f"Failed to get allowed MCP servers for agent: {str(e)}" - ) + verbose_logger.warning(f"Failed to get allowed MCP servers for agent: {str(e)}") return [] @staticmethod @@ -1509,9 +1339,7 @@ async def _get_agent_tool_permissions_for_server( try: obj_perm = agent_object_permission if obj_perm is None: - obj_perm = await MCPRequestHandler._get_agent_object_permission( - user_api_key_auth - ) + obj_perm = await MCPRequestHandler._get_agent_object_permission(user_api_key_auth) if obj_perm is None: return None @@ -1523,20 +1351,14 @@ async def _get_agent_tool_permissions_for_server( global_mcp_server_manager, ) - tools = global_mcp_server_manager.expand_tool_permissions( - mcp_tool_permissions - ).get(server_id) + tools = global_mcp_server_manager.expand_tool_permissions(mcp_tool_permissions).get(server_id) return list(tools) if tools else None except Exception as e: - verbose_logger.warning( - f"Failed to get agent tool permissions for server: {str(e)}" - ) + verbose_logger.warning(f"Failed to get agent tool permissions for server: {str(e)}") return None @staticmethod - def _get_config_server_ids_for_access_groups( - config_mcp_servers, access_groups: List[str] - ) -> Set[str]: + def _get_config_server_ids_for_access_groups(config_mcp_servers, access_groups: List[str]) -> Set[str]: """ Helper to get server_ids from config-loaded servers that match any of the given access groups. """ @@ -1548,9 +1370,7 @@ def _get_config_server_ids_for_access_groups( return server_ids @staticmethod - async def _get_db_server_ids_for_access_groups( - prisma_client, access_groups: List[str] - ) -> Set[str]: + async def _get_db_server_ids_for_access_groups(prisma_client, access_groups: List[str]) -> Set[str]: """ Helper to get server_ids from DB servers that match any of the given access groups. """ @@ -1563,9 +1383,7 @@ async def _get_db_server_ids_for_access_groups( for server in mcp_servers: server_ids.add(server.server_id) except Exception as e: - verbose_logger.debug( - f"Error getting MCP servers from access groups: {e}" - ) + verbose_logger.debug(f"Error getting MCP servers from access groups: {e}") return server_ids @staticmethod @@ -1589,18 +1407,12 @@ async def _get_mcp_servers_from_access_groups( ) # Use the new helper for DB servers - db_server_ids = ( - await MCPRequestHandler._get_db_server_ids_for_access_groups( - prisma_client, access_groups - ) - ) + db_server_ids = await MCPRequestHandler._get_db_server_ids_for_access_groups(prisma_client, access_groups) server_ids.update(db_server_ids) return list(server_ids) except Exception as e: - verbose_logger.warning( - f"Failed to get MCP servers from access groups: {str(e)}" - ) + verbose_logger.warning(f"Failed to get MCP servers from access groups: {str(e)}") return [] @staticmethod @@ -1611,12 +1423,8 @@ async def get_mcp_access_groups( Get list of MCP access groups for the given user/key based on permissions """ access_groups: List[str] = [] - access_groups_for_key = await MCPRequestHandler._get_mcp_access_groups_for_key( - user_api_key_auth - ) - access_groups_for_team = ( - await MCPRequestHandler._get_mcp_access_groups_for_team(user_api_key_auth) - ) + access_groups_for_key = await MCPRequestHandler._get_mcp_access_groups_for_key(user_api_key_auth) + access_groups_for_team = await MCPRequestHandler._get_mcp_access_groups_for_team(user_api_key_auth) ######################################################### # If team has access groups, then key must have a subset of the team's access groups @@ -1709,9 +1517,7 @@ async def _get_mcp_access_groups_for_team( return object_permissions.mcp_access_groups or [] except Exception as e: - verbose_logger.warning( - f"Failed to get MCP access groups for team: {str(e)}" - ) + verbose_logger.warning(f"Failed to get MCP access groups for team: {str(e)}") return [] @staticmethod @@ -1719,14 +1525,10 @@ def get_mcp_access_groups_from_headers(headers: Headers) -> Optional[List[str]]: """ Extract and parse the x-mcp-access-groups header as a list of strings. """ - mcp_access_groups_header = headers.get( - MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME - ) + mcp_access_groups_header = headers.get(MCPRequestHandler.LITELLM_MCP_ACCESS_GROUPS_HEADER_NAME) if mcp_access_groups_header is not None: try: - return [ - s.strip() for s in mcp_access_groups_header.split(",") if s.strip() - ] + return [s.strip() for s in mcp_access_groups_header.split(",") if s.strip()] except Exception: return None return None diff --git a/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py b/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py index 2f5973ca3712..4f58f4bdbb38 100644 --- a/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/byok_oauth_endpoints.py @@ -79,9 +79,7 @@ def _oauth_token_error(code: str, status: int = 400) -> JSONResponse: FastAPI's default ``HTTPException`` renders ``{"detail": ...}`` which spec-compliant OAuth clients parsing the ``error`` field won't recognize. """ - return JSONResponse( - status_code=status, content={"error": code}, headers=TOKEN_NO_CACHE_HEADERS - ) + return JSONResponse(status_code=status, content={"error": code}, headers=TOKEN_NO_CACHE_HEADERS) def _user_id_from_session_cookie(request: Request) -> Optional[str]: @@ -160,8 +158,7 @@ def _build_authorize_html( # Build access checklist rows access_rows = "".join( - f'
✓{e(item)}
' - for item in access_items + f'
✓{e(item)}
' for item in access_items ) access_section = "" if access_rows: @@ -177,7 +174,9 @@ def _build_authorize_html( # Help link for step 2 help_link_html = "" if help_url: - help_link_html = f'Where do I find my API key? ↗' + help_link_html = ( + f'Where do I find my API key? ↗' + ) return f""" @@ -722,14 +721,10 @@ async def byok_authorize_post( # Reject new codes if the store is at capacity (prevents memory exhaustion # from a burst of abandoned OAuth flows). if len(_byok_auth_codes) >= _AUTH_CODES_MAX_SIZE: - raise HTTPException( - status_code=503, detail="Too many pending authorization flows" - ) + raise HTTPException(status_code=503, detail="Too many pending authorization flows") if code_challenge_method != "S256": - raise HTTPException( - status_code=400, detail="Only S256 code_challenge_method is supported" - ) + raise HTTPException(status_code=400, detail="Only S256 code_challenge_method is supported") # Identity comes from the authenticated session, not the OAuth client_id # form field (RFC 6749 §2.2: client_id identifies the client application, @@ -806,11 +801,7 @@ async def byok_token( # actually submitted a value, so we stay RFC 6749-backward-compatible # without breaking OAuth 2.1 clients. PKCE + client_id binding # (checked below) cover the security role redirect_uri played. - if ( - record.get("redirect_uri") - and redirect_uri - and redirect_uri != record["redirect_uri"] - ): + if record.get("redirect_uri") and redirect_uri and redirect_uri != record["redirect_uri"]: return _oauth_token_error("invalid_grant") # RFC 6749 §4.1.3: if the client was identified at /authorize, the @@ -865,9 +856,7 @@ async def byok_token( ) return _oauth_token_error("server_error", status=500) else: - verbose_proxy_logger.warning( - "byok_token: prisma_client is None — credential not persisted" - ) + verbose_proxy_logger.warning("byok_token: prisma_client is None — credential not persisted") now = int(time.time()) payload = { diff --git a/litellm/proxy/_experimental/mcp_server/cost_calculator.py b/litellm/proxy/_experimental/mcp_server/cost_calculator.py index b8fdba23d92c..9b6f89bc7bd6 100644 --- a/litellm/proxy/_experimental/mcp_server/cost_calculator.py +++ b/litellm/proxy/_experimental/mcp_server/cost_calculator.py @@ -32,9 +32,7 @@ def calculate_mcp_tool_call_cost( # Get the response cost from logging object model_call_details # This is set when a user modifies the response in a post_mcp_tool_call_hook ######################################################### - response_cost = litellm_logging_obj.model_call_details.get( - "response_cost", None - ) + response_cost = litellm_logging_obj.model_call_details.get("response_cost", None) if response_cost is not None: return response_cost @@ -44,9 +42,7 @@ def calculate_mcp_tool_call_cost( mcp_tool_call_metadata: StandardLoggingMCPToolCall = ( cast( StandardLoggingMCPToolCall, - litellm_logging_obj.model_call_details.get( - "mcp_tool_call_metadata", {} - ), + litellm_logging_obj.model_call_details.get("mcp_tool_call_metadata", {}), ) or {} ) @@ -56,12 +52,8 @@ def calculate_mcp_tool_call_cost( ######################################################### # User defined cost per query ######################################################### - default_cost_per_query = mcp_server_cost_info.get( - "default_cost_per_query", None - ) - tool_name_to_cost_per_query: dict = ( - mcp_server_cost_info.get("tool_name_to_cost_per_query", {}) or {} - ) + default_cost_per_query = mcp_server_cost_info.get("default_cost_per_query", None) + tool_name_to_cost_per_query: dict = mcp_server_cost_info.get("tool_name_to_cost_per_query", {}) or {} tool_name = mcp_tool_call_metadata.get("name", "") ######################################################### diff --git a/litellm/proxy/_experimental/mcp_server/db.py b/litellm/proxy/_experimental/mcp_server/db.py index bc1068d77d04..2dd046ceadaf 100644 --- a/litellm/proxy/_experimental/mcp_server/db.py +++ b/litellm/proxy/_experimental/mcp_server/db.py @@ -3,7 +3,7 @@ import hashlib import json from datetime import datetime, timedelta, timezone -from typing import Any, Dict, Iterable, List, Optional, Set, Union, cast +from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Set, Union, cast from litellm._logging import verbose_proxy_logger from litellm._uuid import uuid @@ -39,6 +39,9 @@ from litellm.types.llms.custom_http import httpxSpecialProvider from litellm.types.mcp import MCPCredentials +if TYPE_CHECKING: + from litellm.types.mcp_server.mcp_server_manager import MCPServer + def _is_global_env_var_scope(scope: Any) -> bool: """``scope="user"`` entries are placeholders the user fills in; everything @@ -166,14 +169,11 @@ def _reencrypt_global_env_var_values( ) if decrypted is None: verbose_proxy_logger.warning( - "rotate_mcp_server_credentials_master_key: could not decrypt " - "global env var %s, skipping", + "rotate_mcp_server_credentials_master_key: could not decrypt global env var %s, skipping", entry.get("name"), ) continue - entry["value"] = encrypt_value_helper( - decrypted, new_encryption_key=new_encryption_key - ) + entry["value"] = encrypt_value_helper(decrypted, new_encryption_key=new_encryption_key) rotated = True return rebuilt if rotated else None @@ -237,9 +237,7 @@ def _prepare_mcp_server_data( # Handle credentials serialization credentials = data_dict.get("credentials") if credentials is not None: - data_dict["credentials"] = encrypt_credentials( - credentials=credentials, encryption_key=_get_salt_key() - ) + data_dict["credentials"] = encrypt_credentials(credentials=credentials, encryption_key=_get_salt_key()) data_dict["credentials"] = safe_dumps(data_dict["credentials"]) # Serialize JSON fields from ``data_dict`` (not ``data``) so the @@ -265,13 +263,9 @@ def _prepare_mcp_server_data( data_dict["env"] = safe_dumps(data_dict["env"]) if "tool_name_to_display_name" in data_dict: - data_dict["tool_name_to_display_name"] = safe_dumps( - data_dict["tool_name_to_display_name"] or {} - ) + data_dict["tool_name_to_display_name"] = safe_dumps(data_dict["tool_name_to_display_name"] or {}) if "tool_name_to_description" in data_dict: - data_dict["tool_name_to_description"] = safe_dumps( - data_dict["tool_name_to_description"] or {} - ) + data_dict["tool_name_to_description"] = safe_dumps(data_dict["tool_name_to_description"] or {}) # mcp_access_groups is already List[str], no serialization needed @@ -283,9 +277,7 @@ def _prepare_mcp_server_data( return data_dict -def encrypt_credentials( - credentials: MCPCredentials, encryption_key: Optional[str] -) -> MCPCredentials: +def encrypt_credentials(credentials: MCPCredentials, encryption_key: Optional[str]) -> MCPCredentials: auth_value = credentials.get("auth_value") if auth_value is not None: credentials["auth_value"] = encrypt_value_helper( @@ -363,35 +355,24 @@ async def get_all_mcp_servers( where: Dict[str, Any] = {} if approval_status is not None: where["approval_status"] = approval_status - mcp_servers = await MCPServerRepository(prisma_client).table.find_many( - where=where if where else {} - ) + mcp_servers = await MCPServerRepository(prisma_client).table.find_many(where=where if where else {}) - tables = [ - LiteLLM_MCPServerTable(**mcp_server.model_dump()) - for mcp_server in mcp_servers - ] + tables = [LiteLLM_MCPServerTable(**mcp_server.model_dump()) for mcp_server in mcp_servers] for table in tables: decrypt_global_env_var_values(table.env_vars) return tables except Exception as e: verbose_proxy_logger.debug( - "litellm.proxy._experimental.mcp_server.db.py::get_all_mcp_servers - {}".format( - str(e) - ) + "litellm.proxy._experimental.mcp_server.db.py::get_all_mcp_servers - {}".format(str(e)) ) return [] -async def get_mcp_server( - prisma_client: PrismaClient, server_id: str -) -> Optional[LiteLLM_MCPServerTable]: +async def get_mcp_server(prisma_client: PrismaClient, server_id: str) -> Optional[LiteLLM_MCPServerTable]: """ Returns the matching mcp server from the db iff exists """ - mcp_server: Optional[LiteLLM_MCPServerTable] = await MCPServerRepository( - prisma_client - ).table.find_unique( + mcp_server: Optional[LiteLLM_MCPServerTable] = await MCPServerRepository(prisma_client).table.find_unique( where={ "server_id": server_id, } @@ -403,15 +384,11 @@ async def get_mcp_server( return table -async def get_mcp_servers( - prisma_client: PrismaClient, server_ids: Iterable[str] -) -> List[LiteLLM_MCPServerTable]: +async def get_mcp_servers(prisma_client: PrismaClient, server_ids: Iterable[str]) -> List[LiteLLM_MCPServerTable]: """ Returns the matching mcp servers from the db with the server_ids """ - _mcp_servers: List[LiteLLM_MCPServerTable] = await MCPServerRepository( - prisma_client - ).table.find_many( + _mcp_servers: List[LiteLLM_MCPServerTable] = await MCPServerRepository(prisma_client).table.find_many( where={ "server_id": {"in": server_ids}, } @@ -425,15 +402,11 @@ async def get_mcp_servers( return final_mcp_servers -async def get_mcp_servers_by_verificationtoken( - prisma_client: PrismaClient, token: str -) -> List[str]: +async def get_mcp_servers_by_verificationtoken(prisma_client: PrismaClient, token: str) -> List[str]: """ Returns the mcp servers from the db for the verification token """ - verification_token_record: LiteLLM_TeamTable = await VerificationTokenRepository( - prisma_client - ).table.find_unique( + verification_token_record: LiteLLM_TeamTable = await VerificationTokenRepository(prisma_client).table.find_unique( where={ "token": token, }, @@ -443,23 +416,16 @@ async def get_mcp_servers_by_verificationtoken( ) mcp_servers: Optional[List[str]] = [] - if ( - verification_token_record is not None - and verification_token_record.object_permission is not None - ): + if verification_token_record is not None and verification_token_record.object_permission is not None: mcp_servers = verification_token_record.object_permission.mcp_servers return mcp_servers or [] -async def get_mcp_servers_by_team( - prisma_client: PrismaClient, team_id: str -) -> List[str]: +async def get_mcp_servers_by_team(prisma_client: PrismaClient, team_id: str) -> List[str]: """ Returns the mcp servers from the db for the team id """ - team_record: LiteLLM_TeamTable = await TeamRepository( - prisma_client - ).table.find_unique( + team_record: LiteLLM_TeamTable = await TeamRepository(prisma_client).table.find_unique( where={ "team_id": team_id, }, @@ -489,19 +455,12 @@ async def get_all_mcp_servers_for_user( # Get the mcp servers for the key if user.api_key: - token_mcp_servers = await get_mcp_servers_by_verificationtoken( - prisma_client, user.api_key - ) + token_mcp_servers = await get_mcp_servers_by_verificationtoken(prisma_client, user.api_key) mcp_server_ids.update(token_mcp_servers) # check for special team membership - if ( - SpecialMCPServerName.all_team_servers in mcp_server_ids - and user.team_id is not None - ): - team_mcp_servers = await get_mcp_servers_by_team( - prisma_client, user.team_id - ) + if SpecialMCPServerName.all_team_servers in mcp_server_ids and user.team_id is not None: + team_mcp_servers = await get_mcp_servers_by_team(prisma_client, user.team_id) mcp_server_ids.update(team_mcp_servers) if len(mcp_server_ids) > 0: @@ -516,9 +475,7 @@ async def get_objectpermissions_for_mcp_server( """ Get all the object permissions records and the associated team and verficiationtoken records that have access to the mcp server """ - object_permission_records = await ObjectPermissionRepository( - prisma_client - ).table.find_many( + object_permission_records = await ObjectPermissionRepository(prisma_client).table.find_many( where={ "mcp_servers": {"has": mcp_server_id}, }, @@ -531,9 +488,7 @@ async def get_objectpermissions_for_mcp_server( return object_permission_records -async def get_virtualkeys_for_mcp_server( - prisma_client: PrismaClient, server_id: str -) -> List: +async def get_virtualkeys_for_mcp_server(prisma_client: PrismaClient, server_id: str) -> List: """ Get all the virtual keys that have access to the mcp server """ @@ -562,9 +517,7 @@ async def delete_mcp_server_from_virtualkey(): pass -async def delete_mcp_server( - prisma_client: PrismaClient, server_id: str -) -> Optional[LiteLLM_MCPServerTable]: +async def delete_mcp_server(prisma_client: PrismaClient, server_id: str) -> Optional[LiteLLM_MCPServerTable]: """ Delete the mcp server from the db by server_id @@ -641,19 +594,13 @@ async def update_mcp_server( # exclude_unset=True makes this a true partial update: fields the caller did # not provide are not written, so they keep their existing DB value instead # of being reset to a schema default (transport=sse, allow_all_keys=False...). - data_dict = _prepare_mcp_server_data( - data, exclude_unset=True, fields_set=fields_set - ) + data_dict = _prepare_mcp_server_data(data, exclude_unset=True, fields_set=fields_set) # Pre-fetch existing record once if we need it for auth_type or credential logic existing = None - has_credentials = ( - "credentials" in data_dict and data_dict["credentials"] is not None - ) + has_credentials = "credentials" in data_dict and data_dict["credentials"] is not None if data.auth_type or has_credentials: - existing = await MCPServerRepository(prisma_client).table.find_unique( - where={"server_id": data.server_id} - ) + existing = await MCPServerRepository(prisma_client).table.find_unique(where={"server_id": data.server_id}) # Clear stale credentials when auth_type changes but no new credentials provided if ( @@ -673,9 +620,7 @@ async def update_mcp_server( # Only merge when auth_type is unchanged. Switching auth types # (e.g. oauth2 → api_key) should replace credentials entirely # to avoid stale secrets from the previous auth type lingering. - auth_type_unchanged = ( - data.auth_type is None or data.auth_type == existing.auth_type - ) + auth_type_unchanged = data.auth_type is None or data.auth_type == existing.auth_type if auth_type_unchanged: existing_creds = ( json.loads(existing.credentials) @@ -703,9 +648,7 @@ async def update_mcp_server( return updated_mcp_server -async def rotate_mcp_server_credentials_master_key( - prisma_client: PrismaClient, touched_by: str, new_master_key: str -): +async def rotate_mcp_server_credentials_master_key(prisma_client: PrismaClient, touched_by: str, new_master_key: str): from litellm.litellm_core_utils.safe_json_dumps import safe_dumps mcp_servers = await MCPServerRepository(prisma_client).table.find_many() @@ -726,9 +669,7 @@ async def rotate_mcp_server_credentials_master_key( ) update_data["credentials"] = safe_dumps(encrypted_credentials) - rotated_env_vars = _reencrypt_global_env_var_values( - mcp_server.env_vars, new_master_key - ) + rotated_env_vars = _reencrypt_global_env_var_values(mcp_server.env_vars, new_master_key) if rotated_env_vars is not None: update_data["env_vars"] = safe_dumps(rotated_env_vars) @@ -788,9 +729,7 @@ def _decode_oauth_payload(stored: str) -> Optional[Dict[str, Any]]: return None -async def rotate_mcp_user_credentials_master_key( - prisma_client: PrismaClient, new_master_key: str -): +async def rotate_mcp_user_credentials_master_key(prisma_client: PrismaClient, new_master_key: str): """Re-encrypt every ``LiteLLM_MCPUserCredentials`` row with ``new_master_key``. Reads each ``credential_b64`` with the current salt key (falling back to @@ -812,9 +751,7 @@ async def rotate_mcp_user_credentials_master_key( ) skipped += 1 continue - re_encrypted = encrypt_value_helper( - plaintext, new_encryption_key=new_master_key - ) + re_encrypted = encrypt_value_helper(plaintext, new_encryption_key=new_master_key) await MCPUserCredentialsRepository(prisma_client).table.update( where={ "user_id_server_id": { @@ -832,9 +769,7 @@ async def rotate_mcp_user_credentials_master_key( ) -async def rotate_mcp_user_env_vars_master_key( - prisma_client: PrismaClient, new_master_key: str -): +async def rotate_mcp_user_env_vars_master_key(prisma_client: PrismaClient, new_master_key: str): """Re-encrypt every ``LiteLLM_MCPUserEnvVars`` row with ``new_master_key``. Reads each ``values_b64`` blob with the current salt key and writes it back @@ -854,16 +789,13 @@ async def rotate_mcp_user_env_vars_master_key( ) if plaintext is None: verbose_proxy_logger.warning( - "rotate_mcp_user_env_vars_master_key: could not decrypt env vars " - "for user_id=%s server_id=%s, skipping", + "rotate_mcp_user_env_vars_master_key: could not decrypt env vars for user_id=%s server_id=%s, skipping", row.user_id, row.server_id, ) skipped += 1 continue - re_encrypted = encrypt_value_helper( - plaintext, new_encryption_key=new_master_key - ) + re_encrypted = encrypt_value_helper(plaintext, new_encryption_key=new_master_key) await prisma_client.db.litellm_mcpuserenvvars.update( where={ "user_id_server_id": { @@ -963,9 +895,7 @@ async def store_user_oauth_credential( expires_at: Optional[str] = None if expires_in is not None: - expires_at = ( - datetime.now(timezone.utc) + timedelta(seconds=expires_in) - ).isoformat() + expires_at = (datetime.now(timezone.utc) + timedelta(seconds=expires_in)).isoformat() payload: Dict[str, Any] = { "type": "oauth2", @@ -986,10 +916,7 @@ async def store_user_oauth_credential( existing = await MCPUserCredentialsRepository(prisma_client).table.find_unique( where={"user_id_server_id": {"user_id": user_id, "server_id": server_id}} ) - if ( - existing is not None - and _decode_oauth_payload(existing.credential_b64) is None - ): + if existing is not None and _decode_oauth_payload(existing.credential_b64) is None: # Existing row is either a BYOK secret or an OAuth2 row that no # longer decrypts (e.g. after a salt-key rotation). In either # case, refuse to overwrite — the caller would clobber data @@ -1056,9 +983,7 @@ async def list_user_oauth_credentials( ) -> List[Dict[str, Any]]: """Return all OAuth2 credential payloads for a user, tagged with server_id.""" - rows = await MCPUserCredentialsRepository(prisma_client).table.find_many( - where={"user_id": user_id} - ) + rows = await MCPUserCredentialsRepository(prisma_client).table.find_many(where={"user_id": user_id}) results: List[Dict[str, Any]] = [] for row in rows: payload = _decode_oauth_payload(row.credential_b64) @@ -1115,9 +1040,7 @@ async def refresh_user_oauth_token( token_data["client_secret"] = client_secret try: - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.Oauth2Check - ) + async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Check) response = await async_client.post( token_url, headers={"Accept": "application/json"}, @@ -1137,8 +1060,7 @@ async def refresh_user_oauth_token( access_token: Optional[str] = body.get("access_token") if not access_token: verbose_proxy_logger.warning( - "refresh_user_oauth_token: token response missing access_token for " - "user=%s server=%s", + "refresh_user_oauth_token: token response missing access_token for user=%s server=%s", user_id, server_id, ) @@ -1155,9 +1077,9 @@ async def refresh_user_oauth_token( new_refresh_token: Optional[str] = body.get("refresh_token") or refresh_token raw_scope = body.get("scope") - scopes: Optional[List[str]] = ( - raw_scope.split() if isinstance(raw_scope, str) and raw_scope else None - ) or cred.get("scopes") + scopes: Optional[List[str]] = (raw_scope.split() if isinstance(raw_scope, str) and raw_scope else None) or cred.get( + "scopes" + ) await store_user_oauth_credential( prisma_client=prisma_client, @@ -1199,18 +1121,14 @@ async def resolve_valid_user_oauth_token( """ if not cred or not cred.get("access_token"): return None - if not is_oauth_credential_expired( - cred, buffer_seconds=MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS - ): + if not is_oauth_credential_expired(cred, buffer_seconds=MCP_PER_USER_TOKEN_EXPIRY_BUFFER_SECONDS): return cred if not cred.get("refresh_token"): return None if prisma_client is None: from litellm.proxy.utils import get_prisma_client_or_throw - prisma_client = get_prisma_client_or_throw( - "Database not connected. Cannot refresh OAuth token." - ) + prisma_client = get_prisma_client_or_throw("Database not connected. Cannot refresh OAuth token.") refreshed = await refresh_user_oauth_token( prisma_client=prisma_client, user_id=user_id, @@ -1222,6 +1140,89 @@ async def resolve_valid_user_oauth_token( return refreshed +async def resolve_user_oauth_access_token( + user_id: str | None, + server: "MCPServer", + prefetched_creds: dict[str, dict[str, object]] | None = None, +) -> str | None: + """Resolve a user's valid OAuth2 access token for a server: Redis cache, else DB + refresh. + + The egress token-resolution core shared by v1's header builder and the v2 ``OAuthTokenStore`` + adapter. Redis fast-path (skipped when ``prefetched_creds`` is supplied), else a DB read through + ``resolve_valid_user_oauth_token`` (which refreshes an expired token when a ``refresh_token`` is + stored), re-warming the Redis cache with the per-server TTL. Returns ``None`` when there is no + usable token; any error is swallowed to ``None`` so a transient failure reads as "not + authorized" rather than raising. + """ + server_id = getattr(server, "server_id", None) + if not user_id or not server_id: + return None + try: + from litellm.proxy._experimental.mcp_server.oauth2_token_cache import ( + _compute_per_user_token_ttl, + mcp_per_user_token_cache, + ) + + if prefetched_creds is None: + cached_token = await mcp_per_user_token_cache.get(user_id, server_id) + if cached_token is not None: + return cached_token + + prisma_client = None + if prefetched_creds is not None: + cred = prefetched_creds.get(server_id) + else: + from litellm.proxy.utils import get_prisma_client_or_throw + + prisma_client = get_prisma_client_or_throw( + "Database not connected. Connect a database to use OAuth2 MCP tools." + ) + cred = await get_user_oauth_credential(prisma_client, user_id, server_id) + + if not cred or not cred.get("access_token"): + return None + + cred = await resolve_valid_user_oauth_token( + user_id=user_id, + server=server, + cred=cred, + prisma_client=prisma_client, + ) + if cred is None: + # Refresh failed or token expired with no usable refresh_token — clear the stale + # Redis entry so the next request doesn't reuse it. + await mcp_per_user_token_cache.delete(user_id, server_id) + return None + + access_token: str = cred["access_token"] + if prefetched_creds is None: + ttl = _compute_per_user_token_ttl(server, _remaining_token_seconds(cred.get("expires_at"))) + await mcp_per_user_token_cache.set(user_id, server_id, access_token, ttl) + return access_token + except Exception as e: + verbose_proxy_logger.warning( + "resolve_user_oauth_access_token: failed for user=%s server=%s: %s", + user_id, + server_id, + e, + ) + return None + + +def _remaining_token_seconds(expires_at: str | None) -> int | None: + """Seconds until ``expires_at`` (ISO 8601), or None when absent/past/unparseable.""" + if not expires_at: + return None + try: + exp_dt = datetime.fromisoformat(expires_at) + except (ValueError, TypeError): + return None + if exp_dt.tzinfo is None: + exp_dt = exp_dt.replace(tzinfo=timezone.utc) + remaining = int((exp_dt - datetime.now(timezone.utc)).total_seconds()) + return remaining if remaining > 0 else None + + async def approve_mcp_server( prisma_client: PrismaClient, server_id: str, @@ -1283,9 +1284,7 @@ async def get_mcp_submissions( for item in items: decrypt_global_env_var_values(item.env_vars) - pending = sum( - 1 for i in items if i.approval_status == MCPApprovalStatus.pending_review - ) + pending = sum(1 for i in items if i.approval_status == MCPApprovalStatus.pending_review) active = sum(1 for i in items if i.approval_status == MCPApprovalStatus.active) rejected = sum(1 for i in items if i.approval_status == MCPApprovalStatus.rejected) @@ -1352,9 +1351,7 @@ async def get_user_env_vars_bulk( ids = list(server_ids) if not ids: return {} - rows = await prisma_client.db.litellm_mcpuserenvvars.find_many( - where={"user_id": user_id, "server_id": {"in": ids}} - ) + rows = await prisma_client.db.litellm_mcpuserenvvars.find_many(where={"user_id": user_id, "server_id": {"in": ids}}) return {row.server_id: _decode_user_env_vars(row.values_b64) for row in rows} @@ -1411,6 +1408,4 @@ async def delete_user_env_vars( Uses ``delete_many`` so a missing row is a no-op; real DB errors still propagate to the caller instead of being silently swallowed. """ - await prisma_client.db.litellm_mcpuserenvvars.delete_many( - where={"user_id": user_id, "server_id": server_id} - ) + await prisma_client.db.litellm_mcpuserenvvars.delete_many(where={"user_id": user_id, "server_id": server_id}) diff --git a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py index 3beddd2c4354..7a8df83f9f9e 100644 --- a/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/discoverable_endpoints.py @@ -50,9 +50,7 @@ def _prune_oauth_metadata_cache(now: Optional[float] = None) -> None: now = now if now is not None else time.time() expired_cache_keys = [ - cache_key - for cache_key, (expires_at, _payload) in _OAUTH_METADATA_CACHE.items() - if expires_at <= now + cache_key for cache_key, (expires_at, _payload) in _OAUTH_METADATA_CACHE.items() if expires_at <= now ] for cache_key in expired_cache_keys: _OAUTH_METADATA_CACHE.pop(cache_key, None) @@ -130,9 +128,7 @@ def decode_state_hash(encrypted_state: str) -> dict: return state_data -def _get_validated_client_redirect_uri( - request: Request, state_data: Dict[str, Any] -) -> str: +def _get_validated_client_redirect_uri(request: Request, state_data: Dict[str, Any]) -> str: """Return a trusted (same-origin, loopback, or ops-allowlisted) client redirect URI from OAuth state. """ @@ -217,24 +213,17 @@ def _validate_token_response( "error": "token_validation_failed", "server_id": server_id, "field": key, - "message": ( - f"OAuth token rejected: required field '{key}' is absent" - ), + "message": (f"OAuth token rejected: required field '{key}' is absent"), }, ) - if _normalize_for_token_comparison(actual) != _normalize_for_token_comparison( - expected - ): + if _normalize_for_token_comparison(actual) != _normalize_for_token_comparison(expected): raise HTTPException( status_code=403, detail={ "error": "token_validation_failed", "server_id": server_id, "field": key, - "message": ( - f"OAuth token rejected: '{key}' = '{actual}', " - f"expected '{expected}'" - ), + "message": (f"OAuth token rejected: '{key}' = '{actual}', expected '{expected}'"), }, ) @@ -247,9 +236,7 @@ async def _extract_user_id_from_request(request: Request) -> Optional[str]: auth pipeline (which has side effects such as rate-limit increments and spend logging). Returns ``None`` if no cached credential is found. """ - auth_header = request.headers.get("Authorization") or request.headers.get( - "authorization" - ) + auth_header = request.headers.get("Authorization") or request.headers.get("authorization") if not auth_header: return None lower = auth_header.lower() @@ -289,22 +276,16 @@ async def _store_per_user_token_server_side( raw_expires = token_response.get("expires_in") try: - expires_in: Optional[int] = ( - int(raw_expires) if raw_expires is not None else None - ) + expires_in: Optional[int] = int(raw_expires) if raw_expires is not None else None except (TypeError, ValueError): expires_in = None refresh_token: Optional[str] = token_response.get("refresh_token") or None raw_scope = token_response.get("scope") - scopes: Optional[list] = ( - raw_scope.split() if isinstance(raw_scope, str) and raw_scope else None - ) + scopes: Optional[list] = raw_scope.split() if isinstance(raw_scope, str) and raw_scope else None try: - prisma_client = get_prisma_client_or_throw( - "Database not connected. Cannot store per-user OAuth token." - ) + prisma_client = get_prisma_client_or_throw("Database not connected. Cannot store per-user OAuth token.") from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 store_user_oauth_credential, ) @@ -356,9 +337,7 @@ async def authorize_with_server( if mcp_server.auth_type != "oauth2": raise HTTPException(status_code=400, detail="MCP server is not OAuth2") if mcp_server.authorization_url is None: - raise HTTPException( - status_code=400, detail="MCP server authorization url is not set" - ) + raise HTTPException(status_code=400, detail="MCP server authorization url is not set") # Trusted redirect_uri: same-origin, loopback, or ops-allowlisted. # The URI is encrypted into the OAuth state and decoded on @@ -418,9 +397,7 @@ async def exchange_token_with_server( raise HTTPException(status_code=400, detail="MCP server token url is not set") resolved_client_id = mcp_server.client_id if mcp_server.client_id else client_id - resolved_client_secret = ( - mcp_server.client_secret if mcp_server.client_secret else client_secret - ) + resolved_client_secret = mcp_server.client_secret if mcp_server.client_secret else client_secret if grant_type == "refresh_token": if not refresh_token: @@ -494,8 +471,7 @@ async def exchange_token_with_server( ) except Exception as exc: verbose_logger.warning( - "exchange_token_with_server: server-side storage failed " - "for user=%s server=%s: %s", + "exchange_token_with_server: server-side storage failed for user=%s server=%s: %s", user_id, mcp_server.server_id, exc, @@ -545,9 +521,7 @@ async def register_client_with_server( return dummy_return if mcp_server.authorization_url is None: - raise HTTPException( - status_code=400, detail="MCP server authorization url is not set" - ) + raise HTTPException(status_code=400, detail="MCP server authorization url is not set") if mcp_server.registration_url is None: return dummy_return @@ -564,9 +538,7 @@ async def register_client_with_server( "Accept": "application/json", } - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.Oauth2Register - ) + async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Register) response = await async_client.post( mcp_server.registration_url, headers=headers, @@ -605,11 +577,7 @@ async def authorize( lookup_name: Optional[str] = mcp_server_name or client_id client_ip = IPAddressUtils.get_mcp_client_ip(request) mcp_server = ( - global_mcp_server_manager.get_mcp_server_by_name( - lookup_name, client_ip=client_ip - ) - if lookup_name - else None + global_mcp_server_manager.get_mcp_server_by_name(lookup_name, client_ip=client_ip) if lookup_name else None ) if mcp_server is None and mcp_server_name is None: mcp_server = _resolve_oauth2_server_for_root_endpoints(client_ip=client_ip) @@ -670,9 +638,7 @@ async def token_endpoint( lookup_name = mcp_server_name or client_id client_ip = IPAddressUtils.get_mcp_client_ip(request) - mcp_server = global_mcp_server_manager.get_mcp_server_by_name( - lookup_name, client_ip=client_ip - ) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name(lookup_name, client_ip=client_ip) if mcp_server is None and mcp_server_name is None: mcp_server = _resolve_oauth2_server_for_root_endpoints(client_ip=client_ip) if mcp_server is None: @@ -781,9 +747,7 @@ async def callback( # 2. Neither success nor error parameters present — most likely a stray # GET / dropped SSO redirect chain. Surface a 400 instead of 422. if not code or not state: - missing = [ - name for name, value in (("code", code), ("state", state)) if not value - ] + missing = [name for name, value in (("code", code), ("state", state)) if not value] return _render_oauth_error_html( "invalid_request", f"Missing authorization {' and '.join(repr(m) for m in missing)} parameter(s).", @@ -811,9 +775,7 @@ async def callback( # a generic "authentication incomplete" redirect. raise except Exception: - return HTMLResponse( - "Authentication incomplete. You can close this window." - ) + return HTMLResponse("Authentication incomplete. You can close this window.") # ------------------------------ @@ -880,14 +842,9 @@ async def fetch_upstream_oauth_protected_resource( candidates = [f"{host_base}/.well-known/oauth-protected-resource"] # RFC 9728 §3.1 path fallback if upstream.path and upstream.path not in ("", "/"): - candidates.append( - f"{host_base}/.well-known/oauth-protected-resource" - f"{upstream.path.rstrip('/')}" - ) + candidates.append(f"{host_base}/.well-known/oauth-protected-resource{upstream.path.rstrip('/')}") - async_client = get_async_httpx_client( - llm_provider=httpxSpecialProvider.Oauth2Check - ) + async_client = get_async_httpx_client(llm_provider=httpxSpecialProvider.Oauth2Check) network_errors: list[Exception] = [] for candidate in candidates: @@ -988,9 +945,7 @@ async def _build_oauth_protected_resource_response( mcp_server: Optional[MCPServer] = None if mcp_server_name: - mcp_server = global_mcp_server_manager.get_mcp_server_by_name( - mcp_server_name, client_ip=client_ip - ) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name, client_ip=client_ip) # Build resource URL based on the pattern if mcp_server_name: @@ -1007,9 +962,7 @@ async def _build_oauth_protected_resource_response( # directs the client at the real IdP (Okta, Keycloak, …) instead of us. if mcp_server is not None and mcp_server.is_oauth_passthrough: try: - upstream_metadata = await fetch_upstream_oauth_protected_resource( - mcp_server - ) + upstream_metadata = await fetch_upstream_oauth_protected_resource(mcp_server) except Exception as exc: verbose_logger.warning( "Failed to fetch upstream oauth-protected-resource metadata " @@ -1018,8 +971,7 @@ async def _build_oauth_protected_resource_response( raise HTTPException( status_code=502, detail=( - "Failed to fetch upstream oauth-protected-resource " - f"metadata for MCP server {mcp_server.name!r}" + f"Failed to fetch upstream oauth-protected-resource metadata for MCP server {mcp_server.name!r}" ), ) @@ -1032,29 +984,19 @@ async def _build_oauth_protected_resource_response( # so we must not fall through to the default gateway metadata — # that would point clients at the wrong IdP. verbose_logger.warning( - "Upstream oauth-protected-resource metadata unavailable for " - f"pass-through MCP server {mcp_server.name!r}" + f"Upstream oauth-protected-resource metadata unavailable for pass-through MCP server {mcp_server.name!r}" ) raise HTTPException( status_code=502, - detail=( - "Upstream oauth-protected-resource metadata unavailable " - f"for MCP server {mcp_server.name!r}" - ), + detail=(f"Upstream oauth-protected-resource metadata unavailable for MCP server {mcp_server.name!r}"), ) return { "authorization_servers": [ - ( - f"{request_base_url}/{mcp_server_name}" - if mcp_server_name - else f"{request_base_url}" - ) + (f"{request_base_url}/{mcp_server_name}" if mcp_server_name else f"{request_base_url}") ], "resource": resource_url, - "scopes_supported": ( - mcp_server.scopes if mcp_server and mcp_server.scopes else [] - ), + "scopes_supported": (mcp_server.scopes if mcp_server and mcp_server.scopes else []), } @@ -1086,9 +1028,7 @@ async def oauth_protected_resource_mcp_standard(request: Request, mcp_server_nam f"/.well-known/oauth-protected-resource{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}/mcp" ) @router.get("/.well-known/oauth-protected-resource") -async def oauth_protected_resource_mcp( - request: Request, mcp_server_name: Optional[str] = None -): +async def oauth_protected_resource_mcp(request: Request, mcp_server_name: Optional[str] = None): """ OAuth protected resource discovery endpoint using LiteLLM legacy URL pattern. @@ -1129,38 +1069,26 @@ def _build_oauth_authorization_server_response( mcp_server_name = resolved.server_name or resolved.name authorization_endpoint = ( - f"{request_base_url}/{mcp_server_name}/authorize" - if mcp_server_name - else f"{request_base_url}/authorize" - ) - token_endpoint = ( - f"{request_base_url}/{mcp_server_name}/token" - if mcp_server_name - else f"{request_base_url}/token" + f"{request_base_url}/{mcp_server_name}/authorize" if mcp_server_name else f"{request_base_url}/authorize" ) + token_endpoint = f"{request_base_url}/{mcp_server_name}/token" if mcp_server_name else f"{request_base_url}/token" mcp_server: Optional[MCPServer] = None if mcp_server_name: - mcp_server = global_mcp_server_manager.get_mcp_server_by_name( - mcp_server_name, client_ip=client_ip - ) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name, client_ip=client_ip) return { "issuer": request_base_url, # point to your proxy "authorization_endpoint": authorization_endpoint, "token_endpoint": token_endpoint, "response_types_supported": ["code"], - "scopes_supported": ( - mcp_server.scopes if mcp_server and mcp_server.scopes else [] - ), + "scopes_supported": (mcp_server.scopes if mcp_server and mcp_server.scopes else []), "grant_types_supported": ["authorization_code", "refresh_token"], "code_challenge_methods_supported": ["S256"], "token_endpoint_auth_methods_supported": ["client_secret_post"], # Claude expects a registration endpoint, even if we just fake it "registration_endpoint": ( - f"{request_base_url}/{mcp_server_name}/register" - if mcp_server_name - else f"{request_base_url}/register" + f"{request_base_url}/{mcp_server_name}/register" if mcp_server_name else f"{request_base_url}/register" ), } @@ -1169,9 +1097,7 @@ def _build_oauth_authorization_server_response( @router.get( f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/mcp/{{mcp_server_name}}" ) -async def oauth_authorization_server_mcp_standard( - request: Request, mcp_server_name: str -): +async def oauth_authorization_server_mcp_standard(request: Request, mcp_server_name: str): """ OAuth authorization server discovery endpoint using standard MCP URL pattern. @@ -1189,9 +1115,7 @@ async def oauth_authorization_server_mcp_standard( f"/.well-known/oauth-authorization-server{'' if get_server_root_path() == '/' else get_server_root_path()}/{{mcp_server_name}}" ) @router.get("/.well-known/oauth-authorization-server") -async def oauth_authorization_server_mcp( - request: Request, mcp_server_name: Optional[str] = None -): +async def oauth_authorization_server_mcp(request: Request, mcp_server_name: Optional[str] = None): """ OAuth authorization server discovery endpoint. @@ -1307,9 +1231,7 @@ async def register_client(request: Request, mcp_server_name: Optional[str] = Non ) return dummy_return - mcp_server = global_mcp_server_manager.get_mcp_server_by_name( - mcp_server_name, client_ip=client_ip - ) + mcp_server = global_mcp_server_manager.get_mcp_server_by_name(mcp_server_name, client_ip=client_ip) if mcp_server is None: return dummy_return return await register_client_with_server( diff --git a/litellm/proxy/_experimental/mcp_server/elicitation_handler.py b/litellm/proxy/_experimental/mcp_server/elicitation_handler.py index e42270bf10bd..030f4dfeca68 100644 --- a/litellm/proxy/_experimental/mcp_server/elicitation_handler.py +++ b/litellm/proxy/_experimental/mcp_server/elicitation_handler.py @@ -70,9 +70,7 @@ async def handle_elicitation_request( ) # No downstream session — we're in Tool Bridge mode # or the client doesn't support elicitation - verbose_logger.info( - "MCP elicitation: no downstream session available, declining" - ) + verbose_logger.info("MCP elicitation: no downstream session available, declining") return ElicitResult( action="decline", ) @@ -105,23 +103,17 @@ async def _relay_elicitation_to_downstream( if downstream_capabilities is not None: elicit_caps = getattr(downstream_capabilities, "elicitation", None) if elicit_caps is None: - verbose_logger.info( - "MCP elicitation: downstream client does not support elicitation" - ) + verbose_logger.info("MCP elicitation: downstream client does not support elicitation") return ElicitResult(action="decline") if mode == "url": url_cap = getattr(elicit_caps, "url", None) if url_cap is None: - verbose_logger.info( - "MCP elicitation: downstream client does not support URL mode" - ) + verbose_logger.info("MCP elicitation: downstream client does not support URL mode") return ElicitResult(action="decline") if mode == "form": form_cap = getattr(elicit_caps, "form", None) if form_cap is None: - verbose_logger.info( - "MCP elicitation: downstream client does not support form mode" - ) + verbose_logger.info("MCP elicitation: downstream client does not support form mode") return ElicitResult(action="decline") try: if mode == "url" and isinstance(params, ElicitRequestURLParams): @@ -145,9 +137,7 @@ async def _relay_elicitation_to_downstream( else: # Fallback for generic ElicitRequestParams — pass an empty schema # since elicit() requires requestedSchema as a positional arg. - verbose_logger.info( - "MCP elicitation: relaying generic elicitation to downstream" - ) + verbose_logger.info("MCP elicitation: relaying generic elicitation to downstream") result = await downstream_session.elicit( message=getattr(params, "message", ""), requestedSchema=getattr(params, "requestedSchema", {}), diff --git a/litellm/proxy/_experimental/mcp_server/exceptions.py b/litellm/proxy/_experimental/mcp_server/exceptions.py index a00e797a6bdb..b3f7ca9bbe2e 100644 --- a/litellm/proxy/_experimental/mcp_server/exceptions.py +++ b/litellm/proxy/_experimental/mcp_server/exceptions.py @@ -63,15 +63,9 @@ def to_http_exception( if challenge is None and self.status_code == 401 and base_url: prefix = base_url.rstrip("/") if request_path and request_path.startswith(f"/{self.server_name}/mcp"): - resource_metadata_url = ( - f"{prefix}/.well-known/oauth-protected-resource/" - f"{self.server_name}/mcp" - ) + resource_metadata_url = f"{prefix}/.well-known/oauth-protected-resource/{self.server_name}/mcp" else: - resource_metadata_url = ( - f"{prefix}/.well-known/oauth-protected-resource/" - f"mcp/{self.server_name}" - ) + resource_metadata_url = f"{prefix}/.well-known/oauth-protected-resource/mcp/{self.server_name}" challenge = f'Bearer resource_metadata="{resource_metadata_url}"' detail = "Forbidden" if self.status_code == 403 else "Unauthorized" return HTTPException( diff --git a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py index 6997f5241de9..b668833e638b 100644 --- a/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py +++ b/litellm/proxy/_experimental/mcp_server/guardrail_translation/handler.py @@ -41,9 +41,7 @@ async def process_input_messages( ) -> Dict[str, Any]: mcp_tool_name = data.get("mcp_tool_name") or data.get("name") mcp_arguments = data.get("mcp_arguments") or data.get("arguments") - mcp_tool_description = data.get("mcp_tool_description") or data.get( - "description" - ) + mcp_tool_description = data.get("mcp_tool_description") or data.get("description") if mcp_arguments is None or not isinstance(mcp_arguments, dict): mcp_arguments = {} diff --git a/litellm/proxy/_experimental/mcp_server/mcp_context.py b/litellm/proxy/_experimental/mcp_server/mcp_context.py index 519185094414..8a85c0c516b6 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_context.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_context.py @@ -11,9 +11,7 @@ # Set server-side in proxy_server.py route handlers when a request arrives via # /toolset/{name}/mcp or the toolset fallback in dynamic_mcp_route. # Never populated from client-supplied headers. -_mcp_active_toolset_id: ContextVar[Optional[str]] = ContextVar( - "_mcp_active_toolset_id", default=None -) +_mcp_active_toolset_id: ContextVar[Optional[str]] = ContextVar("_mcp_active_toolset_id", default=None) # Per-request merged InitializeResult.instructions; set in MCP HTTP/SSE handlers. _mcp_gateway_initialize_instructions: ContextVar[Optional[str]] = ContextVar( @@ -22,6 +20,4 @@ # Per-request scoped server name; set in MCP HTTP/SSE handlers when the path # identifies exactly one upstream server. Never populated from client-supplied headers. -_mcp_gateway_server_name: ContextVar[Optional[str]] = ContextVar( - "_mcp_gateway_server_name", default=None -) +_mcp_gateway_server_name: ContextVar[Optional[str]] = ContextVar("_mcp_gateway_server_name", default=None) diff --git a/litellm/proxy/_experimental/mcp_server/mcp_debug.py b/litellm/proxy/_experimental/mcp_server/mcp_debug.py index 254f208e2312..42e2b17d6970 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_debug.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_debug.py @@ -162,8 +162,7 @@ def resolve_auth_resolution( has_server_specific = bool( mcp_server_auth_headers and ( - mcp_server_auth_headers.get(server.alias or "") - or mcp_server_auth_headers.get(server.server_name or "") + mcp_server_auth_headers.get(server.alias or "") or mcp_server_auth_headers.get(server.server_name or "") ) ) if has_server_specific or mcp_auth_header: @@ -219,9 +218,7 @@ def build_debug_headers( if k.lower() == hdr_name: inbound_parts.append(f"{hdr_name}={MCPDebug._mask(v)}") break - debug[f"{_RESPONSE_HEADER_PREFIX}-inbound-auth"] = ( - "; ".join(inbound_parts) if inbound_parts else "(none)" - ) + debug[f"{_RESPONSE_HEADER_PREFIX}-inbound-auth"] = "; ".join(inbound_parts) if inbound_parts else "(none)" # --- OAuth2 token --- oauth2_token = (oauth2_headers or {}).get("Authorization") @@ -230,26 +227,19 @@ def build_debug_headers( litellm_raw = litellm_api_key.removeprefix("Bearer ").strip() if oauth2_raw == litellm_raw: debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = ( - f"{MCPDebug._mask(oauth2_token)} " - f"(SAME_AS_LITELLM_KEY - likely misconfigured)" + f"{MCPDebug._mask(oauth2_token)} (SAME_AS_LITELLM_KEY - likely misconfigured)" ) else: - debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask( - oauth2_token - ) + debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask(oauth2_token) else: - debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask( - oauth2_token - ) + debug[f"{_RESPONSE_HEADER_PREFIX}-oauth2-token"] = MCPDebug._mask(oauth2_token) # --- Auth resolution --- debug[f"{_RESPONSE_HEADER_PREFIX}-auth-resolution"] = auth_resolution # --- Server info --- debug[f"{_RESPONSE_HEADER_PREFIX}-outbound-url"] = server_url or "(unknown)" - debug[f"{_RESPONSE_HEADER_PREFIX}-server-auth-type"] = ( - server_auth_type or "(none)" - ) + debug[f"{_RESPONSE_HEADER_PREFIX}-server-auth-type"] = server_auth_type or "(none)" return debug @@ -301,9 +291,7 @@ def maybe_build_debug_headers( auth_resolution = "no-auth" for server_name in mcp_servers or []: - server = global_mcp_server_manager.get_mcp_server_by_name( - server_name, client_ip=client_ip - ) + server = global_mcp_server_manager.get_mcp_server_by_name(server_name, client_ip=client_ip) if server: server_url = server.url server_auth_type = server.auth_type diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py index b9e0379e4451..cb9f4685bfd4 100644 --- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py +++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py @@ -63,9 +63,16 @@ ) from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import ( raise_public, + raise_user_oauth_challenge, to_server_spec, to_subject, ) +from litellm.proxy._experimental.mcp_server.outbound_credentials.per_user_oauth_store import ( + LazyPerUserOAuthTokenStore, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( + AuthorizationCodeConfig, +) from litellm.proxy._experimental.mcp_server.utils import ( MCP_TOOL_PREFIX_SEPARATOR, MCPMissingUserEnvVarsError, @@ -96,6 +103,7 @@ ) from litellm.proxy.auth.ip_address_utils import IPAddressUtils from litellm.proxy.common_utils.encrypt_decrypt_utils import decrypt_value_helper +from litellm.proxy.common_utils.user_api_key_cache import get_management_object_ttl from litellm.proxy.utils import ProxyLogging from litellm.repositories.table_repositories import MCPServerRepository from litellm.types.llms.custom_http import httpxSpecialProvider @@ -158,9 +166,7 @@ def invalidate_user_env_vars_cache(user_id: str, server_id: str) -> None: _user_env_vars_cache.pop((user_id, server_id), None) -def _write_user_env_vars_cache( - user_id: str, server_id: str, values: Dict[str, str] -) -> None: +def _write_user_env_vars_cache(user_id: str, server_id: str, values: Dict[str, str]) -> None: cache_key = (user_id, server_id) # Re-insert at the tail so eviction drops the oldest-written entry, not a # freshly refreshed one, and only sheds a single entry instead of wiping the @@ -186,6 +192,10 @@ def _should_strip_caller_authorization( Strip rules: - **M2M (client_credentials) servers**: never forward the caller's ``Authorization`` — the proxy fetches its own upstream token. + - **Migrated per-user OAuth (authorization_code) servers**: never forward + the caller's ``Authorization`` — the v2 resolver injects the stored + per-user token, so a caller-supplied bearer cannot override another + user's stored credential. Delegate / pass-through keep forwarding it. - **OAuth pass-through servers**: strip when the ``Authorization`` header is actually the LiteLLM API key — either because admission validated it (``user_api_key_auth.api_key`` is set) and the caller @@ -198,15 +208,17 @@ def _should_strip_caller_authorization( """ if mcp_server.has_client_credentials: return True + if mcp_server.auth_type == MCPAuth.oauth2 and to_server_spec(mcp_server) is not None: + # Migrated per-user OAuth (authorization_code): the v2 resolver injects the + # stored token, so a caller-forwarded Authorization must not be forwarded + # upstream — it would override another user's stored credential. Delegate and + # pass-through return None from to_server_spec and keep forwarding the bearer. + return True if not mcp_server.is_oauth_passthrough: return False - normalized_raw_headers = { - str(k).lower(): v for k, v in (raw_headers or {}).items() if isinstance(k, str) - } - has_explicit_litellm_admission_header = ( - normalized_raw_headers.get("x-litellm-api-key") is not None - ) + normalized_raw_headers = {str(k).lower(): v for k, v in (raw_headers or {}).items() if isinstance(k, str)} + has_explicit_litellm_admission_header = normalized_raw_headers.get("x-litellm-api-key") is not None admission_consumed_authorization_as_litellm_key = ( user_api_key_auth is not None and bool(getattr(user_api_key_auth, "api_key", None)) @@ -217,6 +229,18 @@ def _should_strip_caller_authorization( ) +def _without_authorization( + headers: Optional[dict[str, str]], +) -> Optional[dict[str, str]]: + """A copy of ``headers`` with any ``Authorization`` key removed (case-insensitive), or + None if nothing remains. Drops only the credential, keeping other forwarded headers. + """ + if not headers: + return None + filtered = {k: v for k, v in headers.items() if k.lower() != "authorization"} + return filtered or None + + def _extract_upstream_auth_failure( exc: BaseException, ) -> Optional[Tuple[int, Optional[str]]]: @@ -259,10 +283,7 @@ def _extract_upstream_auth_failure( if current.__cause__ is not None: stack.append(current.__cause__) - if ( - current.__context__ is not None - and current.__context__ is not current.__cause__ - ): + if current.__context__ is not None and current.__context__ is not current.__cause__: stack.append(current.__context__) return None @@ -281,9 +302,7 @@ def _warn(field_name: str, value: Optional[str]) -> None: if result.is_valid: return - warning_text = ( - "; ".join(result.warnings) if result.warnings else "Validation failed" - ) + warning_text = "; ".join(result.warnings) if result.warnings else "Validation failed" verbose_logger.warning( "MCP server '%s' has invalid %s '%s': %s", server_id, @@ -296,9 +315,7 @@ def _warn(field_name: str, value: Optional[str]) -> None: _warn("server_name", server_name) -def _warn_internal_delegate_pkce_if_applicable( - server: MCPServer, *, source: str -) -> None: +def _warn_internal_delegate_pkce_if_applicable(server: MCPServer, *, source: str) -> None: """Surface internal + upstream PKCE delegate in logs for operators.""" if server.auth_type != MCPAuth.oauth2: return @@ -360,10 +377,7 @@ def _deserialize_json_list(data: Any) -> Optional[List[Dict[str, Any]]]: data = parsed if not isinstance(data, list): return None - return [ - item.model_dump(mode="json") if hasattr(item, "model_dump") else item - for item in data - ] + return [item.model_dump(mode="json") if hasattr(item, "model_dump") else item for item in data] def _normalize_mcp_server_cost_info(mcp_info: MCPInfo) -> None: @@ -431,9 +445,7 @@ async def _sampling_callback(context, params): ) auth_context = get_active_auth_context() - resolved_auth = user_api_key_auth or ( - auth_context.user_api_key_auth if auth_context else None - ) + resolved_auth = user_api_key_auth or (auth_context.user_api_key_auth if auth_context else None) # Forward original HTTP headers and client IP so that # header-dependent guardrails, tag-based routing, trace # correlation, and forward_llm_provider_auth_headers work @@ -472,11 +484,7 @@ async def _elicitation_callback(context, params): # In Gateway mode, we relay the elicitation request to the downstream client # that triggered the current operation. downstream_session = get_active_mcp_session() - downstream_capabilities = ( - getattr(downstream_session, "capabilities", None) - if downstream_session - else None - ) + downstream_capabilities = getattr(downstream_session, "capabilities", None) if downstream_session else None return await handle_elicitation_request( context=context, @@ -508,9 +516,7 @@ def _resolve_oauth2_flow( unless authorization_url is present (interactive OAuth). """ if oauth2_flow in ("client_credentials", "authorization_code"): - return cast( - Literal["client_credentials", "authorization_code"], oauth2_flow - ) + return cast(Literal["client_credentials", "authorization_code"], oauth2_flow) if oauth2_flow: # Ignore unknown/untyped values and continue legacy inference. return None @@ -523,7 +529,9 @@ def _resolve_oauth2_flow( return None def __init__(self, cred_provider: Optional[UpstreamCredentialProvider] = None): - self._cred_provider = cred_provider or UpstreamCredentialProvider() + self._cred_provider = cred_provider or UpstreamCredentialProvider( + oauth_token_store=LazyPerUserOAuthTokenStore(self.get_mcp_server_by_id) + ) self.registry: Dict[str, MCPServer] = {} self.config_mcp_servers: Dict[str, MCPServer] = {} """ @@ -554,18 +562,12 @@ def __init__(self, cred_provider: Optional[UpstreamCredentialProvider] = None): # not return instructions, and to apply a short cooldown after failures. self._upstream_initialize_instructions_probed_at: Dict[str, float] = {} - def _remember_upstream_initialize_instructions( - self, server: MCPServer, client: MCPClient - ) -> None: + def _remember_upstream_initialize_instructions(self, server: MCPServer, client: MCPClient) -> None: raw = getattr(client, "_last_initialize_instructions", None) if raw and str(raw).strip(): - self._upstream_initialize_instructions_by_server_id[server.server_id] = str( - raw - ).strip() + self._upstream_initialize_instructions_by_server_id[server.server_id] = str(raw).strip() - async def _ensure_upstream_initialize_instructions_cached( - self, server: MCPServer - ) -> None: + async def _ensure_upstream_initialize_instructions_cached(self, server: MCPServer) -> None: """ Open one upstream session and cache InitializeResult.instructions if missing. @@ -600,20 +602,13 @@ async def _ensure_upstream_initialize_instructions_cached( ): return - last_probed_at = self._upstream_initialize_instructions_probed_at.get( - server.server_id - ) - if ( - last_probed_at is not None - and (time.monotonic() - last_probed_at) < MCP_HEALTH_CHECK_TIMEOUT - ): + last_probed_at = self._upstream_initialize_instructions_probed_at.get(server.server_id) + if last_probed_at is not None and (time.monotonic() - last_probed_at) < MCP_HEALTH_CHECK_TIMEOUT: return # Record the attempt up-front so that a failure / empty response does not # cause every subsequent initialize request to re-open the upstream session. - self._upstream_initialize_instructions_probed_at[server.server_id] = ( - time.monotonic() - ) + self._upstream_initialize_instructions_probed_at[server.server_id] = time.monotonic() try: resolved_static_headers = await self._resolve_static_headers_with_env_vars( @@ -621,9 +616,7 @@ async def _ensure_upstream_initialize_instructions_cached( user_api_key_auth=None, raise_on_missing=False, ) - extra_headers: Optional[Dict[str, str]] = ( - dict(resolved_static_headers) if resolved_static_headers else None - ) + extra_headers: Optional[Dict[str, str]] = dict(resolved_static_headers) if resolved_static_headers else None client = await self._create_mcp_client( server=server, mcp_auth_header=None, @@ -634,9 +627,7 @@ async def _ensure_upstream_initialize_instructions_cached( async def _noop(_session): return "ok" - await asyncio.wait_for( - client.run_with_session(_noop), timeout=MCP_HEALTH_CHECK_TIMEOUT - ) + await asyncio.wait_for(client.run_with_session(_noop), timeout=MCP_HEALTH_CHECK_TIMEOUT) self._remember_upstream_initialize_instructions(server, client) except Exception as e: verbose_logger.debug( @@ -689,15 +680,10 @@ async def load_servers_from_config( if mcp_aliases and alias is None: # Check if this server_name has an alias in mcp_aliases for alias_name, target_server_name in mcp_aliases.items(): - if ( - target_server_name == server_name - and alias_name not in used_aliases - ): + if target_server_name == server_name and alias_name not in used_aliases: alias = alias_name used_aliases.add(alias_name) - verbose_logger.debug( - f"Mapped alias '{alias_name}' to server '{server_name}'" - ) + verbose_logger.debug(f"Mapped alias '{alias_name}' to server '{server_name}'") break # Create a temporary server object to use with get_server_prefix utility @@ -732,9 +718,7 @@ async def load_servers_from_config( else: mcp_oauth_metadata = None - resolved_scopes = server_config.get("scopes") or ( - mcp_oauth_metadata.scopes if mcp_oauth_metadata else None - ) + resolved_scopes = server_config.get("scopes") or (mcp_oauth_metadata.scopes if mcp_oauth_metadata else None) resolved_authorization_url = server_config.get("authorization_url") or ( mcp_oauth_metadata.authorization_url if mcp_oauth_metadata else None ) @@ -773,9 +757,7 @@ async def load_servers_from_config( # TODO: utility fn the default values transport=server_config.get("transport", MCPTransport.http), auth_type=auth_type, - authentication_token=server_config.get( - "authentication_token", server_config.get("auth_value", None) - ), + authentication_token=server_config.get("authentication_token", server_config.get("auth_value", None)), mcp_info=mcp_info, extra_headers=server_config.get("extra_headers", None), allowed_tools=server_config.get("allowed_tools", None), @@ -785,12 +767,8 @@ async def load_servers_from_config( static_headers=server_config.get("static_headers", None), env_vars=server_config.get("env_vars", None), allow_all_keys=bool(server_config.get("allow_all_keys", False)), - available_on_public_internet=bool( - server_config.get("available_on_public_internet", True) - ), - delegate_auth_to_upstream=bool( - server_config.get("delegate_auth_to_upstream", False) - ), + available_on_public_internet=bool(server_config.get("available_on_public_internet", True)), + delegate_auth_to_upstream=bool(server_config.get("delegate_auth_to_upstream", False)), oauth_passthrough=bool(server_config.get("oauth_passthrough", False)), # AWS SigV4 fields aws_access_key_id=server_config.get("aws_access_key_id", None), @@ -802,9 +780,7 @@ async def load_servers_from_config( aws_session_name=server_config.get("aws_session_name", None), instructions=server_config.get("instructions", None), # Token Exchange (OBO) fields - token_exchange_endpoint=server_config.get( - "token_exchange_endpoint", None - ), + token_exchange_endpoint=server_config.get("token_exchange_endpoint", None), audience=server_config.get("audience", None), subject_token_type=server_config.get( "subject_token_type", @@ -821,24 +797,18 @@ async def load_servers_from_config( # Check if this is an OpenAPI-based server spec_path = server_config.get("spec_path", None) if spec_path: - verbose_logger.info( - f"Loading OpenAPI spec from {spec_path} for server {server_name}" - ) + verbose_logger.info(f"Loading OpenAPI spec from {spec_path} for server {server_name}") await self._register_openapi_tools( spec_path=spec_path, server=new_server, base_url=server_config.get("url", ""), ) - verbose_logger.debug( - f"Loaded MCP Servers: {json.dumps(self.config_mcp_servers, indent=4, default=str)}" - ) + verbose_logger.debug(f"Loaded MCP Servers: {json.dumps(self.config_mcp_servers, indent=4, default=str)}") self.initialize_tool_name_to_mcp_server_name_mapping() - async def _register_openapi_tools( - self, spec_path: str, server: MCPServer, base_url: str - ): + async def _register_openapi_tools(self, spec_path: str, server: MCPServer, base_url: str): """ Register tools from an OpenAPI specification for a given server. @@ -874,9 +844,7 @@ async def _register_openapi_tools( # Use base_url from config if provided, otherwise extract from spec if not base_url: base_url = get_openapi_base_url(spec, spec_path) - verbose_logger.info( - f"Registering OpenAPI tools for server {server.name} with base URL: {base_url}" - ) + verbose_logger.info(f"Registering OpenAPI tools for server {server.name} with base URL: {base_url}") # Get server prefix for tool naming server_prefix = get_server_prefix(server) @@ -930,20 +898,14 @@ async def _register_openapi_tools( operation = path_item[method] # Resolve $ref params and merge path-level params into the operation. - resolved_operation = resolve_operation_params( - operation, path_item, components - ) + resolved_operation = resolve_operation_params(operation, path_item, components) # Generate tool name (without prefix initially) - operation_id = operation.get( - "operationId", f"{method}_{path.replace('/', '_')}" - ) + operation_id = operation.get("operationId", f"{method}_{path.replace('/', '_')}") base_tool_name = operation_id.replace(" ", "_").lower() # Add server prefix to tool name - prefixed_tool_name = add_server_prefix_to_name( - base_tool_name, server_prefix - ) + prefixed_tool_name = add_server_prefix_to_name(base_tool_name, server_prefix) # Get description description = operation.get( @@ -955,9 +917,7 @@ async def _register_openapi_tools( input_schema = build_input_schema(resolved_operation) # Create tool function with headers using imported function - tool_func = create_tool_function( - path, method, resolved_operation, base_url, headers=headers - ) + tool_func = create_tool_function(path, method, resolved_operation, base_url, headers=headers) tool_func.__name__ = prefixed_tool_name tool_func.__doc__ = description @@ -970,26 +930,16 @@ async def _register_openapi_tools( ) # Update tool name to server name mapping (for both prefixed and base names) - self.tool_name_to_mcp_server_name_mapping[base_tool_name] = ( - server_prefix - ) - self.tool_name_to_mcp_server_name_mapping[prefixed_tool_name] = ( - server_prefix - ) + self.tool_name_to_mcp_server_name_mapping[base_tool_name] = server_prefix + self.tool_name_to_mcp_server_name_mapping[prefixed_tool_name] = server_prefix registered_count += 1 - verbose_logger.debug( - f"Registered OpenAPI tool: {prefixed_tool_name} for server {server.name}" - ) + verbose_logger.debug(f"Registered OpenAPI tool: {prefixed_tool_name} for server {server.name}") - verbose_logger.info( - f"Successfully registered {registered_count} OpenAPI tools for server {server.name}" - ) + verbose_logger.info(f"Successfully registered {registered_count} OpenAPI tools for server {server.name}") except Exception as e: - verbose_logger.error( - f"Failed to register OpenAPI tools for server {server.name}: {str(e)}" - ) + verbose_logger.error(f"Failed to register OpenAPI tools for server {server.name}: {str(e)}") raise e def _cleanup_server_tool_routing_artifacts(self, server: MCPServer) -> None: @@ -1020,9 +970,7 @@ def _cleanup_server_tool_routing_artifacts(self, server: MCPServer) -> None: owned_normalized = {normalize_server_name(x) for x in owned_raw} stale_mapping_keys: List[str] = [] - for tool_name, mapped_server in list( - self.tool_name_to_mcp_server_name_mapping.items() - ): + for tool_name, mapped_server in list(self.tool_name_to_mcp_server_name_mapping.items()): if mapped_server in owned_raw: stale_mapping_keys.append(tool_name) elif normalize_server_name(str(mapped_server)) in owned_normalized: @@ -1039,14 +987,10 @@ def remove_server(self, mcp_server: LiteLLM_MCPServerTable): if evicted is None and mcp_server.server_name: evicted = self.registry.pop(mcp_server.server_name, None) if evicted is not None: - verbose_logger.debug( - "Removed MCP Server: %s", mcp_server.server_id or mcp_server.server_name - ) + verbose_logger.debug("Removed MCP Server: %s", mcp_server.server_id or mcp_server.server_name) self._cleanup_server_tool_routing_artifacts(evicted) else: - verbose_logger.warning( - f"Server ID {mcp_server.server_id} not found in registry" - ) + verbose_logger.warning(f"Server ID {mcp_server.server_id} not found in registry") def _resolve_env_vars_list( self, @@ -1072,20 +1016,14 @@ async def build_mcp_server_from_table( ) -> MCPServer: _mcp_info: MCPInfo = mcp_server.mcp_info or {} env_dict = _deserialize_json_dict(getattr(mcp_server, "env", None)) - static_headers_dict = _deserialize_json_dict( - getattr(mcp_server, "static_headers", None) - ) + static_headers_dict = _deserialize_json_dict(getattr(mcp_server, "static_headers", None)) env_vars_list = self._resolve_env_vars_list( mcp_server, env_vars_are_encrypted=( - credentials_are_encrypted - if env_vars_are_encrypted is None - else env_vars_are_encrypted + credentials_are_encrypted if env_vars_are_encrypted is None else env_vars_are_encrypted ), ) - credentials_dict = _deserialize_json_dict( - getattr(mcp_server, "credentials", None) - ) + credentials_dict = _deserialize_json_dict(getattr(mcp_server, "credentials", None)) encrypted_auth_value: Optional[str] = None encrypted_client_id: Optional[str] = None @@ -1132,9 +1070,7 @@ async def build_mcp_server_from_table( client_secret_value = encrypted_client_secret # AWS SigV4 credential fields - aws_creds = self._extract_aws_credentials( - credentials_dict, credentials_are_encrypted - ) + aws_creds = self._extract_aws_credentials(credentials_dict, credentials_are_encrypted) scopes: Optional[List[str]] = None if credentials_dict: @@ -1142,9 +1078,7 @@ async def build_mcp_server_from_table( if scopes_value is not None: scopes = self._extract_scopes(scopes_value) - name_for_prefix = ( - mcp_server.alias or mcp_server.server_name or mcp_server.server_id - ) + name_for_prefix = mcp_server.alias or mcp_server.server_name or mcp_server.server_id mcp_info: MCPInfo = _mcp_info.copy() if "server_name" not in mcp_info: @@ -1155,20 +1089,14 @@ async def build_mcp_server_from_table( auth_type = cast(MCPAuthType, mcp_server.auth_type) server_url = mcp_server.url - needs_discovery = ( - bool(server_url) - and auth_type == MCPAuth.oauth2 - and not mcp_server.authorization_url - ) + needs_discovery = bool(server_url) and auth_type == MCPAuth.oauth2 and not mcp_server.authorization_url mcp_oauth_metadata = ( await self._descovery_metadata(server_url=server_url) # type: ignore[arg-type] if needs_discovery else None ) - resolved_scopes = scopes or ( - mcp_oauth_metadata.scopes if mcp_oauth_metadata else None - ) + resolved_scopes = scopes or (mcp_oauth_metadata.scopes if mcp_oauth_metadata else None) new_server = MCPServer( server_id=mcp_server.server_id, @@ -1185,26 +1113,20 @@ async def build_mcp_server_from_table( static_headers=static_headers_dict, env_vars=env_vars_list, client_id=client_id_value or getattr(mcp_server, "client_id", None), - client_secret=client_secret_value - or getattr(mcp_server, "client_secret", None), + client_secret=client_secret_value or getattr(mcp_server, "client_secret", None), oauth2_flow=self._resolve_oauth2_flow( auth_type=auth_type, oauth2_flow=getattr(mcp_server, "oauth2_flow", None), - token_url=mcp_server.token_url - or getattr(mcp_oauth_metadata, "token_url", None), + token_url=mcp_server.token_url or getattr(mcp_oauth_metadata, "token_url", None), authorization_url=mcp_server.authorization_url or getattr(mcp_oauth_metadata, "authorization_url", None), client_id=client_id_value or getattr(mcp_server, "client_id", None), - client_secret=client_secret_value - or getattr(mcp_server, "client_secret", None), + client_secret=client_secret_value or getattr(mcp_server, "client_secret", None), ), scopes=resolved_scopes, - authorization_url=mcp_server.authorization_url - or getattr(mcp_oauth_metadata, "authorization_url", None), - token_url=mcp_server.token_url - or getattr(mcp_oauth_metadata, "token_url", None), - registration_url=mcp_server.registration_url - or getattr(mcp_oauth_metadata, "registration_url", None), + authorization_url=mcp_server.authorization_url or getattr(mcp_oauth_metadata, "authorization_url", None), + token_url=mcp_server.token_url or getattr(mcp_oauth_metadata, "token_url", None), + registration_url=mcp_server.registration_url or getattr(mcp_oauth_metadata, "registration_url", None), command=getattr(mcp_server, "command", None), args=getattr(mcp_server, "args", None) or [], env=env_dict, @@ -1212,21 +1134,13 @@ async def build_mcp_server_from_table( allowed_tools=getattr(mcp_server, "allowed_tools", None), disallowed_tools=getattr(mcp_server, "disallowed_tools", None), allow_all_keys=mcp_server.allow_all_keys, - available_on_public_internet=bool( - getattr(mcp_server, "available_on_public_internet", True) - ), - delegate_auth_to_upstream=bool( - getattr(mcp_server, "delegate_auth_to_upstream", False) - ), + available_on_public_internet=bool(getattr(mcp_server, "available_on_public_internet", True)), + delegate_auth_to_upstream=bool(getattr(mcp_server, "delegate_auth_to_upstream", False)), oauth_passthrough=bool(getattr(mcp_server, "oauth_passthrough", False)), created_at=getattr(mcp_server, "created_at", None), updated_at=getattr(mcp_server, "updated_at", None), - tool_name_to_display_name=_deserialize_json_dict( - getattr(mcp_server, "tool_name_to_display_name", None) - ), - tool_name_to_description=_deserialize_json_dict( - getattr(mcp_server, "tool_name_to_description", None) - ), + tool_name_to_display_name=_deserialize_json_dict(getattr(mcp_server, "tool_name_to_display_name", None)), + tool_name_to_description=_deserialize_json_dict(getattr(mcp_server, "tool_name_to_description", None)), is_byok=bool(getattr(mcp_server, "is_byok", False)), byok_description=getattr(mcp_server, "byok_description", None) or [], byok_api_key_help_url=getattr(mcp_server, "byok_api_key_help_url", None), @@ -1241,29 +1155,19 @@ async def build_mcp_server_from_table( aws_session_name=aws_creds.get("aws_session_name"), instructions=mcp_server.instructions, # Token Exchange (OBO) fields — read from credentials JSON blob - token_exchange_endpoint=( - credentials_dict.get("token_exchange_endpoint") - if credentials_dict - else None - ), + token_exchange_endpoint=(credentials_dict.get("token_exchange_endpoint") if credentials_dict else None), audience=(credentials_dict.get("audience") if credentials_dict else None), - subject_token_type=( - credentials_dict.get("subject_token_type") if credentials_dict else None - ) + subject_token_type=(credentials_dict.get("subject_token_type") if credentials_dict else None) or "urn:ietf:params:oauth:token-type:access_token", timeout=getattr(mcp_server, "timeout", None), ) _warn_internal_delegate_pkce_if_applicable(new_server, source="database") return new_server - async def _maybe_register_openapi_tools( - self, server: MCPServer, *, initialize_mapping: bool = True - ): + async def _maybe_register_openapi_tools(self, server: MCPServer, *, initialize_mapping: bool = True): """Register OpenAPI tools if the server has a spec_path configured.""" if server.spec_path: - verbose_logger.info( - f"Loading OpenAPI spec from {server.spec_path} for server {server.name}" - ) + verbose_logger.info(f"Loading OpenAPI spec from {server.spec_path} for server {server.name}") await self._register_openapi_tools( spec_path=server.spec_path, server=server, @@ -1287,9 +1191,7 @@ async def add_server(self, mcp_server: LiteLLM_MCPServerTable): # `credentials` field is the only one still encrypted here). # Re-decrypting plaintext would zero the values, so build with # env_vars_are_encrypted=False. - new_server = await self.build_mcp_server_from_table( - mcp_server, env_vars_are_encrypted=False - ) + new_server = await self.build_mcp_server_from_table(mcp_server, env_vars_are_encrypted=False) self._assign_unique_short_prefix(new_server) self.registry[mcp_server.server_id] = new_server await self._maybe_register_openapi_tools(new_server) @@ -1314,9 +1216,7 @@ async def update_server(self, mcp_server: LiteLLM_MCPServerTable): if mcp_server.server_id in self.registry: # See add_server: db.py helpers already decrypted env var # values, so don't decrypt them a second time here. - new_server = await self.build_mcp_server_from_table( - mcp_server, env_vars_are_encrypted=False - ) + new_server = await self.build_mcp_server_from_table(mcp_server, env_vars_are_encrypted=False) # Carry the previously-resolved short prefix across so the # tool names stay stable for clients holding cached lists. existing_prefix = self.registry[mcp_server.server_id].short_prefix @@ -1340,15 +1240,9 @@ def get_all_mcp_server_ids(self) -> Set[str]: def get_allow_all_keys_server_ids(self) -> List[str]: """Return server IDs that bypass per-key restrictions.""" - return [ - server.server_id - for server in self.get_registry().values() - if server.allow_all_keys is True - ] + return [server.server_id for server in self.get_registry().values() if server.allow_all_keys is True] - async def get_allowed_mcp_servers( - self, user_api_key_auth: Optional[UserAPIKeyAuth] = None - ) -> List[str]: + async def get_allowed_mcp_servers(self, user_api_key_auth: Optional[UserAPIKeyAuth] = None) -> List[str]: """ Get the allowed MCP Servers for the user. @@ -1364,12 +1258,9 @@ async def get_allowed_mcp_servers( try: # The key explicitly opted out of every MCP server. Return zero before # layering on allow_all_keys servers so the opt-out is absolute. - key_object_permission = ( - user_api_key_auth.object_permission if user_api_key_auth else None - ) + key_object_permission = user_api_key_auth.object_permission if user_api_key_auth else None if key_object_permission is not None and ( - SpecialMCPServerNames.no_mcp_servers.value - in (key_object_permission.mcp_servers or []) + SpecialMCPServerNames.no_mcp_servers.value in (key_object_permission.mcp_servers or []) ): return [] @@ -1384,23 +1275,13 @@ async def get_allowed_mcp_servers( ) # If admin but NO explicit object permission, get all servers - if ( - user_api_key_auth - and _user_has_admin_view(user_api_key_auth) - and not has_explicit_object_permission - ): - verbose_logger.debug( - "Admin user without explicit object_permission - returning all servers" - ) + if user_api_key_auth and _user_has_admin_view(user_api_key_auth) and not has_explicit_object_permission: + verbose_logger.debug("Admin user without explicit object_permission - returning all servers") return list(self.get_registry().keys()) # Get allowed servers from object permissions (respects object_permission even for admins) - allowed_mcp_servers = await MCPRequestHandler.get_allowed_mcp_servers( - user_api_key_auth - ) - verbose_logger.debug( - f"Allowed MCP Servers for user api key auth: {allowed_mcp_servers}" - ) + allowed_mcp_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_api_key_auth) + verbose_logger.debug(f"Allowed MCP Servers for user api key auth: {allowed_mcp_servers}") combined_servers = set(allowed_mcp_servers) # Only skip allow_all_keys servers when the request is inside a toolset # scope. toolset_mcp_route / dynamic_mcp_route set _mcp_active_toolset_id @@ -1441,9 +1322,7 @@ async def get_allowed_mcp_servers( combined_servers.update(delegate_server_ids) if len(combined_servers) == 0: - verbose_logger.debug( - "No allowed MCP Servers found for user api key auth." - ) + verbose_logger.debug("No allowed MCP Servers found for user api key auth.") return list(combined_servers) except Exception: # noqa: BLE001 verbose_logger.exception( @@ -1464,7 +1343,6 @@ async def resolve_toolset_tool_permissions( Redis-backed ``DualCache`` in production) so that cache entries are shared across workers and cold-cache DB hits are minimised. """ - from litellm.constants import DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL from litellm.proxy._experimental.mcp_server.toolset_db import list_mcp_toolsets from litellm.proxy.proxy_server import prisma_client, user_api_key_cache @@ -1490,7 +1368,7 @@ async def resolve_toolset_tool_permissions( await user_api_key_cache.async_set_cache( key=cache_key, value=tool_permissions, - ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL, + ttl=get_management_object_ttl(user_api_key_cache), ) return tool_permissions except Exception as e: @@ -1524,15 +1402,12 @@ def invalidate_toolset_cache(self, toolset_id: Optional[str] = None) -> None: keys_to_remove = [ k for k in cache_dict - if (k.startswith("toolset_perms:") and toolset_id in k) - or k.startswith("toolset_name:") + if (k.startswith("toolset_perms:") and toolset_id in k) or k.startswith("toolset_name:") ] for k in keys_to_remove: cache_dict.pop(k, None) except Exception as e: - verbose_logger.warning( - f"invalidate_toolset_cache: failed to evict in-memory entries: {e}" - ) + verbose_logger.warning(f"invalidate_toolset_cache: failed to evict in-memory entries: {e}") async def get_toolset_by_name_cached( self, @@ -1547,7 +1422,6 @@ async def get_toolset_by_name_cached( deployments. On a cache hit we reconstruct the ``MCPToolset`` Pydantic object so callers can always use attribute access (e.g. ``toolset.toolset_id``). """ - from litellm.constants import DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL from litellm.proxy.proxy_server import user_api_key_cache from litellm.types.mcp_server.mcp_toolset import MCPToolset @@ -1570,18 +1444,12 @@ async def get_toolset_by_name_cached( toolset = await get_mcp_toolset_by_name(prisma_client, toolset_name) await user_api_key_cache.async_set_cache( key=cache_key, - value=( - toolset.model_dump(mode="json") - if toolset is not None - else "__not_found__" - ), - ttl=DEFAULT_MANAGEMENT_OBJECT_IN_MEMORY_CACHE_TTL, + value=(toolset.model_dump(mode="json") if toolset is not None else "__not_found__"), + ttl=get_management_object_ttl(user_api_key_cache), ) return toolset - def filter_server_ids_by_ip( - self, server_ids: List[str], client_ip: Optional[str] - ) -> List[str]: + def filter_server_ids_by_ip(self, server_ids: List[str], client_ip: Optional[str]) -> List[str]: """ Filter server IDs by client IP — external callers only see public servers. @@ -1623,9 +1491,7 @@ async def get_tools_for_server(self, server_id: str) -> List[MCPTool]: return [] return await self._get_tools_from_server(server) except Exception as e: - verbose_logger.warning( - f"Failed to get tools from server {server_id}: {str(e)}" - ) + verbose_logger.warning(f"Failed to get tools from server {server_id}: {str(e)}") return [] async def list_tools( @@ -1694,9 +1560,7 @@ async def _fetch_server_tools(server_id: str) -> List[MCPTool]: # Flatten results into single list list_tools_result: List[MCPTool] = [tool for tools in results for tool in tools] - verbose_logger.info( - f"Successfully fetched {len(list_tools_result)} tools total from all servers" - ) + verbose_logger.info(f"Successfully fetched {len(list_tools_result)} tools total from all servers") return list_tools_result ######################################################### @@ -1818,9 +1682,7 @@ async def _resolve_static_headers_with_env_vars( # the user hasn't filled it in -- only vars without a global fallback do. referenced = collect_env_var_references(strings=(static_headers or {}).values()) referenced_user_vars = referenced & user_var_names - required_user_vars = { - name for name in referenced_user_vars if name not in global_values - } + required_user_vars = {name for name in referenced_user_vars if name not in global_values} user_values: Dict[str, str] = {} if required_user_vars: @@ -1834,28 +1696,21 @@ async def _resolve_static_headers_with_env_vars( if raise_on_missing: raise verbose_logger.warning( - "MCPServerManager: best-effort user env var load failed for " - "server=%s: %s", + "MCPServerManager: best-effort user env var load failed for server=%s: %s", server.server_id, exc, ) if raise_on_missing: - missing = sorted( - name for name in required_user_vars if not user_values.get(name) - ) + missing = sorted(name for name in required_user_vars if not user_values.get(name)) if missing: # A cached negative must never produce a 412: cache # invalidation is process-local, so a user who just stored # values on another worker would otherwise be told their # credentials are missing until the entry expires. Confirm # against the DB before raising. - user_values = await self._load_user_env_vars( - server, user_api_key_auth, force_refresh=True - ) - missing = sorted( - name for name in required_user_vars if not user_values.get(name) - ) + user_values = await self._load_user_env_vars(server, user_api_key_auth, force_refresh=True) + missing = sorted(name for name in required_user_vars if not user_values.get(name)) if missing: raise MCPMissingUserEnvVarsError( server_id=server.server_id, @@ -1867,9 +1722,7 @@ async def _resolve_static_headers_with_env_vars( # Only honor stored user values for currently user-scoped vars, and let # admin globals win, so a stale row from when a var was user-scoped can # never override the global value the admin set after switching it. - scoped_user_values = { - name: value for name, value in user_values.items() if name in user_var_names - } + scoped_user_values = {name: value for name, value in user_values.items() if name in user_var_names} merged_vars: Dict[str, str] = {**scoped_user_values, **global_values} if not static_headers: return static_headers @@ -1934,6 +1787,7 @@ async def _create_mcp_client( stdio_env: Optional[Dict[str, str]] = None, subject_token: Optional[str] = None, user_api_key_auth: Optional[UserAPIKeyAuth] = None, + cred_provider: Optional[UpstreamCredentialProvider] = None, ) -> MCPClient: """ Create an MCPClient instance for the given server. @@ -1957,34 +1811,26 @@ async def _create_mcp_client( """ transport = server.transport or MCPTransport.sse spec = None if transport == MCPTransport.stdio else to_server_spec(server) - # A per-request override is the caller-supplied credential v1 turns into the upstream - # auth, so it must win; defer those to v1 (this defer falls away once the per-user modes - # stop writing mcp_auth_header). An inbound header already in extra_headers is handled on - # the v2 path below, not here. - if spec is not None and mcp_auth_header: + provider = cred_provider or self._cred_provider + # A caller-supplied per-request override (mcp_auth_header / x-mcp-*) defers to the v1 path + # so it wins - except for authorization_code, whose per-user token the v2 resolver owns. A + # caller must not be able to substitute another user's stored credential, so we keep the v2 + # spec and ignore the override there; the REST tools preview supplies its not-yet-persisted + # token through the resolver (cred_provider), never this path. + if spec is not None and mcp_auth_header and not isinstance(spec.config, AuthorizationCodeConfig): spec = None auth_value = ( - await resolve_mcp_auth(server, mcp_auth_header, subject_token=subject_token) - if spec is None - else None + await resolve_mcp_auth(server, mcp_auth_header, subject_token=subject_token) if spec is None else None ) # Create sampling and elicitation callbacks for this client - sampling_cb = ( - _create_sampling_callback(user_api_key_auth=user_api_key_auth) - if server.allow_sampling - else None - ) - elicitation_cb = ( - _create_elicitation_callback() if server.allow_elicitation else None - ) + sampling_cb = _create_sampling_callback(user_api_key_auth=user_api_key_auth) if server.allow_sampling else None + elicitation_cb = _create_elicitation_callback() if server.allow_elicitation else None # Handle stdio transport if transport == MCPTransport.stdio: resolved_env = ( - stdio_env - if stdio_env is not None - else (dict(server.env) if server.env is not None else None) + stdio_env if stdio_env is not None else (dict(server.env) if server.env is not None else None) ) # Ensure npm-based STDIO MCP servers have a writable cache dir. @@ -2026,9 +1872,7 @@ async def _create_mcp_client( transport_type=transport, auth_type=server.auth_type, auth_value=auth_value, - timeout=( - server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT - ), + timeout=(server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT), stdio_config=stdio_config, extra_headers=extra_headers, sampling_callback=sampling_cb, @@ -2039,9 +1883,7 @@ async def _create_mcp_client( server_url = server.url or "" if spec is not None: - match await self._cred_provider.resolve_credentials( - to_subject(user_api_key_auth, subject_token), spec - ): + match await provider.resolve_credentials(to_subject(user_api_key_auth, subject_token), spec): case Ok(auth): resolved_auth = auth # Do not override an Authorization already supplied via extra_headers @@ -2052,23 +1894,20 @@ async def _create_mcp_client( if ( header_name and extra_headers - and any( - key.lower() == header_name.lower() - for key in extra_headers - ) + and any(key.lower() == header_name.lower() for key in extra_headers) ): resolved_auth = None case Error(err): + if err.tag == "unauthorized": + # The arm signals a missing per-user token semantically; raise the + # per-server OAuth challenge here, where the full MCPServer is in hand. + raise_user_oauth_challenge(server) raise_public(err) return MCPClient( server_url=server_url, transport_type=transport, auth_type=server.auth_type, - timeout=( - server.timeout - if server.timeout is not None - else MCP_CLIENT_TIMEOUT - ), + timeout=(server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT), extra_headers=extra_headers, resolved_auth=resolved_auth, sampling_callback=sampling_cb, @@ -2093,9 +1932,7 @@ async def _create_mcp_client( transport_type=transport, auth_type=server.auth_type, auth_value=auth_value, - timeout=( - server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT - ), + timeout=(server.timeout if server.timeout is not None else MCP_CLIENT_TIMEOUT), extra_headers=extra_headers, aws_auth=aws_auth, sampling_callback=sampling_cb, @@ -2162,12 +1999,10 @@ async def _get_tools_from_server( static_headers = server.static_headers or {} has_static_authorization = any( - isinstance(k, str) and k.lower() == "authorization" - for k in static_headers.keys() + isinstance(k, str) and k.lower() == "authorization" for k in static_headers.keys() ) has_extra_authorization = bool(extra_headers) and any( - isinstance(k, str) and k.lower() == "authorization" - for k in (extra_headers or {}).keys() + isinstance(k, str) and k.lower() == "authorization" for k in (extra_headers or {}).keys() ) if ( @@ -2197,12 +2032,8 @@ async def _get_tools_from_server( if server.spec_path: # OpenAPI tools were stored in the registry under the prefix # active at registration time — fetch by that same prefix. - _tools = global_mcp_tool_registry.list_tools( - tool_prefix=get_server_prefix(server) - ) - tools = global_mcp_tool_registry.convert_tools_to_mcp_sdk_tool_type( - _tools - ) + _tools = global_mcp_tool_registry.list_tools(tool_prefix=get_server_prefix(server)) + tools = global_mcp_tool_registry.convert_tools_to_mcp_sdk_tool_type(_tools) # OpenAPI tools are stored in the registry with their prefix already # applied (e.g. "test_petstore-getinventory"). Do NOT pass them # through _create_prefixed_tools — that would add the prefix a second @@ -2212,9 +2043,7 @@ async def _get_tools_from_server( sep = MCP_TOOL_PREFIX_SEPARATOR tools = [ ( - t.model_copy( - update={"name": t.name[len(prefix) + len(sep) :]} - ) + t.model_copy(update={"name": t.name[len(prefix) + len(sep) :]}) if t.name.startswith(f"{prefix}{sep}") else t ) @@ -2222,14 +2051,10 @@ async def _get_tools_from_server( ] return tools else: - tools = await self._fetch_tools_with_timeout( - client, server.name, server=server - ) + tools = await self._fetch_tools_with_timeout(client, server.name, server=server) self._remember_upstream_initialize_instructions(server, client) - prefixed_or_original_tools = self._create_prefixed_tools( - tools, server, add_prefix=add_prefix - ) + prefixed_or_original_tools = self._create_prefixed_tools(tools, server, add_prefix=add_prefix) return prefixed_or_original_tools @@ -2239,9 +2064,7 @@ async def _get_tools_from_server( # aggregator catches this explicitly to keep absorbing. raise except Exception as e: - verbose_logger.warning( - f"Failed to get tools from server {server.name}: {str(e)}" - ) + verbose_logger.warning(f"Failed to get tools from server {server.name}: {str(e)}") return [] async def get_prompts_from_server( @@ -2285,16 +2108,12 @@ async def get_prompts_from_server( prompts = await client.list_prompts() - prefixed_or_original_prompts = self._create_prefixed_prompts( - prompts, server, add_prefix=add_prefix - ) + prefixed_or_original_prompts = self._create_prefixed_prompts(prompts, server, add_prefix=add_prefix) return prefixed_or_original_prompts except Exception as e: - verbose_logger.warning( - f"Failed to get prompts from server {server.name}: {str(e)}" - ) + verbose_logger.warning(f"Failed to get prompts from server {server.name}: {str(e)}") return [] async def get_resources_from_server( @@ -2329,16 +2148,12 @@ async def get_resources_from_server( resources = await client.list_resources() - prefixed_resources = self._create_prefixed_resources( - resources, server, add_prefix=add_prefix - ) + prefixed_resources = self._create_prefixed_resources(resources, server, add_prefix=add_prefix) return prefixed_resources except Exception as e: - verbose_logger.warning( - f"Failed to get resources from server {server.name}: {str(e)}" - ) + verbose_logger.warning(f"Failed to get resources from server {server.name}: {str(e)}") return [] async def get_resource_templates_from_server( @@ -2380,9 +2195,7 @@ async def get_resource_templates_from_server( return prefixed_templates except Exception as e: - verbose_logger.warning( - f"Failed to get resource templates from server {server.name}: {str(e)}" - ) + verbose_logger.warning(f"Failed to get resource templates from server {server.name}: {str(e)}") return [] async def read_resource_from_server( @@ -2503,15 +2316,8 @@ async def _descovery_metadata( authorization_servers, resource_scopes, ) = await self._attempt_well_known_discovery(server_url) - metadata = await self._fetch_authorization_server_metadata( - authorization_servers, server_url - ) - if ( - metadata is None - and not resource_scopes - and authorization_servers - and response.status_code == 200 - ): + metadata = await self._fetch_authorization_server_metadata(authorization_servers, server_url) + if metadata is None and not resource_scopes and authorization_servers and response.status_code == 200: verbose_logger.warning( "MCP OAuth discovery for %s received 200 OK without RFC 9728 challenge and no discoverable authorization metadata.", server_url, @@ -2530,13 +2336,11 @@ async def _descovery_metadata( header_value: Optional[str] = None if exc.response is not None: - header_value = exc.response.headers.get( - "WWW-Authenticate" - ) or exc.response.headers.get("www-authenticate") + header_value = exc.response.headers.get("WWW-Authenticate") or exc.response.headers.get( + "www-authenticate" + ) - resource_metadata_url, scopes = self._parse_www_authenticate_header( - header_value - ) + resource_metadata_url, scopes = self._parse_www_authenticate_header(header_value) authorization_servers = [] resource_scopes = None @@ -2544,9 +2348,7 @@ async def _descovery_metadata( ( authorization_servers, resource_scopes, - ) = await self._fetch_oauth_metadata_from_resource( - resource_metadata_url, server_url - ) + ) = await self._fetch_oauth_metadata_from_resource(resource_metadata_url, server_url) else: ( authorization_servers, @@ -2558,16 +2360,12 @@ async def _descovery_metadata( try: parsed_url = urlparse(server_url) if parsed_url.scheme and parsed_url.netloc: - authorization_servers = [ - f"{parsed_url.scheme}://{parsed_url.netloc}" - ] + authorization_servers = [f"{parsed_url.scheme}://{parsed_url.netloc}"] except Exception: authorization_servers = [] if authorization_servers: - metadata = await self._fetch_authorization_server_metadata( - authorization_servers, server_url - ) + metadata = await self._fetch_authorization_server_metadata(authorization_servers, server_url) preferred_scopes = scopes or resource_scopes if metadata is None and preferred_scopes: @@ -2577,14 +2375,10 @@ async def _descovery_metadata( return metadata except Exception as exc: # pragma: no cover - network/transient issues - verbose_logger.debug( - "MCP OAuth discovery failed for %s: %s", server_url, exc - ) + verbose_logger.debug("MCP OAuth discovery failed for %s: %s", server_url, exc) return None - def _parse_www_authenticate_header( - self, header_value: Optional[str] - ) -> Tuple[Optional[str], Optional[List[str]]]: + def _parse_www_authenticate_header(self, header_value: Optional[str]) -> Tuple[Optional[str], Optional[List[str]]]: if not header_value: return None, None @@ -2593,8 +2387,7 @@ def _parse_www_authenticate_header( param_pattern = re.compile(r"([a-zA-Z0-9_]+)\s*=\s*\"?([^\",]+)\"?") params: Dict[str, str] = { - match.group(1).lower(): match.group(2).strip() - for match in param_pattern.finditer(params_section) + match.group(1).lower(): match.group(2).strip() for match in param_pattern.finditer(params_section) } resource_metadata_url = params.get("resource_metadata") @@ -2612,9 +2405,7 @@ async def _fetch_oauth_metadata_from_resource( return [], None try: - response = await self._fetch_oauth_discovery_url( - resource_metadata_url, server_url - ) + response = await self._fetch_oauth_discovery_url(resource_metadata_url, server_url) response.raise_for_status() data = response.json() except SSRFError as exc: @@ -2636,23 +2427,15 @@ async def _fetch_oauth_metadata_from_resource( raw_servers = data.get("authorization_servers") if isinstance(raw_servers, list): - authorization_servers = [ - entry - for entry in raw_servers - if isinstance(entry, str) and entry.strip() != "" - ] + authorization_servers = [entry for entry in raw_servers if isinstance(entry, str) and entry.strip() != ""] else: authorization_servers = [] - scopes = self._extract_scopes( - data.get("scopes_supported") or data.get("scopes") - ) + scopes = self._extract_scopes(data.get("scopes_supported") or data.get("scopes")) return authorization_servers, scopes - async def _attempt_well_known_discovery( - self, server_url: str - ) -> Tuple[List[str], Optional[List[str]]]: + async def _attempt_well_known_discovery(self, server_url: str) -> Tuple[List[str], Optional[List[str]]]: try: parsed = urlparse(server_url) except Exception: @@ -2684,9 +2467,7 @@ async def _fetch_authorization_server_metadata( self, authorization_servers: List[str], server_url: str ) -> Optional[MCPOAuthMetadata]: for issuer in authorization_servers: - metadata = await self._fetch_single_authorization_server_metadata( - issuer, server_url - ) + metadata = await self._fetch_single_authorization_server_metadata(issuer, server_url) if metadata is not None: return metadata return None @@ -2707,13 +2488,9 @@ async def _fetch_single_authorization_server_metadata( candidate_urls: List[str] = [] if path: - candidate_urls.append( - f"{base}/.well-known/oauth-authorization-server/{path}" - ) + candidate_urls.append(f"{base}/.well-known/oauth-authorization-server/{path}") candidate_urls.append(f"{base}/.well-known/openid-configuration/{path}") - candidate_urls.append( - f"{issuer_url.rstrip('/')}/.well-known/openid-configuration" - ) + candidate_urls.append(f"{issuer_url.rstrip('/')}/.well-known/openid-configuration") candidate_urls.append(f"{base}/.well-known/oauth-authorization-server") candidate_urls.append(f"{base}/.well-known/openid-configuration") candidate_urls.append(issuer_url.rstrip("/")) @@ -2764,14 +2541,8 @@ async def _fetch_single_authorization_server_metadata( def _build_azure_authorization_server_metadata( parsed_issuer_url: Any, ) -> Optional[MCPOAuthMetadata]: - path_parts = [ - part for part in (parsed_issuer_url.path or "").split("/") if part - ] - if ( - parsed_issuer_url.netloc not in _AZURE_ENTRA_HOSTS - or len(path_parts) != 2 - or path_parts[1] != "v2.0" - ): + path_parts = [part for part in (parsed_issuer_url.path or "").split("/") if part] + if parsed_issuer_url.netloc not in _AZURE_ENTRA_HOSTS or len(path_parts) != 2 or path_parts[1] != "v2.0": return None tenant = path_parts[0] @@ -2881,33 +2652,24 @@ async def _fetch_tools_with_timeout( ) try: with anyio.fail_after(MCP_TOOL_LISTING_TIMEOUT): - tools = await client.list_tools( - raise_on_error=should_surface_upstream_auth - ) + tools = await client.list_tools(raise_on_error=should_surface_upstream_auth) verbose_logger.debug(f"Tools from {server_name}: {tools}") return tools except TimeoutError: verbose_logger.warning(f"Timeout while listing tools from {server_name}") return [] except asyncio.CancelledError: - verbose_logger.warning( - f"Task cancelled while listing tools from {server_name}" - ) + verbose_logger.warning(f"Task cancelled while listing tools from {server_name}") return [] except ConnectionError as e: - verbose_logger.warning( - f"Connection error while listing tools from {server_name}: {str(e)}" - ) + verbose_logger.warning(f"Connection error while listing tools from {server_name}: {str(e)}") return [] except Exception as e: if should_surface_upstream_auth: auth_info = _extract_upstream_auth_failure(e) if auth_info is not None: status_code, www_authenticate = auth_info - verbose_logger.info( - f"Upstream auth failure from MCP server " - f"{server_name}: HTTP {status_code}" - ) + verbose_logger.info(f"Upstream auth failure from MCP server {server_name}: HTTP {status_code}") raise MCPUpstreamAuthError( status_code=status_code, www_authenticate=www_authenticate, @@ -2978,9 +2740,7 @@ def _assign_unique_short_prefix( "attempts; the 3-character prefix space is too crowded." ) - def _create_prefixed_tools( - self, tools: List[MCPTool], server: MCPServer, add_prefix: bool = True - ) -> List[MCPTool]: + def _create_prefixed_tools(self, tools: List[MCPTool], server: MCPServer, add_prefix: bool = True) -> List[MCPTool]: """ Create prefixed tools and update tool mapping. @@ -3014,9 +2774,7 @@ def _create_prefixed_tools( qualified = add_server_prefix_to_name(original_name, known_prefix) self.tool_name_to_mcp_server_name_mapping[qualified] = prefix - verbose_logger.info( - f"Successfully fetched {len(prefixed_tools)} tools from server {server.name}" - ) + verbose_logger.info(f"Successfully fetched {len(prefixed_tools)} tools from server {server.name}") return prefixed_tools def _create_prefixed_prompts( @@ -3043,9 +2801,7 @@ def _create_prefixed_prompts( prompt.name = name_to_use prefixed_prompts.append(prompt) - verbose_logger.info( - f"Successfully fetched {len(prefixed_prompts)} prompts from server {server.name}" - ) + verbose_logger.info(f"Successfully fetched {len(prefixed_prompts)} prompts from server {server.name}") return prefixed_prompts def _create_prefixed_resources( @@ -3057,17 +2813,11 @@ def _create_prefixed_resources( prefix = get_server_prefix(server) for resource in resources: - name_to_use = ( - add_server_prefix_to_name(resource.name, prefix) - if add_prefix - else resource.name - ) + name_to_use = add_server_prefix_to_name(resource.name, prefix) if add_prefix else resource.name resource.name = name_to_use prefixed_resources.append(resource) - verbose_logger.info( - f"Successfully fetched {len(prefixed_resources)} resources from server {server.name}" - ) + verbose_logger.info(f"Successfully fetched {len(prefixed_resources)} resources from server {server.name}") return prefixed_resources def _create_prefixed_resource_templates( @@ -3083,9 +2833,7 @@ def _create_prefixed_resource_templates( for resource_template in resource_templates: name_to_use = ( - add_server_prefix_to_name(resource_template.name, prefix) - if add_prefix - else resource_template.name + add_server_prefix_to_name(resource_template.name, prefix) if add_prefix else resource_template.name ) resource_template.name = name_to_use prefixed_templates.append(resource_template) @@ -3106,20 +2854,14 @@ def check_allowed_or_banned_tools(self, tool_name: str, server: MCPServer) -> bo if server_applies_tool_allowlist(server): if not server.allowed_tools: return False - return ( - tool_name in server.allowed_tools - or f"{server.name}-{tool_name}" in server.allowed_tools - ) + return tool_name in server.allowed_tools or f"{server.name}-{tool_name}" in server.allowed_tools if server.disallowed_tools: return ( - tool_name not in server.disallowed_tools - and f"{server.name}-{tool_name}" not in server.disallowed_tools + tool_name not in server.disallowed_tools and f"{server.name}-{tool_name}" not in server.disallowed_tools ) return True - def validate_allowed_params( - self, tool_name: str, arguments: Dict[str, Any], server: MCPServer - ) -> None: + def validate_allowed_params(self, tool_name: str, arguments: Dict[str, Any], server: MCPServer) -> None: """ Filter arguments to only include allowed parameters for the given tool. @@ -3146,18 +2888,14 @@ def validate_allowed_params( unprefixed_tool_name, _ = split_server_prefix_from_name(tool_name) # Check both prefixed and unprefixed tool names - allowed_params_list = server.allowed_params.get( - tool_name - ) or server.allowed_params.get(unprefixed_tool_name) + allowed_params_list = server.allowed_params.get(tool_name) or server.allowed_params.get(unprefixed_tool_name) # If this tool doesn't have allowed_params specified, allow all params if allowed_params_list is None: return None # Filter arguments to only include allowed parameters - disallowed_params = [ - param for param in arguments.keys() if param not in allowed_params_list - ] + disallowed_params = [param for param in arguments.keys() if param not in allowed_params_list] if disallowed_params: raise HTTPException( @@ -3320,42 +3058,22 @@ async def pre_call_tool_check( "name": name, "arguments": arguments, "server_name": server_name, - "mcp_rate_limit_server_name": server.alias - or server.server_name - or server.name, + "mcp_rate_limit_server_name": server.alias or server.server_name or server.name, "user_api_key_auth": user_api_key_auth, - "user_api_key_user_id": ( - getattr(user_api_key_auth, "user_id", None) - if user_api_key_auth - else None - ), - "user_api_key_team_id": ( - getattr(user_api_key_auth, "team_id", None) - if user_api_key_auth - else None - ), + "user_api_key_user_id": (getattr(user_api_key_auth, "user_id", None) if user_api_key_auth else None), + "user_api_key_team_id": (getattr(user_api_key_auth, "team_id", None) if user_api_key_auth else None), "user_api_key_end_user_id": ( - getattr(user_api_key_auth, "end_user_id", None) - if user_api_key_auth - else None - ), - "user_api_key_hash": ( - getattr(user_api_key_auth, "api_key_hash", None) - if user_api_key_auth - else None + getattr(user_api_key_auth, "end_user_id", None) if user_api_key_auth else None ), + "user_api_key_hash": (getattr(user_api_key_auth, "api_key_hash", None) if user_api_key_auth else None), "incoming_bearer_token": incoming_bearer_token, } # Create MCP request object for processing - mcp_request_obj = proxy_logging_obj._create_mcp_request_object_from_kwargs( - pre_hook_kwargs - ) + mcp_request_obj = proxy_logging_obj._create_mcp_request_object_from_kwargs(pre_hook_kwargs) # Convert to LLM format for existing guardrail compatibility - synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format( - mcp_request_obj, pre_hook_kwargs - ) + synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(mcp_request_obj, pre_hook_kwargs) hook_result: Dict[str, Any] = {} try: @@ -3367,11 +3085,7 @@ async def pre_call_tool_check( ) if modified_data: # Convert response back to MCP format and apply modifications - modified_kwargs = ( - proxy_logging_obj._convert_mcp_hook_response_to_kwargs( - modified_data, pre_hook_kwargs - ) - ) + modified_kwargs = proxy_logging_obj._convert_mcp_hook_response_to_kwargs(modified_data, pre_hook_kwargs) if modified_kwargs.get("arguments") != arguments: hook_result["arguments"] = modified_kwargs["arguments"] if modified_kwargs.get("extra_headers"): @@ -3416,9 +3130,7 @@ def _create_during_hook_task( "user_api_key_auth": user_api_key_auth, } - synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format( - request_obj, during_hook_kwargs - ) + synthetic_llm_data = proxy_logging_obj._convert_mcp_to_llm_format(request_obj, during_hook_kwargs) return asyncio.create_task( proxy_logging_obj.during_call_hook( @@ -3499,14 +3211,22 @@ async def _call_regular_mcp_tool( extra_headers = None else: extra_headers = oauth2_headers + # Migrated authorization_code: the v2 resolver injects the stored per-user + # token, so drop the caller-forwarded Authorization (apply-if-absent would + # otherwise let it shadow the resolved token). Delegate keeps it. Centralized + # via _should_strip_caller_authorization to match _prepare_mcp_server_headers. + if extra_headers and _should_strip_caller_authorization( + mcp_server=mcp_server, + raw_headers=raw_headers, + user_api_key_auth=user_api_key_auth, + ): + extra_headers = _without_authorization(extra_headers) if mcp_server.extra_headers and raw_headers: if extra_headers is None: extra_headers = {} - normalized_raw_headers = { - str(k).lower(): v for k, v in raw_headers.items() if isinstance(k, str) - } + normalized_raw_headers = {str(k).lower(): v for k, v in raw_headers.items() if isinstance(k, str)} strip_caller_authorization = _should_strip_caller_authorization( mcp_server=mcp_server, raw_headers=raw_headers, @@ -3527,9 +3247,7 @@ async def _call_regular_mcp_tool( # MCPMissingUserEnvVarsError when the calling user has not filled in # a required per-user variable — the REST layer converts that into # a friendly 412 with a setup URL. - resolved_static_headers = await self._resolve_static_headers_with_env_vars( - mcp_server, user_api_key_auth - ) + resolved_static_headers = await self._resolve_static_headers_with_env_vars(mcp_server, user_api_key_auth) if resolved_static_headers: if extra_headers is None: extra_headers = {} @@ -3581,21 +3299,13 @@ async def _call_regular_mcp_tool( ) async def _call_tool_via_client(client, params): - return await client.call_tool( - params, host_progress_callback=host_progress_callback - ) + return await client.call_tool(params, host_progress_callback=host_progress_callback) - tasks.append( - asyncio.create_task(_call_tool_via_client(client, call_tool_params)) - ) + tasks.append(asyncio.create_task(_call_tool_via_client(client, call_tool_params))) - _timeout = ( - mcp_server.timeout if mcp_server.timeout is not None else MCP_CLIENT_TIMEOUT - ) + _timeout = mcp_server.timeout if mcp_server.timeout is not None else MCP_CLIENT_TIMEOUT try: - mcp_responses = await asyncio.wait_for( - asyncio.gather(*tasks), timeout=_timeout - ) + mcp_responses = await asyncio.wait_for(asyncio.gather(*tasks), timeout=_timeout) except asyncio.TimeoutError: raise HTTPException( status_code=504, @@ -3609,9 +3319,7 @@ async def _call_tool_via_client(client, params): GuardrailRaisedException, HTTPException, ) as e: - verbose_logger.error( - f"Guardrail blocked MCP tool call during result check: {str(e)}" - ) + verbose_logger.error(f"Guardrail blocked MCP tool call during result check: {str(e)}") raise e # If proxy_logging_obj is None, the tool call result is at index 0 @@ -3639,9 +3347,7 @@ def _candidate_matches_server_name(candidate: MCPServer) -> bool: candidate.server_name, candidate.name, ): - if identifier and normalize_server_name(identifier) == ( - normalized_server_name - ): + if identifier and normalize_server_name(identifier) == (normalized_server_name): return True return False @@ -3653,9 +3359,7 @@ def _candidate_matches_server_name(candidate: MCPServer) -> bool: break if mcp_server is None: fallback = self._get_mcp_server_from_tool_name(name) - if fallback is not None and ( - not server_name or _candidate_matches_server_name(fallback) - ): + if fallback is not None and (not server_name or _candidate_matches_server_name(fallback)): mcp_server = fallback if mcp_server is None: raise ValueError(f"Tool {name} not found") @@ -3670,6 +3374,18 @@ def _candidate_matches_server_name(candidate: MCPServer) -> bool: return mcp_server + async def has_user_oauth_token(self, server: MCPServer, user_api_key_auth: Optional[UserAPIKeyAuth]) -> bool: + """Whether the v2 resolver can produce a per-user token for this server right now. + + This is the preemptive 401's existence check, routed through the same resolver that drives + the egress so every authorization_code resolution (egress and the discovery challenge) runs + through v2. Returns False for a server the resolver does not own (a None spec). + """ + spec = to_server_spec(server) + if spec is None: + return False + return await self._cred_provider.has_user_token(to_subject(user_api_key_auth, None), spec) + async def _resolve_oauth2_headers_for_tool_call( self, mcp_server: MCPServer, @@ -3677,11 +3393,13 @@ async def _resolve_oauth2_headers_for_tool_call( user_api_key_auth: Optional[UserAPIKeyAuth], ) -> Optional[Dict[str, str]]: """Look up per-user OAuth headers when the client did not supply a token.""" - if ( - not mcp_server.needs_user_oauth_token - or oauth2_headers - or user_api_key_auth is None - ): + if not mcp_server.needs_user_oauth_token or oauth2_headers or user_api_key_auth is None: + return oauth2_headers + + if to_server_spec(mcp_server) is not None: + # Migrated to v2: the resolver owns this server's per-user token (inject or fail-closed + # 401). Building it into extra_headers here would let the v2 graft defer to it and + # shadow the resolver, double-resolving and hiding the per-server challenge. return oauth2_headers user_id = getattr(user_api_key_auth, "user_id", None) @@ -3723,9 +3441,7 @@ async def _gather_openapi_tool_tasks( GuardrailRaisedException, HTTPException, ) as e: - verbose_logger.error( - f"Guardrail blocked MCP tool call during result check: {str(e)}" - ) + verbose_logger.error(f"Guardrail blocked MCP tool call during result check: {str(e)}") raise e async def call_tool( @@ -3792,15 +3508,11 @@ async def call_tool( ) tasks.append(during_hook_task) - oauth2_headers = await self._resolve_oauth2_headers_for_tool_call( - mcp_server, oauth2_headers, user_api_key_auth - ) + oauth2_headers = await self._resolve_oauth2_headers_for_tool_call(mcp_server, oauth2_headers, user_api_key_auth) # For OpenAPI servers, call the tool handler directly instead of via MCP client if mcp_server.spec_path: - verbose_logger.debug( - "Calling OpenAPI tool %s directly via HTTP handler", name - ) + verbose_logger.debug("Calling OpenAPI tool %s directly via HTTP handler", name) if hook_result.get("extra_headers"): verbose_logger.warning( "pre_mcp_call hook returned extra_headers for OpenAPI-backed " @@ -3809,11 +3521,7 @@ async def call_tool( "transport to enable hook header injection.", server_name, ) - tasks.append( - asyncio.create_task( - self._call_openapi_tool_handler(mcp_server, name, arguments) - ) - ) + tasks.append(asyncio.create_task(self._call_openapi_tool_handler(mcp_server, name, arguments))) else: return await self._call_regular_mcp_tool( mcp_server=mcp_server, @@ -3842,9 +3550,7 @@ def initialize_tool_name_to_mcp_server_name_mapping(self): """ try: if asyncio.get_running_loop(): - asyncio.create_task( - self._initialize_tool_name_to_mcp_server_name_mapping() - ) + asyncio.create_task(self._initialize_tool_name_to_mcp_server_name_mapping()) except RuntimeError as e: # no running event loop verbose_logger.exception( f"No running event loop - skipping tool name to MCP server name mapping initialization: {str(e)}" @@ -3866,14 +3572,12 @@ async def _initialize_tool_name_to_mcp_server_name_mapping(self): # at startup we have none, so an upstream 401 is normal. # Swallow it so we keep mapping the remaining servers. verbose_logger.debug( - f"Skipping tool name mapping for server {server.name} " - f"due to upstream auth error: {str(e)}" + f"Skipping tool name mapping for server {server.name} due to upstream auth error: {str(e)}" ) continue except Exception as e: verbose_logger.warning( - f"Failed to get tools from server {server.name} during " - f"tool name mapping initialization: {str(e)}" + f"Failed to get tools from server {server.name} during tool name mapping initialization: {str(e)}" ) continue for tool in tools: @@ -3916,9 +3620,7 @@ def _get_mcp_server_from_tool_name(self, tool_name: str) -> Optional[MCPServer]: # If not found and tool name is prefixed, extract the prefix and # match against any known form. - if is_tool_name_prefixed( - tool_name, known_server_prefixes=set(prefix_to_server.keys()) - ): + if is_tool_name_prefixed(tool_name, known_server_prefixes=set(prefix_to_server.keys())): ( original_tool_name, server_name_from_prefix, @@ -3944,9 +3646,7 @@ async def reload_servers_from_database(self): self._upstream_initialize_instructions_probed_at.clear() # perform authz check to filter the mcp servers user has access to - prisma_client = get_prisma_client_or_throw( - "Database not connected. Connect a database to your proxy" - ) + prisma_client = get_prisma_client_or_throw("Database not connected. Connect a database to your proxy") # Load only "active", legacy "approved", and NULL (no approval workflow) rows. # Pending/rejected servers are excluded at the DB level so we never load them. from litellm.proxy._experimental.mcp_server.db import LiteLLM_MCPServerTable @@ -3988,16 +3688,12 @@ async def reload_servers_from_database(self): alias=getattr(server, "alias", None), server_name=getattr(server, "server_name", None), ) - verbose_logger.debug( - f"Building server from DB: {server.server_id} ({server.server_name})" - ) + verbose_logger.debug(f"Building server from DB: {server.server_id} ({server.server_name})") # raw_rows come straight from the DB, so their global env var # values (like credentials) are still encrypted here, unlike the # already-decrypted records add_server/update_server are handed. # Decrypt them while building the registry entry. - new_server = await self.build_mcp_server_from_table( - server, env_vars_are_encrypted=True - ) + new_server = await self.build_mcp_server_from_table(server, env_vars_are_encrypted=True) # Carry the cached short_prefix from the previous registry entry # (if any) so the prefix is stable across reloads. if existing_server is not None and existing_server.short_prefix: @@ -4021,9 +3717,7 @@ async def reload_servers_from_database(self): # Register OpenAPI tools *after* the final short prefix is assigned # so the tools are stored in the global registry under the same # prefix that lookups will use. - await self._maybe_register_openapi_tools( - new_server, initialize_mapping=False - ) + await self._maybe_register_openapi_tools(new_server, initialize_mapping=False) registered_registry[server_id] = new_server if new_server.spec_path: registered_openapi_tools = True @@ -4039,9 +3733,7 @@ async def reload_servers_from_database(self): if registered_openapi_tools: self.initialize_tool_name_to_mcp_server_name_mapping() - verbose_logger.debug( - "MCP registry refreshed (%s servers in registry)", len(registered_registry) - ) + verbose_logger.debug("MCP registry refreshed (%s servers in registry)", len(registered_registry)) def get_mcp_servers_from_ids(self, server_ids: List[str]) -> List[MCPServer]: servers = [] @@ -4063,9 +3755,7 @@ def _get_general_settings(self) -> Dict[str, Any]: # Fallback if proxy_server not available return {} - def _is_server_accessible_from_ip( - self, server: MCPServer, client_ip: Optional[str] - ) -> bool: + def _is_server_accessible_from_ip(self, server: MCPServer, client_ip: Optional[str]) -> bool: """ Check if a server is accessible from the given client IP. @@ -4083,9 +3773,7 @@ def _is_server_accessible_from_ip( return True # Non-public server: only accessible from internal IPs general_settings = self._get_general_settings() - internal_networks = IPAddressUtils.parse_internal_networks( - general_settings.get("mcp_internal_ip_ranges") - ) + internal_networks = IPAddressUtils.parse_internal_networks(general_settings.get("mcp_internal_ip_ranges")) return IPAddressUtils.is_internal_ip(client_ip, internal_networks) def get_mcp_server_by_id(self, server_id: str) -> Optional[MCPServer]: @@ -4119,11 +3807,7 @@ def get_public_mcp_servers(self) -> List[MCPServer]: if litellm.public_mcp_servers is None: return [] public_ids = set(litellm.public_mcp_servers) - return [ - server - for server in self.get_registry().values() - if server.server_id in public_ids - ] + return [server for server in self.get_registry().values() if server.server_id in public_ids] public_ids = set(litellm.public_mcp_servers or []) return [ @@ -4156,9 +3840,7 @@ def expand_permission_list(self, identifiers: List[str]) -> List[str]: matches: List[str] = [ server_id for server_id, server in registry.items() - if server.alias == identifier - or server.server_name == identifier - or server.name == identifier + if server.alias == identifier or server.server_name == identifier or server.name == identifier ] if matches: expanded.update(matches) @@ -4198,9 +3880,7 @@ def expand_tool_permissions( result.setdefault(server_id, []).extend(tools or []) return result - def get_mcp_server_by_name( - self, server_name: str, client_ip: Optional[str] = None - ) -> Optional[MCPServer]: + def get_mcp_server_by_name(self, server_name: str, client_ip: Optional[str] = None) -> Optional[MCPServer]: """ Get the MCP Server from the server name. @@ -4235,9 +3915,7 @@ def get_mcp_server_by_name( return server return None - def get_filtered_registry( - self, client_ip: Optional[str] = None - ) -> Dict[str, MCPServer]: + def get_filtered_registry(self, client_ip: Optional[str] = None) -> Dict[str, MCPServer]: """ Get registry filtered by client IP access control. @@ -4248,11 +3926,7 @@ def get_filtered_registry( registry = self.get_registry() if client_ip is None: return registry - return { - k: v - for k, v in registry.items() - if self._is_server_accessible_from_ip(v, client_ip) - } + return {k: v for k, v in registry.items() if self._is_server_accessible_from_ip(v, client_ip)} def _generate_stable_server_id( self, @@ -4281,9 +3955,7 @@ def _generate_stable_server_id( A deterministic server ID string """ # Create a string from all the identifying parameters - params_string = ( - f"{server_name}|{url}|{transport}|{auth_type or ''}|{alias or ''}" - ) + params_string = f"{server_name}|{url}|{transport}|{auth_type or ''}|{alias or ''}" # Generate SHA-256 hash hash_object = hashlib.sha256(params_string.encode("utf-8")) @@ -4349,9 +4021,7 @@ async def health_check_server( user_api_key_auth=None, raise_on_missing=False, ) - extra_headers = ( - dict(resolved_static_headers) if resolved_static_headers else {} - ) + extra_headers = dict(resolved_static_headers) if resolved_static_headers else {} client = await self._create_mcp_client( server=server, @@ -4366,15 +4036,11 @@ async def _noop(session): return "ok" # Add timeout wrapper to prevent hanging - await asyncio.wait_for( - client.run_with_session(_noop), timeout=MCP_HEALTH_CHECK_TIMEOUT - ) + await asyncio.wait_for(client.run_with_session(_noop), timeout=MCP_HEALTH_CHECK_TIMEOUT) self._remember_upstream_initialize_instructions(server, client) status = "healthy" except asyncio.TimeoutError: - health_check_error = ( - f"Health check timed out after {MCP_HEALTH_CHECK_TIMEOUT} seconds" - ) + health_check_error = f"Health check timed out after {MCP_HEALTH_CHECK_TIMEOUT} seconds" status = "unhealthy" except asyncio.CancelledError: health_check_error = "Health check was cancelled" @@ -4387,9 +4053,7 @@ async def _noop(session): server_id=server.server_id, server_name=server.server_name, alias=server.alias, - description=( - server.mcp_info.get("description") if server.mcp_info else None - ), + description=(server.mcp_info.get("description") if server.mcp_info else None), url=server.url, transport=server.transport, auth_type=server.auth_type, @@ -4488,9 +4152,7 @@ def _build_mcp_server_table(self, server: MCPServer) -> LiteLLM_MCPServerTable: server_id=server.server_id, server_name=server.server_name, alias=server.alias, - description=( - server.mcp_info.get("description") if server.mcp_info else None - ), + description=(server.mcp_info.get("description") if server.mcp_info else None), url=server.url, spec_path=server.spec_path, transport=server.transport, @@ -4556,9 +4218,7 @@ async def get_all_mcp_servers_with_health_unfiltered( return await self._run_health_checks(target_server_ids) - async def _run_health_checks( - self, target_server_ids: List[str] - ) -> List[LiteLLM_MCPServerTable]: + async def _run_health_checks(self, target_server_ids: List[str]) -> List[LiteLLM_MCPServerTable]: if not target_server_ids: return [] diff --git a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py index 92ef57d8cd5b..f18ff04c4e89 100644 --- a/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py +++ b/litellm/proxy/_experimental/mcp_server/oauth2_token_cache.py @@ -135,19 +135,12 @@ async def _fetch_token(self, server: "MCPServer") -> Tuple[str, int]: access_token = body.get("access_token") if not access_token: - raise ValueError( - f"OAuth2 token response for MCP server '{server.server_id}' " - f"missing 'access_token'" - ) + raise ValueError(f"OAuth2 token response for MCP server '{server.server_id}' missing 'access_token'") # Safely parse expires_in — providers may return null or non-numeric values raw_expires_in = body.get("expires_in") try: - expires_in = ( - int(raw_expires_in) - if raw_expires_in is not None - else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL - ) + expires_in = int(raw_expires_in) if raw_expires_in is not None else MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL except (TypeError, ValueError): expires_in = MCP_OAUTH2_TOKEN_CACHE_DEFAULT_TTL @@ -289,9 +282,7 @@ async def resolve_mcp_auth( return mcp_auth_header if server.has_token_exchange_config: if subject_token: - return await token_exchange.mcp_token_exchange_handler.exchange_token( - subject_token, server - ) + return await token_exchange.mcp_token_exchange_handler.exchange_token(subject_token, server) # No subject_token — fall back to client_credentials using the same client # credentials and token_url so M2M scenarios still work. if server.client_id and server.client_secret and server.token_url: diff --git a/litellm/proxy/_experimental/mcp_server/oauth_utils.py b/litellm/proxy/_experimental/mcp_server/oauth_utils.py index e8b591c39cff..4d5813dbc5bf 100644 --- a/litellm/proxy/_experimental/mcp_server/oauth_utils.py +++ b/litellm/proxy/_experimental/mcp_server/oauth_utils.py @@ -379,10 +379,8 @@ def _trusted_redirect_uri_is_allowed( ) -> bool: if proxy_base: proxy_parsed = urlparse(proxy_base) - if ( - parsed.scheme == proxy_parsed.scheme - and redirect_netloc - == _strip_default_port(proxy_parsed.scheme, proxy_parsed.netloc) + if parsed.scheme == proxy_parsed.scheme and redirect_netloc == _strip_default_port( + proxy_parsed.scheme, proxy_parsed.netloc ): return True @@ -418,9 +416,7 @@ def _build_trusted_redirect_rejection_message( redirect_origin = _origin_label(parsed.scheme, redirect_netloc) proxy_parsed = urlparse(proxy_base) if proxy_base else None proxy_netloc_norm = ( - _strip_default_port(proxy_parsed.scheme, proxy_parsed.netloc) - if proxy_parsed and proxy_parsed.netloc - else "" + _strip_default_port(proxy_parsed.scheme, proxy_parsed.netloc) if proxy_parsed and proxy_parsed.netloc else "" ) mismatch_parts: List[str] = [] @@ -433,16 +429,10 @@ def _build_trusted_redirect_rejection_message( "or trust X-Forwarded-Proto from your ingress)" ) if redirect_netloc != proxy_netloc_norm: - mismatch_parts.append( - f"host/port: redirect_uri {redirect_netloc!r} does not match " - "the proxy origin" - ) + mismatch_parts.append(f"host/port: redirect_uri {redirect_netloc!r} does not match the proxy origin") if mismatch_parts: - return ( - f"redirect_uri origin ({redirect_origin}) does not match the proxy " - "origin. " + "; ".join(mismatch_parts) - ) + return f"redirect_uri origin ({redirect_origin}) does not match the proxy origin. " + "; ".join(mismatch_parts) return ( f"redirect_uri ({redirect_uri!r}) is not allowed: not same-origin with " f"the proxy origin, not loopback, and not listed in " @@ -457,9 +447,7 @@ def _raise_trusted_redirect_uri_rejected( redirect_netloc: str, proxy_base: Optional[str], ) -> NoReturn: - description = _build_trusted_redirect_rejection_message( - redirect_uri, parsed, redirect_netloc, proxy_base - ) + description = _build_trusted_redirect_rejection_message(redirect_uri, parsed, redirect_netloc, proxy_base) hint = ( "Align the proxy public URL with the browser URL. Set PROXY_BASE_URL to your " @@ -525,6 +513,4 @@ def validate_trusted_redirect_uri(request: Request, redirect_uri: str) -> None: proxy_base = _resolve_proxy_base_for_redirect(request) if _trusted_redirect_uri_is_allowed(parsed, redirect_netloc, proxy_base): return - _raise_trusted_redirect_uri_rejected( - request, redirect_uri, parsed, redirect_netloc, proxy_base - ) + _raise_trusted_redirect_uri_rejected(request, redirect_uri, parsed, redirect_netloc, proxy_base) diff --git a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py index de70fe1331e6..1ee300be7182 100644 --- a/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py +++ b/litellm/proxy/_experimental/mcp_server/openapi_to_mcp_generator.py @@ -58,8 +58,8 @@ def sanitize_openapi_tool_name(raw_name: str) -> str: # Per-request extra headers forwarded from the client request. # Populated from MCPServer.extra_headers names matched against raw request # headers in server.py before dispatching to a local/OpenAPI tool handler. -_request_extra_headers: contextvars.ContextVar[Optional[Dict[str, str]]] = ( - contextvars.ContextVar("_request_extra_headers", default=None) +_request_extra_headers: contextvars.ContextVar[Optional[Dict[str, str]]] = contextvars.ContextVar( + "_request_extra_headers", default=None ) @@ -74,14 +74,10 @@ def _sanitize_path_parameter_value(param_value: Any, param_name: str) -> str: normalized_value = value_str.replace("\\", "/") if "/" in normalized_value: - raise ValueError( - f"Path parameter '{param_name}' must not contain path separators" - ) + raise ValueError(f"Path parameter '{param_name}' must not contain path separators") if any(part in {".", ".."} for part in PurePosixPath(normalized_value).parts): - raise ValueError( - f"Path parameter '{param_name}' cannot include '.' or '..' segments" - ) + raise ValueError(f"Path parameter '{param_name}' cannot include '.' or '..' segments") return quote(value_str, safe="") @@ -149,9 +145,7 @@ def get_base_url(spec: Dict[str, Any], spec_path: Optional[str] = None) -> str: return f"{scheme}://{spec['host']}{base_path}" # Fallback: derive base URL from spec_path if it's a URL - if spec_path and ( - spec_path.startswith("http://") or spec_path.startswith("https://") - ): + if spec_path and (spec_path.startswith("http://") or spec_path.startswith("https://")): for suffix in [ "/openapi.json", "/openapi.yaml", @@ -160,24 +154,18 @@ def get_base_url(spec: Dict[str, Any], spec_path: Optional[str] = None) -> str: ]: if spec_path.endswith(suffix): base_url = spec_path[: -len(suffix)] - verbose_logger.info( - f"No server info in OpenAPI spec. Using derived base URL: {base_url}" - ) + verbose_logger.info(f"No server info in OpenAPI spec. Using derived base URL: {base_url}") return base_url if spec_path.split("/")[-1].endswith((".json", ".yaml", ".yml")): base_url = "/".join(spec_path.split("/")[:-1]) - verbose_logger.info( - f"No server info in OpenAPI spec. Using derived base URL: {base_url}" - ) + verbose_logger.info(f"No server info in OpenAPI spec. Using derived base URL: {base_url}") return base_url return "" -def _resolve_ref( - param: Dict[str, Any], component_params: Dict[str, Any] -) -> Optional[Dict[str, Any]]: +def _resolve_ref(param: Dict[str, Any], component_params: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Resolve a single parameter, following a $ref if present. Returns the resolved param dict, or None if the $ref target is absent from @@ -190,9 +178,7 @@ def _resolve_ref( return component_params.get(ref.split("/")[-1]) -def _resolve_param_list( - raw: List[Dict[str, Any]], component_params: Dict[str, Any] -) -> List[Dict[str, Any]]: +def _resolve_param_list(raw: List[Dict[str, Any]], component_params: Dict[str, Any]) -> List[Dict[str, Any]]: """Resolve $refs in a parameter list, dropping any unresolvable entries.""" result = [] for p in raw: @@ -225,9 +211,7 @@ def resolve_operation_params( path_level = _resolve_param_list(path_item.get("parameters", []), component_params) op_level = _resolve_param_list(operation.get("parameters", []), component_params) op_keys = {(p["name"], p.get("in")) for p in op_level} - merged = [ - p for p in path_level if (p["name"], p.get("in")) not in op_keys - ] + op_level + merged = [p for p in path_level if (p["name"], p.get("in")) not in op_keys] + op_level result = dict(operation) result["parameters"] = merged return result @@ -330,9 +314,7 @@ def _merge_openapi_tool_request_headers( static = static_headers or {} static_lower_names = {k.lower() for k in static} - effective_headers: Dict[str, str] = { - k: v for k, v in request_extra.items() if k.lower() not in static_lower_names - } + effective_headers: Dict[str, str] = {k: v for k, v in request_extra.items() if k.lower() not in static_lower_names} effective_headers.update(static) override_auth = _request_auth_header.get() @@ -424,11 +406,7 @@ async def tool_function(**kwargs: Any) -> str: elif body_value: # If it's a string, try to parse as JSON try: - json_body = ( - json.loads(body_value) - if isinstance(body_value, str) - else {"data": body_value} - ) + json_body = json.loads(body_value) if isinstance(body_value, str) else {"data": body_value} except (json.JSONDecodeError, TypeError): json_body = {"data": body_value} @@ -437,21 +415,13 @@ async def tool_function(**kwargs: Any) -> str: if original_method == "get": response = await client.get(url, params=params, headers=effective_headers) elif original_method == "post": - response = await client.post( - url, params=params, json=json_body, headers=effective_headers - ) + response = await client.post(url, params=params, json=json_body, headers=effective_headers) elif original_method == "put": - response = await client.put( - url, params=params, json=json_body, headers=effective_headers - ) + response = await client.put(url, params=params, json=json_body, headers=effective_headers) elif original_method == "delete": - response = await client.delete( - url, params=params, headers=effective_headers - ) + response = await client.delete(url, params=params, headers=effective_headers) elif original_method == "patch": - response = await client.patch( - url, params=params, json=json_body, headers=effective_headers - ) + response = await client.patch(url, params=params, json=json_body, headers=effective_headers) else: return f"Unsupported HTTP method: {original_method}" @@ -488,16 +458,12 @@ def register_tools_from_openapi(spec: Dict[str, Any], base_url: str): while unique in used_names: n += 1 suffix = f"_{n}" - unique = ( - tool_name[: _OPENAPI_TOOL_NAME_MAX_LEN - len(suffix)] + suffix - ) + unique = tool_name[: _OPENAPI_TOOL_NAME_MAX_LEN - len(suffix)] + suffix tool_name = unique used_names.add(tool_name) # Get description - description = operation.get( - "summary", operation.get("description", f"{method.upper()} {path}") - ) + description = operation.get("summary", operation.get("description", f"{method.upper()} {path}")) # Build input schema input_schema = build_input_schema(operation) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py index 39db2314aeeb..815fc2ba29dd 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/adapter.py @@ -20,6 +20,7 @@ from litellm.proxy._experimental.mcp_server.outbound_credentials.types import ( ApiKeyConfig, + AuthorizationCodeConfig, CredError, NoneConfig, ServerSpec, @@ -33,9 +34,7 @@ from litellm.types.mcp_server.mcp_server_manager import MCPServer -def to_subject( - user_api_key_auth: Optional[UserAPIKeyAuth], subject_token: Optional[str] -) -> Subject: +def to_subject(user_api_key_auth: Optional[UserAPIKeyAuth], subject_token: Optional[str]) -> Subject: """Map v1's authenticated principal onto the resolver's Subject. tenant_id / subject_id are empty for an unauthenticated caller; the per-user arms must reject @@ -61,22 +60,19 @@ def to_server_spec(server: MCPServer) -> Optional[ServerSpec]: Dispatches on the declared ``auth_type``. The match is exhaustive over ``MCPAuthType`` with an ``assert_never`` tail, so a newly added auth mode fails the type gate here until it is explicitly mapped or explicitly deferred, rather than silently falling through to v1. Live - modes: ``none`` and the static-header family (``api_key`` plus the Authorization schemes), - all shared-key; every other mode returns None and stays on v1. + modes: ``none``, the static-header family (``api_key`` plus the Authorization schemes, + all shared-key), and ``oauth2`` per-user tokens (``authorization_code``); client_credentials + (M2M), delegated/passthrough oauth2, token exchange, and SigV4 return None and stay on v1. """ if server.is_byok: - return ( - None # per-user BYOK source not migrated yet -> defer to v1 (any auth_type) - ) + return None # per-user BYOK source not migrated yet -> defer to v1 (any auth_type) resource = server.url or server.server_id auth_type = server.auth_type match auth_type: case None | MCPAuth.none: if server.is_oauth_passthrough: return None # passthrough is not migrated yet -> defer to v1 - return ServerSpec( - server_id=server.server_id, resource=resource, config=NoneConfig() - ) + return ServerSpec(server_id=server.server_id, resource=resource, config=NoneConfig()) case MCPAuth.api_key: return _shared_key_spec(server, resource, "X-API-Key", "") case MCPAuth.bearer_token: @@ -86,11 +82,18 @@ def to_server_spec(server: MCPServer) -> Optional[ServerSpec]: case MCPAuth.authorization: return _shared_key_spec(server, resource, "Authorization", "") case MCPAuth.basic: - return _shared_key_spec( - server, resource, "Authorization", "Basic", encode=True - ) - case MCPAuth.oauth2 | MCPAuth.oauth2_token_exchange | MCPAuth.aws_sigv4: - return None # OAuth grants and SigV4 are not migrated yet -> defer to v1 + return _shared_key_spec(server, resource, "Authorization", "Basic", encode=True) + case MCPAuth.oauth2: + if server.needs_user_oauth_token and not server.delegate_auth_to_upstream: + return ServerSpec( + server_id=server.server_id, + resource=resource, + config=AuthorizationCodeConfig(), + ) + # client_credentials (M2M) and delegate/passthrough oauth2 stay on v1 + return None + case MCPAuth.oauth2_token_exchange | MCPAuth.aws_sigv4: + return None # token exchange and SigV4 are not migrated yet -> defer to v1 assert_never(auth_type) @@ -126,7 +129,12 @@ def raise_public(error: CredError) -> NoReturn: """Map a resolver CredError onto the proxy's public HTTP contract. The one edge that raises.""" match error.tag: case "unauthorized": - raise HTTPException(status_code=401, detail=error.summary) + challenge = error.unauthorized + raise HTTPException( + status_code=401, + detail=challenge.body if challenge.body is not None else error.summary, + headers=({"WWW-Authenticate": challenge.www_authenticate} if challenge.www_authenticate else None), + ) case "misconfigured": raise HTTPException(status_code=500, detail=error.summary) case "upstream_unavailable": @@ -138,3 +146,25 @@ def raise_public(error: CredError) -> NoReturn: case "not_implemented": raise HTTPException(status_code=501, detail=error.summary) assert_never(error.tag) + + +def raise_user_oauth_challenge(server: MCPServer) -> NoReturn: + """Raise the 401 an ``authorization_code`` server returns at egress when the user has no token. + + Points at the server's RFC 9728 Protected Resource Metadata (``resource_metadata``), which names + the upstream authorization server the client must complete OAuth with. The URL is per-server and + relative, so it resolves against the caller's own host (correct even behind a reverse proxy) + without needing request context. The listing-phase 401 still emits the RFC 8414 ``authorization_uri`` + form pending the format unification; both target the same server, so the difference is cosmetic. + """ + from litellm.proxy.utils import get_server_root_path # noqa: PLC0415 + + root = get_server_root_path() + prefix = "" if root == "/" else root + name = server.alias or server.server_name or server.name or server.server_id + resource_metadata = f"/.well-known/oauth-protected-resource{prefix}/mcp/{name}" + raise HTTPException( + status_code=401, + detail="Unauthorized", + headers={"WWW-Authenticate": f'Bearer resource_metadata="{resource_metadata}"'}, + ) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.py new file mode 100644 index 000000000000..2504ff67e3ec --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/authz_code_refresher.py @@ -0,0 +1,113 @@ +"""v2-native refresher for the ``authorization_code`` mode: the refresh_token grant, then persist. + +Mints a fresh access token from a stored refresh_token by POSTing the RFC 6749 refresh_token grant to +the server's token endpoint, persists the rotated triple, and returns the new typed ``OAuthToken`` for +``RefreshingTokenStore`` to cache. The HTTP post and the persist are injected, so the orchestration +and the (untyped) response parsing stay testable without a live IdP or DB. Replaces v1's +``refresh_user_oauth_token`` as part of step 1b; rotation safety - one refresh per (user, server) +across replicas - is the wrapping store's distributed single-flight, not this refresher's concern. +""" + +from __future__ import annotations + +import time +from collections.abc import Awaitable, Callable +from typing import TYPE_CHECKING, Protocol + +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, +) + +if TYPE_CHECKING: + from litellm.types.mcp_server.mcp_server_manager import MCPServer + +ServerLookup = Callable[[str], "MCPServer | None"] +TokenEndpointPost = Callable[[str, dict[str, str]], Awaitable["dict[str, object] | None"]] + + +class CredentialPersist(Protocol): + async def __call__( + self, + user_id: str, + server_id: str, + access_token: str, + refresh_token: str | None, + expires_in: int | None, + scopes: tuple[str, ...] | None, + ) -> None: ... + + +def _parse_expires_in(raw: object) -> int | None: + if isinstance(raw, bool): + return None + if isinstance(raw, int): + return raw + if isinstance(raw, str): + try: + return int(raw) + except ValueError: + return None + return None + + +def _parse_scopes(raw: object) -> tuple[str, ...] | None: + return tuple(raw.split()) if isinstance(raw, str) and raw else None + + +class AuthorizationCodeRefresher: + """``TokenRefresher`` for authorization_code: refresh_token grant against the server, then persist. + + ``token_endpoint`` POSTs the OAuth form and returns the parsed JSON body (``None`` on any + transport/HTTP failure, mirroring v1: a failed refresh is a miss, not a 500). ``persist`` writes + the rotated triple for ``(user, server)`` - the v1 ``store_user_oauth_credential`` write, which + stays. Returns ``None`` (the arm challenges) when there is no refresh_token, the server lacks a + token endpoint, or the grant fails; never a stale or partial token. A rotated refresh_token from + the response replaces the old one; an omitted one is carried forward, as are the recorded scopes + when the response omits ``scope``. + """ + + def __init__( + self, + server_lookup: ServerLookup, + token_endpoint: TokenEndpointPost, + persist: CredentialPersist, + *, + clock: Callable[[], float] = time.time, + ) -> None: + self._server_lookup = server_lookup + self._token_endpoint = token_endpoint + self._persist = persist + self._clock = clock + + async def refresh(self, user_id: str, server_id: str, token: OAuthToken) -> OAuthToken | None: + if token.refresh_token is None: + return None + server = self._server_lookup(server_id) + if server is None or not server.token_url: + return None + + form = { + "grant_type": "refresh_token", + "refresh_token": token.refresh_token, + **({"client_id": server.client_id} if server.client_id else {}), + **({"client_secret": server.client_secret} if server.client_secret else {}), + } + body = await self._token_endpoint(server.token_url, form) + if body is None: + return None + access_token = body.get("access_token") + if not isinstance(access_token, str) or not access_token: + return None + + rotated = body.get("refresh_token") + new_refresh = rotated if isinstance(rotated, str) and rotated else token.refresh_token + expires_in = _parse_expires_in(body.get("expires_in")) + scopes = _parse_scopes(body.get("scope")) or token.scopes + + await self._persist(user_id, server_id, access_token, new_refresh, expires_in, scopes or None) + return OAuthToken( + access_token=access_token, + expires_at=self._clock() + expires_in if expires_in is not None else None, + refresh_token=new_refresh, + scopes=scopes, + ) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/dual_cache_token_backend.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/dual_cache_token_backend.py new file mode 100644 index 000000000000..66fe2169a46f --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/dual_cache_token_backend.py @@ -0,0 +1,74 @@ +"""Cross-replica ``TokenCacheBackend``: stores the token in LiteLLM's shared ``DualCache``. + +Plugs into the foundation's ``CachedOAuthTokenStore`` via the ``TokenCacheBackend`` seam. The token is +encrypted + serialized by the injected codec and written under a per-``(user, server)`` key with the +given TTL, so every worker reads one refresh rather than each re-reading and re-refreshing - matching +v1's ``MCPPerUserTokenCache`` (same NaCl encryption and key, so a token cached by either is readable by +the other across the cutover). A missing or undecryptable entry reads as a miss. +""" + +from __future__ import annotations + +from dataclasses import KW_ONLY, dataclass +from typing import Protocol + +from litellm._logging import verbose_logger +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.token_cache_codec import ( + OAuthTokenCacheCodec, +) + + +class AsyncCache(Protocol): + """The slice of LiteLLM's ``DualCache`` this backend needs (Redis-backed, shared across workers).""" + + async def async_get_cache(self, key: str) -> object | None: ... + + async def async_set_cache(self, key: str, value: str, ttl: float | None = None) -> None: ... + + async def async_delete_cache(self, key: str) -> None: ... + + +@dataclass(frozen=True, slots=True) +class DualCacheTokenCacheBackend: + """Every method degrades a cache or codec failure to its safe value - ``get`` to a miss + (``None``), ``set``/``delete`` to a no-op - so a Redis outage or an undecryptable entry reads as a + cache miss rather than a request error, matching v1 and this layer's "boundary failure = miss" + contract. The guarantee holds here regardless of whether the injected cache/codec also swallow. + """ + + cache: AsyncCache + codec: OAuthTokenCacheCodec + _: KW_ONLY + key_prefix: str = "mcp:per_user_token:" + + def _key(self, user_id: str, server_id: str) -> str: + return f"{self.key_prefix}{user_id}:{server_id}" + + async def get(self, user_id: str, server_id: str) -> OAuthToken | None: + try: + blob = await self.cache.async_get_cache(self._key(user_id, server_id)) + return self.codec.decode(blob) if isinstance(blob, str) else None + except Exception as exc: # noqa: BLE001 + verbose_logger.debug("MCP per-user token cache get failed (miss): %s", exc) + return None + + async def set(self, user_id: str, server_id: str, token: OAuthToken, ttl_seconds: float) -> None: + if ttl_seconds <= 0: + return + try: + await self.cache.async_set_cache( + self._key(user_id, server_id), + self.codec.encode(token), + ttl=ttl_seconds, + ) + except Exception as exc: # noqa: BLE001 + verbose_logger.debug("MCP per-user token cache set failed (ignored): %s", exc) + + async def delete(self, user_id: str, server_id: str) -> None: + try: + await self.cache.async_delete_cache(self._key(user_id, server_id)) + except Exception as exc: # noqa: BLE001 + verbose_logger.debug("MCP per-user token cache delete failed (ignored): %s", exc) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py index 2345fa981235..e4d8fd25748e 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/httpx_auth.py @@ -19,9 +19,7 @@ class NoOpAuth(httpx.Auth): """Attaches nothing — the `none` mode (and the seam-level default).""" - def auth_flow( - self, request: httpx.Request - ) -> Generator[httpx.Request, httpx.Response, None]: + def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]: yield request @@ -38,8 +36,6 @@ def __init__(self, header_value: str, header_name: str = "Authorization") -> Non self.header_name = header_name self._header_value = SecretStr(header_value) - def auth_flow( - self, request: httpx.Request - ) -> Generator[httpx.Request, httpx.Response, None]: + def auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]: request.headers[self.header_name] = self._header_value.get_secret_value() yield request diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/oauth_token_store.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/oauth_token_store.py new file mode 100644 index 000000000000..fd2cb2f3e06e --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/oauth_token_store.py @@ -0,0 +1,289 @@ +"""Per-user OAuth token store for the ``authorization_code`` mode. + +The resolver reads a user's token through the injected ``OAuthTokenStore`` seam; +``CachedOAuthTokenStore`` is an expiry-aware cache in front of it. ``TokenStoreUnavailable`` +signals an unreachable backing store, so an outage is never cached or read as "not authorized". + +``RefreshingTokenStore`` mints a fresh token through an injected ``TokenRefresher`` when the stored +one is near expiry, under in-process per-(user, server) single-flight so concurrent callers share +one refresh. Distributed (cross-replica) single-flight and reactive-401 refresh are the later +hardening. The mode plugs in its own source and refresher; the cache, store seam, and refresh +machinery are shared across the oauth2 modes (authorization_code / client_credentials / +token_exchange). +""" + +from __future__ import annotations + +import asyncio +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Protocol + + +@dataclass(frozen=True, slots=True, repr=False) +class OAuthToken: + """A user's OAuth credential: the bearer value, when it expires, and how to refresh it. + + ``expires_at`` is epoch seconds (``None`` means no known expiry). ``refresh_token`` is what a + ``TokenRefresher`` uses to mint a new access token when this one nears expiry (the refresh + mechanism, ``RefreshingTokenStore``, is in this module; the concrete per-mode refresher lands + with each mode); it is never minted into a header directly. ``repr`` masks both secrets so a + stray log line cannot leak them (the values are still plain ``str`` for the header path, since + ``SecretStr`` resolves as unknown under this repo's basedpyright). + + ``scopes`` is the recorded grant. A refresh response that omits ``scope`` (RFC 6749 §5.1: an + omitted ``scope`` means unchanged) carries the prior value forward, so a refresh never silently + drops it; the resolver itself does not read it. + """ + + access_token: str + expires_at: float | None = None + refresh_token: str | None = None + scopes: tuple[str, ...] = () + + def __repr__(self) -> str: + has_refresh = self.refresh_token is not None + return f"OAuthToken(access_token=***, expires_at={self.expires_at!r}, has_refresh_token={has_refresh}, scopes={self.scopes!r})" + + +class TokenStoreUnavailable(Exception): + """Raised by ``fetch`` when the backing token store is unreachable (e.g. the DB is down). + + Distinct from returning ``None`` for "the user has not authorized this server": a read-through + cache skips caching the failure, and the resolver maps it to its fail-closed status rather than + treating an outage as a definite absence. + """ + + +class OAuthTokenStore(Protocol): + """Per-user OAuth token lookup for the ``authorization_code`` mode. + + Returns the user's token for an upstream, or ``None`` when they have not completed the OAuth + flow (the arm turns that into a 401 challenge). The ``(user_id, server_id)`` pair fully scopes + the lookup, so an implementation must never return one subject's token to another. Raises + ``TokenStoreUnavailable`` when the backing store is unreachable, so an outage is never cached or + read as a definite absence. + """ + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: ... + + +class TokenRefresher(Protocol): + """Mints a fresh token from an expired one and persists it, returning the new token. + + The action is mode-specific: the ``authorization_code`` refresh_token grant, the + ``client_credentials`` grant, or an RFC 8693 re-exchange. Returns ``None`` when it cannot + refresh (e.g. no ``refresh_token``), which the caller turns into a 401 challenge. It must + persist the new token so later requests (and the surrounding cache) read it without refreshing. + + ``server_id`` selects the upstream's config (token endpoint, client credentials, scopes) the + grant runs against; ``(user_id, server_id)`` is the key the new token is persisted under. They + are not derivable from ``token``, so the seam threads them alongside it. + """ + + async def refresh(self, user_id: str, server_id: str, token: OAuthToken) -> OAuthToken | None: ... + + +class TokenCacheBackend(Protocol): + """Storage behind ``CachedOAuthTokenStore``: hold a token under ``(user_id, server_id)`` for + ``ttl_seconds``, then forget it. The default ``InMemoryTokenCacheBackend`` is per-process; a + cross-replica deployment injects a shared (Redis) backend so every worker reads one refresh, + matching v1. ``get`` returns ``None`` once the entry's TTL has elapsed. + """ + + async def get(self, user_id: str, server_id: str) -> OAuthToken | None: ... + + async def set(self, user_id: str, server_id: str, token: OAuthToken, ttl_seconds: float) -> None: ... + + async def delete(self, user_id: str, server_id: str) -> None: ... + + +class InMemoryTokenCacheBackend: + """Per-process token cache: a bounded dict with wall-clock TTLs (the default backend).""" + + def __init__(self, *, max_size: int = 4096, clock: Callable[[], float] = time.time) -> None: + self._max_size = max_size + self._clock = clock + self._cache: dict[tuple[str, str], tuple[OAuthToken, float]] = {} + + async def get(self, user_id: str, server_id: str) -> OAuthToken | None: + key = (user_id, server_id) + hit = self._cache.get(key) + if hit is None: + return None + token, valid_until = hit + if self._clock() < valid_until: + return token + self._cache.pop(key, None) + return None + + async def set(self, user_id: str, server_id: str, token: OAuthToken, ttl_seconds: float) -> None: + key = (user_id, server_id) + if key not in self._cache and len(self._cache) >= self._max_size: + # Evict the oldest entry (insertion order), rather than clearing the whole cache and + # forcing every key to re-read the store at once. + self._cache.pop(next(iter(self._cache)), None) + self._cache[key] = (token, self._clock() + ttl_seconds) + + async def delete(self, user_id: str, server_id: str) -> None: + self._cache.pop((user_id, server_id), None) + + +class CachedOAuthTokenStore: + """Expiry-aware cache over an ``OAuthTokenStore``. Caches positive tokens only. + + A cached token is served only while it is unexpired (minus ``expiry_skew_seconds``), or for + ``default_ttl_seconds`` if it carries no expiry; past that the inner store is read again. A + "not authorized" (``None``) result is never cached: every miss re-reads the inner store, so a + token written after the OAuth flow is visible immediately on every replica, matching v1 (which + never caches misses). The clock is injected (wall-clock, since ``expires_at`` is epoch) so + expiry is deterministic in tests, and a store outage (``TokenStoreUnavailable``) propagates + without being cached. + """ + + def __init__( + self, + inner: OAuthTokenStore, + *, + default_ttl_seconds: float, + expiry_skew_seconds: float = 60.0, + max_size: int = 4096, + backend: TokenCacheBackend | None = None, + clock: Callable[[], float] = time.time, + ) -> None: + self._inner = inner + self._default_ttl_seconds = default_ttl_seconds + self._expiry_skew_seconds = expiry_skew_seconds + self._clock = clock + self._backend: TokenCacheBackend = backend or InMemoryTokenCacheBackend(max_size=max_size, clock=clock) + + def _ttl(self, token: OAuthToken) -> float: + if token.expires_at is not None: + return max(0.0, token.expires_at - self._expiry_skew_seconds - self._clock()) + return self._default_ttl_seconds + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: + hit = await self._backend.get(user_id, server_id) + if hit is not None: + return hit + + token = await self._inner.fetch(user_id, server_id) + if token is None: + # Never cache "not authorized": drop any stale entry and re-read on the next call, so + # a token stored after the OAuth flow is seen immediately rather than after a TTL. + await self._backend.delete(user_id, server_id) + return token + await self._backend.set(user_id, server_id, token, self._ttl(token)) + return token + + async def invalidate(self, user_id: str, server_id: str) -> None: + """Drop a cached entry after the user (re)authorizes or revokes, so a stale token or a + stale "not authorized" None cannot mask the change.""" + await self._backend.delete(user_id, server_id) + + +class RefreshCoordinator(Protocol): + """Ensures one refresh runs per ``(user_id, server_id)`` at a time. Concurrent callers either + share the winner's result (the default ``InProcessRefreshCoordinator``) or, in a cross-replica + coordinator, wait for the holder and ``reread`` the token it persisted - so the IdP sees one + refresh per key across all workers, not one per worker. + """ + + async def run( + self, + user_id: str, + server_id: str, + refresh: Callable[[], Awaitable[OAuthToken | None]], + reread: Callable[[], Awaitable[OAuthToken | None]], + ) -> OAuthToken | None: ... + + +class InProcessRefreshCoordinator: + """Single-flight within one event loop (the default): the first caller per key refreshes while + concurrent callers await the same in-flight task and share its result. ``reread`` is unused here - + the shared task already yields the new token - and exists for the cross-replica coordinator, where + losers re-read the persisted token instead of sharing an in-process future. + """ + + def __init__(self) -> None: + # In-flight refreshes, one task per (user, server); each entry is removed by the task's + # done-callback, so the map is bounded by concurrent refreshes, not by distinct keys seen. + self._inflight: dict[tuple[str, str], asyncio.Future[OAuthToken | None]] = {} + + async def run( + self, + user_id: str, + server_id: str, + refresh: Callable[[], Awaitable[OAuthToken | None]], + reread: Callable[[], Awaitable[OAuthToken | None]], + ) -> OAuthToken | None: + key = (user_id, server_id) + task = self._inflight.get(key) + if task is None: + # The task is detached from the caller, so a cancelled caller does not abort the refresh. + task = asyncio.ensure_future(refresh()) + self._inflight[key] = task + task.add_done_callback(lambda _t, k=key: self._inflight.pop(k, None)) + return await task + + +class RefreshingTokenStore: + """An ``OAuthTokenStore`` that proactively refreshes a near-expiry token. + + Reads from an inner store; if the token is within ``expiry_skew_seconds`` of expiry, it mints a + fresh one via the injected ``TokenRefresher``, serialized per ``(user, server)`` by the injected + ``RefreshCoordinator`` so callers don't stampede the IdP. The refresher persists the new token so + later requests (and the surrounding cache) read it without refreshing again. An expired token the + refresher cannot renew (``None``) is surfaced as ``None`` so the arm challenges, never a stale + bearer. + + The default coordinator is in-process; a cross-replica deployment injects a distributed one (Redis + SET NX). Reactive-401 refresh is later hardening (it lives in the egress transport, which sees the + upstream's 401). Composes under ``CachedOAuthTokenStore`` so the refreshed token is cached. + """ + + def __init__( + self, + inner: OAuthTokenStore, + refresher: TokenRefresher, + *, + expiry_skew_seconds: float = 60.0, + coordinator: RefreshCoordinator | None = None, + clock: Callable[[], float] = time.time, + ) -> None: + self._inner = inner + self._refresher = refresher + self._expiry_skew_seconds = expiry_skew_seconds + self._clock = clock + self._coordinator: RefreshCoordinator = coordinator or InProcessRefreshCoordinator() + + def _is_expired(self, token: OAuthToken) -> bool: + return token.expires_at is not None and self._clock() >= token.expires_at - self._expiry_skew_seconds + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: + token = await self._inner.fetch(user_id, server_id) + if token is None or not self._is_expired(token): + return token + + async def refresh_latest_token() -> OAuthToken | None: + latest_token = await self._inner.fetch(user_id, server_id) + if latest_token is None or not self._is_expired(latest_token): + return latest_token + return await self._refresher.refresh(user_id, server_id, latest_token) + + async def reread_fresh_token() -> OAuthToken | None: + # A loser re-reads what the winner persisted. If the winner's refresh failed, the store + # still holds the expired token; surface None (-> challenge) like the winner did rather + # than the stale bearer the upstream would 401. + latest_token = await self._inner.fetch(user_id, server_id) + if latest_token is None or self._is_expired(latest_token): + return None + return latest_token + + return await self._coordinator.run( + user_id, + server_id, + refresh=refresh_latest_token, + reread=reread_fresh_token, + ) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.py new file mode 100644 index 000000000000..7453709f358d --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/per_user_oauth_store.py @@ -0,0 +1,225 @@ +"""Composition root for the v2-native authorization_code per-user OAuth token store (step 1b). + +Assembles ``Cached(Refreshing(V2PerUserTokenStore))`` and replaces ``V1PerUserTokenStore`` in the +resolver. The runtime collaborators (DB, HTTP, the shared cache, Redis) are LiteLLM globals not ready +at import time, so the chain is built lazily on first use. When Redis is wired it uses the +cross-replica path (DualCache-backed cache + ``SET NX PX`` coordinator); otherwise it falls back to +the foundation's in-process defaults (correct for a single replica). The DB read/refresh-grant/persist +collaborators acquire their globals per call, mirroring v1's lazy-import pattern. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable +from typing import TYPE_CHECKING + +from litellm._logging import verbose_logger +from litellm.proxy._experimental.mcp_server.outbound_credentials.authz_code_refresher import ( + AuthorizationCodeRefresher, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.dual_cache_token_backend import ( + AsyncCache, + DualCacheTokenCacheBackend, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + CachedOAuthTokenStore, + OAuthToken, + OAuthTokenStore, + RefreshCoordinator, + RefreshingTokenStore, + TokenCacheBackend, + TokenStoreUnavailable, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.redis_distributed_lock import ( + RedisDistributedLock, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.redis_refresh_coordinator import ( + RedisRefreshCoordinator, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.token_cache_codec import ( + OAuthTokenCacheCodec, +) +from litellm.proxy._experimental.mcp_server.outbound_credentials.v2_token_store import ( + V2PerUserTokenStore, +) + +if TYPE_CHECKING: + from litellm.types.mcp_server.mcp_server_manager import MCPServer + +# A token with no declared expiry is cached for this long; one with an expiry is cached until then. +_DEFAULT_TTL_SECONDS = 300.0 + +ServerLookup = Callable[[str], "MCPServer | None"] +StoreBuilder = Callable[[ServerLookup], tuple[OAuthTokenStore, bool]] + + +async def _read_credential(user_id: str, server_id: str) -> dict[str, object] | None: + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + get_user_oauth_credential, + ) + from litellm.proxy.proxy_server import prisma_client # noqa: PLC0415 + + if prisma_client is None: + raise TokenStoreUnavailable("Database not connected") + return await get_user_oauth_credential(prisma_client, user_id, server_id) + + +async def _persist_credential( + user_id: str, + server_id: str, + access_token: str, + refresh_token: str | None, + expires_in: int | None, + scopes: tuple[str, ...] | None, +) -> None: + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + store_user_oauth_credential, + ) + from litellm.proxy.proxy_server import prisma_client # noqa: PLC0415 + + if prisma_client is None: + return + await store_user_oauth_credential( + prisma_client=prisma_client, + user_id=user_id, + server_id=server_id, + access_token=access_token, + refresh_token=refresh_token, + expires_in=expires_in, + scopes=list(scopes) if scopes else None, + skip_byok_guard=True, + ) + + +async def _post_token_endpoint(url: str, form: dict[str, str]) -> dict[str, object] | None: + from litellm.llms.custom_httpx.http_handler import ( # noqa: PLC0415 + get_async_httpx_client, # pyright: ignore + ) + from litellm.types.llms.custom_http import httpxSpecialProvider # noqa: PLC0415 + + # litellm's httpx handler and httpx.Response are only partially typed; the IdP returns a JSON + # object and the refresher validates each field, so the untyped boundary is contained here. + provider = httpxSpecialProvider.Oauth2Check + headers = {"Accept": "application/json"} + # A failed refresh is a miss, not a 500 (matches v1), so any error becomes None. + try: + client = get_async_httpx_client(llm_provider=provider) # pyright: ignore + response = await client.post(url, headers=headers, data=form) # pyright: ignore + response.raise_for_status() # pyright: ignore + body: dict[str, object] = response.json() # pyright: ignore + except Exception as exc: # noqa: BLE001 + verbose_logger.warning("MCP OAuth refresh request failed: %s", exc) + return None + else: + return body # pyright: ignore + + +def _redis_cache_is_available() -> bool: + from litellm.proxy.proxy_server import user_api_key_cache # noqa: PLC0415 + + return user_api_key_cache.redis_cache is not None + + +def _runtime_backend_and_coordinator() -> tuple[TokenCacheBackend | None, RefreshCoordinator | None, bool]: + """The cross-replica cache + coordinator when Redis is wired, else ``(None, None, False)`` so the + foundation's in-process defaults are used (a single replica needs no shared cache or lock). + """ + from litellm.proxy.common_utils.encrypt_decrypt_utils import ( # noqa: PLC0415 + decrypt_value_helper, + encrypt_value_helper, + ) + from litellm.proxy.proxy_server import user_api_key_cache # noqa: PLC0415 + + redis_cache = user_api_key_cache.redis_cache + if redis_cache is None: + return None, None, False + codec = OAuthTokenCacheCodec( + encrypt_value_helper, + lambda blob: decrypt_value_helper(blob, "mcp_per_user_token", exception_type="debug"), + ) + # user_api_key_cache satisfies the AsyncCache slice (DualCache types ttl via **kwargs) and the + # Redis client from init_async_client() is partially typed - both are untyped-boundary casts. + cache: AsyncCache = user_api_key_cache # pyright: ignore + redis_client = redis_cache.init_async_client() # pyright: ignore + lock = RedisDistributedLock( + redis_client, # pyright: ignore + namespace_key=redis_cache.check_and_fix_namespace, + ) + backend = DualCacheTokenCacheBackend(cache, codec) + coordinator = RedisRefreshCoordinator(lock) + return backend, coordinator, True + + +def _build_per_user_oauth_token_store( + server_lookup: ServerLookup, +) -> tuple[CachedOAuthTokenStore, bool]: + backend, coordinator, uses_redis = _runtime_backend_and_coordinator() + refresher = AuthorizationCodeRefresher(server_lookup, _post_token_endpoint, _persist_credential) + refreshing = RefreshingTokenStore(V2PerUserTokenStore(_read_credential), refresher, coordinator=coordinator) + return CachedOAuthTokenStore(refreshing, default_ttl_seconds=_DEFAULT_TTL_SECONDS, backend=backend), uses_redis + + +def build_per_user_oauth_token_store( + server_lookup: ServerLookup, +) -> CachedOAuthTokenStore: + store, _uses_redis = _build_per_user_oauth_token_store(server_lookup) + return store + + +class LazyPerUserOAuthTokenStore: + """``OAuthTokenStore`` that builds the v2-native chain on first ``fetch``. + + The chain's cache/lock collaborators are LiteLLM runtime globals not available when the resolver + is constructed at import time, so construction is deferred to the first request (by when they are + wired). A no-Redis chain is replaced once Redis becomes available. + """ + + def __init__( + self, + server_lookup: ServerLookup, + *, + store_builder: StoreBuilder = _build_per_user_oauth_token_store, + redis_available: Callable[[], bool] = _redis_cache_is_available, + ) -> None: + self._server_lookup = server_lookup + self._store_builder = store_builder + self._redis_available = redis_available + self._store: OAuthTokenStore | None = None + self._uses_redis = False + self._fetch_lock = asyncio.Condition() + self._local_fetches = 0 + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: + if self._uses_redis: + store = self._store + if store is not None: + return await store.fetch(user_id, server_id) + + store, uses_redis = await self._store_for_fetch() + try: + return await store.fetch(user_id, server_id) + finally: + if not uses_redis: + await self._finish_local_fetch() + + async def _store_for_fetch(self) -> tuple[OAuthTokenStore, bool]: + async with self._fetch_lock: + while ( + self._store is not None and not self._uses_redis and self._redis_available() and self._local_fetches > 0 + ): + await self._fetch_lock.wait() + store = self._store + if store is None or (not self._uses_redis and self._redis_available()): + store, self._uses_redis = self._store_builder(self._server_lookup) + self._store = store + uses_redis = self._uses_redis + if not uses_redis: + self._local_fetches += 1 + return store, uses_redis + + async def _finish_local_fetch(self) -> None: + async with self._fetch_lock: + self._local_fetches -= 1 + if self._local_fetches == 0: + self._fetch_lock.notify_all() diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/presented_token_store.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/presented_token_store.py new file mode 100644 index 000000000000..c88d31dd6bc2 --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/presented_token_store.py @@ -0,0 +1,26 @@ +"""One-shot ``OAuthTokenStore`` for the create/test tools preview. + +The preview tests an unsaved server, so no per-user credential is persisted yet. The operator holds +the just-authorized token; this serves it through the same v2 resolver path runtime uses for the +stored token, so the preview never relies on the caller-credential-override path that +``_create_mcp_client`` refuses for ``authorization_code``. It backs a single preview call, so it +returns its one token regardless of the lookup key. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, +) + + +@dataclass(frozen=True, slots=True) +class PresentedOAuthTokenStore: + """Serves one in-hand token for the single preview call it backs (no DB, no cache).""" + + token: OAuthToken + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: + return self.token diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/redis_distributed_lock.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/redis_distributed_lock.py new file mode 100644 index 000000000000..e31539073537 --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/redis_distributed_lock.py @@ -0,0 +1,94 @@ +"""Concrete ``DistributedLock`` over a Redis client: ``SET NX PX`` / owner-only renew / delete. + +The cross-replica lock the ``RedisRefreshCoordinator`` elects refreshers with. ``acquire`` is an +atomic ``SET key token NX PX ttl`` (only the first caller wins; the entry self-expires so a crashed +holder can't wedge refresh). ``extend`` renews the lease only when the token still matches, and +``release`` deletes the key only when it still holds this caller's token, so a holder whose lock already +PX-expired and was re-acquired by another worker cannot delete the new holder's lock. ``is_held`` is +``EXISTS``. Every key is run through the injected ``namespace_key`` before it reaches Redis, so lock +keys carry the same namespace as cache keys and cannot collide with another deployment sharing Redis. + +The Redis client is injected (in production the async client from LiteLLM's ``RedisCache``), so the +lock is unit-testable with a fake. A transport error on ``acquire`` returns ``LockAcquisition.ERROR`` - +distinct from ``HELD`` - so the coordinator refreshes anyway instead of mistaking a dead backend for a +busy holder; a Redis blip degrades to an extra refresh, never a stale bearer. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import KW_ONLY, dataclass +from typing import Protocol + +from litellm._logging import verbose_logger +from litellm.proxy._experimental.mcp_server.outbound_credentials.redis_refresh_coordinator import ( + LockAcquisition, +) + +# Delete the key only if it still holds this caller's token, so a holder whose lock already expired +# (PX) and was re-acquired by another worker cannot delete the new holder's lock. +_RELEASE_IF_OWNER = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end" +_EXTEND_IF_OWNER = ( + "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('pexpire', KEYS[1], ARGV[2]) else return 0 end" +) + + +class RedisCommands(Protocol): + """The slice of the async Redis client this lock needs.""" + + async def set(self, name: str, value: str, *, nx: bool = False, px: int | None = None) -> object | None: ... + + async def eval(self, script: str, numkeys: int, *keys_and_args: str) -> object: ... + + async def exists(self, *names: str) -> int: ... + + +@dataclass(frozen=True, slots=True) +class RedisDistributedLock: + client: RedisCommands + _: KW_ONLY + namespace_key: Callable[[str], str] = lambda key: key + + async def acquire(self, key: str, token: str, ttl_seconds: float) -> LockAcquisition: + try: + result = await self.client.set(self.namespace_key(key), token, nx=True, px=int(ttl_seconds * 1000)) + # Degrade on any Redis client error: redis.exceptions narrows only via an import that + # is Unknown under basedpyright, and the lock must never crash the resolve path. + except Exception as exc: # noqa: BLE001 + verbose_logger.warning("RedisDistributedLock.acquire failed: %s", exc) + return LockAcquisition.ERROR + return LockAcquisition.ACQUIRED if result is not None else LockAcquisition.HELD + + async def extend(self, key: str, token: str, ttl_seconds: float) -> bool: + try: + result = await self.client.eval( + _EXTEND_IF_OWNER, + 1, + self.namespace_key(key), + token, + str(int(ttl_seconds * 1000)), + ) + # Degrade on any Redis client error: redis.exceptions narrows only via an import that + # is Unknown under basedpyright, and the lock must never crash the resolve path. + except Exception as exc: # noqa: BLE001 + verbose_logger.warning("RedisDistributedLock.extend failed: %s", exc) + return False + return result == 1 + + async def release(self, key: str, token: str) -> None: + try: + await self.client.eval(_RELEASE_IF_OWNER, 1, self.namespace_key(key), token) + # Degrade on any Redis client error: redis.exceptions narrows only via an import that + # is Unknown under basedpyright, and the lock must never crash the resolve path. + except Exception as exc: # noqa: BLE001 + verbose_logger.warning("RedisDistributedLock.release failed: %s", exc) + + async def is_held(self, key: str) -> bool: + try: + return await self.client.exists(self.namespace_key(key)) > 0 + # Degrade on any Redis client error: redis.exceptions narrows only via an import that + # is Unknown under basedpyright, and the lock must never crash the resolve path. + except Exception as exc: # noqa: BLE001 + # On error, report "not held" so a waiter stops waiting and re-reads rather than blocking. + verbose_logger.warning("RedisDistributedLock.is_held failed: %s", exc) + return False diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/redis_refresh_coordinator.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/redis_refresh_coordinator.py new file mode 100644 index 000000000000..317f7c703e70 --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/redis_refresh_coordinator.py @@ -0,0 +1,136 @@ +"""Cross-replica ``RefreshCoordinator``: one refresh per ``(user, server)`` across all workers. + +Plugs into the foundation's ``RefreshingTokenStore`` via the ``RefreshCoordinator`` seam. A ``SET NX +PX`` lock elects one worker to run the refresh while the rest wait for it and re-read the token it +persisted - so a rotating refresh_token is used once across the fleet, not once per worker. The holder +renews the ``PX`` lease while refresh runs (up to a refresh budget, so a hung endpoint can't hold the +lock forever), and a loser waits longer than that budget - so a loser only re-reads once the holder has +finished or its bounded lease has lapsed, never mid-refresh, and the surrounding store re-checks expiry +on the next fetch, so a crash self-heals rather than serving stale forever. Reading needs no lock, so +losers don't serialize behind each other. The lock is injected (a thin Redis wrapper in production, a +fake in tests). + +The lock is a single-flight optimization, not a correctness mutex, so it fails open: when the lock +backend is unreachable, ``acquire`` reports ``ERROR`` (distinct from ``HELD``) and this coordinator +refreshes anyway rather than wait on a holder that may not exist and then serve a still-expired token. +That degrades a Redis outage to the no-coordinator behavior (each worker may refresh), never a stale +bearer the upstream would 401. +""" + +from __future__ import annotations + +import asyncio +import time +import uuid +from collections.abc import Awaitable, Callable +from contextlib import suppress +from dataclasses import KW_ONLY, dataclass +from enum import Enum +from typing import Protocol + +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, +) + + +class LockAcquisition(Enum): + """Outcome of a best-effort ``acquire``. ``ERROR`` is kept distinct from ``HELD`` so a caller can + tell "someone else is refreshing" (wait and re-read) from "the lock backend is down" (no election + happened, so refresh anyway) instead of conflating both into a single ``False``.""" + + ACQUIRED = "acquired" # won the election; this worker refreshes + HELD = "held" # another worker holds it; wait then re-read + ERROR = "error" # lock backend unreachable; holder unknown, so refresh anyway + + +class DistributedLock(Protocol): + """A best-effort cross-replica lock. ``acquire`` is ``SET key token NX PX ttl`` reported as a + ``LockAcquisition`` (won / held by another / backend error); ``release`` deletes the key only if + it still holds this caller's ``token`` (so it cannot delete a lock another worker re-acquired + after PX-expiry); ``extend`` refreshes the ``PX`` lease only for the owner; ``is_held`` is + ``EXISTS`` (so a waiter can poll without taking the lock).""" + + async def acquire(self, key: str, token: str, ttl_seconds: float) -> LockAcquisition: ... + + async def extend(self, key: str, token: str, ttl_seconds: float) -> bool: ... + + async def release(self, key: str, token: str) -> None: ... + + async def is_held(self, key: str) -> bool: ... + + +@dataclass(frozen=True, slots=True) +class RedisRefreshCoordinator: + lock: DistributedLock + _: KW_ONLY + key_prefix: str = "mcp:refresh_lock:" + lock_ttl_seconds: float = 10.0 + # The holder renews its lease while a slow token endpoint runs, but only up to this budget; past it + # it stops renewing and the lock lapses, so a hung refresh degrades to "maybe an extra refresh" + # rather than holding every loser behind it indefinitely. + refresh_budget_seconds: float = 20.0 + # How long a loser waits for the holder before giving up and re-reading. It MUST outlast the + # holder's max lock-hold (refresh_budget_seconds + one lock_ttl_seconds tail); otherwise a loser + # bails while the holder is still legitimately refreshing, re-reads the still-expired token, and + # challenges the user mid-refresh. + wait_timeout_seconds: float = 35.0 + poll_interval_seconds: float = 0.05 + sleep: Callable[[float], Awaitable[None]] = asyncio.sleep + clock: Callable[[], float] = time.monotonic + new_token: Callable[[], str] = lambda: uuid.uuid4().hex + + def _key(self, user_id: str, server_id: str) -> str: + return f"{self.key_prefix}{user_id}:{server_id}" + + async def run( + self, + user_id: str, + server_id: str, + refresh: Callable[[], Awaitable[OAuthToken | None]], + reread: Callable[[], Awaitable[OAuthToken | None]], + ) -> OAuthToken | None: + key = self._key(user_id, server_id) + token = self.new_token() + match await self.lock.acquire(key, token, self.lock_ttl_seconds): + case LockAcquisition.ACQUIRED: + return await self._refresh_with_lease_renewal(key, token, refresh) + case LockAcquisition.ERROR: + # No election happened (lock backend down), so waiting would just re-read the + # still-expired token. Refresh anyway; worst case is an extra refresh, not a stale bearer. + return await refresh() + case LockAcquisition.HELD: + # Another worker holds the lock; wait for it to finish (release or PX-expiry), then read + # the token it persisted - the winner wrote the fresh token to the store, so a plain + # re-read sees it without us refreshing again. + deadline = self.clock() + self.wait_timeout_seconds + while self.clock() < deadline and await self.lock.is_held(key): + await self.sleep(self.poll_interval_seconds) + return await reread() + + async def _refresh_with_lease_renewal( + self, + key: str, + token: str, + refresh: Callable[[], Awaitable[OAuthToken | None]], + ) -> OAuthToken | None: + refresh_task = asyncio.ensure_future(refresh()) + renewal_task = asyncio.create_task(self._renew_lease_until_done(key, token, refresh_task)) + try: + return await refresh_task + finally: + renewal_task.cancel() + with suppress(asyncio.CancelledError): + await renewal_task + await self.lock.release(key, token) + + async def _renew_lease_until_done( + self, + key: str, + token: str, + refresh_task: asyncio.Future[OAuthToken | None], + ) -> None: + budget_deadline = self.clock() + self.refresh_budget_seconds + while not refresh_task.done() and self.clock() < budget_deadline: + await self.sleep(self.lock_ttl_seconds / 2) + if not refresh_task.done() and not await self.lock.extend(key, token, self.lock_ttl_seconds): + return diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py index 969bbf01ec82..f9a9fa00b239 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/resolver.py @@ -7,9 +7,9 @@ an arm fails the type gate (basedpyright `reportMatchNotExhaustive`); a bypassed gate fails loudly at runtime instead of returning `None`. -`none` and `api_key` (shared-key source) are live; the remaining arms are `not_implemented` -stubs that each land in a follow-up PR with their injected seam. The self-contained arms read -straight from the config and need no collaborator. Pure v2: no imports from v1. +`none` and `api_key` (shared-key source) are live, as is `authorization_code`, which reads the +user's token from the injected `OAuthTokenStore`. The remaining arms are `not_implemented` stubs +that each land in a follow-up PR with their seam. Pure v2: no imports from v1. """ from __future__ import annotations @@ -21,6 +21,11 @@ NoOpAuth, StaticHeaderAuth, ) +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, + OAuthTokenStore, + TokenStoreUnavailable, +) from litellm.proxy._experimental.mcp_server.outbound_credentials.result import ( Error, Ok, @@ -43,16 +48,25 @@ ) +class _NullOAuthTokenStore: + """Fail-closed default: with no token store wired, every user reads as not authorized.""" + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: + return None + + class UpstreamCredentialProvider: """Produces the one `httpx.Auth` for a `(subject, upstream)` pair, per declared mode. - Collaborators (the per-mode credential stores and token fetchers) are injected as each arm - is built; the live `none` and `api_key`-shared arms read from the config and need none. + Collaborators (the per-mode credential stores and token fetchers) are injected as each arm is + built; the live `none` and `api_key`-shared arms read from the config and need none, while + `authorization_code` reads the user's token from the injected `OAuthTokenStore`. """ - async def resolve_credentials( - self, subject: Subject, server: ServerSpec - ) -> Result[httpx.Auth, CredError]: + def __init__(self, oauth_token_store: OAuthTokenStore | None = None) -> None: + self._oauth_token_store: OAuthTokenStore = oauth_token_store or _NullOAuthTokenStore() + + async def resolve_credentials(self, subject: Subject, server: ServerSpec) -> Result[httpx.Auth, CredError]: match server.config: case NoneConfig(): return Ok(NoOpAuth()) @@ -65,29 +79,48 @@ async def resolve_credentials( case TokenExchangeConfig(): return _not_implemented(AuthSpecKind.token_exchange) case AuthorizationCodeConfig(): - return _not_implemented(AuthSpecKind.authorization_code) + return await self._authorization_code(subject, server) case AwsSigV4Config(): return _not_implemented(AuthSpecKind.aws_sigv4) assert_never(server.config) + async def has_user_token(self, subject: Subject, server: ServerSpec) -> bool: + """Whether a usable per-user token exists for this server (the preemptive 401's check). + + Reads from the same per-user store as the ``authorization_code`` arm, so the discovery + challenge and the egress agree on whether the user is authorized. Returns a typed ``bool`` + (no ``httpx.Auth``), unlike ``resolve_credentials``. A non-per-user mode has no token in the + store, so it reads as False without a per-mode branch here. + """ + return await self._authz_token(subject, server) is not None + def _api_key(self, config: ApiKeyConfig) -> Result[httpx.Auth, CredError]: match config.key_source: case SharedKey() as source: - header_name, header_value = config.header( - source.value.get_secret_value() - ) + header_name, header_value = config.header(source.value.get_secret_value()) return Ok(StaticHeaderAuth(header_value, header_name=header_name)) case Byok(): # Per-user key pulled from the credential store; lands with that seam. - return Error( - CredError.of_not_implemented( - "api_key BYOK source not implemented yet" - ) - ) + return Error(CredError.of_not_implemented("api_key BYOK source not implemented yet")) assert_never(config.key_source) + async def _authorization_code(self, subject: Subject, server: ServerSpec) -> Result[StaticHeaderAuth, CredError]: + token = await self._authz_token(subject, server) + if token is None: + return Error(CredError.of_unauthorized("Authorization required: complete the OAuth flow for this server.")) + return Ok(StaticHeaderAuth(f"Bearer {token.access_token}", header_name="Authorization")) + + async def _authz_token(self, subject: Subject, server: ServerSpec) -> OAuthToken | None: + """The user's authorization_code token, or None when absent or the store is unreachable. + + A store outage is mapped to None (the OAuth challenge), not raised, so a transient outage + does not 500; it is the store, not this resolver, that declines to cache the failure. + """ + try: + return await self._oauth_token_store.fetch(subject.subject_id, server.server_id) + except TokenStoreUnavailable: + return None + def _not_implemented(kind: AuthSpecKind) -> Result[httpx.Auth, CredError]: - return Error( - CredError.of_not_implemented(f"{kind.value}: resolver arm not implemented yet") - ) + return Error(CredError.of_not_implemented(f"{kind.value}: resolver arm not implemented yet")) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_cache_codec.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_cache_codec.py new file mode 100644 index 000000000000..b0ed708f607e --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/token_cache_codec.py @@ -0,0 +1,34 @@ +"""Serialize + encrypt boundary for caching an OAuth token in a shared (Redis) cache. + +A cross-replica cache must serialize the token, and a plaintext bearer in Redis is a leak, so this +encrypts the value (NaCl in production via the injected ``encrypt``, identity in tests). It caches +**only** the ``access_token``: the hot path needs just the bearer, expiry is carried by the cache +entry's TTL (set from the token's ``expires_at`` by the cache), and the long-lived refresh_token stays +in the DB - the refresh path is always a cache miss that re-reads it - so it never reaches Redis. A +decoded token therefore carries only the bearer (``expires_at`` and ``refresh_token`` both None); the +TTL, not the value, bounds its life. An empty/undecryptable blob (e.g. master-key rotation) is a miss. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass + +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, +) + + +@dataclass(frozen=True, slots=True) +class OAuthTokenCacheCodec: + encrypt: Callable[[str], str] + decrypt: Callable[[str], str | None] + + def encode(self, token: OAuthToken) -> str: + return self.encrypt(token.access_token) + + def decode(self, blob: str) -> OAuthToken | None: + access_token = self.decrypt(blob) + if not access_token: + return None + return OAuthToken(access_token=access_token, refresh_token=None) diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py index 2088dc77252e..671de63eabe1 100644 --- a/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/types.py @@ -25,6 +25,8 @@ from __future__ import annotations +from collections.abc import Mapping +from dataclasses import dataclass from enum import Enum from typing import Annotated, Literal @@ -59,6 +61,19 @@ class AuthSpecKind(str, Enum): aws_sigv4 = "aws_sigv4" # AWS SigV4 per-request signing (e.g. Bedrock AgentCore) +@dataclass(frozen=True, slots=True) +class Unauthorized: + """A 401 plus the optional challenge a client needs to recover. + + ``detail`` is the human message; ``www_authenticate`` and ``body`` carry a scheme-specific + challenge (e.g. BYOK's provisioning prompt) so the edge can reproduce it verbatim. + """ + + detail: str + www_authenticate: str | None = None + body: Mapping[str, str] | None = None + + @tagged_union(frozen=True) class CredError: """Why a credential could not be produced. Fail-closed: an arm yields this or an `httpx.Auth`. @@ -76,28 +91,21 @@ class CredError: "not_implemented", ] = tag() - unauthorized: str = ( - case() - ) # no usable credential for this (subject, server) -> 401 challenge - misconfigured: str = ( - case() - ) # the declared mode is missing required config -> 5xx (operator) - upstream_unavailable: str = ( - case() - ) # the IdP / token endpoint could not be reached -> 503 - unsupported_mode: str = ( - case() - ) # a raw mode string did not parse into AuthSpecKind (boundary) - precondition_required: str = ( - case() - ) # a required per-user value (e.g. an env var) has not been provided -> 412 - not_implemented: str = ( - case() - ) # the declared mode's resolver arm is not built yet -> 501 (not operator error) + unauthorized: Unauthorized = case() # no usable credential for this (subject, server) -> 401 challenge + misconfigured: str = case() # the declared mode is missing required config -> 5xx (operator) + upstream_unavailable: str = case() # the IdP / token endpoint could not be reached -> 503 + unsupported_mode: str = case() # a raw mode string did not parse into AuthSpecKind (boundary) + precondition_required: str = case() # a required per-user value (e.g. an env var) has not been provided -> 412 + not_implemented: str = case() # the declared mode's resolver arm is not built yet -> 501 (not operator error) @staticmethod - def of_unauthorized(detail: str) -> CredError: - return CredError(unauthorized=detail) + def of_unauthorized( + detail: str, + *, + www_authenticate: str | None = None, + body: Mapping[str, str] | None = None, + ) -> CredError: + return CredError(unauthorized=Unauthorized(detail=detail, www_authenticate=www_authenticate, body=body)) @staticmethod def of_misconfigured(detail: str) -> CredError: @@ -125,7 +133,7 @@ def summary(self) -> str: # only while that stays true (a `case _` would defeat reportMatchNotExhaustive). match self.tag: case "unauthorized": - return f"unauthorized: {self.unauthorized}" + return f"unauthorized: {self.unauthorized.detail}" case "misconfigured": return f"misconfigured: {self.misconfigured}" case "upstream_unavailable": @@ -268,9 +276,7 @@ class Ambient(BaseModel): source: Literal["ambient"] = "ambient" -AwsCredentialSource = Annotated[ - StaticKeys | AssumeRole | Ambient, Field(discriminator="source") -] +AwsCredentialSource = Annotated[StaticKeys | AssumeRole | Ambient, Field(discriminator="source")] class AwsSigV4Config(BaseModel): diff --git a/litellm/proxy/_experimental/mcp_server/outbound_credentials/v2_token_store.py b/litellm/proxy/_experimental/mcp_server/outbound_credentials/v2_token_store.py new file mode 100644 index 000000000000..f1b68042c946 --- /dev/null +++ b/litellm/proxy/_experimental/mcp_server/outbound_credentials/v2_token_store.py @@ -0,0 +1,75 @@ +"""v2-native per-user OAuth token read store for the ``authorization_code`` mode. + +The raw "inner" store that ``RefreshingTokenStore`` and ``CachedOAuthTokenStore`` wrap: it reads the +user's persisted credential and returns a typed ``OAuthToken`` (access token, epoch expiry, refresh +token), validating the decoded credential blob at this boundary so no ``Any`` leaks past it. It does +not cache or refresh - those are the decorators. This replaces ``V1PerUserTokenStore`` (which handed +the whole read + cache + refresh to v1's core) as step 1b: the ``read_credential`` collaborator is +injected, so the DB/decoding plumbing stays testable and out of this seam. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from datetime import datetime, timezone + +from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( + OAuthToken, +) + +CredentialReader = Callable[[str, str], Awaitable["dict[str, object] | None"]] + + +def _iso_to_epoch(expires_at: str) -> float | None: + try: + dt = datetime.fromisoformat(expires_at) + except ValueError: + return None + # A timezone-naive expiry is stored as UTC (db.py writes ``datetime.now(timezone.utc)``), + # so anchor it to UTC before ``.timestamp()`` - otherwise a non-UTC host would read it as + # local time and skew the expiry, diverging from v1's ``_remaining_token_seconds``. + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.timestamp() + + +def _to_scopes(raw: object) -> tuple[str, ...]: + if isinstance(raw, (list, tuple)): + return tuple(s for s in raw if isinstance(s, str)) + return () + + +def _to_oauth_token(payload: dict[str, object]) -> OAuthToken | None: + access_token = payload.get("access_token") + if not isinstance(access_token, str): + return None + refresh_token = payload.get("refresh_token") + expires_at = payload.get("expires_at") + return OAuthToken( + access_token=access_token, + expires_at=_iso_to_epoch(expires_at) if isinstance(expires_at, str) else None, + refresh_token=refresh_token if isinstance(refresh_token, str) else None, + scopes=_to_scopes(payload.get("scopes")), + ) + + +class V2PerUserTokenStore: + """``OAuthTokenStore`` that reads the user's persisted authorization_code credential, typed. + + The injected ``read_credential`` returns the decoded credential payload for a ``(user, server)`` + pair, or ``None`` when the user has not completed OAuth. A backing-store outage surfaces as + ``TokenStoreUnavailable`` from the reader, which the arm turns into a challenge rather than a + 500, so ``fetch`` lets it propagate. Refresh is the wrapping ``RefreshingTokenStore``'s job, so + the returned token carries ``expires_at`` and ``refresh_token`` for it to act on. + """ + + def __init__(self, read_credential: CredentialReader) -> None: + self._read_credential = read_credential + + async def fetch(self, user_id: str, server_id: str) -> OAuthToken | None: + if not user_id: + return None + payload = await self._read_credential(user_id, server_id) + if payload is None: + return None + return _to_oauth_token(payload) diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py index 7b4f1e13a52d..d30d8af2af2c 100644 --- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py +++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py @@ -55,16 +55,12 @@ def _connection_error_message(exc: BaseException) -> str: ) if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)): return ( - "Failed to connect to MCP server: the server is unreachable. " - "Check the URL and that the server is running." + "Failed to connect to MCP server: the server is unreachable. Check the URL and that the server is running." ) if isinstance(exc, httpx.TimeoutException): return "Failed to connect to MCP server: the connection timed out." if isinstance(exc, httpx.HTTPStatusError): - return ( - f"Failed to connect to MCP server: it returned HTTP " - f"{exc.response.status_code}." - ) + return f"Failed to connect to MCP server: it returned HTTP {exc.response.status_code}." return "Failed to connect to MCP server. Check proxy logs for details." @@ -117,10 +113,7 @@ def _get_oauth2_server_ids(allowed_server_ids: List[str]) -> Set[str]: return { sid for sid in allowed_server_ids - if getattr( - global_mcp_server_manager.get_mcp_server_by_id(sid), "auth_type", None - ) - == MCPAuth.oauth2 + if getattr(global_mcp_server_manager.get_mcp_server_by_id(sid), "auth_type", None) == MCPAuth.oauth2 } async def _get_user_oauth_extra_headers( @@ -159,9 +152,7 @@ async def _get_user_oauth_extra_headers( prisma_client = get_prisma_client_or_throw( "Database not connected. Connect a database to use OAuth2 MCP tools." ) - cred = await get_user_oauth_credential( - prisma_client, user_id, server_id - ) + cred = await get_user_oauth_credential(prisma_client, user_id, server_id) cred = await resolve_valid_user_oauth_token( user_id=user_id, server=server, @@ -200,9 +191,7 @@ async def _prefetch_user_oauth_creds( creds = await list_user_oauth_credentials(prisma_client, user_id) return {c["server_id"]: c for c in creds if "server_id" in c} except Exception as e: - verbose_logger.warning( - f"_prefetch_user_oauth_creds: failed to prefetch for user={user_id}: {e}" - ) + verbose_logger.warning(f"_prefetch_user_oauth_creds: failed to prefetch for user={user_id}: {e}") return {} async def _get_bulk_user_oauth_headers( @@ -234,9 +223,7 @@ async def _get_bulk_user_oauth_headers( if c.get("access_token") and c.get("server_id") } except Exception: - verbose_logger.debug( - "Failed to bulk-fetch OAuth credentials", exc_info=True - ) + verbose_logger.debug("Failed to bulk-fetch OAuth credentials", exc_info=True) return {} def _create_tool_response_objects(tools, server: MCPServer): @@ -273,12 +260,8 @@ def _extract_mcp_headers_from_request( """ headers = request.headers raw_headers = dict(headers) - mcp_auth_header = mcp_request_handler_cls._get_mcp_auth_header_from_headers( - headers - ) - mcp_server_auth_headers = ( - mcp_request_handler_cls._get_mcp_server_auth_headers_from_headers(headers) - ) + mcp_auth_header = mcp_request_handler_cls._get_mcp_auth_header_from_headers(headers) + mcp_server_auth_headers = mcp_request_handler_cls._get_mcp_server_auth_headers_from_headers(headers) return mcp_auth_header, mcp_server_auth_headers, raw_headers def _resolve_mcp_server_id_for_rest( @@ -295,9 +278,7 @@ def _resolve_mcp_server_id_for_rest( allowed = set(allowed_server_ids) if server_id in allowed: return server_id - by_name = global_mcp_server_manager.get_mcp_server_by_name( - server_id, client_ip=client_ip - ) + by_name = global_mcp_server_manager.get_mcp_server_by_name(server_id, client_ip=client_ip) if by_name is not None and by_name.server_id in allowed: return by_name.server_id return server_id @@ -334,14 +315,10 @@ async def _resolve_allowed_mcp_servers_with_ip_filter( allowed_server_ids_set.update(servers) allowed_server_ids_set = set( - global_mcp_server_manager.filter_server_ids_by_ip( - list(allowed_server_ids_set), _rest_client_ip - ) + global_mcp_server_manager.filter_server_ids_by_ip(list(allowed_server_ids_set), _rest_client_ip) ) - canonical_server_id = _resolve_mcp_server_id_for_rest( - server_id, allowed_server_ids_set, _rest_client_ip - ) + canonical_server_id = _resolve_mcp_server_id_for_rest(server_id, allowed_server_ids_set, _rest_client_ip) if canonical_server_id not in allowed_server_ids_set: _server = global_mcp_server_manager.get_mcp_server_by_id( @@ -350,9 +327,7 @@ async def _resolve_allowed_mcp_servers_with_ip_filter( if ( _server is not None and _rest_client_ip is not None - and not global_mcp_server_manager._is_server_accessible_from_ip( - _server, _rest_client_ip - ) + and not global_mcp_server_manager._is_server_accessible_from_ip(_server, _rest_client_ip) ): raise HTTPException( status_code=403, @@ -431,21 +406,12 @@ async def _get_tools_for_single_server( ): # Dict keys may be server_ids OR names/aliases; normalize so lookup # by concrete server_id resolves name-keyed restrictions too. - allowed_tools_for_server = ( - global_mcp_server_manager.expand_tool_permissions( - user_api_key_auth.object_permission.mcp_tool_permissions - ).get(server.server_id) - ) - if ( - allowed_tools_for_server is not None - and len(allowed_tools_for_server) > 0 - ): + allowed_tools_for_server = global_mcp_server_manager.expand_tool_permissions( + user_api_key_auth.object_permission.mcp_tool_permissions + ).get(server.server_id) + if allowed_tools_for_server is not None and len(allowed_tools_for_server) > 0: # Filter tools to only include those in the allowed list - tools = [ - tool - for tool in tools - if _tool_name_matches(tool.name, allowed_tools_for_server) - ] + tools = [tool for tool in tools if _tool_name_matches(tool.name, allowed_tools_for_server)] return _create_tool_response_objects(tools, server) @@ -457,9 +423,7 @@ async def _resolve_allowed_mcp_servers_for_tool_call( auth_contexts = await build_effective_auth_contexts(user_api_key_dict) allowed_server_ids_set = set() for auth_context in auth_contexts: - servers = await global_mcp_server_manager.get_allowed_mcp_servers( - user_api_key_auth=auth_context - ) + servers = await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth=auth_context) allowed_server_ids_set.update(servers) if server_id not in allowed_server_ids_set: raise HTTPException( @@ -491,22 +455,15 @@ async def _list_tools_for_single_server( _name_resolved = None if server_id not in allowed_server_ids: _name_resolved = global_mcp_server_manager.get_mcp_server_by_name(server_id) - if _name_resolved is not None and _name_resolved.server_id in set( - allowed_server_ids - ): + if _name_resolved is not None and _name_resolved.server_id in set(allowed_server_ids): server_id = _name_resolved.server_id if server_id not in allowed_server_ids: - _server = ( - global_mcp_server_manager.get_mcp_server_by_id(server_id) - or _name_resolved - ) + _server = global_mcp_server_manager.get_mcp_server_by_id(server_id) or _name_resolved if ( _server is not None and rest_client_ip is not None - and not global_mcp_server_manager._is_server_accessible_from_ip( - _server, rest_client_ip - ) + and not global_mcp_server_manager._is_server_accessible_from_ip(_server, rest_client_ip) ): raise HTTPException( status_code=403, @@ -535,12 +492,8 @@ async def _list_tools_for_single_server( "message": f"Server with id {server_id} not found", } - server_auth_header = _get_server_auth_header( - server, mcp_server_auth_headers, mcp_auth_header - ) - user_oauth_extra_headers = await _get_user_oauth_extra_headers( - server, user_api_key_dict - ) + server_auth_header = _get_server_auth_header(server, mcp_server_auth_headers, mcp_auth_header) + user_oauth_extra_headers = await _get_user_oauth_extra_headers(server, user_api_key_dict) try: list_tools_result = await _get_tools_for_single_server( @@ -572,9 +525,7 @@ async def _list_tools_for_single_server( @router.get("/tools/list", dependencies=[Depends(user_api_key_auth)]) async def list_tool_rest_api( request: Request, - server_id: Optional[str] = Query( - None, description="The server id to list tools for" - ), + server_id: Optional[str] = Query(None, description="The server id to list tools for"), include_disabled_tools: bool = Query( False, description=( @@ -615,19 +566,14 @@ async def list_tool_rest_api( # The full catalog (allowlist filter skipped) is admin-only so the # REST endpoint can't be used to enumerate deliberately-disabled tools. apply_tool_filters = not ( - include_disabled_tools - and user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN + include_disabled_tools and user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN ) # Extract auth headers from request headers = request.headers raw_headers_from_request = dict(headers) - mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers( - headers - ) - mcp_server_auth_headers = ( - MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers) - ) + mcp_auth_header = MCPRequestHandler._get_mcp_auth_header_from_headers(headers) + mcp_server_auth_headers = MCPRequestHandler._get_mcp_server_auth_headers_from_headers(headers) auth_contexts = await build_effective_auth_contexts(user_api_key_dict) @@ -696,15 +642,11 @@ async def list_tool_rest_api( # Query all servers the user has access to errors = [] for allowed_server_id in allowed_server_ids: - server = global_mcp_server_manager.get_mcp_server_by_id( - allowed_server_id - ) + server = global_mcp_server_manager.get_mcp_server_by_id(allowed_server_id) if server is None: continue - server_auth_header = _get_server_auth_header( - server, mcp_server_auth_headers, mcp_auth_header - ) + server_auth_header = _get_server_auth_header(server, mcp_server_auth_headers, mcp_auth_header) user_oauth_extra_headers = await _get_user_oauth_extra_headers( server, user_api_key_dict, @@ -722,23 +664,17 @@ async def list_tool_rest_api( ) list_tools_result.extend(tools_result) except Exception as e: - verbose_logger.exception( - f"Error getting tools from {server.name}: {e}" - ) + verbose_logger.exception(f"Error getting tools from {server.name}: {e}") errors.append(f"{server.name}: {str(e)}") continue if errors and not list_tools_result: - error_message = "Failed to get tools from servers: " + "; ".join( - errors - ) + error_message = "Failed to get tools from servers: " + "; ".join(errors) return { "tools": list_tools_result, "error": "partial_failure" if error_message else None, - "message": ( - error_message if error_message else "Successfully retrieved tools" - ), + "message": (error_message if error_message else "Successfully retrieved tools"), } except MCPUpstreamAuthError as e: @@ -751,18 +687,14 @@ async def list_tool_rest_api( except HTTPException as http_exc: # Internal access/IP 403s keep the legacy error-dict response shape # so the existing contract stays intact. - verbose_logger.exception( - "HTTPException in list_tool_rest_api: %s", str(http_exc) - ) + verbose_logger.exception("HTTPException in list_tool_rest_api: %s", str(http_exc)) return { "tools": [], "error": "unexpected_error", "message": (f"An unexpected error occurred: {http_exc.detail}"), } except Exception as e: - verbose_logger.exception( - "Unexpected error in list_tool_rest_api: %s", str(e) - ) + verbose_logger.exception("Unexpected error in list_tool_rest_api: %s", str(e)) return { "tools": [], "error": "unexpected_error", @@ -852,9 +784,7 @@ async def call_tool_rest_api( ( allowed_mcp_servers, canonical_server_id, - ) = await _resolve_allowed_mcp_servers_with_ip_filter( - request, user_api_key_dict, server_id - ) + ) = await _resolve_allowed_mcp_servers_with_ip_filter(request, user_api_key_dict, server_id) # Look up per-user OAuth headers for this server (mirrors list_tool_rest_api). user_oauth_extra_headers: Optional[Dict[str, str]] = None @@ -863,9 +793,7 @@ async def call_tool_rest_api( None, ) if target_server is not None: - user_oauth_extra_headers = await _get_user_oauth_extra_headers( - target_server, user_api_key_dict - ) + user_oauth_extra_headers = await _get_user_oauth_extra_headers(target_server, user_api_key_dict) # Call execute_mcp_tool directly (permission checks already done) result = await execute_mcp_tool( @@ -958,9 +886,7 @@ def _extract_credentials( client_id: Optional[str] = creds.get("client_id") client_secret: Optional[str] = creds.get("client_secret") scopes_raw = creds.get("scopes") - scopes: Optional[List[str]] = ( - scopes_raw if isinstance(scopes_raw, list) else None - ) + scopes: Optional[List[str]] = scopes_raw if isinstance(scopes_raw, list) else None return client_id, client_secret, scopes async def _execute_with_mcp_client( @@ -991,12 +917,8 @@ async def _execute_with_mcp_client( try: client_id, client_secret, scopes = _extract_credentials(request) - _oauth2_flow: Optional[ - Literal["client_credentials", "authorization_code"] - ] = request.oauth2_flow or ( - "client_credentials" - if client_id and client_secret and request.token_url - else None + _oauth2_flow: Optional[Literal["client_credentials", "authorization_code"]] = request.oauth2_flow or ( + "client_credentials" if client_id and client_secret and request.token_url else None ) # client_credentials requires token_url to fetch a token; without it the # incoming auth header would be dropped with nothing to replace it. @@ -1024,18 +946,56 @@ async def _execute_with_mcp_client( instructions=request.instructions, ) - stdio_env = global_mcp_server_manager._build_stdio_env( - server_model, raw_headers - ) + stdio_env = global_mcp_server_manager._build_stdio_env(server_model, raw_headers) # For M2M OAuth servers, drop the incoming Authorization header so that # resolve_mcp_auth can auto-fetch a token via client_credentials. - effective_oauth2_headers = ( - None if server_model.has_client_credentials else oauth2_headers + effective_oauth2_headers = None if server_model.has_client_credentials else oauth2_headers + + # Interactive authorization_code tools preview: the operator holds a just-authorized + # token but it is not persisted yet. Resolve it through the v2 resolver via a one-shot + # presented store - the same path runtime uses for the stored token - rather than the + # caller-override path _create_mcp_client refuses for authorization_code. The bare token + # becomes the upstream credential, so it is not also forwarded as a caller header. Gated + # to the v2-mapped oauth2 case (to_server_spec non-None); M2M (client_credentials), + # delegate/passthrough, and token-exchange are unaffected. + from litellm.proxy._experimental.mcp_server.outbound_credentials import ( # noqa: PLC0415 + UpstreamCredentialProvider, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import ( # noqa: PLC0415 + to_server_spec, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.oauth_token_store import ( # noqa: PLC0415 + OAuthToken, + ) + from litellm.proxy._experimental.mcp_server.outbound_credentials.presented_token_store import ( # noqa: PLC0415 + PresentedOAuthTokenStore, + ) + + forwarded_authorization = ( + effective_oauth2_headers.get("Authorization") if effective_oauth2_headers else None + ) + is_interactive_authz_code = ( + server_model.auth_type == MCPAuth.oauth2 + and forwarded_authorization is not None + and to_server_spec(server_model) is not None + ) + preview_cred_provider = ( + UpstreamCredentialProvider( + oauth_token_store=PresentedOAuthTokenStore( + OAuthToken( + access_token=forwarded_authorization[7:] + if forwarded_authorization[:7].lower() == "bearer " + else forwarded_authorization + ) + ) + ) + if is_interactive_authz_code + else None ) merged_headers = merge_mcp_headers( - extra_headers=effective_oauth2_headers, + extra_headers=(None if preview_cred_provider else effective_oauth2_headers), static_headers=request.static_headers, ) @@ -1044,6 +1004,7 @@ async def _execute_with_mcp_client( mcp_auth_header=mcp_auth_header, extra_headers=merged_headers, stdio_env=stdio_env, + cred_provider=preview_cred_provider, ) return await operation(client) @@ -1080,9 +1041,7 @@ async def _preview_openapi_tools(spec_path: str) -> dict: if operation is None: continue - resolved_op = resolve_operation_params( - operation, path_item, components - ) + resolved_op = resolve_operation_params(operation, path_item, components) raw_op_id = operation.get("operationId", f"{method}_{path}") # Match what register_tools_from_openapi does so the preview @@ -1096,9 +1055,7 @@ async def _preview_openapi_tools(spec_path: str) -> dict: while unique in used_names: n += 1 suffix = f"_{n}" - unique = ( - op_id[: _OPENAPI_TOOL_NAME_MAX_LEN - len(suffix)] + suffix - ) + unique = op_id[: _OPENAPI_TOOL_NAME_MAX_LEN - len(suffix)] + suffix op_id = unique used_names.add(op_id) summary = operation.get("summary", "") @@ -1107,9 +1064,7 @@ async def _preview_openapi_tools(spec_path: str) -> dict: tools.append( { "name": op_id, - "description": description - or summary - or f"{method.upper()} {path}", + "description": description or summary or f"{method.upper()} {path}", "inputSchema": input_schema, } ) @@ -1173,9 +1128,7 @@ async def test_tools_list( }, ) - new_mcp_server_request = _inherit_credentials_from_existing_server( - new_mcp_server_request - ) + new_mcp_server_request = _inherit_credentials_from_existing_server(new_mcp_server_request) # For OpenAPI spec servers, generate tools from the spec directly if new_mcp_server_request.spec_path: @@ -1206,13 +1159,9 @@ async def _list_tools_operation(client): async def _list_tools_session_operation(session): return await session.list_tools() - list_tools_response = await client.run_with_session( - _list_tools_session_operation - ) + list_tools_response = await client.run_with_session(_list_tools_session_operation) list_tools_result: List[MCPTool] = list_tools_response.tools - model_dumped_tools: List[dict] = [ - tool.model_dump() for tool in list_tools_result - ] + model_dumped_tools: List[dict] = [tool.model_dump() for tool in list_tools_result] return { "tools": model_dumped_tools, "error": None, diff --git a/litellm/proxy/_experimental/mcp_server/sampling_handler.py b/litellm/proxy/_experimental/mcp_server/sampling_handler.py index b659ba6f813b..65630f74e90f 100644 --- a/litellm/proxy/_experimental/mcp_server/sampling_handler.py +++ b/litellm/proxy/_experimental/mcp_server/sampling_handler.py @@ -97,25 +97,19 @@ def _resolve_model_from_preferences( for model_name in available_model_names: if hint_name.lower() in model_name.lower(): verbose_logger.debug( - "MCP sampling model resolution: substring hint match " - "'%s' -> '%s'", + "MCP sampling model resolution: substring hint match '%s' -> '%s'", hint_name, model_name, ) return model_name verbose_logger.debug( - "MCP sampling model resolution: no hint matched from %s " - "against %d available models", + "MCP sampling model resolution: no hint matched from %s against %d available models", [getattr(h, "name", None) for h in model_preferences.hints], len(available_model_names), ) # 2. Priority-based selection (cost/speed/intelligence) - if ( - model_preferences - and available_model_names - and _has_priorities(model_preferences) - ): + if model_preferences and available_model_names and _has_priorities(model_preferences): best = _select_model_by_priority(available_model_names, model_preferences) if best is not None: verbose_logger.debug( @@ -134,8 +128,7 @@ def _resolve_model_from_preferences( # Fall back to first available model if available_model_names: verbose_logger.debug( - "MCP sampling model resolution: no default configured, " - "falling back to first available model '%s'", + "MCP sampling model resolution: no default configured, falling back to first available model '%s'", available_model_names[0], ) return available_model_names[0] @@ -247,14 +240,9 @@ def _normalise(values: List[float], invert: bool = False) -> List[float]: best_name = None best_score = -1.0 for i, entry in enumerate(scored): - score = ( - cost_weight * cost_scores[i] - + speed_weight * speed_scores[i] - + intel_weight * intel_scores[i] - ) + score = cost_weight * cost_scores[i] + speed_weight * speed_scores[i] + intel_weight * intel_scores[i] verbose_logger.debug( - "MCP priority scoring: model=%s cost_score=%.3f speed_score=%.3f " - "intel_score=%.3f → weighted=%.3f", + "MCP priority scoring: model=%s cost_score=%.3f speed_score=%.3f intel_score=%.3f → weighted=%.3f", entry["name"], cost_scores[i], speed_scores[i], @@ -353,11 +341,7 @@ def _convert_single_content( tool_use_id = getattr(content, "toolUseId", "") nested_content = getattr(content, "content", []) if isinstance(nested_content, list): - text_parts = [ - getattr(c, "text", str(c)) - for c in nested_content - if getattr(c, "type", None) == "text" - ] + text_parts = [getattr(c, "text", str(c)) for c in nested_content if getattr(c, "type", None) == "text"] result_text = "\n".join(text_parts) if text_parts else "" else: result_text = str(nested_content) @@ -417,9 +401,7 @@ def _convert_mcp_messages_to_openai( # above (e.g. unexpected role, single non-list content). converted = _convert_mcp_content_to_openai(content) converted_parts = ( - converted - if isinstance(converted, list) - else ([converted] if isinstance(converted, dict) else []) + converted if isinstance(converted, list) else ([converted] if isinstance(converted, dict) else []) ) # Separate marker items from regular content parts @@ -488,9 +470,7 @@ def _extract_tool_calls(content: Any) -> List[Dict[str, Any]]: "type": "function", "function": { "name": getattr(item, "name", ""), - "arguments": json.dumps( - getattr(item, "input", {}), default=str - ), + "arguments": json.dumps(getattr(item, "input", {}), default=str), }, } ) @@ -517,11 +497,7 @@ def _extract_tool_results(content: Any) -> List[Dict[str, Any]]: # Extract text from nested content nested_content = getattr(item, "content", []) if isinstance(nested_content, list): - text_parts = [ - getattr(c, "text", str(c)) - for c in nested_content - if getattr(c, "type", None) == "text" - ] + text_parts = [getattr(c, "text", str(c)) for c in nested_content if getattr(c, "type", None) == "text"] result_text = "\n".join(text_parts) if text_parts else "" else: result_text = str(nested_content) @@ -597,8 +573,7 @@ def _convert_openai_response_to_mcp_result( """ if not response.choices: verbose_logger.warning( - "MCP sampling: LLM returned empty choices list for model=%s " - "(possible content filter or provider error)", + "MCP sampling: LLM returned empty choices list for model=%s (possible content filter or provider error)", model_name, ) return ErrorData( @@ -661,9 +636,7 @@ def _convert_openai_response_to_mcp_result( ) -async def _check_model_access( - model: str, user_api_key_auth: Any -) -> Optional["ErrorData"]: +async def _check_model_access(model: str, user_api_key_auth: Any) -> Optional["ErrorData"]: """Enforce model-permission checks for MCP sampling requests. Runs the same authorization checks as ``/chat/completions``: @@ -681,9 +654,7 @@ async def _check_model_access( _user_role = getattr(user_api_key_auth, "user_role", None) _has_real_credential = bool(_api_key) or bool(_token) - _is_admin = ( - _user_role in ("proxy_admin", "proxy_admin_viewer") if _user_role else False - ) + _is_admin = _user_role in ("proxy_admin", "proxy_admin_viewer") if _user_role else False if not _has_real_credential and not _is_admin: verbose_logger.warning( @@ -760,9 +731,7 @@ async def _check_model_access( model=model, team_object=team_obj, llm_router=_llm_router, - team_model_aliases=getattr( - user_api_key_auth, "team_model_aliases", None - ), + team_model_aliases=getattr(user_api_key_auth, "team_model_aliases", None), ) if _user_id and _proxy_logging_obj: await _check_team_member_model_access( @@ -824,10 +793,7 @@ async def _check_model_access( ) return ErrorData( code=-1, - message=( - f"Model access denied: the API key is not authorized " - f"to use model '{model}'. {access_err}" - ), + message=(f"Model access denied: the API key is not authorized to use model '{model}'. {access_err}"), ) @@ -859,9 +825,7 @@ async def _run_budget_checks( ) import litellm except ImportError as import_err: - verbose_logger.warning( - "MCP sampling: budget check imports unavailable: %s", import_err - ) + verbose_logger.warning("MCP sampling: budget check imports unavailable: %s", import_err) return None # Can't enforce budgets without the modules _team_id = getattr(user_api_key_auth, "team_id", None) @@ -1102,9 +1066,7 @@ async def _build_completion_kwargs( from litellm.proxy.proxy_server import proxy_config completion_kwargs["user"] = getattr(user_api_key_auth, "user_id", None) - _dummy_request = _build_sampling_request( - raw_headers=raw_headers, client_ip=client_ip - ) + _dummy_request = _build_sampling_request(raw_headers=raw_headers, client_ip=client_ip) completion_kwargs = await add_litellm_data_to_request( data=completion_kwargs, request=_dummy_request, @@ -1236,9 +1198,7 @@ async def handle_sampling_create_message( user_api_key_auth=user_api_key_auth, ) - result = _convert_openai_response_to_mcp_result( - response=response, model_name=model - ) + result = _convert_openai_response_to_mcp_result(response=response, model_name=model) verbose_logger.info( "MCP sampling: completed successfully, model=%s, stopReason=%s", getattr(result, "model", "unknown"), diff --git a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py index a9c4d2ece466..f24d5715e837 100644 --- a/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py +++ b/litellm/proxy/_experimental/mcp_server/semantic_tool_filter.py @@ -62,14 +62,10 @@ async def build_router_from_mcp_registry(self) -> None: all_tools = [] for server_id, server in registry.items(): try: - tools = await global_mcp_server_manager.get_tools_for_server( - server_id - ) + tools = await global_mcp_server_manager.get_tools_for_server(server_id) all_tools.extend(tools) except Exception as e: - verbose_logger.warning( - f"Failed to fetch tools from server {server_id}: {e}" - ) + verbose_logger.warning(f"Failed to fetch tools from server {server_id}: {e}") continue if not all_tools: @@ -77,9 +73,7 @@ async def build_router_from_mcp_registry(self) -> None: self.tool_router = None return - verbose_logger.info( - f"Fetched {len(all_tools)} tools from {len(registry)} MCP servers" - ) + verbose_logger.info(f"Fetched {len(all_tools)} tools from {len(registry)} MCP servers") self._build_router(all_tools) except Exception as e: @@ -180,9 +174,7 @@ async def filter_tools( # Router should be built on startup - if not, something went wrong if self.tool_router is None: - verbose_logger.warning( - "Router not initialized - was build_router_from_mcp_registry() called on startup?" - ) + verbose_logger.warning("Router not initialized - was build_router_from_mcp_registry() called on startup?") return available_tools # Run semantic filtering @@ -252,9 +244,7 @@ def _name_matches_canonical(client_name: str, canonical: str) -> bool: separator = client_name[-len(canonical) - 1] return separator in ("_", "-") - def _get_tools_by_names( - self, tool_names: List[str], available_tools: List[Any] - ) -> List[Any]: + def _get_tools_by_names(self, tool_names: List[str], available_tools: List[Any]) -> List[Any]: """ Get tools from available_tools by their names, preserving the semantic router's ordering. diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py index d7975303802f..4b55510a629b 100644 --- a/litellm/proxy/_experimental/mcp_server/server.py +++ b/litellm/proxy/_experimental/mcp_server/server.py @@ -109,9 +109,7 @@ def _invalidate_byok_cred_cache(user_id: str, server_id: str) -> None: _byok_cred_cache.pop((user_id, server_id), None) -def _write_byok_cred_cache( - user_id: str, server_id: str, credential: Optional[str] -) -> None: +def _write_byok_cred_cache(user_id: str, server_id: str, credential: Optional[str]) -> None: """Write a credential value to the cache, evicting all entries if at capacity.""" if len(_byok_cred_cache) >= _BYOK_CRED_CACHE_MAX_SIZE: _byok_cred_cache.clear() @@ -140,8 +138,8 @@ def _write_byok_cred_cache( # Robust auth lookup keyed by session_object. _session_obj_auth_storage: "weakref.WeakKeyDictionary[Any, MCPAuthenticatedUser]" = weakref.WeakKeyDictionary() - active_mcp_session_var: contextvars.ContextVar[Optional[_McpServerSession]] = ( - contextvars.ContextVar("active_mcp_session", default=None) + active_mcp_session_var: contextvars.ContextVar[Optional[_McpServerSession]] = contextvars.ContextVar( + "active_mcp_session", default=None ) except ImportError as e: verbose_logger.debug(f"MCP module not found: {e}") @@ -283,6 +281,7 @@ def _proxy_exception_to_http_exception(exc: ProxyException) -> HTTPException: from litellm.proxy._experimental.mcp_server.mcp_server_manager import ( MCPServerManager, _should_strip_caller_authorization, + _without_authorization, global_mcp_server_manager, ) from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import ( @@ -437,10 +436,7 @@ async def _purge_expired_stateful_session_auth_contexts( for session_id, last_seen in _stateful_session_auth_context_last_seen.items(): if _stateful_session_active_request_counts.get(session_id, 0) > 0: continue - if ( - now - last_seen >= _STATEFUL_SESSION_IDLE_TIMEOUT_SECONDS - or session_id not in server_instances - ): + if now - last_seen >= _STATEFUL_SESSION_IDLE_TIMEOUT_SECONDS or session_id not in server_instances: expired_session_ids.append(session_id) for session_id in expired_session_ids: @@ -510,9 +506,7 @@ async def _cleanup_expired_stateful_session_auth_contexts() -> None: try: await _purge_expired_stateful_session_auth_contexts() except Exception as e: - verbose_logger.exception( - f"Error cleaning up expired MCP stateful sessions: {e}" - ) + verbose_logger.exception(f"Error cleaning up expired MCP stateful sessions: {e}") async def initialize_session_managers(): """Initialize the session managers. Can be called from main app lifespan.""" @@ -539,14 +533,10 @@ async def initialize_session_managers(): await _session_manager_cm.__aenter__() await _session_manager_stateful_cm.__aenter__() await _sse_session_manager_cm.__aenter__() - _stateful_auth_context_cleanup_task = asyncio.create_task( - _cleanup_expired_stateful_session_auth_contexts() - ) + _stateful_auth_context_cleanup_task = asyncio.create_task(_cleanup_expired_stateful_session_auth_contexts()) _SESSION_MANAGERS_INITIALIZED = True - verbose_logger.info( - "MCP Server started with StreamableHTTP and SSE session managers!" - ) + verbose_logger.info("MCP Server started with StreamableHTTP and SSE session managers!") async def shutdown_session_managers(): """Shutdown the session managers.""" @@ -617,12 +607,8 @@ async def handle_list_tools() -> List[Tool]: raw_headers, _client_ip, ) = await get_or_extract_auth_context() - verbose_logger.debug( - f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}" - ) - verbose_logger.debug( - f"MCP list_tools - MCP servers from context: {mcp_servers}" - ) + verbose_logger.debug(f"MCP list_tools - User API Key Auth from context: {user_api_key_auth}") + verbose_logger.debug(f"MCP list_tools - MCP servers from context: {mcp_servers}") verbose_logger.debug( f"MCP list_tools - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}" ) @@ -638,9 +624,7 @@ async def handle_list_tools() -> List[Tool]: log_list_tools_to_spendlogs=True, list_tools_log_source="mcp_protocol", ) - verbose_logger.info( - f"MCP list_tools - Successfully returned {len(tools)} tools" - ) + verbose_logger.info(f"MCP list_tools - Successfully returned {len(tools)} tools") return tools except Exception as e: verbose_logger.exception(f"Error in list_tools endpoint: {str(e)}") @@ -652,9 +636,7 @@ async def handle_list_tools() -> List[Tool]: active_mcp_session_var.reset(_session_reset_token) @server.call_tool() - async def mcp_server_tool_call( - name: str, arguments: Dict[str, Any] | None - ) -> CallToolResult: + async def mcp_server_tool_call(name: str, arguments: Dict[str, Any] | None) -> CallToolResult: """ Call a specific tool with the provided arguments Args: @@ -692,9 +674,7 @@ async def mcp_server_tool_call( f"MCP mcp_server_tool_call - user_api_key_auth={user_api_key_auth}, user_role={getattr(user_api_key_auth, 'user_role', 'N/A')}" ) - verbose_logger.debug( - f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}" - ) + verbose_logger.debug(f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}") host_progress_callback = None try: host_ctx = server.request_context @@ -703,9 +683,7 @@ async def mcp_server_tool_call( if host_token and hasattr(host_ctx, "session") and host_ctx.session: host_session = host_ctx.session - async def forward_progress( - progress: float, total: Optional[float] - ): + async def forward_progress(progress: float, total: Optional[float]): """Forward progress notifications from external MCP to Host""" try: await host_session.send_progress_notification( @@ -713,18 +691,12 @@ async def forward_progress( progress=progress, total=total, ) - verbose_logger.debug( - f"Forwarded progress {progress}/{total} to Host" - ) + verbose_logger.debug(f"Forwarded progress {progress}/{total} to Host") except Exception as e: - verbose_logger.error( - f"Failed to forward progress to Host: {e}" - ) + verbose_logger.error(f"Failed to forward progress to Host: {e}") host_progress_callback = forward_progress - verbose_logger.debug( - f"Host progressToken captured: {host_token[:8]}..." - ) + verbose_logger.debug(f"Host progressToken captured: {host_token[:8]}...") except Exception as e: verbose_logger.warning(f"Could not capture host progress context: {e}") try: @@ -775,9 +747,7 @@ async def forward_progress( isError=True, ) except BlockedPiiEntityError as e: - verbose_logger.error( - f"BlockedPiiEntityError in MCP tool call: {str(e)}" - ) + verbose_logger.error(f"BlockedPiiEntityError in MCP tool call: {str(e)}") return CallToolResult( content=[ TextContent( @@ -788,15 +758,9 @@ async def forward_progress( isError=True, ) except GuardrailRaisedException as e: - verbose_logger.error( - f"GuardrailRaisedException in MCP tool call: {str(e)}" - ) + verbose_logger.error(f"GuardrailRaisedException in MCP tool call: {str(e)}") return CallToolResult( - content=[ - TextContent( - text=f"Error: Guardrail violation - {str(e)}", type="text" - ) - ], + content=[TextContent(text=f"Error: Guardrail violation - {str(e)}", type="text")], isError=True, ) except HTTPException as e: @@ -840,12 +804,8 @@ async def list_prompts() -> List[Prompt]: raw_headers, _client_ip, ) = await get_or_extract_auth_context() - verbose_logger.debug( - f"MCP list_prompts - User API Key Auth from context: {user_api_key_auth}" - ) - verbose_logger.debug( - f"MCP list_prompts - MCP servers from context: {mcp_servers}" - ) + verbose_logger.debug(f"MCP list_prompts - User API Key Auth from context: {user_api_key_auth}") + verbose_logger.debug(f"MCP list_prompts - MCP servers from context: {mcp_servers}") verbose_logger.debug( f"MCP list_prompts - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}" ) @@ -859,9 +819,7 @@ async def list_prompts() -> List[Prompt]: oauth2_headers=oauth2_headers, raw_headers=raw_headers, ) - verbose_logger.info( - f"MCP list_prompts - Successfully returned {len(prompts)} prompts" - ) + verbose_logger.info(f"MCP list_prompts - Successfully returned {len(prompts)} prompts") return prompts except Exception as e: verbose_logger.exception(f"Error in list_prompts endpoint: {str(e)}") @@ -873,9 +831,7 @@ async def list_prompts() -> List[Prompt]: active_mcp_session_var.reset(_session_reset_token) @server.get_prompt() - async def get_prompt( - name: str, arguments: Optional[Dict[str, str]] - ) -> GetPromptResult: + async def get_prompt(name: str, arguments: Optional[Dict[str, str]]) -> GetPromptResult: """ Get a specific prompt with the provided arguments @@ -906,9 +862,7 @@ async def get_prompt( _client_ip, ) = await get_or_extract_auth_context() - verbose_logger.debug( - f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}" - ) + verbose_logger.debug(f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}") return await mcp_get_prompt( name=name, arguments=arguments, @@ -943,12 +897,8 @@ async def list_resources() -> List[Resource]: raw_headers, _client_ip, ) = await get_or_extract_auth_context() - verbose_logger.debug( - f"MCP list_resources - User API Key Auth from context: {user_api_key_auth}" - ) - verbose_logger.debug( - f"MCP list_resources - MCP servers from context: {mcp_servers}" - ) + verbose_logger.debug(f"MCP list_resources - User API Key Auth from context: {user_api_key_auth}") + verbose_logger.debug(f"MCP list_resources - MCP servers from context: {mcp_servers}") verbose_logger.debug( f"MCP list_resources - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}" ) @@ -961,9 +911,7 @@ async def list_resources() -> List[Resource]: oauth2_headers=oauth2_headers, raw_headers=raw_headers, ) - verbose_logger.info( - f"MCP list_resources - Successfully returned {len(resources)} resources" - ) + verbose_logger.info(f"MCP list_resources - Successfully returned {len(resources)} resources") return resources except Exception as e: verbose_logger.exception(f"Error in list_resources endpoint: {str(e)}") @@ -992,12 +940,8 @@ async def list_resource_templates() -> List[ResourceTemplate]: raw_headers, _client_ip, ) = await get_or_extract_auth_context() - verbose_logger.debug( - f"MCP list_resource_templates - User API Key Auth from context: {user_api_key_auth}" - ) - verbose_logger.debug( - f"MCP list_resource_templates - MCP servers from context: {mcp_servers}" - ) + verbose_logger.debug(f"MCP list_resource_templates - User API Key Auth from context: {user_api_key_auth}") + verbose_logger.debug(f"MCP list_resource_templates - MCP servers from context: {mcp_servers}") verbose_logger.debug( f"MCP list_resource_templates - MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}" ) @@ -1015,9 +959,7 @@ async def list_resource_templates() -> List[ResourceTemplate]: ) return resource_templates except Exception as e: - verbose_logger.exception( - f"Error in list_resource_templates endpoint: {str(e)}" - ) + verbose_logger.exception(f"Error in list_resource_templates endpoint: {str(e)}") return [] finally: if _session_reset_token is not None: @@ -1089,9 +1031,7 @@ async def _get_allowed_mcp_servers_from_mcp_server_names( for server in allowed_mcp_servers: if server: - match_list = [ - s.lower() for s in iter_known_server_prefixes(server) if s - ] + match_list = [s.lower() for s in iter_known_server_prefixes(server) if s] if server_or_group.lower() in match_list: filtered_server[server.server_id] = server @@ -1100,10 +1040,8 @@ async def _get_allowed_mcp_servers_from_mcp_server_names( if not server_name_matched: try: - access_group_server_ids = ( - await MCPRequestHandler._get_mcp_servers_from_access_groups( - [server_or_group] - ) + access_group_server_ids = await MCPRequestHandler._get_mcp_servers_from_access_groups( + [server_or_group] ) # Only include servers that the user has access to for server_id in access_group_server_ids: @@ -1111,9 +1049,7 @@ async def _get_allowed_mcp_servers_from_mcp_server_names( if server_id == server.server_id: filtered_server[server.server_id] = server except Exception as e: - verbose_logger.debug( - f"Could not resolve '{server_or_group}' as access group: {e}" - ) + verbose_logger.debug(f"Could not resolve '{server_or_group}' as access group: {e}") if filtered_server: return list(filtered_server.values()) @@ -1123,8 +1059,7 @@ async def _get_allowed_mcp_servers_from_mcp_server_names( # closed so URL/header namespacing cannot silently fall back to # the caller's full allowed-server set. verbose_logger.debug( - "MCP scope filter resolved to no servers for requested names %s; " - "returning empty list (fail-closed).", + "MCP scope filter resolved to no servers for requested names %s; returning empty list (fail-closed).", mcp_servers, ) return [] @@ -1188,18 +1123,12 @@ def filter_tools_by_allowed_tools( if server_applies_tool_allowlist(mcp_server): if not mcp_server.allowed_tools: return [] - tools_to_return = [ - tool - for tool in tools - if _tool_name_matches(tool.name, mcp_server.allowed_tools) - ] + tools_to_return = [tool for tool in tools if _tool_name_matches(tool.name, mcp_server.allowed_tools)] # Filter by disallowed_tools (blacklist) if mcp_server.disallowed_tools: tools_to_return = [ - tool - for tool in tools_to_return - if not _tool_name_matches(tool.name, mcp_server.disallowed_tools) + tool for tool in tools_to_return if not _tool_name_matches(tool.name, mcp_server.disallowed_tools) ] return tools_to_return @@ -1265,15 +1194,11 @@ async def _get_allowed_mcp_servers( "IP filtering will be skipped. This is expected for internal calls." ) - allowed_mcp_server_ids = ( - await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth) - ) + allowed_mcp_server_ids = await global_mcp_server_manager.get_allowed_mcp_servers(user_api_key_auth) ( allowed_mcp_server_ids, _ip_blocked, - ) = global_mcp_server_manager.filter_server_ids_by_ip_with_info( - allowed_mcp_server_ids, client_ip - ) + ) = global_mcp_server_manager.filter_server_ids_by_ip_with_info(allowed_mcp_server_ids, client_ip) verbose_logger.debug( "MCP IP filter: client_ip=%s, allowed_server_ids=%s", client_ip, @@ -1291,9 +1216,7 @@ async def _get_allowed_mcp_servers( ) allowed_mcp_servers: List[MCPServer] = [] for allowed_mcp_server_id in allowed_mcp_server_ids: - mcp_server = global_mcp_server_manager.get_mcp_server_by_id( - allowed_mcp_server_id - ) + mcp_server = global_mcp_server_manager.get_mcp_server_by_id(allowed_mcp_server_id) if mcp_server is not None: # Apply oauth2_flow resolution for legacy DB rows where it may be NULL resolved_flow = MCPServerManager._resolve_oauth2_flow( @@ -1306,9 +1229,7 @@ async def _get_allowed_mcp_servers( ) if resolved_flow and resolved_flow != mcp_server.oauth2_flow: # Create a new instance with the resolved flow for this request - mcp_server = mcp_server.model_copy( - update={"oauth2_flow": resolved_flow} - ) + mcp_server = mcp_server.model_copy(update={"oauth2_flow": resolved_flow}) allowed_mcp_servers.append(mcp_server) if mcp_servers is not None: @@ -1360,115 +1281,21 @@ async def _get_user_oauth_extra_headers_from_db( user_api_key_auth: Optional[UserAPIKeyAuth], prefetched_creds: Optional[Dict[str, Dict[str, Any]]] = None, ) -> Optional[Dict[str, str]]: - """Look up stored OAuth2 token for (user, server) and return as extra_headers dict. - - Lookup order: - 1. Redis cache (fast path, NaCl-decrypted) — skipped when prefetched_creds supplied - 2. prefetched_creds dict (pre-fetched batch DB query) or fresh DB query - 3. Auto-refresh when the stored token is expired and a refresh_token exists + """Stored OAuth2 token for (user, server) as an ``Authorization: Bearer`` header, or None. - Args: - prefetched_creds: Optional dict keyed by server_id with credential payloads. - When provided, the Redis and individual DB lookups are - skipped in favour of the pre-fetched batch result. + Thin wrapper over ``resolve_user_oauth_access_token`` (Redis cache, else DB + refresh); + ``prefetched_creds`` skips the per-server Redis/DB lookups for the batch path. """ - if server.auth_type != MCPAuth.oauth2: - return None - if user_api_key_auth is None: + if server.auth_type != MCPAuth.oauth2 or user_api_key_auth is None: return None - user_id = getattr(user_api_key_auth, "user_id", None) - server_id = getattr(server, "server_id", None) - if not user_id or not server_id: - return None - try: - from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 - get_user_oauth_credential, - resolve_valid_user_oauth_token, - ) - from litellm.proxy._experimental.mcp_server.oauth2_token_cache import ( # noqa: PLC0415 - _compute_per_user_token_ttl, - mcp_per_user_token_cache, - ) - - # ── Fast path: Redis cache ──────────────────────────────────────── - # Only used when prefetched_creds is not supplied (individual lookup). - if prefetched_creds is None: - cached_token = await mcp_per_user_token_cache.get(user_id, server_id) - if cached_token is not None: - verbose_logger.debug( - "_get_user_oauth_extra_headers_from_db: Redis hit for user=%s server=%s", - user_id, - server_id, - ) - return {"Authorization": f"Bearer {cached_token}"} - - # ── Slow path: DB lookup ────────────────────────────────────────── - prisma_client = None - if prefetched_creds is not None: - cred = prefetched_creds.get(server_id) - else: - from litellm.proxy.utils import ( # noqa: PLC0415 - get_prisma_client_or_throw, - ) - - prisma_client = get_prisma_client_or_throw( - "Database not connected. Connect a database to use OAuth2 MCP tools." - ) - cred = await get_user_oauth_credential( - prisma_client, user_id, server_id - ) - - if not cred or not cred.get("access_token"): - return None - - cred = await resolve_valid_user_oauth_token( - user_id=user_id, - server=server, - cred=cred, - prisma_client=prisma_client, - ) - if cred is None: - # Refresh failed or token expired with no usable refresh_token — - # clear the stale Redis entry so the next request doesn't reuse it. - await mcp_per_user_token_cache.delete(user_id, server_id) - return None - - access_token: str = cred["access_token"] - - # Warm (or re-warm) the Redis cache from the DB result. - # Always write regardless of whether expires_at is present — tokens - # without an expiry are still valid and should be cached using the - # server/default TTL so subsequent requests are fast. - if prefetched_creds is None: - raw_expires = None - expires_at = cred.get("expires_at") - if expires_at: - from datetime import datetime, timezone # noqa: PLC0415 - - try: - exp_dt = datetime.fromisoformat(expires_at) - if exp_dt.tzinfo is None: - exp_dt = exp_dt.replace(tzinfo=timezone.utc) - remaining = int( - (exp_dt - datetime.now(timezone.utc)).total_seconds() - ) - raw_expires = max(remaining, 0) if remaining > 0 else None - except (ValueError, TypeError): - pass - ttl = _compute_per_user_token_ttl(server, raw_expires) - await mcp_per_user_token_cache.set( - user_id, server_id, access_token, ttl - ) + from litellm.proxy._experimental.mcp_server.db import ( # noqa: PLC0415 + resolve_user_oauth_access_token, + ) - return {"Authorization": f"Bearer {access_token}"} - except Exception as e: - verbose_logger.warning( - "_get_user_oauth_extra_headers_from_db: failed to retrieve credential for user=%s server=%s: %s", - user_id, - server_id, - e, - ) - return None + token = await resolve_user_oauth_access_token( + getattr(user_api_key_auth, "user_id", None), server, prefetched_creds + ) + return {"Authorization": f"Bearer {token}"} if token else None async def _prefetch_oauth_creds_for_user( user_api_key_auth: Optional[UserAPIKeyAuth], @@ -1477,9 +1304,7 @@ async def _prefetch_oauth_creds_for_user( Returns a dict keyed by server_id to avoid N+1 queries in asyncio.gather loops. """ - user_id = ( - getattr(user_api_key_auth, "user_id", None) if user_api_key_auth else None - ) + user_id = getattr(user_api_key_auth, "user_id", None) if user_api_key_auth else None if not user_id: return {} try: @@ -1494,9 +1319,7 @@ async def _prefetch_oauth_creds_for_user( creds = await list_user_oauth_credentials(prisma_client, user_id) return {c["server_id"]: c for c in creds if "server_id" in c} except Exception as e: - verbose_logger.warning( - f"_prefetch_oauth_creds_for_user: failed to prefetch for user={user_id}: {e}" - ) + verbose_logger.warning(f"_prefetch_oauth_creds_for_user: failed to prefetch for user={user_id}: {e}") return {} def _prepare_mcp_server_headers( @@ -1529,14 +1352,22 @@ def _prepare_mcp_server_headers( else: # Copy to avoid mutating the original dict (important for parallel fetching) extra_headers = oauth2_headers.copy() if oauth2_headers else None + # Migrated authorization_code: the v2 resolver injects the stored per-user + # token, so drop the caller-forwarded Authorization (apply-if-absent would + # otherwise let it shadow the resolved token). Delegate keeps it. Centralized + # via _should_strip_caller_authorization to match _call_regular_mcp_tool. + if extra_headers and _should_strip_caller_authorization( + mcp_server=server, + raw_headers=raw_headers, + user_api_key_auth=user_api_key_auth, + ): + extra_headers = _without_authorization(extra_headers) if server.extra_headers and raw_headers: if extra_headers is None: extra_headers = {} - normalized_raw_headers = { - str(k).lower(): v for k, v in raw_headers.items() if isinstance(k, str) - } + normalized_raw_headers = {str(k).lower(): v for k, v in raw_headers.items() if isinstance(k, str)} # Centralized strip decision shared with # ``MCPServerManager._call_regular_mcp_tool`` so the two @@ -1576,21 +1407,13 @@ def _merge_gateway_initialize_instructions( texts: List[Tuple[str, str]] = [] for server in allowed_mcp_servers: - label = ( - server.alias - or server.server_name - or server.name - or server.server_id - or "mcp" - ) + label = server.alias or server.server_name or server.name or server.server_id or "mcp" if server.instructions and server.instructions.strip(): texts.append((label, server.instructions.strip())) continue if server.spec_path: continue - cached = global_mcp_server_manager._upstream_initialize_instructions_by_server_id.get( - server.server_id - ) + cached = global_mcp_server_manager._upstream_initialize_instructions_by_server_id.get(server.server_id) if cached and cached.strip(): texts.append((label, cached.strip())) @@ -1618,9 +1441,7 @@ async def _gateway_initialize_instructions_request_scope( # cancel sibling probes or 500 the gateway initialize request. await asyncio.gather( *[ - global_mcp_server_manager._ensure_upstream_initialize_instructions_cached( - s - ) + global_mcp_server_manager._ensure_upstream_initialize_instructions_cached(s) for s in allowed if s is not None ], @@ -1631,10 +1452,7 @@ async def _gateway_initialize_instructions_request_scope( if scoped_server_endpoint and len(allowed) == 1: scoped_server = allowed[0] scoped_server_name = ( - scoped_server.alias - or scoped_server.server_name - or scoped_server.name - or scoped_server.server_id + scoped_server.alias or scoped_server.server_name or scoped_server.name or scoped_server.server_id ) instructions_token = _mcp_gateway_initialize_instructions.set(merged) server_name_token = _mcp_gateway_server_name.set(scoped_server_name) @@ -1680,9 +1498,7 @@ async def _get_tools_from_mcp_servers( rules_obj = Rules() list_tools_call_id = str(uuid.uuid4()) # Derive trace_id from raw_headers when not explicitly passed (same as A2A / MCP call_tool) - effective_litellm_trace_id = litellm_trace_id or get_chain_id_from_headers( - raw_headers - ) + effective_litellm_trace_id = litellm_trace_id or get_chain_id_from_headers(raw_headers) spend_logs_metadata: Dict[str, Any] = { "mcp_operation": "list_tools", } @@ -1719,9 +1535,9 @@ async def _get_tools_from_mcp_servers( _metadata_variable_name="metadata", ) - user_identifier = getattr( - user_api_key_auth, "end_user_id", None - ) or getattr(user_api_key_auth, "user_id", None) + user_identifier = getattr(user_api_key_auth, "end_user_id", None) or getattr( + user_api_key_auth, "user_id", None + ) if user_identifier: list_tools_request_data["user"] = user_identifier @@ -1736,9 +1552,7 @@ async def _get_tools_from_mcp_servers( litellm_logging_obj.call_type = CallTypes.list_mcp_tools.value litellm_logging_obj.model = "MCP: list_tools" except Exception as logging_error: - verbose_logger.debug( - "Failed to initialize logging for MCP list_tools: %s", logging_error - ) + verbose_logger.debug("Failed to initialize logging for MCP list_tools: %s", logging_error) litellm_logging_obj = None try: @@ -1749,14 +1563,9 @@ async def _get_tools_from_mcp_servers( # Pre-fetch OAuth credentials only when at least one server uses OAuth2, # to avoid an unnecessary DB round-trip on requests with no OAuth2 MCP servers. - _has_oauth2_server = any( - getattr(s, "auth_type", None) == MCPAuth.oauth2 - for s in allowed_mcp_servers - ) + _has_oauth2_server = any(getattr(s, "auth_type", None) == MCPAuth.oauth2 for s in allowed_mcp_servers) _prefetched_oauth_creds = ( - await _prefetch_oauth_creds_for_user(user_api_key_auth) - if _has_oauth2_server - else {} + await _prefetch_oauth_creds_for_user(user_api_key_auth) if _has_oauth2_server else {} ) async def _fetch_and_filter_server_tools( @@ -1778,8 +1587,17 @@ async def _fetch_and_filter_server_tools( # Prefer server-stored per-user OAuth when configured, so a stale # Authorization header from the MCP client cannot override Redis/DB # (same issue as call_tool in mcp_server_manager: VS Code caches tokens). + from litellm.proxy._experimental.mcp_server.outbound_credentials.adapter import ( # noqa: PLC0415 + to_server_spec, + ) + + # A server migrated to the v2 resolver gets its token from the resolver at connect + # time; building it here would double-resolve and be shadowed by the v2 graft. The + # preemptive 401 already challenged a missing token, so one exists for the connect. + migrated_to_v2 = to_server_spec(server) is not None if ( - server.auth_type == MCPAuth.oauth2 + not migrated_to_v2 + and server.auth_type == MCPAuth.oauth2 and getattr(server, "needs_user_oauth_token", False) and user_api_key_auth is not None ): @@ -1792,7 +1610,7 @@ async def _fetch_and_filter_server_tools( extra_headers = db_headers # If still no OAuth2 token, fall back to pre-fetched creds (non-stale-client path) - elif extra_headers is None and server.auth_type == MCPAuth.oauth2: + elif not migrated_to_v2 and extra_headers is None and server.auth_type == MCPAuth.oauth2: extra_headers = await _get_user_oauth_extra_headers_from_db( server, user_api_key_auth, @@ -1832,15 +1650,11 @@ async def _fetch_and_filter_server_tools( # swallow the auth error. raise except Exception as e: - verbose_logger.exception( - f"Error getting tools from server {server.name}: {str(e)}" - ) + verbose_logger.exception(f"Error getting tools from server {server.name}: {str(e)}") return [] # Fetch tools from all servers in parallel - tasks = [ - _fetch_and_filter_server_tools(server) for server in allowed_mcp_servers - ] + tasks = [_fetch_and_filter_server_tools(server) for server in allowed_mcp_servers] results = await asyncio.gather(*tasks) # Flatten results into single list @@ -1885,9 +1699,7 @@ async def _fetch_and_filter_server_tools( log_exc, ) - verbose_logger.info( - f"Successfully fetched {len(all_tools)} tools total from all MCP servers" - ) + verbose_logger.info(f"Successfully fetched {len(all_tools)} tools total from all MCP servers") return all_tools except Exception as e: @@ -1897,9 +1709,7 @@ async def _fetch_and_filter_server_tools( from litellm.proxy.proxy_server import proxy_logging_obj if proxy_logging_obj: - traceback_str = traceback.format_exc( - limit=MAXIMUM_TRACEBACK_LINES_TO_LOG - ) + traceback_str = traceback.format_exc(limit=MAXIMUM_TRACEBACK_LINES_TO_LOG) await proxy_logging_obj.post_call_failure_hook( request_data=list_tools_request_data or {}, original_exception=e, @@ -1908,9 +1718,7 @@ async def _fetch_and_filter_server_tools( traceback_str=traceback_str, ) except Exception: - verbose_logger.debug( - "Failed to log MCP list_tools failure via post_call_failure_hook" - ) + verbose_logger.debug("Failed to log MCP list_tools failure via post_call_failure_hook") raise async def _get_prompts_from_mcp_servers( @@ -1968,18 +1776,12 @@ async def _get_prompts_from_mcp_servers( all_prompts.extend(prompts) - verbose_logger.debug( - f"Successfully fetched {len(prompts)} prompts from server {server.name}" - ) + verbose_logger.debug(f"Successfully fetched {len(prompts)} prompts from server {server.name}") except Exception as e: - verbose_logger.exception( - f"Error getting prompts from server {server.name}: {str(e)}" - ) + verbose_logger.exception(f"Error getting prompts from server {server.name}: {str(e)}") # Continue with other servers instead of failing completely - verbose_logger.info( - f"Successfully fetched {len(all_prompts)} prompts total from all MCP servers" - ) + verbose_logger.info(f"Successfully fetched {len(all_prompts)} prompts total from all MCP servers") return all_prompts @@ -2025,17 +1827,11 @@ async def _get_resources_from_mcp_servers( ) all_resources.extend(resources) - verbose_logger.debug( - f"Successfully fetched {len(resources)} resources from server {server.name}" - ) + verbose_logger.debug(f"Successfully fetched {len(resources)} resources from server {server.name}") except Exception as e: - verbose_logger.exception( - f"Error getting resources from server {server.name}: {str(e)}" - ) + verbose_logger.exception(f"Error getting resources from server {server.name}: {str(e)}") - verbose_logger.info( - f"Successfully fetched {len(all_resources)} resources total from all MCP servers" - ) + verbose_logger.info(f"Successfully fetched {len(all_resources)} resources total from all MCP servers") return all_resources @@ -2072,14 +1868,12 @@ async def _get_resource_templates_from_mcp_servers( ) try: - resource_templates = ( - await global_mcp_server_manager.get_resource_templates_from_server( - server=server, - mcp_auth_header=server_auth_header, - extra_headers=extra_headers, - add_prefix=True, # Always add server prefix - raw_headers=raw_headers, - ) + resource_templates = await global_mcp_server_manager.get_resource_templates_from_server( + server=server, + mcp_auth_header=server_auth_header, + extra_headers=extra_headers, + add_prefix=True, # Always add server prefix + raw_headers=raw_headers, ) all_resource_templates.extend(resource_templates) verbose_logger.debug( @@ -2125,11 +1919,7 @@ async def filter_tools_by_key_team_permissions( # prefix (resolved from the server) rather than the first separator, so a # prefix containing the separator still reduces to the stored bare name. server = global_mcp_server_manager.get_mcp_server_by_id(server_id) - return [ - t - for t in tools - if strip_known_server_prefix(t.name, server) in allowed_tool_names - ] + return [t for t in tools if strip_known_server_prefix(t.name, server) in allowed_tool_names] async def _merge_toolset_permissions( user_api_key_auth: Optional[UserAPIKeyAuth], @@ -2149,11 +1939,7 @@ async def _merge_toolset_permissions( if not toolset_ids: return user_api_key_auth - toolset_perms = ( - await global_mcp_server_manager.resolve_toolset_tool_permissions( - toolset_ids=toolset_ids - ) - ) + toolset_perms = await global_mcp_server_manager.resolve_toolset_tool_permissions(toolset_ids=toolset_ids) if not toolset_perms: return user_api_key_auth @@ -2169,9 +1955,7 @@ async def _merge_toolset_permissions( # filtering doesn't silently drop servers that the toolset references but that # aren't already in the key's explicit mcp_servers list. merged_servers = list(set(op.mcp_servers or []) | set(existing.keys())) - updated_op = op.model_copy( - update={"mcp_servers": merged_servers, "mcp_tool_permissions": existing} - ) + updated_op = op.model_copy(update={"mcp_servers": merged_servers, "mcp_tool_permissions": existing}) return user_api_key_auth.model_copy(update={"object_permission": updated_op}) async def _list_mcp_tools( @@ -2216,13 +2000,9 @@ async def _list_mcp_tools( log_list_tools_to_spendlogs=log_list_tools_to_spendlogs, list_tools_log_source=list_tools_log_source, ) - verbose_logger.debug( - f"Successfully fetched {len(managed_tools)} tools from managed MCP servers" - ) + verbose_logger.debug(f"Successfully fetched {len(managed_tools)} tools from managed MCP servers") except Exception as e: - verbose_logger.exception( - f"Error getting tools from managed MCP servers: {str(e)}" - ) + verbose_logger.exception(f"Error getting tools from managed MCP servers: {str(e)}") # Continue with empty managed tools list instead of failing completely return managed_tools @@ -2260,13 +2040,9 @@ async def _list_mcp_prompts( oauth2_headers=oauth2_headers, raw_headers=raw_headers, ) - verbose_logger.debug( - f"Successfully fetched {len(managed_prompts)} prompts from managed MCP servers" - ) + verbose_logger.debug(f"Successfully fetched {len(managed_prompts)} prompts from managed MCP servers") except Exception as e: - verbose_logger.exception( - f"Error getting tools from managed MCP servers: {str(e)}" - ) + verbose_logger.exception(f"Error getting tools from managed MCP servers: {str(e)}") # Continue with empty managed tools list instead of failing completely return managed_prompts @@ -2294,13 +2070,9 @@ async def _list_mcp_resources( oauth2_headers=oauth2_headers, raw_headers=raw_headers, ) - verbose_logger.debug( - f"Successfully fetched {len(managed_resources)} resources from managed MCP servers" - ) + verbose_logger.debug(f"Successfully fetched {len(managed_resources)} resources from managed MCP servers") except Exception as e: - verbose_logger.exception( - f"Error getting resources from managed MCP servers: {str(e)}" - ) + verbose_logger.exception(f"Error getting resources from managed MCP servers: {str(e)}") return managed_resources @@ -2354,9 +2126,7 @@ def _resolve_display_name_to_original( display_map = server.tool_name_to_display_name or {} for unprefixed_name, display_name in display_map.items(): if display_name == name: - return add_server_prefix_to_name( - unprefixed_name, get_server_prefix(server) - ) + return add_server_prefix_to_name(unprefixed_name, get_server_prefix(server)) return name async def _get_byok_credential( @@ -2417,9 +2187,7 @@ async def _check_byok_credential( "server_name": mcp_server.server_name or mcp_server.name, "message": "User identity is required for BYOK servers", }, - headers={ - "WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"' - }, + headers={"WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"'}, ) # Check shared credential cache before hitting the DB. @@ -2481,9 +2249,7 @@ async def _check_byok_credential( "Complete the OAuth authorization flow to provide your API key." ), }, - headers={ - "WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"' - }, + headers={"WWW-Authenticate": 'Bearer resource_metadata="/.well-known/oauth-protected-resource"'}, ) async def execute_mcp_tool( @@ -2543,9 +2309,7 @@ async def execute_mcp_tool( for registry_server in global_mcp_server_manager.get_registry().values(): for known_prefix in iter_known_server_prefixes(registry_server): all_registry_prefixes.add(normalize_server_name(known_prefix)) - name_is_prefixed = is_tool_name_prefixed( - name, known_server_prefixes=all_registry_prefixes - ) + name_is_prefixed = is_tool_name_prefixed(name, known_server_prefixes=all_registry_prefixes) if requested_server is not None and not name_is_prefixed: # REST callers may pass server_id with the upstream tool name (no @@ -2561,10 +2325,8 @@ async def execute_mcp_tool( mcp_server = global_mcp_server_manager._get_mcp_server_from_tool_name(name) if mcp_server is None and requested_server is not None: for known_prefix in iter_known_server_prefixes(requested_server): - candidate = ( - global_mcp_server_manager._get_mcp_server_from_tool_name( - add_server_prefix_to_name(name, known_prefix) - ) + candidate = global_mcp_server_manager._get_mcp_server_from_tool_name( + add_server_prefix_to_name(name, known_prefix) ) if candidate is not None: mcp_server = candidate @@ -2573,10 +2335,7 @@ async def execute_mcp_tool( server_name = mcp_server.name if requested_server is not None: - if ( - mcp_server is not None - and mcp_server.server_id != requested_server.server_id - ): + if mcp_server is not None and mcp_server.server_id != requested_server.server_id: raise HTTPException( status_code=403, detail={ @@ -2603,21 +2362,15 @@ async def execute_mcp_tool( detail=f"User not allowed to call this tool. Allowed MCP servers: {allowed_mcp_servers}", ) - standard_logging_mcp_tool_call: StandardLoggingMCPToolCall = ( - _get_standard_logging_mcp_tool_call( - name=original_tool_name, # Use original name for logging - arguments=arguments, - server_name=server_name, - session_id=_mcp_session_id_from_headers(raw_headers), - ) - ) - litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get( - "litellm_logging_obj", None + standard_logging_mcp_tool_call: StandardLoggingMCPToolCall = _get_standard_logging_mcp_tool_call( + name=original_tool_name, # Use original name for logging + arguments=arguments, + server_name=server_name, + session_id=_mcp_session_id_from_headers(raw_headers), ) + litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get("litellm_logging_obj", None) if litellm_logging_obj: - litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = ( - standard_logging_mcp_tool_call - ) + litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = standard_logging_mcp_tool_call litellm_logging_obj.model = f"MCP: {name}" litellm_logging_obj.model_call_details["model"] = f"MCP: {name}" # Resolve the MCP server early so BYOK checks and credential injection @@ -2626,13 +2379,11 @@ async def execute_mcp_tool( mcp_server = global_mcp_server_manager._get_mcp_server_from_tool_name(name) if mcp_server: - standard_logging_mcp_tool_call["mcp_server_cost_info"] = ( - mcp_server.mcp_info or {} - ).get("mcp_server_cost_info") + standard_logging_mcp_tool_call["mcp_server_cost_info"] = (mcp_server.mcp_info or {}).get( + "mcp_server_cost_info" + ) if litellm_logging_obj: - litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = ( - standard_logging_mcp_tool_call - ) + litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = standard_logging_mcp_tool_call # BYOK: retrieve the stored per-user credential. A single DB call # both checks existence and fetches the value, avoiding a double query. @@ -2712,9 +2463,7 @@ async def execute_mcp_tool( # configured auth_type so the generator doesn't need to know the prefix. auth_header_value: Optional[str] = None if mcp_auth_header: - server_auth_type = ( - getattr(mcp_server, "auth_type", None) if mcp_server else None - ) + server_auth_type = getattr(mcp_server, "auth_type", None) if mcp_server else None if server_auth_type == MCPAuth.api_key: auth_header_value = f"ApiKey {mcp_auth_header}" elif server_auth_type == MCPAuth.basic: @@ -2728,19 +2477,12 @@ async def execute_mcp_tool( # _prepare_mcp_server_headers for managed MCP). forwarded_headers: Optional[Dict[str, str]] = None if mcp_server and mcp_server.extra_headers and raw_headers: - normalized_raw = { - str(k).lower(): v - for k, v in raw_headers.items() - if isinstance(k, str) - } + normalized_raw = {str(k).lower(): v for k, v in raw_headers.items() if isinstance(k, str)} skip_caller_authorization = bool(mcp_server.has_client_credentials) for header_name in mcp_server.extra_headers: if not isinstance(header_name, str): continue - if ( - skip_caller_authorization - and header_name.lower() == "authorization" - ): + if skip_caller_authorization and header_name.lower() == "authorization": continue value = normalized_raw.get(header_name.lower()) if value is not None: @@ -2800,28 +2542,20 @@ async def call_mcp_tool( Call a specific tool with the provided arguments (handles prefixed tool names). """ start_time = datetime.now() - litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get( - "litellm_logging_obj", None - ) + litellm_logging_obj: Optional[LiteLLMLoggingObj] = kwargs.get("litellm_logging_obj", None) try: if arguments is None: - raise HTTPException( - status_code=400, detail="Request arguments are required" - ) + raise HTTPException(status_code=400, detail="Request arguments are required") ## CHECK IF USER IS ALLOWED TO CALL THIS TOOL - allowed_mcp_server_ids = ( - await global_mcp_server_manager.get_allowed_mcp_servers( - user_api_key_auth=user_api_key_auth, - ) + allowed_mcp_server_ids = await global_mcp_server_manager.get_allowed_mcp_servers( + user_api_key_auth=user_api_key_auth, ) allowed_mcp_servers: List[MCPServer] = [] for allowed_mcp_server_id in allowed_mcp_server_ids: - allowed_server = global_mcp_server_manager.get_mcp_server_by_id( - allowed_mcp_server_id - ) + allowed_server = global_mcp_server_manager.get_mcp_server_by_id(allowed_mcp_server_id) if allowed_server is not None: allowed_mcp_servers.append(allowed_server) @@ -2872,9 +2606,7 @@ async def call_mcp_tool( end_time=end_time, ) litellm_logging_obj.call_type = CallTypes.call_mcp_tool.value - await litellm_logging_obj.async_success_handler( - result=response, start_time=start_time, end_time=end_time - ) + await litellm_logging_obj.async_success_handler(result=response, start_time=start_time, end_time=end_time) return response async def mcp_get_prompt( @@ -3087,21 +2819,15 @@ def _get_mcp_servers_in_path(path: str) -> Optional[List[str]]: # Path found at the end, remove it from servers path_part = "/" + path_match.group(1) servers_part = servers_and_path[: -len(path_part)] - mcp_servers_from_path = [ - s.strip() for s in servers_part.split(",") if s.strip() - ] + mcp_servers_from_path = [s.strip() for s in servers_part.split(",") if s.strip()] else: # No path, just comma-separated servers - mcp_servers_from_path = [ - s.strip() for s in servers_and_path.split(",") if s.strip() - ] + mcp_servers_from_path = [s.strip() for s in servers_and_path.split(",") if s.strip()] else: # Single server case - use regex approach for server/path separation # This handles cases like "custom_solutions/user_123/chat/completions" # where we want to extract "custom_solutions/user_123" as the server name - single_server_match = re.match( - r"^([^/]+(?:/[^/]+)?)(?:/.*)?$", servers_and_path - ) + single_server_match = re.match(r"^([^/]+(?:/[^/]+)?)(?:/.*)?$", servers_and_path) if single_server_match: server_name = single_server_match.group(1) mcp_servers_from_path = [server_name] @@ -3149,15 +2875,9 @@ def _get_session_id_from_scope(scope: Scope) -> Optional[str]: Returns None if not present. """ for header_name, header_value in scope.get("headers", []): - name = ( - header_name if isinstance(header_name, bytes) else header_name.encode() - ) + name = header_name if isinstance(header_name, bytes) else header_name.encode() if name.lower() == b"mcp-session-id": - return ( - header_value.decode() - if isinstance(header_value, bytes) - else str(header_value) - ) + return header_value.decode() if isinstance(header_value, bytes) else str(header_value) return None def _owner_fingerprint_for( @@ -3208,9 +2928,7 @@ def _bytes_for_hash(value: Any) -> Optional[bytes]: user_id_hash = hashlib.sha256(uid_material).hexdigest() return f"user:{user_id_hash}" if oauth2_headers: - authz = oauth2_headers.get("Authorization") or oauth2_headers.get( - "authorization" - ) + authz = oauth2_headers.get("Authorization") or oauth2_headers.get("authorization") authz_bytes = _bytes_for_hash(authz) if authz_bytes: return f"oauth:{hashlib.sha256(authz_bytes).hexdigest()}" @@ -3361,11 +3079,7 @@ def _normalize_header_name(header_name: Any) -> Optional[bytes]: "Stripping stale header to force new session creation.", _session_id, ) - scope["headers"] = [ - (k, v) - for k, v in _headers - if _normalize_header_name(k) != _mcp_session_header - ] + scope["headers"] = [(k, v) for k, v in _headers if _normalize_header_name(k) != _mcp_session_header] return False async def _apply_toolset_scope( @@ -3390,9 +3104,7 @@ async def _apply_toolset_scope( # drop the sentinel. Checked before the admin branch, mirroring # get_allowed_mcp_servers. original_op = user_api_key_auth.object_permission - if original_op is not None and SpecialMCPServerNames.no_mcp_servers.value in ( - original_op.mcp_servers or [] - ): + if original_op is not None and SpecialMCPServerNames.no_mcp_servers.value in (original_op.mcp_servers or []): raise HTTPException( status_code=403, detail="API key is scoped to no MCP servers; toolset access is denied.", @@ -3413,11 +3125,7 @@ async def _apply_toolset_scope( detail=f"API key does not have access to toolset '{toolset_id}'.", ) - tool_permissions = ( - await global_mcp_server_manager.resolve_toolset_tool_permissions( - toolset_ids=[toolset_id] - ) - ) + tool_permissions = await global_mcp_server_manager.resolve_toolset_tool_permissions(toolset_ids=[toolset_id]) server_ids = list(tool_permissions.keys()) existing_op = user_api_key_auth.object_permission if existing_op is not None: @@ -3483,14 +3191,8 @@ async def _raise_preemptive_401_for_unauthenticated_servers( a server it will be 403'd on immediately after authentication. """ for server_name in mcp_servers or []: - server = global_mcp_server_manager.get_mcp_server_by_name( - server_name, client_ip=client_ip - ) - if ( - server is not None - and allowed_server_ids is not None - and server.server_id not in allowed_server_ids - ): + server = global_mcp_server_manager.get_mcp_server_by_name(server_name, client_ip=client_ip) + if server is not None and allowed_server_ids is not None and server.server_id not in allowed_server_ids: # Caller's narrowed scope excludes this server — skip the # preemptive challenge and let downstream authorization # return 403. @@ -3501,12 +3203,6 @@ async def _raise_preemptive_401_for_unauthenticated_servers( # If no stored token exists, fail fast with 401 so clients can # kick off PKCE/interactive OAuth flow immediately. if server.needs_user_oauth_token: - stored_oauth_headers = await _get_user_oauth_extra_headers_from_db( - server=server, - user_api_key_auth=user_api_key_auth, - ) - if stored_oauth_headers: - continue if getattr(server, "delegate_auth_to_upstream", False) is True: # Delegate-auth servers run upstream PKCE: challenge with # the proxied resource_metadata (RFC 9728), not the @@ -3521,6 +3217,10 @@ async def _raise_preemptive_401_for_unauthenticated_servers( detail="Unauthorized", headers={"www-authenticate": www_authenticate}, ) + # The v2 resolver owns the existence check, so every authorization_code + # resolution (egress and this discovery challenge) runs through it. + if await global_mcp_server_manager.has_user_oauth_token(server, user_api_key_auth): + continue request = StarletteRequest(scope) base_url = get_request_base_url(request) @@ -3549,9 +3249,7 @@ async def _raise_preemptive_401_for_unauthenticated_servers( if ( server and server.is_oauth_passthrough - and not _client_has_passthrough_authorization( - server, oauth2_headers, mcp_server_auth_headers - ) + and not _client_has_passthrough_authorization(server, oauth2_headers, mcp_server_auth_headers) ): www_authenticate = _get_passthrough_www_authenticate( scope=scope, @@ -3635,13 +3333,9 @@ async def _probe_upstream_auth( # AsyncHTTPHandler.post() calls raise_for_status(); a 401/403 from # upstream lands here. Return its status so the caller can map it # to the appropriate response. - return exc.response.status_code, exc.response.headers.get( - "www-authenticate" - ) + return exc.response.status_code, exc.response.headers.get("www-authenticate") except Exception as exc: - verbose_logger.debug( - f"_probe_upstream_auth: probe to {url} failed ({exc}), allowing request through" - ) + verbose_logger.debug(f"_probe_upstream_auth: probe to {url} failed ({exc}), allowing request through") return 200, None async def _check_passthrough_upstream_auth( @@ -3689,10 +3383,7 @@ async def _check_passthrough_upstream_auth( return probe_results = await asyncio.gather( - *[ - _probe_upstream_auth(srv.url or "", forwarded_auth) - for srv in passthrough_servers - ] + *[_probe_upstream_auth(srv.url or "", forwarded_auth) for srv in passthrough_servers] ) for srv, (probe_status, _) in zip(passthrough_servers, probe_results): if probe_status == 401: @@ -3718,9 +3409,7 @@ async def _check_passthrough_upstream_auth( detail="Forbidden", ) - async def handle_streamable_http_mcp( - scope: Scope, receive: Receive, send: Send - ) -> None: + async def handle_streamable_http_mcp(scope: Scope, receive: Receive, send: Send) -> None: """Handle MCP requests through StreamableHTTP.""" try: path = scope.get("path", "") @@ -3737,28 +3426,20 @@ async def handle_streamable_http_mcp( # Extract client IP for MCP access control _client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope)) - verbose_logger.debug( - f"MCP request mcp_servers (header/path): {mcp_servers}" - ) + verbose_logger.debug(f"MCP request mcp_servers (header/path): {mcp_servers}") verbose_logger.debug( f"MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}" ) # Strip any client-supplied x-mcp-toolset-id to prevent forgery. - scope["headers"] = [ - (k, v) - for k, v in scope.get("headers", []) - if k.lower() != b"x-mcp-toolset-id" - ] + scope["headers"] = [(k, v) for k, v in scope.get("headers", []) if k.lower() != b"x-mcp-toolset-id"] # Apply toolset scope if set server-side via ContextVar (set by # /toolset/{name}/mcp and /{name}/mcp route handlers in proxy_server.py). active_toolset_id = _mcp_active_toolset_id.get() toolset_allowed_server_ids: Optional[Set[str]] = None if active_toolset_id and user_api_key_auth is not None: - user_api_key_auth = await _apply_toolset_scope( - user_api_key_auth, active_toolset_id - ) + user_api_key_auth = await _apply_toolset_scope(user_api_key_auth, active_toolset_id) op = user_api_key_auth.object_permission toolset_allowed_server_ids = set(op.mcp_servers or []) if op else set() @@ -3780,9 +3461,7 @@ async def handle_streamable_http_mcp( # Pre-flight auth check for pass-through servers. Must run after # toolset scoping so the probe list is derived from the fully-authorized # server set, not the raw user-supplied names. - await _check_passthrough_upstream_auth( - scope, user_api_key_auth, mcp_servers, _client_ip - ) + await _check_passthrough_upstream_auth(scope, user_api_key_auth, mcp_servers, _client_ip) # Inject masked debug headers when client sends x-litellm-mcp-debug: true _debug_headers = MCPDebug.maybe_build_debug_headers( @@ -3821,9 +3500,7 @@ async def handle_streamable_http_mcp( # response sees a pristine ``receive`` channel. if session_id: expected_owner = _stateful_session_owners.get(session_id) - request_owner = _owner_fingerprint_for( - user_api_key_auth, oauth2_headers, _client_ip - ) + request_owner = _owner_fingerprint_for(user_api_key_auth, oauth2_headers, _client_ip) if expected_owner is not None and expected_owner != request_owner: verbose_logger.warning( "Rejecting MCP request: session '%s' owner mismatch.", @@ -3843,9 +3520,7 @@ async def handle_streamable_http_mcp( # non-DELETE requests have their session header stripped and should # be routed as no-session requests. if session_id: - handled = await _handle_stale_mcp_session( - scope, receive, send, session_manager_stateful - ) + handled = await _handle_stale_mcp_session(scope, receive, send, session_manager_stateful) if handled: # Request was fully handled (e.g., DELETE on non-existent session) return @@ -3857,9 +3532,7 @@ async def handle_streamable_http_mcp( is_initialize = _is_initialize_request(body) use_stateful = bool(session_id or is_initialize) - target_manager = ( - session_manager_stateful if use_stateful else session_manager_stateless - ) + target_manager = session_manager_stateful if use_stateful else session_manager_stateless verbose_logger.debug( f"MCP routing to {'stateful' if use_stateful else 'stateless'} manager" @@ -3871,9 +3544,7 @@ async def handle_streamable_http_mcp( # session. Cap how many a single caller can hold so an authenticated # client cannot spam `initialize` and exhaust memory. if is_initialize and not session_id: - request_owner = _owner_fingerprint_for( - user_api_key_auth, oauth2_headers, _client_ip - ) + request_owner = _owner_fingerprint_for(user_api_key_auth, oauth2_headers, _client_ip) if not await _enforce_stateful_session_cap_for_owner(request_owner): verbose_logger.warning( "Rejecting MCP initialize: caller already holds the maximum number of active stateful sessions." @@ -3952,15 +3623,8 @@ async def wrapped_receive(): ) session_lock: Optional[asyncio.Lock] = None - if ( - use_stateful - and session_id - and request_method in ("POST", "DELETE") - and not is_jsonrpc_response - ): - session_lock = _stateful_session_locks.setdefault( - session_id, asyncio.Lock() - ) + if use_stateful and session_id and request_method in ("POST", "DELETE") and not is_jsonrpc_response: + session_lock = _stateful_session_locks.setdefault(session_id, asyncio.Lock()) active_request_session_ids: List[str] = [] @@ -3969,8 +3633,7 @@ def _increment_active_request_session(session_id_to_track: str) -> None: return active_request_session_ids.append(session_id_to_track) _stateful_session_active_request_counts[session_id_to_track] = ( - _stateful_session_active_request_counts.get(session_id_to_track, 0) - + 1 + _stateful_session_active_request_counts.get(session_id_to_track, 0) + 1 ) if use_stateful and session_id: @@ -3999,9 +3662,7 @@ async def _dispatch() -> None: local_send = _wrap_send_with_stateful_session_auth_context( local_send, auth_user, - _owner_fingerprint_for( - user_api_key_auth, oauth2_headers, _client_ip - ), + _owner_fingerprint_for(user_api_key_auth, oauth2_headers, _client_ip), _track_initialized_stateful_session, ) @@ -4023,36 +3684,18 @@ async def _dispatch() -> None: await _dispatch() finally: for active_request_session_id in active_request_session_ids: - active_request_count = ( - _stateful_session_active_request_counts.get( - active_request_session_id, 0 - ) - - 1 - ) + active_request_count = _stateful_session_active_request_counts.get(active_request_session_id, 0) - 1 if active_request_count > 0: - _stateful_session_active_request_counts[ - active_request_session_id - ] = active_request_count + _stateful_session_active_request_counts[active_request_session_id] = active_request_count else: - _stateful_session_active_request_counts.pop( - active_request_session_id, None - ) + _stateful_session_active_request_counts.pop(active_request_session_id, None) - if ( - scope.get("method") != "DELETE" - and active_request_session_id in _stateful_session_auth_contexts - ): - _stateful_session_auth_context_last_seen[ - active_request_session_id - ] = time.monotonic() + if scope.get("method") != "DELETE" and active_request_session_id in _stateful_session_auth_contexts: + _stateful_session_auth_context_last_seen[active_request_session_id] = time.monotonic() # Periodic cleanup iterates _stateful_session_auth_context_last_seen, # so locks for untracked sessions must be dropped here. - if ( - active_request_count <= 0 - and active_request_session_id - not in _stateful_session_auth_contexts - ): + if active_request_count <= 0 and active_request_session_id not in _stateful_session_auth_contexts: _stateful_session_locks.pop(active_request_session_id, None) except MCPUpstreamAuthError as e: # Upstream delegated auth returned 401; surface it to the client so @@ -4082,9 +3725,7 @@ async def _dispatch() -> None: ) await error_response(scope, receive, send) except Exception as response_error: - verbose_logger.exception( - f"Failed to send error response: {response_error}" - ) + verbose_logger.exception(f"Failed to send error response: {response_error}") # If we can't send a proper response, re-raise the original error raise e @@ -4105,19 +3746,13 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None: # Extract client IP for MCP access control _sse_client_ip = IPAddressUtils.get_mcp_client_ip(StarletteRequest(scope)) - verbose_logger.debug( - f"MCP request mcp_servers (header/path): {mcp_servers}" - ) + verbose_logger.debug(f"MCP request mcp_servers (header/path): {mcp_servers}") verbose_logger.debug( f"MCP server auth headers: {list(mcp_server_auth_headers.keys()) if mcp_server_auth_headers else None}" ) # Strip any client-supplied x-mcp-toolset-id to prevent forgery. - scope["headers"] = [ - (k, v) - for k, v in scope.get("headers", []) - if k.lower() != b"x-mcp-toolset-id" - ] + scope["headers"] = [(k, v) for k, v in scope.get("headers", []) if k.lower() != b"x-mcp-toolset-id"] # Apply toolset scope if set server-side via ContextVar so the # downstream probe list matches the fully-authorized server set @@ -4125,9 +3760,7 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None: active_toolset_id = _mcp_active_toolset_id.get() toolset_allowed_server_ids: Optional[Set[str]] = None if active_toolset_id and user_api_key_auth is not None: - user_api_key_auth = await _apply_toolset_scope( - user_api_key_auth, active_toolset_id - ) + user_api_key_auth = await _apply_toolset_scope(user_api_key_auth, active_toolset_id) op = user_api_key_auth.object_permission toolset_allowed_server_ids = set(op.mcp_servers or []) if op else set() @@ -4152,9 +3785,7 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None: # being stuck with a silently empty tool list. Must run after # toolset scoping so the probe list is derived from the fully- # authorized server set, not the raw user-supplied names. - await _check_passthrough_upstream_auth( - scope, user_api_key_auth, mcp_servers, _sse_client_ip - ) + await _check_passthrough_upstream_auth(scope, user_api_key_auth, mcp_servers, _sse_client_ip) set_auth_context( user_api_key_auth=user_api_key_auth, mcp_auth_header=mcp_auth_header, @@ -4207,9 +3838,7 @@ async def handle_sse_mcp(scope: Scope, receive: Receive, send: Send) -> None: ) await error_response(scope, receive, send) except Exception as response_error: - verbose_logger.exception( - f"Failed to send error response: {response_error}" - ) + verbose_logger.exception(f"Failed to send error response: {response_error}") # If we can't send a proper response, re-raise the original error raise e @@ -4303,9 +3932,7 @@ def _set_or_update_auth_context( touch_last_seen: bool = True, copy_existing_session_auth_context: bool = False, ) -> MCPAuthenticatedUser: - auth_user = ( - _stateful_session_auth_contexts.get(session_id) if session_id else None - ) + auth_user = _stateful_session_auth_contexts.get(session_id) if session_id else None if auth_user is not None and session_id is not None: if touch_last_seen: _stateful_session_auth_context_last_seen[session_id] = time.monotonic() @@ -4352,16 +3979,12 @@ async def wrapped_send(message: Message) -> None: for key, value in message.get("headers", []): header_name = key if isinstance(key, bytes) else str(key).encode() if header_name.lower() == b"mcp-session-id": - session_id = ( - value.decode() if isinstance(value, bytes) else str(value) - ) + session_id = value.decode() if isinstance(value, bytes) else str(value) if on_session_registered is not None: on_session_registered(session_id) auth_context_var.set(auth_user) _stateful_session_auth_contexts[session_id] = auth_user - _stateful_session_auth_context_last_seen[session_id] = ( - time.monotonic() - ) + _stateful_session_auth_context_last_seen[session_id] = time.monotonic() _stateful_session_owners[session_id] = owner_fingerprint break await send(message) diff --git a/litellm/proxy/_experimental/mcp_server/sse_transport.py b/litellm/proxy/_experimental/mcp_server/sse_transport.py index 63ffd403c66d..0a896328ddea 100644 --- a/litellm/proxy/_experimental/mcp_server/sse_transport.py +++ b/litellm/proxy/_experimental/mcp_server/sse_transport.py @@ -35,9 +35,7 @@ class SseServerTransport: """ _endpoint: str - _read_stream_writers: dict[ - UUID, MemoryObjectSendStream[types.JSONRPCMessage | Exception] - ] + _read_stream_writers: dict[UUID, MemoryObjectSendStream[types.JSONRPCMessage | Exception]] def __init__(self, endpoint: str) -> None: """ @@ -48,9 +46,7 @@ def __init__(self, endpoint: str) -> None: super().__init__() self._endpoint = endpoint self._read_stream_writers = {} - verbose_logger.debug( - f"SseServerTransport initialized with endpoint: {endpoint}" - ) + verbose_logger.debug(f"SseServerTransport initialized with endpoint: {endpoint}") @asynccontextmanager async def connect_sse(self, request: Request): @@ -75,9 +71,7 @@ async def connect_sse(self, request: Request): sse_stream_writer: MemoryObjectSendStream[dict[str, Any]] sse_stream_reader: MemoryObjectReceiveStream[dict[str, Any]] - sse_stream_writer, sse_stream_reader = anyio.create_memory_object_stream( - 0, dict[str, Any] - ) + sse_stream_writer, sse_stream_reader = anyio.create_memory_object_stream(0, dict[str, Any]) async def sse_writer(): verbose_logger.debug("Starting SSE writer") @@ -90,25 +84,19 @@ async def sse_writer(): await sse_stream_writer.send( { "event": "message", - "data": message.model_dump_json( - by_alias=True, exclude_none=True - ), + "data": message.model_dump_json(by_alias=True, exclude_none=True), } ) async with anyio.create_task_group() as tg: - response = EventSourceResponse( - content=sse_stream_reader, data_sender_callable=sse_writer - ) + response = EventSourceResponse(content=sse_stream_reader, data_sender_callable=sse_writer) verbose_logger.debug("Starting SSE response task") tg.start_soon(response, request.scope, request.receive, request._send) verbose_logger.debug("Yielding read and write streams") yield (read_stream, write_stream) - async def handle_post_message( - self, scope: Scope, receive: Receive, send: Send - ) -> Response: + async def handle_post_message(self, scope: Scope, receive: Receive, send: Send) -> Response: verbose_logger.debug("Handling POST message") request = Request(scope, receive) diff --git a/litellm/proxy/_experimental/mcp_server/tool_registry.py b/litellm/proxy/_experimental/mcp_server/tool_registry.py index bb30ff55c5cd..2da22671c919 100644 --- a/litellm/proxy/_experimental/mcp_server/tool_registry.py +++ b/litellm/proxy/_experimental/mcp_server/tool_registry.py @@ -52,11 +52,7 @@ def list_tools(self, tool_prefix: Optional[str] = None) -> List[MCPTool]: List all registered tools """ if tool_prefix: - return [ - tool - for tool in self.tools.values() - if tool.name.startswith(tool_prefix) - ] + return [tool for tool in self.tools.values() if tool.name.startswith(tool_prefix)] return list(self.tools.values()) def unregister_tools_with_prefix(self, prefix: str) -> int: @@ -75,13 +71,9 @@ def unregister_tools_with_prefix(self, prefix: str) -> int: verbose_logger.debug("Unregistered MCP tool %s", name) return removed - def convert_tools_to_mcp_sdk_tool_type( - self, tools: List[MCPTool] - ) -> List["MCPToolSDKTool"]: + def convert_tools_to_mcp_sdk_tool_type(self, tools: List[MCPTool]) -> List["MCPToolSDKTool"]: if MCPToolSDKTool is None: - raise ImportError( - "MCP SDK is not installed. Please install it with: pip install 'litellm[proxy]'" - ) + raise ImportError("MCP SDK is not installed. Please install it with: pip install 'litellm[proxy]'") return [ MCPToolSDKTool( name=tool.name, @@ -108,9 +100,7 @@ def load_tools_from_config( fires. """ if mcp_tools_config is None: - raise ValueError( - "mcp_tools_config is required, please set `mcp_tools` in your proxy config" - ) + raise ValueError("mcp_tools_config is required, please set `mcp_tools` in your proxy config") for tool_config in mcp_tools_config: if not isinstance(tool_config, dict): @@ -131,9 +121,7 @@ def load_tools_from_config( handler = get_instance_fn(handler_name, config_file_path) if handler is None: - verbose_logger.warning( - f"Warning: Could not find handler {handler_name} for tool {name}" - ) + verbose_logger.warning(f"Warning: Could not find handler {handler_name} for tool {name}") continue # Register the tool @@ -148,9 +136,7 @@ def load_tools_from_config( input_schema=input_schema, handler=handler, ) - verbose_logger.debug( - "all registered tools: %s", json.dumps(self.tools, indent=4, default=str) - ) + verbose_logger.debug("all registered tools: %s", json.dumps(self.tools, indent=4, default=str)) global_mcp_tool_registry = MCPToolRegistry() diff --git a/litellm/proxy/_experimental/mcp_server/toolset_db.py b/litellm/proxy/_experimental/mcp_server/toolset_db.py index a996131653f4..9652a3a28884 100644 --- a/litellm/proxy/_experimental/mcp_server/toolset_db.py +++ b/litellm/proxy/_experimental/mcp_server/toolset_db.py @@ -39,9 +39,7 @@ async def get_mcp_toolset( prisma_client: PrismaClient, toolset_id: str, ) -> Optional[MCPToolset]: - row = await MCPToolsetRepository(prisma_client).table.find_unique( - where={"toolset_id": toolset_id} - ) + row = await MCPToolsetRepository(prisma_client).table.find_unique(where={"toolset_id": toolset_id}) if row is None: return None return _toolset_from_row(row) @@ -59,9 +57,7 @@ async def list_mcp_toolsets( return [_toolset_from_row(r) for r in rows] except Exception as e: verbose_proxy_logger.warning( - "litellm.proxy._experimental.mcp_server.toolset_db::list_mcp_toolsets - {}".format( - str(e) - ) + "litellm.proxy._experimental.mcp_server.toolset_db::list_mcp_toolsets - {}".format(str(e)) ) return [] @@ -70,9 +66,7 @@ async def get_mcp_toolset_by_name( prisma_client: PrismaClient, toolset_name: str, ) -> Optional[MCPToolset]: - row = await MCPToolsetRepository(prisma_client).table.find_first( - where={"toolset_name": toolset_name} - ) + row = await MCPToolsetRepository(prisma_client).table.find_first(where={"toolset_name": toolset_name}) if row is None: return None return _toolset_from_row(row) @@ -106,9 +100,7 @@ async def delete_mcp_toolset( toolset_id: str, ) -> Optional[MCPToolset]: try: - row = await MCPToolsetRepository(prisma_client).table.delete( - where={"toolset_id": toolset_id} - ) + row = await MCPToolsetRepository(prisma_client).table.delete(where={"toolset_id": toolset_id}) except Exception as e: from prisma.errors import RecordNotFoundError diff --git a/litellm/proxy/_experimental/mcp_server/ui_session_utils.py b/litellm/proxy/_experimental/mcp_server/ui_session_utils.py index 37a3228ebf05..1b37b8849878 100644 --- a/litellm/proxy/_experimental/mcp_server/ui_session_utils.py +++ b/litellm/proxy/_experimental/mcp_server/ui_session_utils.py @@ -28,10 +28,7 @@ async def resolve_ui_session_team_ids( ) -> List[str]: """Resolve the real team ids backing a UI session token.""" - if ( - user_api_key_auth.team_id != UI_SESSION_TOKEN_TEAM_ID - or not user_api_key_auth.user_id - ): + if user_api_key_auth.team_id != UI_SESSION_TOKEN_TEAM_ID or not user_api_key_auth.user_id: return [] from litellm.proxy.auth.auth_checks import get_user_object @@ -78,8 +75,5 @@ async def build_effective_auth_contexts( resolved_team_ids = await resolve_ui_session_team_ids(user_api_key_auth) if resolved_team_ids: - return [ - clone_user_api_key_auth_with_team(user_api_key_auth, team_id) - for team_id in resolved_team_ids - ] + return [clone_user_api_key_auth_with_team(user_api_key_auth, team_id) for team_id in resolved_team_ids] return [user_api_key_auth] diff --git a/litellm/proxy/_experimental/mcp_server/utils.py b/litellm/proxy/_experimental/mcp_server/utils.py index 3418417a8f80..9cb6d404b011 100644 --- a/litellm/proxy/_experimental/mcp_server/utils.py +++ b/litellm/proxy/_experimental/mcp_server/utils.py @@ -30,13 +30,9 @@ # module is reloaded (e.g. ``importlib.reload``). Tests that override these # variables must reload this module — see # ``tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server_identity_env.py``. -LITELLM_MCP_SERVER_NAME = os.environ.get( - "LITELLM_MCP_SERVER_NAME", "litellm-mcp-server" -) +LITELLM_MCP_SERVER_NAME = os.environ.get("LITELLM_MCP_SERVER_NAME", "litellm-mcp-server") LITELLM_MCP_SERVER_VERSION = "1.0.0" -LITELLM_MCP_SERVER_DESCRIPTION = os.environ.get( - "LITELLM_MCP_SERVER_DESCRIPTION", "MCP Server for LiteLLM" -) +LITELLM_MCP_SERVER_DESCRIPTION = os.environ.get("LITELLM_MCP_SERVER_DESCRIPTION", "MCP Server for LiteLLM") MCP_TOOL_PREFIX_SEPARATOR = os.environ.get("MCP_TOOL_PREFIX_SEPARATOR", "-") MCP_TOOL_PREFIX_FORMAT = "{server_name}{separator}{tool_name}" @@ -391,9 +387,7 @@ def is_tool_name_prefixed( return True -def validate_mcp_server_name( - server_name: str, raise_http_exception: bool = False -) -> None: +def validate_mcp_server_name(server_name: str, raise_http_exception: bool = False) -> None: """ Validate that MCP server name does not contain 'MCP_TOOL_PREFIX_SEPARATOR'. @@ -410,9 +404,7 @@ def validate_mcp_server_name( from fastapi import HTTPException from starlette import status - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail={"error": error_message} - ) + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail={"error": error_message}) else: raise Exception(error_message) @@ -527,9 +519,7 @@ def _sub(match: "re.Match[str]") -> str: return _ENV_VAR_PATTERN.sub(_sub, value) -def interpolate_headers( - headers: Mapping[str, str], variables: Mapping[str, str] -) -> Dict[str, str]: +def interpolate_headers(headers: Mapping[str, str], variables: Mapping[str, str]) -> Dict[str, str]: """Return a copy of ``headers`` with every value passed through ``interpolate_env_vars``.""" return {k: interpolate_env_vars(v, variables) for k, v in headers.items()} diff --git a/litellm/proxy/_experimental/out/404.html b/litellm/proxy/_experimental/out/404.html index 6d246c816523..dd2a01991deb 100644 --- a/litellm/proxy/_experimental/out/404.html +++ b/litellm/proxy/_experimental/out/404.html @@ -1 +1 @@ -404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file diff --git a/litellm/proxy/_experimental/out/404/index.html b/litellm/proxy/_experimental/out/404/index.html index 6d246c816523..dd2a01991deb 100644 --- a/litellm/proxy/_experimental/out/404/index.html +++ b/litellm/proxy/_experimental/out/404/index.html @@ -1 +1 @@ -404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file diff --git a/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.__PAGE__.txt b/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.__PAGE__.txt index 650adb6b757b..55b18876d5b8 100644 --- a/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.__PAGE__.txt +++ b/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.__PAGE__.txt @@ -1,9 +1,9 @@ 1:"$Sreact.fragment" -2:I[347257,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientPageRoot"] -3:I[871135,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js","/litellm-asset-prefix/_next/static/chunks/0a6c418370a8c183.js","/litellm-asset-prefix/_next/static/chunks/832ddb9b0d31572d.js","/litellm-asset-prefix/_next/static/chunks/5be4dad131b2e215.js","/litellm-asset-prefix/_next/static/chunks/d822f57dff3b67b9.js","/litellm-asset-prefix/_next/static/chunks/95d00009e9d5f9b7.js","/litellm-asset-prefix/_next/static/chunks/aa582f16c8866dd8.js","/litellm-asset-prefix/_next/static/chunks/00ff280cdb7d7ee5.js","/litellm-asset-prefix/_next/static/chunks/a4a51ad6586a4936.js","/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","/litellm-asset-prefix/_next/static/chunks/945f24285ff1ffdf.js","/litellm-asset-prefix/_next/static/chunks/6d5b1e69e87af9ca.js","/litellm-asset-prefix/_next/static/chunks/1683ea4bc387a0e0.js","/litellm-asset-prefix/_next/static/chunks/7f375817c88ba600.js","/litellm-asset-prefix/_next/static/chunks/b6093ff35368ddd0.js","/litellm-asset-prefix/_next/static/chunks/1d5cb651ca79a976.js","/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","/litellm-asset-prefix/_next/static/chunks/43164991d3581805.js","/litellm-asset-prefix/_next/static/chunks/c6a1d77d2da7b533.js","/litellm-asset-prefix/_next/static/chunks/c2b633d80a28ed33.js","/litellm-asset-prefix/_next/static/chunks/ee97701fb3b5781f.js","/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","/litellm-asset-prefix/_next/static/chunks/a6615835e862bb65.js","/litellm-asset-prefix/_next/static/chunks/1a1bd0064a7cceca.js","/litellm-asset-prefix/_next/static/chunks/908828a91f602d8b.js","/litellm-asset-prefix/_next/static/chunks/2c1f9d7eb08aad46.js","/litellm-asset-prefix/_next/static/chunks/c058ac3e89dc33df.js","/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","/litellm-asset-prefix/_next/static/chunks/054be755a9981063.js"],"default"] -6:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] +2:I[347257,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"ClientPageRoot"] +3:I[871135,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js","/litellm-asset-prefix/_next/static/chunks/0whkizop7gd0~.js","/litellm-asset-prefix/_next/static/chunks/0-ih8xcz_89nt.js","/litellm-asset-prefix/_next/static/chunks/0pd5zl~lciww9.js","/litellm-asset-prefix/_next/static/chunks/02ihc5xweq16v.js","/litellm-asset-prefix/_next/static/chunks/0lg.6rbfsd-l9.js","/litellm-asset-prefix/_next/static/chunks/0mzw3maijoev6.js","/litellm-asset-prefix/_next/static/chunks/043q3g5-5-aju.js","/litellm-asset-prefix/_next/static/chunks/04amwk-x_vjxu.js","/litellm-asset-prefix/_next/static/chunks/0-dhh1_d1.b1u.js","/litellm-asset-prefix/_next/static/chunks/0pwkd9r.mc_ee.js","/litellm-asset-prefix/_next/static/chunks/011mgw.-67gs_.js","/litellm-asset-prefix/_next/static/chunks/0~-ovi6c4wjt1.js","/litellm-asset-prefix/_next/static/chunks/0_y-b9_d9dsuv.js","/litellm-asset-prefix/_next/static/chunks/0c2apcdkbqq0o.js","/litellm-asset-prefix/_next/static/chunks/0zrbitbm~0koh.js","/litellm-asset-prefix/_next/static/chunks/0sx3mu2_l9g_y.js","/litellm-asset-prefix/_next/static/chunks/0ngre0.s4-ej6.js","/litellm-asset-prefix/_next/static/chunks/0l7em-5kjv49e.js","/litellm-asset-prefix/_next/static/chunks/05t1k89l9tc3s.js","/litellm-asset-prefix/_next/static/chunks/17n.qg70cy9.9.js","/litellm-asset-prefix/_next/static/chunks/00q4mtjboprhm.js","/litellm-asset-prefix/_next/static/chunks/0el08tticy_20.js","/litellm-asset-prefix/_next/static/chunks/0-3i_.uof35pm.js","/litellm-asset-prefix/_next/static/chunks/14566-_ogh-19.js","/litellm-asset-prefix/_next/static/chunks/0w39dn9x3dp9g.js","/litellm-asset-prefix/_next/static/chunks/0q6~n4y84cejn.js","/litellm-asset-prefix/_next/static/chunks/0v1rxqc1hqmrl.js","/litellm-asset-prefix/_next/static/chunks/0c4pfjjue0uc-.js"],"default"] +6:I[897367,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"OutletBoundary"] 7:"$Sreact.suspense" -0:{"buildId":"WL7_sh-6Yp06TbwG9Go-Z","rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/6d5b1e69e87af9ca.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/1683ea4bc387a0e0.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/7f375817c88ba600.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/b6093ff35368ddd0.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/1d5cb651ca79a976.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/43164991d3581805.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/c6a1d77d2da7b533.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/c2b633d80a28ed33.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/ee97701fb3b5781f.js","async":true}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","async":true}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/a6615835e862bb65.js","async":true}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/1a1bd0064a7cceca.js","async":true}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/908828a91f602d8b.js","async":true}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/2c1f9d7eb08aad46.js","async":true}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/c058ac3e89dc33df.js","async":true}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","async":true}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","async":true}],["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/054be755a9981063.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"loading":null,"isPartial":false} +0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/011mgw.-67gs_.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/0~-ovi6c4wjt1.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/0_y-b9_d9dsuv.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/0c2apcdkbqq0o.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/0zrbitbm~0koh.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/0sx3mu2_l9g_y.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/0ngre0.s4-ej6.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/0l7em-5kjv49e.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/05t1k89l9tc3s.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/17n.qg70cy9.9.js","async":true}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/00q4mtjboprhm.js","async":true}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/0el08tticy_20.js","async":true}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/0-3i_.uof35pm.js","async":true}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/14566-_ogh-19.js","async":true}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/0w39dn9x3dp9g.js","async":true}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/0q6~n4y84cejn.js","async":true}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/0v1rxqc1hqmrl.js","async":true}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/0c4pfjjue0uc-.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"5rDiFx0t_mOGYmV_8kSkw"} 4:{} -5:{} +5:"$0:rsc:props:children:0:props:serverProvidedParams:params" 8:null diff --git a/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.txt b/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.txt index 5bc2f7758dbc..55176f9118b6 100644 --- a/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.txt +++ b/litellm/proxy/_experimental/out/__next.!KGRhc2hib2FyZCk.txt @@ -1,7 +1,7 @@ 1:"$Sreact.fragment" -2:I[92825,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientSegmentRoot"] -3:I[216370,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js","/litellm-asset-prefix/_next/static/chunks/0a6c418370a8c183.js","/litellm-asset-prefix/_next/static/chunks/832ddb9b0d31572d.js","/litellm-asset-prefix/_next/static/chunks/5be4dad131b2e215.js","/litellm-asset-prefix/_next/static/chunks/d822f57dff3b67b9.js","/litellm-asset-prefix/_next/static/chunks/95d00009e9d5f9b7.js","/litellm-asset-prefix/_next/static/chunks/aa582f16c8866dd8.js","/litellm-asset-prefix/_next/static/chunks/00ff280cdb7d7ee5.js","/litellm-asset-prefix/_next/static/chunks/a4a51ad6586a4936.js","/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","/litellm-asset-prefix/_next/static/chunks/945f24285ff1ffdf.js"],"default"] -4:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] -5:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] -0:{"buildId":"WL7_sh-6Yp06TbwG9Go-Z","rsc":["$","$1","c",{"children":[[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/0a6c418370a8c183.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/832ddb9b0d31572d.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/5be4dad131b2e215.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/d822f57dff3b67b9.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/95d00009e9d5f9b7.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/aa582f16c8866dd8.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/00ff280cdb7d7ee5.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/a4a51ad6586a4936.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/945f24285ff1ffdf.js","async":true}]],["$","$L2",null,{"Component":"$3","slots":{"children":["$","$L4",null,{"parallelRouterKey":"children","template":["$","$L5",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]},"serverProvidedParams":{"params":{},"promises":["$@6"]}}]]}],"loading":null,"isPartial":false} +2:I[92825,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"ClientSegmentRoot"] +3:I[216370,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js","/litellm-asset-prefix/_next/static/chunks/0whkizop7gd0~.js","/litellm-asset-prefix/_next/static/chunks/0-ih8xcz_89nt.js","/litellm-asset-prefix/_next/static/chunks/0pd5zl~lciww9.js","/litellm-asset-prefix/_next/static/chunks/02ihc5xweq16v.js","/litellm-asset-prefix/_next/static/chunks/0lg.6rbfsd-l9.js","/litellm-asset-prefix/_next/static/chunks/0mzw3maijoev6.js","/litellm-asset-prefix/_next/static/chunks/043q3g5-5-aju.js","/litellm-asset-prefix/_next/static/chunks/04amwk-x_vjxu.js","/litellm-asset-prefix/_next/static/chunks/0-dhh1_d1.b1u.js","/litellm-asset-prefix/_next/static/chunks/0pwkd9r.mc_ee.js"],"default"] +4:I[339756,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +5:I[837457,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +0:{"rsc":["$","$1","c",{"children":[[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/0whkizop7gd0~.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/0-ih8xcz_89nt.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/0pd5zl~lciww9.js","async":true}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/02ihc5xweq16v.js","async":true}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/0lg.6rbfsd-l9.js","async":true}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/0mzw3maijoev6.js","async":true}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/043q3g5-5-aju.js","async":true}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/04amwk-x_vjxu.js","async":true}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/0-dhh1_d1.b1u.js","async":true}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/0pwkd9r.mc_ee.js","async":true}]],["$","$L2",null,{"Component":"$3","slots":{"children":["$","$L4",null,{"parallelRouterKey":"children","template":["$","$L5",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]},"serverProvidedParams":{"params":{},"promises":["$@6"]}}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"5rDiFx0t_mOGYmV_8kSkw"} 6:"$0:rsc:props:children:1:props:serverProvidedParams:params" diff --git a/litellm/proxy/_experimental/out/__next._full.txt b/litellm/proxy/_experimental/out/__next._full.txt index 6fc958eb4ace..f1ff1ff8411c 100644 --- a/litellm/proxy/_experimental/out/__next._full.txt +++ b/litellm/proxy/_experimental/out/__next._full.txt @@ -1,48 +1,30 @@ 1:"$Sreact.fragment" -2:I[867271,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js"],"default"] -3:I[71195,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js"],"default"] -4:I[557951,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js"],"AuthProvider"] -5:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] -6:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] -7:I[92825,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientSegmentRoot"] -8:I[216370,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js","/litellm-asset-prefix/_next/static/chunks/0a6c418370a8c183.js","/litellm-asset-prefix/_next/static/chunks/832ddb9b0d31572d.js","/litellm-asset-prefix/_next/static/chunks/5be4dad131b2e215.js","/litellm-asset-prefix/_next/static/chunks/d822f57dff3b67b9.js","/litellm-asset-prefix/_next/static/chunks/95d00009e9d5f9b7.js","/litellm-asset-prefix/_next/static/chunks/aa582f16c8866dd8.js","/litellm-asset-prefix/_next/static/chunks/00ff280cdb7d7ee5.js","/litellm-asset-prefix/_next/static/chunks/a4a51ad6586a4936.js","/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","/litellm-asset-prefix/_next/static/chunks/945f24285ff1ffdf.js"],"default"] -20:I[168027,[],"default"] -:HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/1b8c5c205e8923d6.css","style"] -:HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.3a6ba036.woff2","font",{"crossOrigin":"","type":"font/woff2"}] -0:{"P":null,"b":"WL7_sh-6Yp06TbwG9Go-Z","c":["",""],"q":"","i":false,"f":[[["",{"children":["(dashboard)",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/1b8c5c205e8923d6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]}]}]}]]}],{"children":[["$","$1","c",{"children":[[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/0a6c418370a8c183.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/832ddb9b0d31572d.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/5be4dad131b2e215.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/d822f57dff3b67b9.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/95d00009e9d5f9b7.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/aa582f16c8866dd8.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/00ff280cdb7d7ee5.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/a4a51ad6586a4936.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/945f24285ff1ffdf.js","async":true,"nonce":"$undefined"}]],["$","$L7",null,{"Component":"$8","slots":{"children":["$","$L5",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]},"serverProvidedParams":{"params":{},"promises":["$@9"]}}]]}],{"children":[["$","$1","c",{"children":["$La",["$Lb","$Lc","$Ld","$Le","$Lf","$L10","$L11","$L12","$L13","$L14","$L15","$L16","$L17","$L18","$L19","$L1a","$L1b","$L1c","$L1d"],"$L1e"]}],{},null,false,false]},null,false,false]},null,false,false],"$L1f",false]],"m":"$undefined","G":["$20",[]],"S":true} -21:I[347257,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ClientPageRoot"] -22:I[871135,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js","/litellm-asset-prefix/_next/static/chunks/0a6c418370a8c183.js","/litellm-asset-prefix/_next/static/chunks/832ddb9b0d31572d.js","/litellm-asset-prefix/_next/static/chunks/5be4dad131b2e215.js","/litellm-asset-prefix/_next/static/chunks/d822f57dff3b67b9.js","/litellm-asset-prefix/_next/static/chunks/95d00009e9d5f9b7.js","/litellm-asset-prefix/_next/static/chunks/aa582f16c8866dd8.js","/litellm-asset-prefix/_next/static/chunks/00ff280cdb7d7ee5.js","/litellm-asset-prefix/_next/static/chunks/a4a51ad6586a4936.js","/litellm-asset-prefix/_next/static/chunks/7b788dd93ad868b3.js","/litellm-asset-prefix/_next/static/chunks/945f24285ff1ffdf.js","/litellm-asset-prefix/_next/static/chunks/6d5b1e69e87af9ca.js","/litellm-asset-prefix/_next/static/chunks/1683ea4bc387a0e0.js","/litellm-asset-prefix/_next/static/chunks/7f375817c88ba600.js","/litellm-asset-prefix/_next/static/chunks/b6093ff35368ddd0.js","/litellm-asset-prefix/_next/static/chunks/1d5cb651ca79a976.js","/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","/litellm-asset-prefix/_next/static/chunks/43164991d3581805.js","/litellm-asset-prefix/_next/static/chunks/c6a1d77d2da7b533.js","/litellm-asset-prefix/_next/static/chunks/c2b633d80a28ed33.js","/litellm-asset-prefix/_next/static/chunks/ee97701fb3b5781f.js","/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","/litellm-asset-prefix/_next/static/chunks/a6615835e862bb65.js","/litellm-asset-prefix/_next/static/chunks/1a1bd0064a7cceca.js","/litellm-asset-prefix/_next/static/chunks/908828a91f602d8b.js","/litellm-asset-prefix/_next/static/chunks/2c1f9d7eb08aad46.js","/litellm-asset-prefix/_next/static/chunks/c058ac3e89dc33df.js","/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","/litellm-asset-prefix/_next/static/chunks/054be755a9981063.js"],"default"] -25:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"OutletBoundary"] -26:"$Sreact.suspense" -28:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ViewportBoundary"] -2a:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] -a:["$","$L21",null,{"Component":"$22","serverProvidedParams":{"searchParams":{},"params":"$0:f:0:1:1:children:0:props:children:1:props:serverProvidedParams:params","promises":["$@23","$@24"]}}] -b:["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/6d5b1e69e87af9ca.js","async":true,"nonce":"$undefined"}] -c:["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/1683ea4bc387a0e0.js","async":true,"nonce":"$undefined"}] -d:["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/7f375817c88ba600.js","async":true,"nonce":"$undefined"}] -e:["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/b6093ff35368ddd0.js","async":true,"nonce":"$undefined"}] -f:["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/1d5cb651ca79a976.js","async":true,"nonce":"$undefined"}] -10:["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/6c4c97f1ea6e7d77.js","async":true,"nonce":"$undefined"}] -11:["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/43164991d3581805.js","async":true,"nonce":"$undefined"}] -12:["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/c6a1d77d2da7b533.js","async":true,"nonce":"$undefined"}] -13:["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/c2b633d80a28ed33.js","async":true,"nonce":"$undefined"}] -14:["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/ee97701fb3b5781f.js","async":true,"nonce":"$undefined"}] -15:["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/5f9c3b92a016f382.js","async":true,"nonce":"$undefined"}] -16:["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/a6615835e862bb65.js","async":true,"nonce":"$undefined"}] -17:["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/1a1bd0064a7cceca.js","async":true,"nonce":"$undefined"}] -18:["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/908828a91f602d8b.js","async":true,"nonce":"$undefined"}] -19:["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/2c1f9d7eb08aad46.js","async":true,"nonce":"$undefined"}] -1a:["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/c058ac3e89dc33df.js","async":true,"nonce":"$undefined"}] -1b:["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/a1ef280b7ad5ae6a.js","async":true,"nonce":"$undefined"}] -1c:["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/3b30ab8eaa03bc21.js","async":true,"nonce":"$undefined"}] -1d:["$","script","script-18",{"src":"/litellm-asset-prefix/_next/static/chunks/054be755a9981063.js","async":true,"nonce":"$undefined"}] -1e:["$","$L25",null,{"children":["$","$26",null,{"name":"Next.MetadataOutlet","children":"$@27"}]}] -1f:["$","$1","h",{"children":[null,["$","$L28",null,{"children":"$L29"}],["$","div",null,{"hidden":true,"children":["$","$L2a",null,{"children":["$","$26",null,{"name":"Next.Metadata","children":"$L2b"}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}] +2:I[867271,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +3:I[71195,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +4:I[557951,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"AuthProvider"] +5:I[339756,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +6:I[837457,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +7:I[92825,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"ClientSegmentRoot"] +8:I[216370,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js","/litellm-asset-prefix/_next/static/chunks/0whkizop7gd0~.js","/litellm-asset-prefix/_next/static/chunks/0-ih8xcz_89nt.js","/litellm-asset-prefix/_next/static/chunks/0pd5zl~lciww9.js","/litellm-asset-prefix/_next/static/chunks/02ihc5xweq16v.js","/litellm-asset-prefix/_next/static/chunks/0lg.6rbfsd-l9.js","/litellm-asset-prefix/_next/static/chunks/0mzw3maijoev6.js","/litellm-asset-prefix/_next/static/chunks/043q3g5-5-aju.js","/litellm-asset-prefix/_next/static/chunks/04amwk-x_vjxu.js","/litellm-asset-prefix/_next/static/chunks/0-dhh1_d1.b1u.js","/litellm-asset-prefix/_next/static/chunks/0pwkd9r.mc_ee.js"],"default"] +c:I[168027,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default",1] +:HL["/litellm-asset-prefix/_next/static/chunks/05qmwjqau64bz.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/0i77.0u.82o9u.css","style"] +:HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.0q-301v4kxxnr.woff2","font",{"crossOrigin":"","type":"font/woff2"}] +0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["(dashboard)",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/05qmwjqau64bz.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/0i77.0u.82o9u.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]}]}]}]}]]}],{"children":[["$","$1","c",{"children":[[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/0whkizop7gd0~.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/0-ih8xcz_89nt.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/0pd5zl~lciww9.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/02ihc5xweq16v.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/0lg.6rbfsd-l9.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/0mzw3maijoev6.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/043q3g5-5-aju.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/04amwk-x_vjxu.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/0-dhh1_d1.b1u.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/0pwkd9r.mc_ee.js","async":true,"nonce":"$undefined"}]],["$","$L7",null,{"Component":"$8","slots":{"children":["$","$L5",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L6",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:props:children:props:children:props:children:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]},"serverProvidedParams":{"params":{},"promises":["$@9"]}}]]}],{"children":["$La",{},null,false,null]},null,false,null]},null,false,null],"$Lb",false]],"m":"$undefined","G":["$c",["$Ld","$Le"]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"5rDiFx0t_mOGYmV_8kSkw"} +f:I[347257,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"ClientPageRoot"] +10:I[871135,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js","/litellm-asset-prefix/_next/static/chunks/0whkizop7gd0~.js","/litellm-asset-prefix/_next/static/chunks/0-ih8xcz_89nt.js","/litellm-asset-prefix/_next/static/chunks/0pd5zl~lciww9.js","/litellm-asset-prefix/_next/static/chunks/02ihc5xweq16v.js","/litellm-asset-prefix/_next/static/chunks/0lg.6rbfsd-l9.js","/litellm-asset-prefix/_next/static/chunks/0mzw3maijoev6.js","/litellm-asset-prefix/_next/static/chunks/043q3g5-5-aju.js","/litellm-asset-prefix/_next/static/chunks/04amwk-x_vjxu.js","/litellm-asset-prefix/_next/static/chunks/0-dhh1_d1.b1u.js","/litellm-asset-prefix/_next/static/chunks/0pwkd9r.mc_ee.js","/litellm-asset-prefix/_next/static/chunks/011mgw.-67gs_.js","/litellm-asset-prefix/_next/static/chunks/0~-ovi6c4wjt1.js","/litellm-asset-prefix/_next/static/chunks/0_y-b9_d9dsuv.js","/litellm-asset-prefix/_next/static/chunks/0c2apcdkbqq0o.js","/litellm-asset-prefix/_next/static/chunks/0zrbitbm~0koh.js","/litellm-asset-prefix/_next/static/chunks/0sx3mu2_l9g_y.js","/litellm-asset-prefix/_next/static/chunks/0ngre0.s4-ej6.js","/litellm-asset-prefix/_next/static/chunks/0l7em-5kjv49e.js","/litellm-asset-prefix/_next/static/chunks/05t1k89l9tc3s.js","/litellm-asset-prefix/_next/static/chunks/17n.qg70cy9.9.js","/litellm-asset-prefix/_next/static/chunks/00q4mtjboprhm.js","/litellm-asset-prefix/_next/static/chunks/0el08tticy_20.js","/litellm-asset-prefix/_next/static/chunks/0-3i_.uof35pm.js","/litellm-asset-prefix/_next/static/chunks/14566-_ogh-19.js","/litellm-asset-prefix/_next/static/chunks/0w39dn9x3dp9g.js","/litellm-asset-prefix/_next/static/chunks/0q6~n4y84cejn.js","/litellm-asset-prefix/_next/static/chunks/0v1rxqc1hqmrl.js","/litellm-asset-prefix/_next/static/chunks/0c4pfjjue0uc-.js"],"default"] +13:I[897367,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"OutletBoundary"] +14:"$Sreact.suspense" +16:I[897367,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"ViewportBoundary"] +18:I[897367,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"MetadataBoundary"] +a:["$","$1","c",{"children":[["$","$Lf",null,{"Component":"$10","serverProvidedParams":{"searchParams":{},"params":"$0:f:0:1:1:children:0:props:children:1:props:serverProvidedParams:params","promises":["$@11","$@12"]}}],[["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/011mgw.-67gs_.js","async":true,"nonce":"$undefined"}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/0~-ovi6c4wjt1.js","async":true,"nonce":"$undefined"}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/0_y-b9_d9dsuv.js","async":true,"nonce":"$undefined"}],["$","script","script-3",{"src":"/litellm-asset-prefix/_next/static/chunks/0c2apcdkbqq0o.js","async":true,"nonce":"$undefined"}],["$","script","script-4",{"src":"/litellm-asset-prefix/_next/static/chunks/0zrbitbm~0koh.js","async":true,"nonce":"$undefined"}],["$","script","script-5",{"src":"/litellm-asset-prefix/_next/static/chunks/0sx3mu2_l9g_y.js","async":true,"nonce":"$undefined"}],["$","script","script-6",{"src":"/litellm-asset-prefix/_next/static/chunks/0ngre0.s4-ej6.js","async":true,"nonce":"$undefined"}],["$","script","script-7",{"src":"/litellm-asset-prefix/_next/static/chunks/0l7em-5kjv49e.js","async":true,"nonce":"$undefined"}],["$","script","script-8",{"src":"/litellm-asset-prefix/_next/static/chunks/05t1k89l9tc3s.js","async":true,"nonce":"$undefined"}],["$","script","script-9",{"src":"/litellm-asset-prefix/_next/static/chunks/17n.qg70cy9.9.js","async":true,"nonce":"$undefined"}],["$","script","script-10",{"src":"/litellm-asset-prefix/_next/static/chunks/00q4mtjboprhm.js","async":true,"nonce":"$undefined"}],["$","script","script-11",{"src":"/litellm-asset-prefix/_next/static/chunks/0el08tticy_20.js","async":true,"nonce":"$undefined"}],["$","script","script-12",{"src":"/litellm-asset-prefix/_next/static/chunks/0-3i_.uof35pm.js","async":true,"nonce":"$undefined"}],["$","script","script-13",{"src":"/litellm-asset-prefix/_next/static/chunks/14566-_ogh-19.js","async":true,"nonce":"$undefined"}],["$","script","script-14",{"src":"/litellm-asset-prefix/_next/static/chunks/0w39dn9x3dp9g.js","async":true,"nonce":"$undefined"}],["$","script","script-15",{"src":"/litellm-asset-prefix/_next/static/chunks/0q6~n4y84cejn.js","async":true,"nonce":"$undefined"}],["$","script","script-16",{"src":"/litellm-asset-prefix/_next/static/chunks/0v1rxqc1hqmrl.js","async":true,"nonce":"$undefined"}],["$","script","script-17",{"src":"/litellm-asset-prefix/_next/static/chunks/0c4pfjjue0uc-.js","async":true,"nonce":"$undefined"}]],["$","$L13",null,{"children":["$","$14",null,{"name":"Next.MetadataOutlet","children":"$@15"}]}]]}] +b:["$","$1","h",{"children":[null,["$","$L16",null,{"children":"$L17"}],["$","div",null,{"hidden":true,"children":["$","$L18",null,{"children":["$","$14",null,{"name":"Next.Metadata","children":"$L19"}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}] +d:["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/05qmwjqau64bz.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}] +e:["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/0i77.0u.82o9u.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}] 9:"$0:f:0:1:1:children:0:props:children:1:props:serverProvidedParams:params" -23:{} -24:"$0:f:0:1:1:children:0:props:children:1:props:serverProvidedParams:params" -29:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]] -2c:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] -27:null -2b:[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"/get_favicon"}],["$","$L2c","4",{}]] +11:{} +12:"$0:f:0:1:1:children:0:props:children:1:props:serverProvidedParams:params" +17:[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]] +1a:I[27201,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"IconMark"] +15:null +19:[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.0~dgapwhi~75y.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"/get_favicon"}],["$","$L1a","4",{}]] diff --git a/litellm/proxy/_experimental/out/__next._head.txt b/litellm/proxy/_experimental/out/__next._head.txt index a018e5d0bbd9..27acd6997928 100644 --- a/litellm/proxy/_experimental/out/__next._head.txt +++ b/litellm/proxy/_experimental/out/__next._head.txt @@ -1,6 +1,6 @@ 1:"$Sreact.fragment" -2:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"ViewportBoundary"] -3:I[897367,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"MetadataBoundary"] +2:I[897367,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"ViewportBoundary"] +3:I[897367,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"MetadataBoundary"] 4:"$Sreact.suspense" -5:I[27201,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"IconMark"] -0:{"buildId":"WL7_sh-6Yp06TbwG9Go-Z","rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.1d32c690.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"/get_favicon"}],["$","$L5","4",{}]]}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],"loading":null,"isPartial":false} +5:I[27201,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"IconMark"] +0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"LiteLLM Dashboard"}],["$","meta","1",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","2",{"rel":"icon","href":"/favicon.ico?favicon.0~dgapwhi~75y.ico","sizes":"48x48","type":"image/x-icon"}],["$","link","3",{"rel":"icon","href":"/get_favicon"}],["$","$L5","4",{}]]}]}]}],["$","meta",null,{"name":"next-size-adjust","content":""}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"5rDiFx0t_mOGYmV_8kSkw"} diff --git a/litellm/proxy/_experimental/out/__next._index.txt b/litellm/proxy/_experimental/out/__next._index.txt index f544b3717ccf..9714fd22643c 100644 --- a/litellm/proxy/_experimental/out/__next._index.txt +++ b/litellm/proxy/_experimental/out/__next._index.txt @@ -1,9 +1,9 @@ 1:"$Sreact.fragment" -2:I[867271,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js"],"default"] -3:I[71195,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js"],"default"] -4:I[557951,["/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js"],"AuthProvider"] -5:I[339756,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] -6:I[837457,["/litellm-asset-prefix/_next/static/chunks/d96012bcfc98706a.js","/litellm-asset-prefix/_next/static/chunks/dbca964212122d58.js"],"default"] -:HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/1b8c5c205e8923d6.css","style"] -0:{"buildId":"WL7_sh-6Yp06TbwG9Go-Z","rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","precedence":"next"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/1b8c5c205e8923d6.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/59002382e3e0d318.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/00435a7c4cda2b39.js","async":true}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","template":["$","$L6",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]}]}]}]}]]}],"loading":null,"isPartial":false} +2:I[867271,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +3:I[71195,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +4:I[557951,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"AuthProvider"] +5:I[339756,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +6:I[837457,["/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js"],"default"] +:HL["/litellm-asset-prefix/_next/static/chunks/05qmwjqau64bz.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/0i77.0u.82o9u.css","style"] +0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/05qmwjqau64bz.css","precedence":"next"}],["$","link","1",{"rel":"stylesheet","href":"/litellm-asset-prefix/_next/static/chunks/0i77.0u.82o9u.css","precedence":"next"}],["$","script","script-0",{"src":"/litellm-asset-prefix/_next/static/chunks/0n.a~e5dwfnkn.js","async":true}],["$","script","script-1",{"src":"/litellm-asset-prefix/_next/static/chunks/0.4.bbjx7y007.js","async":true}],["$","script","script-2",{"src":"/litellm-asset-prefix/_next/static/chunks/0pidya1qvuvx8.js","async":true}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"inter_5972bc34-module__OU16Qa__className","children":["$","$L2",null,{"children":["$","$L3",null,{"children":["$","$L4",null,{"children":["$","$L5",null,{"parallelRouterKey":"children","template":["$","$L6",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]}]}]}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"5rDiFx0t_mOGYmV_8kSkw"} diff --git a/litellm/proxy/_experimental/out/__next._tree.txt b/litellm/proxy/_experimental/out/__next._tree.txt index 883fe73f16a4..c8aadb1d1e24 100644 --- a/litellm/proxy/_experimental/out/__next._tree.txt +++ b/litellm/proxy/_experimental/out/__next._tree.txt @@ -1,4 +1,4 @@ -:HL["/litellm-asset-prefix/_next/static/chunks/4e20891f2fd03463.css","style"] -:HL["/litellm-asset-prefix/_next/static/chunks/1b8c5c205e8923d6.css","style"] -:HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.3a6ba036.woff2","font",{"crossOrigin":"","type":"font/woff2"}] -0:{"buildId":"WL7_sh-6Yp06TbwG9Go-Z","tree":{"name":"","paramType":null,"paramKey":"","hasRuntimePrefetch":false,"slots":{"children":{"name":"(dashboard)","paramType":null,"paramKey":"(dashboard)","hasRuntimePrefetch":false,"slots":{"children":{"name":"__PAGE__","paramType":null,"paramKey":"__PAGE__","hasRuntimePrefetch":false,"slots":null,"isRootLayout":false}},"isRootLayout":false}},"isRootLayout":true},"staleTime":300} +:HL["/litellm-asset-prefix/_next/static/chunks/05qmwjqau64bz.css","style"] +:HL["/litellm-asset-prefix/_next/static/chunks/0i77.0u.82o9u.css","style"] +:HL["/litellm-asset-prefix/_next/static/media/83afe278b6a6bb3c-s.p.0q-301v4kxxnr.woff2","font",{"crossOrigin":"","type":"font/woff2"}] +0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"(dashboard)","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"5rDiFx0t_mOGYmV_8kSkw"} diff --git a/litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_buildManifest.js b/litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_buildManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_buildManifest.js rename to litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_buildManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_clientMiddlewareManifest.js b/litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_clientMiddlewareManifest.js new file mode 100644 index 000000000000..a8acaffa33a1 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_clientMiddlewareManifest.js @@ -0,0 +1 @@ +self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_ssgManifest.js b/litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_ssgManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_ssgManifest.js rename to litellm/proxy/_experimental/out/_next/static/5rDiFx0t_mOGYmV_8kSkw/_ssgManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_clientMiddlewareManifest.json b/litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_clientMiddlewareManifest.json deleted file mode 100644 index 0637a088a01e..000000000000 --- a/litellm/proxy/_experimental/out/_next/static/WL7_sh-6Yp06TbwG9Go-Z/_clientMiddlewareManifest.json +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/0-3i_.uof35pm.js b/litellm/proxy/_experimental/out/_next/static/chunks/0-3i_.uof35pm.js new file mode 100644 index 000000000000..aaaafac2d130 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/0-3i_.uof35pm.js @@ -0,0 +1,2 @@ +(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,184163,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M505.7 661a8 8 0 0012.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"}}]},name:"download",theme:"outlined"};var i=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(i.default,(0,t.default)({},e,{ref:s,icon:n}))});e.s(["default",0,s],184163)},309821,e=>{"use strict";e.i(247167);var t=e.i(271645),r=e.i(135551),n=e.i(201072),i=e.i(121229),s=e.i(726289),a=e.i(864517),l=e.i(343794),o=e.i(529681),c=e.i(242064),u=e.i(931067),d=e.i(209428),m=e.i(703923),f={percent:0,prefixCls:"rc-progress",strokeColor:"#2db7f5",strokeLinecap:"round",strokeWidth:1,trailColor:"#D9D9D9",trailWidth:1,gapPosition:"bottom"},h=function(){var e=(0,t.useRef)([]),r=(0,t.useRef)(null);return(0,t.useEffect)(function(){var t=Date.now(),n=!1;e.current.forEach(function(e){if(e){n=!0;var i=e.style;i.transitionDuration=".3s, .3s, .3s, .06s",r.current&&t-r.current<100&&(i.transitionDuration="0s, 0s")}}),n&&(r.current=Date.now())}),e.current},p=e.i(410160),g=e.i(392221),x=e.i(654310),v=0,y=(0,x.default)();let b=function(e){var r=t.useState(),n=(0,g.default)(r,2),i=n[0],s=n[1];return t.useEffect(function(){var e;s("rc_progress_".concat((y?(e=v,v+=1):e="TEST_OR_SSR",e)))},[]),e||i};var _=function(e){var r=e.bg,n=e.children;return t.createElement("div",{style:{width:"100%",height:"100%",background:r}},n)};function j(e,t){return Object.keys(e).map(function(r){var n=parseFloat(r),i="".concat(Math.floor(n*t),"%");return"".concat(e[r]," ").concat(i)})}var w=t.forwardRef(function(e,r){var n=e.prefixCls,i=e.color,s=e.gradientId,a=e.radius,l=e.style,o=e.ptg,c=e.strokeLinecap,u=e.strokeWidth,d=e.size,m=e.gapDegree,f=i&&"object"===(0,p.default)(i),h=d/2,g=t.createElement("circle",{className:"".concat(n,"-circle-path"),r:a,cx:h,cy:h,stroke:f?"#FFF":void 0,strokeLinecap:c,strokeWidth:u,opacity:+(0!==o),style:l,ref:r});if(!f)return g;var x="".concat(s,"-conic"),v=j(i,(360-m)/360),y=j(i,1),b="conic-gradient(from ".concat(m?"".concat(180+m/2,"deg"):"0deg",", ").concat(v.join(", "),")"),w="linear-gradient(to ".concat(m?"bottom":"top",", ").concat(y.join(", "),")");return t.createElement(t.Fragment,null,t.createElement("mask",{id:x},g),t.createElement("foreignObject",{x:0,y:0,width:d,height:d,mask:"url(#".concat(x,")")},t.createElement(_,{bg:w},t.createElement(_,{bg:b}))))}),k=function(e,t,r,n,i,s,a,l,o,c){var u=arguments.length>10&&void 0!==arguments[10]?arguments[10]:0,d=(100-n)/100*t;return"round"===o&&100!==n&&(d+=c/2)>=t&&(d=t-.01),{stroke:"string"==typeof l?l:void 0,strokeDasharray:"".concat(t,"px ").concat(e),strokeDashoffset:d+u,transform:"rotate(".concat(i+r/100*360*((360-s)/360)+(0===s?0:({bottom:0,top:180,left:90,right:-90})[a]),"deg)"),transformOrigin:"".concat(50,"px ").concat(50,"px"),transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s, opacity .3s ease 0s",fillOpacity:0}},C=["id","prefixCls","steps","strokeWidth","trailWidth","gapDegree","gapPosition","trailColor","strokeLinecap","style","className","strokeColor","percent"];function S(e){var t=null!=e?e:[];return Array.isArray(t)?t:[t]}let E=function(e){var r,n,i,s,a=(0,d.default)((0,d.default)({},f),e),o=a.id,c=a.prefixCls,g=a.steps,x=a.strokeWidth,v=a.trailWidth,y=a.gapDegree,_=void 0===y?0:y,j=a.gapPosition,E=a.trailColor,O=a.strokeLinecap,N=a.style,I=a.className,T=a.strokeColor,R=a.percent,P=(0,m.default)(a,C),D=b(o),$="".concat(D,"-gradient"),A=50-x/2,F=2*Math.PI*A,L=_>0?90+_/2:-90,M=(360-_)/360*F,B="object"===(0,p.default)(g)?g:{count:g,gap:2},U=B.count,z=B.gap,V=S(R),H=S(T),W=H.find(function(e){return e&&"object"===(0,p.default)(e)}),K=W&&"object"===(0,p.default)(W)?"butt":O,q=k(F,M,0,100,L,_,j,E,K,x),X=h();return t.createElement("svg",(0,u.default)({className:(0,l.default)("".concat(c,"-circle"),I),viewBox:"0 0 ".concat(100," ").concat(100),style:N,id:o,role:"presentation"},P),!U&&t.createElement("circle",{className:"".concat(c,"-circle-trail"),r:A,cx:50,cy:50,stroke:E,strokeLinecap:K,strokeWidth:v||x,style:q}),U?(r=Math.round(U*(V[0]/100)),n=100/U,i=0,Array(U).fill(null).map(function(e,s){var a=s<=r-1?H[0]:E,l=a&&"object"===(0,p.default)(a)?"url(#".concat($,")"):void 0,o=k(F,M,i,n,L,_,j,a,"butt",x,z);return i+=(M-o.strokeDashoffset+z)*100/M,t.createElement("circle",{key:s,className:"".concat(c,"-circle-path"),r:A,cx:50,cy:50,stroke:l,strokeWidth:x,opacity:1,style:o,ref:function(e){X[s]=e}})})):(s=0,V.map(function(e,r){var n=H[r]||H[H.length-1],i=k(F,M,s,e,L,_,j,n,K,x);return s+=e,t.createElement(w,{key:r,color:n,ptg:e,radius:A,prefixCls:c,gradientId:$,style:i,strokeLinecap:K,strokeWidth:x,gapDegree:_,ref:function(e){X[r]=e},size:100})}).reverse()))};var O=e.i(491816);e.i(765846);var N=e.i(896091);function I(e){return!e||e<0?0:e>100?100:e}function T({success:e,successPercent:t}){let r=t;return e&&"progress"in e&&(r=e.progress),e&&"percent"in e&&(r=e.percent),r}let R=(e,t,r)=>{var n,i,s,a;let l=-1,o=-1;if("step"===t){let t=r.steps,n=r.strokeWidth;"string"==typeof e||void 0===e?(l="small"===e?2:14,o=null!=n?n:8):"number"==typeof e?[l,o]=[e,e]:[l=14,o=8]=Array.isArray(e)?e:[e.width,e.height],l*=t}else if("line"===t){let t=null==r?void 0:r.strokeWidth;"string"==typeof e||void 0===e?o=t||("small"===e?6:8):"number"==typeof e?[l,o]=[e,e]:[l=-1,o=8]=Array.isArray(e)?e:[e.width,e.height]}else("circle"===t||"dashboard"===t)&&("string"==typeof e||void 0===e?[l,o]="small"===e?[60,60]:[120,120]:"number"==typeof e?[l,o]=[e,e]:Array.isArray(e)&&(l=null!=(i=null!=(n=e[0])?n:e[1])?i:120,o=null!=(a=null!=(s=e[0])?s:e[1])?a:120));return[l,o]},P=e=>{let{prefixCls:r,trailColor:n=null,strokeLinecap:i="round",gapPosition:s,gapDegree:a,width:o=120,type:c,children:u,success:d,size:m=o,steps:f}=e,[h,p]=R(m,"circle"),{strokeWidth:g}=e;void 0===g&&(g=Math.max(3/h*100,6));let x=t.useMemo(()=>a||0===a?a:"dashboard"===c?75:void 0,[a,c]),v=(({percent:e,success:t,successPercent:r})=>{let n=I(T({success:t,successPercent:r}));return[n,I(I(e)-n)]})(e),y="[object Object]"===Object.prototype.toString.call(e.strokeColor),b=(({success:e={},strokeColor:t})=>{let{strokeColor:r}=e;return[r||N.presetPrimaryColors.green,t||null]})({success:d,strokeColor:e.strokeColor}),_=(0,l.default)(`${r}-inner`,{[`${r}-circle-gradient`]:y}),j=t.createElement(E,{steps:f,percent:f?v[1]:v,strokeWidth:g,trailWidth:g,strokeColor:f?b[1]:b,strokeLinecap:i,trailColor:n,prefixCls:r,gapDegree:x,gapPosition:s||"dashboard"===c&&"bottom"||void 0}),w=h<=20,k=t.createElement("div",{className:_,style:{width:h,height:p,fontSize:.15*h+6}},j,!w&&u);return w?t.createElement(O.default,{title:u},k):k};e.i(296059);var D=e.i(694758),$=e.i(915654),A=e.i(183293),F=e.i(246422),L=e.i(838378);let M="--progress-line-stroke-color",B="--progress-percent",U=e=>{let t=e?"100%":"-100%";return new D.Keyframes(`antProgress${e?"RTL":"LTR"}Active`,{"0%":{transform:`translateX(${t}) scaleX(0)`,opacity:.1},"20%":{transform:`translateX(${t}) scaleX(0)`,opacity:.5},to:{transform:"translateX(0) scaleX(1)",opacity:0}})},z=(0,F.genStyleHooks)("Progress",e=>{let t=e.calc(e.marginXXS).div(2).equal(),r=(0,L.mergeToken)(e,{progressStepMarginInlineEnd:t,progressStepMinWidth:t,progressActiveMotionDuration:"2.4s"});return[(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:Object.assign(Object.assign({},(0,A.resetComponent)(e)),{display:"inline-block","&-rtl":{direction:"rtl"},"&-line":{position:"relative",width:"100%",fontSize:e.fontSize},[`${t}-outer`]:{display:"inline-flex",alignItems:"center",width:"100%"},[`${t}-inner`]:{position:"relative",display:"inline-block",width:"100%",flex:1,overflow:"hidden",verticalAlign:"middle",backgroundColor:e.remainingColor,borderRadius:e.lineBorderRadius},[`${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.defaultColor}},[`${t}-success-bg, ${t}-bg`]:{position:"relative",background:e.defaultColor,borderRadius:e.lineBorderRadius,transition:`all ${e.motionDurationSlow} ${e.motionEaseInOutCirc}`},[`${t}-layout-bottom`]:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",[`${t}-text`]:{width:"max-content",marginInlineStart:0,marginTop:e.marginXXS}},[`${t}-bg`]:{overflow:"hidden","&::after":{content:'""',background:{_multi_value_:!0,value:["inherit",`var(${M})`]},height:"100%",width:`calc(1 / var(${B}) * 100%)`,display:"block"},[`&${t}-bg-inner`]:{minWidth:"max-content","&::after":{content:"none"},[`${t}-text-inner`]:{color:e.colorWhite,[`&${t}-text-bright`]:{color:"rgba(0, 0, 0, 0.45)"}}}},[`${t}-success-bg`]:{position:"absolute",insetBlockStart:0,insetInlineStart:0,backgroundColor:e.colorSuccess},[`${t}-text`]:{display:"inline-block",marginInlineStart:e.marginXS,color:e.colorText,lineHeight:1,width:"2em",whiteSpace:"nowrap",textAlign:"start",verticalAlign:"middle",wordBreak:"normal",[r]:{fontSize:e.fontSize},[`&${t}-text-outer`]:{width:"max-content"},[`&${t}-text-outer${t}-text-start`]:{width:"max-content",marginInlineStart:0,marginInlineEnd:e.marginXS}},[`${t}-text-inner`]:{display:"flex",justifyContent:"center",alignItems:"center",width:"100%",height:"100%",marginInlineStart:0,padding:`0 ${(0,$.unit)(e.paddingXXS)}`,[`&${t}-text-start`]:{justifyContent:"start"},[`&${t}-text-end`]:{justifyContent:"end"}},[`&${t}-status-active`]:{[`${t}-bg::before`]:{position:"absolute",inset:0,backgroundColor:e.colorBgContainer,borderRadius:e.lineBorderRadius,opacity:0,animationName:U(),animationDuration:e.progressActiveMotionDuration,animationTimingFunction:e.motionEaseOutQuint,animationIterationCount:"infinite",content:'""'}},[`&${t}-rtl${t}-status-active`]:{[`${t}-bg::before`]:{animationName:U(!0)}},[`&${t}-status-exception`]:{[`${t}-bg`]:{backgroundColor:e.colorError},[`${t}-text`]:{color:e.colorError}},[`&${t}-status-exception ${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.colorError}},[`&${t}-status-success`]:{[`${t}-bg`]:{backgroundColor:e.colorSuccess},[`${t}-text`]:{color:e.colorSuccess}},[`&${t}-status-success ${t}-inner:not(${t}-circle-gradient)`]:{[`${t}-circle-path`]:{stroke:e.colorSuccess}}})}})(r),(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:{[`${t}-circle-trail`]:{stroke:e.remainingColor},[`&${t}-circle ${t}-inner`]:{position:"relative",lineHeight:1,backgroundColor:"transparent"},[`&${t}-circle ${t}-text`]:{position:"absolute",insetBlockStart:"50%",insetInlineStart:0,width:"100%",margin:0,padding:0,color:e.circleTextColor,fontSize:e.circleTextFontSize,lineHeight:1,whiteSpace:"normal",textAlign:"center",transform:"translateY(-50%)",[r]:{fontSize:e.circleIconFontSize}},[`${t}-circle&-status-exception`]:{[`${t}-text`]:{color:e.colorError}},[`${t}-circle&-status-success`]:{[`${t}-text`]:{color:e.colorSuccess}}},[`${t}-inline-circle`]:{lineHeight:1,[`${t}-inner`]:{verticalAlign:"bottom"}}}})(r),(e=>{let{componentCls:t}=e;return{[t]:{[`${t}-steps`]:{display:"inline-block","&-outer":{display:"flex",flexDirection:"row",alignItems:"center"},"&-item":{flexShrink:0,minWidth:e.progressStepMinWidth,marginInlineEnd:e.progressStepMarginInlineEnd,backgroundColor:e.remainingColor,transition:`all ${e.motionDurationSlow}`,"&-active":{backgroundColor:e.defaultColor}}}}}})(r),(e=>{let{componentCls:t,iconCls:r}=e;return{[t]:{[`${t}-small&-line, ${t}-small&-line ${t}-text ${r}`]:{fontSize:e.fontSizeSM}}}})(r)]},e=>({circleTextColor:e.colorText,defaultColor:e.colorInfo,remainingColor:e.colorFillSecondary,lineBorderRadius:100,circleTextFontSize:"1em",circleIconFontSize:`${e.fontSize/e.fontSizeSM}em`}));var V=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);it.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r};let H=e=>{let{prefixCls:r,direction:n,percent:i,size:s,strokeWidth:a,strokeColor:o,strokeLinecap:c="round",children:u,trailColor:d=null,percentPosition:m,success:f}=e,{align:h,type:p}=m,g=o&&"string"!=typeof o?((e,t)=>{let{from:r=N.presetPrimaryColors.blue,to:n=N.presetPrimaryColors.blue,direction:i="rtl"===t?"to left":"to right"}=e,s=V(e,["from","to","direction"]);if(0!==Object.keys(s).length){let e,t=(e=[],Object.keys(s).forEach(t=>{let r=Number.parseFloat(t.replace(/%/g,""));Number.isNaN(r)||e.push({key:r,value:s[t]})}),(e=e.sort((e,t)=>e.key-t.key)).map(({key:e,value:t})=>`${t} ${e}%`).join(", ")),r=`linear-gradient(${i}, ${t})`;return{background:r,[M]:r}}let a=`linear-gradient(${i}, ${r}, ${n})`;return{background:a,[M]:a}})(o,n):{[M]:o,background:o},x="square"===c||"butt"===c?0:void 0,[v,y]=R(null!=s?s:[-1,a||("small"===s?6:8)],"line",{strokeWidth:a}),b=Object.assign(Object.assign({width:`${I(i)}%`,height:y,borderRadius:x},g),{[B]:I(i)/100}),_=T(e),j={width:`${I(_)}%`,height:y,borderRadius:x,backgroundColor:null==f?void 0:f.strokeColor},w=t.createElement("div",{className:`${r}-inner`,style:{backgroundColor:d||void 0,borderRadius:x}},t.createElement("div",{className:(0,l.default)(`${r}-bg`,`${r}-bg-${p}`),style:b},"inner"===p&&u),void 0!==_&&t.createElement("div",{className:`${r}-success-bg`,style:j})),k="outer"===p&&"start"===h,C="outer"===p&&"end"===h;return"outer"===p&&"center"===h?t.createElement("div",{className:`${r}-layout-bottom`},w,u):t.createElement("div",{className:`${r}-outer`,style:{width:v<0?"100%":v}},k&&u,w,C&&u)},W=e=>{let{size:r,steps:n,rounding:i=Math.round,percent:s=0,strokeWidth:a=8,strokeColor:o,trailColor:c=null,prefixCls:u,children:d}=e,m=i(s/100*n),[f,h]=R(null!=r?r:["small"===r?2:14,a],"step",{steps:n,strokeWidth:a}),p=f/n,g=Array.from({length:n});for(let e=0;et.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);it.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r};let q=["normal","exception","active","success"],X=t.forwardRef((e,u)=>{let d,{prefixCls:m,className:f,rootClassName:h,steps:p,strokeColor:g,percent:x=0,size:v="default",showInfo:y=!0,type:b="line",status:_,format:j,style:w,percentPosition:k={}}=e,C=K(e,["prefixCls","className","rootClassName","steps","strokeColor","percent","size","showInfo","type","status","format","style","percentPosition"]),{align:S="end",type:E="outer"}=k,O=Array.isArray(g)?g[0]:g,N="string"==typeof g||Array.isArray(g)?g:void 0,D=t.useMemo(()=>{if(O){let e="string"==typeof O?O:Object.values(O)[0];return new r.FastColor(e).isLight()}return!1},[g]),$=t.useMemo(()=>{var t,r;let n=T(e);return Number.parseInt(void 0!==n?null==(t=null!=n?n:0)?void 0:t.toString():null==(r=null!=x?x:0)?void 0:r.toString(),10)},[x,e.success,e.successPercent]),A=t.useMemo(()=>!q.includes(_)&&$>=100?"success":_||"normal",[_,$]),{getPrefixCls:F,direction:L,progress:M}=t.useContext(c.ConfigContext),B=F("progress",m),[U,V,X]=z(B),Q="line"===b,J=Q&&!p,Y=t.useMemo(()=>{let r;if(!y)return null;let o=T(e),c=j||(e=>`${e}%`),u=Q&&D&&"inner"===E;return"inner"===E||j||"exception"!==A&&"success"!==A?r=c(I(x),I(o)):"exception"===A?r=Q?t.createElement(s.default,null):t.createElement(a.default,null):"success"===A&&(r=Q?t.createElement(n.default,null):t.createElement(i.default,null)),t.createElement("span",{className:(0,l.default)(`${B}-text`,{[`${B}-text-bright`]:u,[`${B}-text-${S}`]:J,[`${B}-text-${E}`]:J}),title:"string"==typeof r?r:void 0},r)},[y,x,$,A,b,B,j]);"line"===b?d=p?t.createElement(W,Object.assign({},e,{strokeColor:N,prefixCls:B,steps:"object"==typeof p?p.count:p}),Y):t.createElement(H,Object.assign({},e,{strokeColor:O,prefixCls:B,direction:L,percentPosition:{align:S,type:E}}),Y):("circle"===b||"dashboard"===b)&&(d=t.createElement(P,Object.assign({},e,{strokeColor:O,prefixCls:B,progressStatus:A}),Y));let G=(0,l.default)(B,`${B}-status-${A}`,{[`${B}-${"dashboard"===b&&"circle"||b}`]:"line"!==b,[`${B}-inline-circle`]:"circle"===b&&R(v,"circle")[0]<=20,[`${B}-line`]:J,[`${B}-line-align-${S}`]:J,[`${B}-line-position-${E}`]:J,[`${B}-steps`]:p,[`${B}-show-info`]:y,[`${B}-${v}`]:"string"==typeof v,[`${B}-rtl`]:"rtl"===L},null==M?void 0:M.className,f,h,V,X);return U(t.createElement("div",Object.assign({ref:u,style:Object.assign(Object.assign({},null==M?void 0:M.style),w),className:G,role:"progressbar","aria-valuenow":$,"aria-valuemin":0,"aria-valuemax":100},(0,o.default)(C,["trailColor","strokeWidth","width","gapDegree","gapPosition","strokeLinecap","success","successPercent"])),d))});e.s(["default",0,X],309821)},519756,e=>{"use strict";e.i(247167);var t=e.i(931067),r=e.i(271645);let n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"}}]},name:"upload",theme:"outlined"};var i=e.i(9583),s=r.forwardRef(function(e,s){return r.createElement(i.default,(0,t.default)({},e,{ref:s,icon:n}))});e.s(["UploadOutlined",0,s],519756)},233538,e=>{"use strict";e.s(["isDisabledReactIssue7711",0,function(e){let t=e.parentElement,r=null;for(;t&&!(t instanceof HTMLFieldSetElement);)t instanceof HTMLLegendElement&&(r=t),t=t.parentElement;let n=(null==t?void 0:t.getAttribute("disabled"))==="";return!(n&&function(e){if(!e)return!1;let t=e.previousElementSibling;for(;null!==t;){if(t instanceof HTMLLegendElement)return!1;t=t.previousElementSibling}return!0}(r))&&n}])},83733,233137,e=>{"use strict";let t,r;var n,i,s=e.i(247167),a=e.i(271645),l=e.i(544508),o=e.i(746725),c=e.i(835696);void 0!==s.default&&"u">typeof globalThis&&"u">typeof Element&&(null==(n=null==s.default?void 0:s.default.env)?void 0:n.NODE_ENV)==="test"&&void 0===(null==(i=null==Element?void 0:Element.prototype)?void 0:i.getAnimations)&&(Element.prototype.getAnimations=function(){return console.warn(["Headless UI has polyfilled `Element.prototype.getAnimations` for your tests.","Please install a proper polyfill e.g. `jsdom-testing-mocks`, to silence these warnings.","","Example usage:","```js","import { mockAnimationsApi } from 'jsdom-testing-mocks'","mockAnimationsApi()","```"].join(` +`)),[]});var u=((t=u||{})[t.None=0]="None",t[t.Closed=1]="Closed",t[t.Enter=2]="Enter",t[t.Leave=4]="Leave",t);e.s(["transitionDataAttributes",0,function(e){let t={};for(let r in e)!0===e[r]&&(t[`data-${r}`]="");return t},"useTransition",0,function(e,t,r,n){let[i,s]=(0,a.useState)(r),{hasFlag:u,addFlag:d,removeFlag:m}=function(e=0){let[t,r]=(0,a.useState)(e),n=(0,a.useCallback)(e=>r(e),[t]),i=(0,a.useCallback)(e=>r(t=>t|e),[t]),s=(0,a.useCallback)(e=>(t&e)===e,[t]);return{flags:t,setFlag:n,addFlag:i,hasFlag:s,removeFlag:(0,a.useCallback)(e=>r(t=>t&~e),[r]),toggleFlag:(0,a.useCallback)(e=>r(t=>t^e),[r])}}(e&&i?3:0),f=(0,a.useRef)(!1),h=(0,a.useRef)(!1),p=(0,o.useDisposables)();return(0,c.useIsoMorphicEffect)(()=>{var i;if(e){if(r&&s(!0),!t){r&&d(3);return}return null==(i=null==n?void 0:n.start)||i.call(n,r),function(e,{prepare:t,run:r,done:n,inFlight:i}){let s=(0,l.disposables)();return function(e,{inFlight:t,prepare:r}){if(null!=t&&t.current)return r();let n=e.style.transition;e.style.transition="none",r(),e.offsetHeight,e.style.transition=n}(e,{prepare:t,inFlight:i}),s.nextFrame(()=>{r(),s.requestAnimationFrame(()=>{s.add(function(e,t){var r,n;let i=(0,l.disposables)();if(!e)return i.dispose;let s=!1;i.add(()=>{s=!0});let a=null!=(n=null==(r=e.getAnimations)?void 0:r.call(e).filter(e=>e instanceof CSSTransition))?n:[];return 0===a.length?t():Promise.allSettled(a.map(e=>e.finished)).then(()=>{s||t()}),i.dispose}(e,n))})}),s.dispose}(t,{inFlight:f,prepare(){h.current?h.current=!1:h.current=f.current,f.current=!0,h.current||(r?(d(3),m(4)):(d(4),m(2)))},run(){h.current?r?(m(3),d(4)):(m(4),d(3)):r?m(1):d(1)},done(){var e;h.current&&"function"==typeof t.getAnimations&&t.getAnimations().length>0||(f.current=!1,m(7),r||s(!1),null==(e=null==n?void 0:n.end)||e.call(n,r))}})}},[e,r,t,p]),e?[i,{closed:u(1),enter:u(2),leave:u(4),transition:u(2)||u(4)}]:[r,{closed:void 0,enter:void 0,leave:void 0,transition:void 0}]}],83733);let d=(0,a.createContext)(null);d.displayName="OpenClosedContext";var m=((r=m||{})[r.Open=1]="Open",r[r.Closed=2]="Closed",r[r.Closing=4]="Closing",r[r.Opening=8]="Opening",r);e.s(["OpenClosedProvider",0,function({value:e,children:t}){return a.default.createElement(d.Provider,{value:e},t)},"ResetOpenClosedProvider",0,function({children:e}){return a.default.createElement(d.Provider,{value:null},e)},"State",0,m,"useOpenClosed",0,function(){return(0,a.useContext)(d)}],233137)},677667,674175,886148,543086,e=>{"use strict";let t,r;var n,i=e.i(290571),s=e.i(783222),a=e.i(433336),l=e.i(271645),o=e.i(394487),c=e.i(914189),u=e.i(144279),d=e.i(294316),m=e.i(83733);let f=(0,l.createContext)(()=>{});function h({value:e,children:t}){return l.default.createElement(f.Provider,{value:e},t)}e.s(["CloseProvider",0,h],674175);var p=e.i(233137),g=e.i(233538),x=e.i(397701),v=e.i(402155),y=e.i(700020);let b=null!=(n=l.default.startTransition)?n:function(e){e()};var _=e.i(998348),j=((t=j||{})[t.Open=0]="Open",t[t.Closed=1]="Closed",t),w=((r=w||{})[r.ToggleDisclosure=0]="ToggleDisclosure",r[r.CloseDisclosure=1]="CloseDisclosure",r[r.SetButtonId=2]="SetButtonId",r[r.SetPanelId=3]="SetPanelId",r[r.SetButtonElement=4]="SetButtonElement",r[r.SetPanelElement=5]="SetPanelElement",r);let k={0:e=>({...e,disclosureState:(0,x.match)(e.disclosureState,{0:1,1:0})}),1:e=>1===e.disclosureState?e:{...e,disclosureState:1},2:(e,t)=>e.buttonId===t.buttonId?e:{...e,buttonId:t.buttonId},3:(e,t)=>e.panelId===t.panelId?e:{...e,panelId:t.panelId},4:(e,t)=>e.buttonElement===t.element?e:{...e,buttonElement:t.element},5:(e,t)=>e.panelElement===t.element?e:{...e,panelElement:t.element}},C=(0,l.createContext)(null);function S(e){let t=(0,l.useContext)(C);if(null===t){let t=Error(`<${e} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(t,S),t}return t}C.displayName="DisclosureContext";let E=(0,l.createContext)(null);E.displayName="DisclosureAPIContext";let O=(0,l.createContext)(null);function N(e,t){return(0,x.match)(t.type,k,e,t)}O.displayName="DisclosurePanelContext";let I=l.Fragment,T=y.RenderFeatures.RenderStrategy|y.RenderFeatures.Static,R=Object.assign((0,y.forwardRefWithAs)(function(e,t){let{defaultOpen:r=!1,...n}=e,i=(0,l.useRef)(null),s=(0,d.useSyncRefs)(t,(0,d.optionalRef)(e=>{i.current=e},void 0===e.as||e.as===l.Fragment)),a=(0,l.useReducer)(N,{disclosureState:+!r,buttonElement:null,panelElement:null,buttonId:null,panelId:null}),[{disclosureState:o,buttonId:u},m]=a,f=(0,c.useEvent)(e=>{m({type:1});let t=(0,v.getOwnerDocument)(i);if(!t||!u)return;let r=e?e instanceof HTMLElement?e:e.current instanceof HTMLElement?e.current:t.getElementById(u):t.getElementById(u);null==r||r.focus()}),g=(0,l.useMemo)(()=>({close:f}),[f]),b=(0,l.useMemo)(()=>({open:0===o,close:f}),[o,f]),_=(0,y.useRender)();return l.default.createElement(C.Provider,{value:a},l.default.createElement(E.Provider,{value:g},l.default.createElement(h,{value:f},l.default.createElement(p.OpenClosedProvider,{value:(0,x.match)(o,{0:p.State.Open,1:p.State.Closed})},_({ourProps:{ref:s},theirProps:n,slot:b,defaultTag:I,name:"Disclosure"})))))}),{Button:(0,y.forwardRefWithAs)(function(e,t){let r=(0,l.useId)(),{id:n=`headlessui-disclosure-button-${r}`,disabled:i=!1,autoFocus:m=!1,...f}=e,[h,p]=S("Disclosure.Button"),x=(0,l.useContext)(O),v=null!==x&&x===h.panelId,b=(0,l.useRef)(null),j=(0,d.useSyncRefs)(b,t,(0,c.useEvent)(e=>{if(!v)return p({type:4,element:e})}));(0,l.useEffect)(()=>{if(!v)return p({type:2,buttonId:n}),()=>{p({type:2,buttonId:null})}},[n,p,v]);let w=(0,c.useEvent)(e=>{var t;if(v){if(1===h.disclosureState)return;switch(e.key){case _.Keys.Space:case _.Keys.Enter:e.preventDefault(),e.stopPropagation(),p({type:0}),null==(t=h.buttonElement)||t.focus()}}else switch(e.key){case _.Keys.Space:case _.Keys.Enter:e.preventDefault(),e.stopPropagation(),p({type:0})}}),k=(0,c.useEvent)(e=>{e.key===_.Keys.Space&&e.preventDefault()}),C=(0,c.useEvent)(e=>{var t;(0,g.isDisabledReactIssue7711)(e.currentTarget)||i||(v?(p({type:0}),null==(t=h.buttonElement)||t.focus()):p({type:0}))}),{isFocusVisible:E,focusProps:N}=(0,s.useFocusRing)({autoFocus:m}),{isHovered:I,hoverProps:T}=(0,a.useHover)({isDisabled:i}),{pressed:R,pressProps:P}=(0,o.useActivePress)({disabled:i}),D=(0,l.useMemo)(()=>({open:0===h.disclosureState,hover:I,active:R,disabled:i,focus:E,autofocus:m}),[h,I,R,E,i,m]),$=(0,u.useResolveButtonType)(e,h.buttonElement),A=v?(0,y.mergeProps)({ref:j,type:$,disabled:i||void 0,autoFocus:m,onKeyDown:w,onClick:C},N,T,P):(0,y.mergeProps)({ref:j,id:n,type:$,"aria-expanded":0===h.disclosureState,"aria-controls":h.panelElement?h.panelId:void 0,disabled:i||void 0,autoFocus:m,onKeyDown:w,onKeyUp:k,onClick:C},N,T,P);return(0,y.useRender)()({ourProps:A,theirProps:f,slot:D,defaultTag:"button",name:"Disclosure.Button"})}),Panel:(0,y.forwardRefWithAs)(function(e,t){let r=(0,l.useId)(),{id:n=`headlessui-disclosure-panel-${r}`,transition:i=!1,...s}=e,[a,o]=S("Disclosure.Panel"),{close:u}=function e(t){let r=(0,l.useContext)(E);if(null===r){let r=Error(`<${t} /> is missing a parent component.`);throw Error.captureStackTrace&&Error.captureStackTrace(r,e),r}return r}("Disclosure.Panel"),[f,h]=(0,l.useState)(null),g=(0,d.useSyncRefs)(t,(0,c.useEvent)(e=>{b(()=>o({type:5,element:e}))}),h);(0,l.useEffect)(()=>(o({type:3,panelId:n}),()=>{o({type:3,panelId:null})}),[n,o]);let x=(0,p.useOpenClosed)(),[v,_]=(0,m.useTransition)(i,f,null!==x?(x&p.State.Open)===p.State.Open:0===a.disclosureState),j=(0,l.useMemo)(()=>({open:0===a.disclosureState,close:u}),[a.disclosureState,u]),w={ref:g,id:n,...(0,m.transitionDataAttributes)(_)},k=(0,y.useRender)();return l.default.createElement(p.ResetOpenClosedProvider,null,l.default.createElement(O.Provider,{value:a.panelId},k({ourProps:w,theirProps:s,slot:j,defaultTag:"div",features:T,visible:v,name:"Disclosure.Panel"})))})});e.s(["Disclosure",0,R],886148);let P=(0,l.createContext)(void 0);var D=e.i(444755);let $=(0,e.i(673706).makeClassName)("Accordion"),A=(0,l.createContext)({isOpen:!1}),F=l.default.forwardRef((e,t)=>{var r;let{defaultOpen:n=!1,children:s,className:a}=e,o=(0,i.__rest)(e,["defaultOpen","children","className"]),c=null!=(r=(0,l.useContext)(P))?r:(0,D.tremorTwMerge)("rounded-tremor-default border");return l.default.createElement(R,Object.assign({as:"div",ref:t,className:(0,D.tremorTwMerge)($("root"),"overflow-hidden","bg-tremor-background border-tremor-border","dark:bg-dark-tremor-background dark:border-dark-tremor-border",c,a),defaultOpen:n},o),({open:e})=>l.default.createElement(A.Provider,{value:{isOpen:e}},s))});F.displayName="Accordion",e.s(["OpenContext",0,A,"default",0,F],543086),e.s(["Accordion",0,F],677667)},130643,e=>{"use strict";var t=e.i(290571),r=e.i(271645),n=e.i(886148),i=e.i(444755);let s=(0,e.i(673706).makeClassName)("AccordionBody"),a=r.default.forwardRef((e,a)=>{let{children:l,className:o}=e,c=(0,t.__rest)(e,["children","className"]);return r.default.createElement(n.Disclosure.Panel,Object.assign({ref:a,className:(0,i.tremorTwMerge)(s("root"),"w-full text-tremor-default px-4 pb-3","text-tremor-content","dark:text-dark-tremor-content",o)},c),l)});a.displayName="AccordionBody",e.s(["AccordionBody",0,a],130643)},898667,e=>{"use strict";var t=e.i(290571),r=e.i(271645),n=e.i(886148);let i=e=>{var n=(0,t.__rest)(e,[]);return r.default.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},n),r.default.createElement("path",{d:"M11.9999 10.8284L7.0502 15.7782L5.63599 14.364L11.9999 8L18.3639 14.364L16.9497 15.7782L11.9999 10.8284Z"}))};var s=e.i(543086),a=e.i(444755);let l=(0,e.i(673706).makeClassName)("AccordionHeader"),o=r.default.forwardRef((e,o)=>{let{children:c,className:u}=e,d=(0,t.__rest)(e,["children","className"]),{isOpen:m}=(0,r.useContext)(s.OpenContext);return r.default.createElement(n.Disclosure.Button,Object.assign({ref:o,className:(0,a.tremorTwMerge)(l("root"),"w-full flex items-center justify-between px-4 py-3","text-tremor-content-emphasis","dark:text-dark-tremor-content-emphasis",u)},d),r.default.createElement("div",{className:(0,a.tremorTwMerge)(l("children"),"flex flex-1 text-inherit mr-4")},c),r.default.createElement("div",null,r.default.createElement(i,{className:(0,a.tremorTwMerge)(l("arrowIcon"),"h-5 w-5 -mr-1","text-tremor-content-subtle","dark:text-dark-tremor-content-subtle",m?"transition-all":"transition-all -rotate-180")})))});o.displayName="AccordionHeader",e.s(["AccordionHeader",0,o],898667)},220508,e=>{"use strict";var t=e.i(271645);let r=t.forwardRef(function(e,r){return t.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:2,stroke:"currentColor","aria-hidden":"true",ref:r},e),t.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"}))});e.s(["CheckCircleIcon",0,r],220508)},503269,214520,601893,694421,140721,942803,35889,722678,e=>{"use strict";var t=e.i(271645),r=e.i(914189);e.s(["useControllable",0,function(e,n,i){let[s,a]=(0,t.useState)(i),l=void 0!==e,o=(0,t.useRef)(l),c=(0,t.useRef)(!1),u=(0,t.useRef)(!1);return!l||o.current||c.current?l||!o.current||u.current||(u.current=!0,o.current=l,console.error("A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen.")):(c.current=!0,o.current=l,console.error("A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen.")),[l?e:s,(0,r.useEvent)(e=>(l||a(e),null==n?void 0:n(e)))]}],503269),e.s(["useDefaultValue",0,function(e){let[r]=(0,t.useState)(e);return r}],214520);let n=(0,t.createContext)(void 0);function i(){return(0,t.useContext)(n)}e.s(["useDisabled",0,i],601893);var s=e.i(174080),a=e.i(746725);function l(e={},t=null,r=[]){for(let[n,i]of Object.entries(e))!function e(t,r,n){if(Array.isArray(n))for(let[i,s]of n.entries())e(t,o(r,i.toString()),s);else n instanceof Date?t.push([r,n.toISOString()]):"boolean"==typeof n?t.push([r,n?"1":"0"]):"string"==typeof n?t.push([r,n]):"number"==typeof n?t.push([r,`${n}`]):null==n?t.push([r,""]):l(n,r,t)}(r,o(t,n),i);return r}function o(e,t){return e?e+"["+t+"]":t}e.s(["attemptSubmit",0,function(e){var t,r;let n=null!=(t=null==e?void 0:e.form)?t:e.closest("form");if(n){for(let t of n.elements)if(t!==e&&("INPUT"===t.tagName&&"submit"===t.type||"BUTTON"===t.tagName&&"submit"===t.type||"INPUT"===t.nodeName&&"image"===t.type))return void t.click();null==(r=n.requestSubmit)||r.call(n)}},"objectToFormEntries",0,l],694421);var c=e.i(700020),u=e.i(2788);let d=(0,t.createContext)(null);function m({children:e}){let r=(0,t.useContext)(d);if(!r)return t.default.createElement(t.default.Fragment,null,e);let{target:n}=r;return n?(0,s.createPortal)(t.default.createElement(t.default.Fragment,null,e),n):null}function f({setForm:e,formId:r}){return(0,t.useEffect)(()=>{if(r){let t=document.getElementById(r);t&&e(t)}},[e,r]),r?null:t.default.createElement(u.Hidden,{features:u.HiddenFeatures.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:t=>{if(!t)return;let r=t.closest("form");r&&e(r)}})}e.s(["FormFields",0,function({data:e,form:r,disabled:n,onReset:i,overrides:s}){let[o,d]=(0,t.useState)(null),h=(0,a.useDisposables)();return(0,t.useEffect)(()=>{if(i&&o)return h.addEventListener(o,"reset",i)},[o,r,i]),t.default.createElement(m,null,t.default.createElement(f,{setForm:d,formId:r}),l(e).map(([e,i])=>t.default.createElement(u.Hidden,{features:u.HiddenFeatures.Hidden,...(0,c.compact)({key:e,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:r,disabled:n,name:e,value:i,...s})})))}],140721);let h=(0,t.createContext)(void 0);function p(){return(0,t.useContext)(h)}e.s(["useProvidedId",0,p],942803);var g=e.i(835696),x=e.i(294316);let v=(0,t.createContext)(null);v.displayName="DescriptionContext";let y=Object.assign((0,c.forwardRefWithAs)(function(e,r){let n=(0,t.useId)(),s=i(),{id:a=`headlessui-description-${n}`,...l}=e,o=function e(){let r=(0,t.useContext)(v);if(null===r){let t=Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(t,e),t}return r}(),u=(0,x.useSyncRefs)(r);(0,g.useIsoMorphicEffect)(()=>o.register(a),[a,o.register]);let d=s||!1,m=(0,t.useMemo)(()=>({...o.slot,disabled:d}),[o.slot,d]),f={ref:u,...o.props,id:a};return(0,c.useRender)()({ourProps:f,theirProps:l,slot:m,defaultTag:"p",name:o.name||"Description"})}),{});e.s(["Description",0,y,"useDescribedBy",0,function(){var e,r;return null!=(r=null==(e=(0,t.useContext)(v))?void 0:e.value)?r:void 0},"useDescriptions",0,function(){let[e,n]=(0,t.useState)([]);return[e.length>0?e.join(" "):void 0,(0,t.useMemo)(()=>function(e){let i=(0,r.useEvent)(e=>(n(t=>[...t,e]),()=>n(t=>{let r=t.slice(),n=r.indexOf(e);return -1!==n&&r.splice(n,1),r}))),s=(0,t.useMemo)(()=>({register:i,slot:e.slot,name:e.name,props:e.props,value:e.value}),[i,e.slot,e.name,e.props,e.value]);return t.default.createElement(v.Provider,{value:s},e.children)},[n])]}],35889);let b=(0,t.createContext)(null);function _(e){var r,n,i;let s=null!=(n=null==(r=(0,t.useContext)(b))?void 0:r.value)?n:void 0;return(null!=(i=null==e?void 0:e.length)?i:0)>0?[s,...e].filter(Boolean).join(" "):s}b.displayName="LabelContext";let j=Object.assign((0,c.forwardRefWithAs)(function(e,n){var s;let a=(0,t.useId)(),l=function e(){let r=(0,t.useContext)(b);if(null===r){let t=Error("You used a