o
    ưi#1                     @   s*  U d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
Z
ddlmZ daee ed< G dd dZd	ed
efddZd
efddZd
efddZded
efddZdee ded
ee fddZdeded
efddZdeded
ee fddZdeded
efddZded
ee fd d!ZdS )"aR  
Centralized manager for Anthropic beta headers across different providers.

This module provides utilities to:
1. Load beta header configuration from JSON (mapping of supported headers per provider)
2. Filter and map beta headers based on provider support
3. Handle provider-specific header name mappings (e.g., advanced-tool-use -> tool-search-tool)
4. Support remote fetching and caching similar to model cost map

Design:
- JSON config contains mapping of beta headers for each provider
- Keys are input header names, values are provider-specific header names (or null if unsupported)
- Only headers present in mapping keys with non-null values can be forwarded
- This enforces stricter validation than the previous unsupported list approach

Configuration can be loaded from:
- Remote URL (default): Fetches from GitHub repository
- Local file: Set LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS=True to use bundled config only

Environment Variables:
- LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS: Set to "True" to disable remote fetching
- LITELLM_ANTHROPIC_BETA_HEADERS_URL: Custom URL for remote config (optional)
    N)files)DictListOptionalSet)verbose_logger_BETA_HEADERS_CONFIGc                   @   sj   e Zd ZdZedefddZededefddZ	e
dedefdd	ZeddededefddZdS )GetAnthropicBetaHeadersConfigz
    Handles fetching, validating, and loading the Anthropic beta headers configuration.
    
    Similar to GetModelCostMap, this class manages the lifecycle of the beta headers
    configuration with support for remote fetching and local fallback.
    returnc               
   C   sj   zt tddjdd} | W S  ty4 } ztd|  i i i i i i dW  Y d}~S d}~ww )zCLoad the local backup beta headers config bundled with the package.litellmz"anthropic_beta_headers_config.jsonzutf-8)encodingz*Failed to load local beta headers config: )	anthropicazure_aibedrockbedrock_converse	vertex_aiprovider_aliasesN)jsonloadsr   joinpath	read_text	Exceptionr   error)contente r   ]/home/app/Keep/.python/lib/python3.10/site-packages/litellm/anthropic_beta_headers_manager.pyload_local_beta_headers_config.   s&   z<GetAnthropicBetaHeadersConfig.load_local_beta_headers_configfetched_configc                    sn   t  tstdt j dS t dkrtd dS g d}t fdd|D }|s5td dS d	S )
zDCheck if fetched config is a non-empty dict with expected structure.z[LiteLLM: Fetched beta headers config is not a dict (type=%s). Falling back to local backup.Fr   zLLiteLLM: Fetched beta headers config is empty. Falling back to local backup.)r   r   r   r   r   c                 3   s    | ]}| v V  qd S Nr   ).0keyr   r   r   	<genexpr>X   s    zEGetAnthropicBetaHeadersConfig._check_is_valid_dict.<locals>.<genexpr>zYLiteLLM: Fetched beta headers config missing provider keys. Falling back to local backup.T)
isinstancedictr   warningtype__name__lenany)r   Zprovider_keysZhas_providerr   r"   r   _check_is_valid_dictD   s&   
z2GetAnthropicBetaHeadersConfig._check_is_valid_dictc                 C   s
   |  |S )z
        Validate the integrity of a fetched beta headers config.
        
        Returns True if all checks pass, False otherwise.
        )r+   )clsr   r   r   r   validate_beta_headers_configc   s   
z:GetAnthropicBetaHeadersConfig.validate_beta_headers_config   urltimeoutc                 C   s   t j| |d}|  | S )z
        Fetch the beta headers config from a remote URL.
        
        Returns the parsed JSON dict. Raises on network/parse errors
        (caller is expected to handle).
        )r0   )httpxgetraise_for_statusr   )r/   r0   responser   r   r    fetch_remote_beta_headers_configl   s   z>GetAnthropicBetaHeadersConfig.fetch_remote_beta_headers_configN)r.   )r(   
__module____qualname____doc__staticmethodr   r   r%   boolr+   classmethodr-   strintr5   r   r   r   r   r	   &   s    r	   r/   r
   c              
   C   s   t dd dkrt S zt| }W n ty4 } ztd| t	| t W  Y d}~S d}~ww tj
|dsEtd|  t S |S )u  
    Public entry point — returns the beta headers config dict.
    
    1. If ``LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS`` is set, uses the local backup only.
    2. Otherwise fetches from ``url``, validates integrity, and falls back
       to the local backup on any failure.
    
    Args:
        url: URL to fetch the remote beta headers configuration from
        
    Returns:
        Dict containing the beta headers configuration
    Z$LITELLM_LOCAL_ANTHROPIC_BETA_HEADERS truez^LiteLLM: Failed to fetch remote beta headers config from %s: %s. Falling back to local backup.Nr"   z_LiteLLM: Fetched beta headers config failed integrity check. Using local backup instead. url=%s)osgetenvlowerr	   r   r5   r   r   r&   r<   r-   )r/   r   r   r   r   r   get_beta_headers_configy   s(   
rC   c                  C   s0   t durt S ddlm}  t| da td t S )a	  
    Load the beta headers configuration.
    Uses caching to avoid repeated fetches/file reads.
    
    This function is called by all public API functions and manages the global cache.
    
    Returns:
        Dict containing the beta headers configuration
    Nr   anthropic_beta_headers_url)r/   z%Loaded and cached beta headers config)r   r   rE   rC   r   debugrD   r   r   r   _load_beta_headers_config   s   

rG   c                   C   s   da td t S )z
    Force reload the beta headers configuration from source (remote or local).
    Clears the cache and fetches fresh configuration.
    
    Returns:
        Dict containing the newly loaded beta headers configuration
    Nz-Reloading beta headers config (cache cleared))r   r   inforG   r   r   r   r   reload_beta_headers_config   s   	
rI   providerc                 C   s   t  }|di }|| | S )z
    Resolve provider aliases to canonical provider names.
    
    Args:
        provider: Provider name (may be an alias)
        
    Returns:
        Canonical provider name
    r   )rG   r2   )rJ   configaliasesr   r   r   get_provider_name   s   
rM   beta_headersc                 C   s   | sg S t  }t|}||i }t }| D ]1}| }||vr-td| d| d q|| }|du rBtd| d| d q|| qtt	|S )aC  
    Filter and transform beta headers based on provider's mapping configuration.
    
    This function:
    1. Only allows headers that are present in the provider's mapping keys
    2. Filters out headers with null values (unsupported)
    3. Maps headers to provider-specific names (e.g., advanced-tool-use -> tool-search-tool)
    
    Args:
        beta_headers: List of Anthropic beta header values
        provider: Provider name (e.g., "anthropic", "bedrock", "vertex_ai")
        
    Returns:
        List of filtered and transformed beta headers for the provider
    zDropping unknown beta header 'z' for provider 'z' (not in mapping)Nz"Dropping unsupported beta header '')
rG   rM   r2   setstripr   rF   addsortedlist)rN   rJ   rK   provider_mappingZfiltered_headersheaderZmapped_headerr   r   r   !filter_and_transform_beta_headers   s*   rW   beta_headerc                 C   s.   t  }t|}||i }| |v o||  duS )a  
    Check if a specific beta header is supported by a provider.
    
    Args:
        beta_header: The Anthropic beta header value
        provider: Provider name
        
    Returns:
        True if the header is in the mapping with a non-null value, False otherwise
    NrG   rM   r2   )rX   rJ   rK   rU   r   r   r   is_beta_header_supported  s   rZ   anthropic_beta_headerc                 C   s.   t  }t|}||i }| |vrdS ||  S )a  
    Get the provider-specific beta header name for a given Anthropic beta header.
    
    This function handles header transformations/mappings (e.g., advanced-tool-use -> tool-search-tool).
    
    Args:
        anthropic_beta_header: The Anthropic beta header value
        provider: Provider name
        
    Returns:
        The provider-specific header name if supported, or None if unsupported/unknown
    NrY   )r[   rJ   rK   rU   r   r   r   get_provider_beta_header&  s   r\   headersc                 C   sX   |  d}|s	| S dd |dD }t||d}|r$d|| d< | S | dd | S )a4  
    Update headers dict by filtering and transforming anthropic-beta header values.
    Modifies the headers dict in place and returns it.
    
    Args:
        headers: Request headers dict (will be modified in place)
        provider: Provider name
        
    Returns:
        Updated headers dict
    zanthropic-betac                 S   s   g | ]
}|  r|  qS r   )rQ   )r    br   r   r   
<listcomp>X      z5update_headers_with_filtered_beta.<locals>.<listcomp>,)rN   rJ   N)r2   splitrW   joinpop)r]   rJ   Zexisting_betaZbeta_valuesZfiltered_beta_valuesr   r   r   !update_headers_with_filtered_betaD  s   
re   c                 C   s,   t  }t| } || i }dd | D S )z
    Get all beta headers that are unsupported by a provider (have null values in mapping).
    
    Args:
        provider: Provider name
        
    Returns:
        List of unsupported Anthropic beta header names
    c                 S   s   g | ]
\}}|d u r|qS r   r   )r    rV   valuer   r   r   r_   y  r`   z+get_unsupported_headers.<locals>.<listcomp>)rG   rM   r2   items)rJ   rK   rU   r   r   r   get_unsupported_headersj  s   
rh   )r8   r   r@   importlib.resourcesr   typingr   r   r   r   r1   Z*litellm.litellm_core_utils.litellm_loggingr   r   __annotations__r	   r<   r%   rC   rG   rI   rM   rW   r:   rZ   r\   re   rh   r   r   r   r   <module>   sT    S*
8


&