
    i8                     j    d Z ddlZddlZddlmZmZmZmZmZ ddl	m
Z
  G d de
      Z G d d      Zy)	a  
Databricks integration utilities for LiteLLM.

This module provides authentication, telemetry, and security utilities
for the Databricks LLM provider integration.

Authentication priority:
1. OAuth M2M (DATABRICKS_CLIENT_ID + DATABRICKS_CLIENT_SECRET) - Recommended for production
2. PAT (DATABRICKS_API_KEY) - Supported for development
3. Databricks SDK automatic auth - Fallback (uses unified auth)
    N)AnyDictLiteralOptionalTuple)BaseLLMExceptionc                       e Zd Zy)DatabricksExceptionN)__name__
__module____qualname__     u/Users/manta/Documents/Projects/TheRoad-I1/.venv/lib/python3.12/site-packages/litellm/llms/databricks/common_utils.pyr
   r
      s    r   r
   c                      e Zd ZdZ ej
                  dej                        df ej
                  dej                        df ej
                  dej                        df ej
                  dej                        df ej
                  dej                        df ej
                  d	ej                        dfgZed
e	de	fd       Z
edeeef   deeef   fd       Zeddee   defd       Zdee   defdZdedededefdZdee   dee   dee   deeef   fdZ	 ddee   dee   ded   dee   dee   dee   deeef   fdZy)DatabricksBasezk
    Base class for Databricks integration with authentication,
    telemetry, and security utilities.
    z(Bearer\s+)[A-Za-z0-9\-_\.]+z\1[REDACTED]z(Authorization:\s*)[^\s,}]+z (api[_-]?key["\s:=]+)[^\s,}"\']+z&(client[_-]?secret["\s:=]+)[^\s,}"\']+z(dapi[a-zA-Z0-9]{32,})z[REDACTED_PAT]z%(access[_-]?token["\s:=]+)[^\s,}"\']+datareturnc                   	 |yt        |t              r*|}| j                  D ]  \  }}|j                  ||      } |S t        |t              rZi }|j                         D ]C  \  }}|j                         	t        	fddD              rd||<   0| j                  |      ||<   E |S t        |t              r|D cg c]  }| j                  |       c}S |S c c}w )a  
        Redact sensitive information (tokens, secrets) from data before logging.

        Handles strings, dicts, and lists recursively. Keys containing sensitive
        terms (authorization, api_key, token, secret, password, credential) are
        fully redacted.

        Args:
            data: String, dict, or other data structure to redact

        Returns:
            Redacted version of the data safe for logging
        Nc              3   &   K   | ]  }|v  
 y wNr   ).0	sensitive	lower_keys     r   	<genexpr>z7DatabricksBase.redact_sensitive_data.<locals>.<genexpr>M   s"      &	 *&s   )authorizationapi_keyapikeytokensecretpassword
credential
[REDACTED])

isinstancestrSENSITIVE_PATTERNSsubdictitemsloweranyredact_sensitive_datalist)
clsr   resultpatternreplacementredactedkeyvalueitemr   s
            @r   r,   z$DatabricksBase.redact_sensitive_data1   s     <dC F(+(>(>$ [&9 )?MdD!H"jjl
UIIK	 &  %1HSM$'$=$=e$DHSM! +" OdD!@DEC--d3EE Fs   =Cheadersc                     |si S i }h d}|j                         D ]<  \  }}|j                         |v r t        |      dkD  r|dd  d||<   2d||<   8|||<   > |S )aR  
        Create a copy of headers with sensitive values redacted for safe logging.

        Shows first 8 characters of sensitive values for debugging purposes,
        with the rest redacted.

        Args:
            headers: HTTP headers dictionary

        Returns:
            New dictionary with sensitive headers redacted
        >   api-key	x-api-keyx-databricks-tokenr   
   N   z...[REDACTED]r#   )r)   r*   len)r.   r6   r2   sensitive_headersr3   r4   s         r   redact_headers_for_loggingz)DatabricksBase.redact_headers_for_loggingc   sx     I
 "--/JCyy{//u:?',Rayk$?HSM$0HSM % * r   Ncustom_user_agentc                 $   	 ddl m} | rr| j                         } d| v r#| j	                  d      d   j                         }n| }|r7|j                  dd      j                  dd      j                         r| d| S d	| S # t        $ r d}Y w xY w)
a'  
        Build the User-Agent string for Databricks API calls.

        If a custom user agent is provided, the partner name (part before /)
        is extracted and prefixed to the litellm user agent with an underscore.
        The custom version is ignored; LiteLLM's version is always used.

        Args:
            custom_user_agent: Optional custom user agent string (e.g., "mycompany/1.0.0")

        Returns:
            User-Agent string in format:
            - Default: "litellm/{version}"
            - With custom: "{partner}_litellm/{version}"

        Examples:
            - None -> "litellm/1.79.1"
            - "mycompany/1.0.0" -> "mycompany_litellm/1.79.1"
            - "partner_product/2.0.0" -> "partner_product_litellm/1.79.1"
            - "acme" -> "acme_litellm/1.79.1"
        r   )versionz0.0.0/_ -z	_litellm/zlitellm/)litellm._versionrB   	Exceptionstripsplitreplaceisalnum)r@   rB   partner_names      r   _build_user_agentz DatabricksBase._build_user_agent   s    .	0  1 7 7 9 ''066s;A>DDF0  ((b199#rBJJL&y	:: '##)  	G	s   B BBapi_basec                     |)	 ddl m}  |       }|j                  j                   d}|S |S # t        $ r t        dd      w xY w)zx
        Get the Databricks API base URL.

        If not provided, attempts to get it from the Databricks SDK.
        r   )WorkspaceClient/serving-endpoints  z~Either set the DATABRICKS_API_BASE and DATABRICKS_API_KEY environment variables, or install the databricks-sdk Python library.status_codemessage)databricks.sdkrQ   confighostImportErrorr
   )selfrO   rQ   databricks_clients       r   _get_api_basezDatabricksBase._get_api_base   sh     :$3$5!/66;;<<NO   ) #H s	   '. A	client_idclient_secretc                    ddl }|j                  d      }d|v r|j                  dd      }| d}	 |j                  |ddd	||fd
did      }|j                  dk7  r$t        |j                  d|j                         |j                         }	|	d   S # |j                  $ r}t        ddt        |             d}~ww xY w)a  
        Obtain an OAuth M2M access token using client credentials flow.

        This is the recommended authentication method for production integrations
        per Databricks Partner requirements.

        Args:
            api_base: Databricks workspace URL
            client_id: OAuth client ID (Service Principal application ID)
            client_secret: OAuth client secret

        Returns:
            Access token string

        Raises:
            DatabricksException: If token request fails
        r   NrC   rR   rE   z/oidc/v1/tokenclient_credentialszall-apis)
grant_typescopeContent-Typez!application/x-www-form-urlencoded   )r   authr6   timeouti  z OAuth M2M token request failed: rT      access_token)
requestsrstriprK   postRequestExceptionr
   r%   rU   textjson)
r[   rO   r^   r_   rj   workspace_url	token_urlresponsee
token_datas
             r   _get_oauth_m2m_tokenz#DatabricksBase._get_oauth_m2m_token   s    . 	 !,=0)112FKM$o^4		}}"6'  /')LM % 	H  3&%$00:8==/J 
 ]]_
.)) (( 	%:3q6(C 	s   B C&B??Cr   c                    |xs ddi}	 ddl m}m} |j                  d        |       }|xs |j                  j
                   d}| |j                  j                         }i ||}||fS # t        $ r t        dd	      w xY w)
a  
        Get Databricks credentials using the Databricks SDK.

        Also registers LiteLLM as a partner for proper telemetry attribution
        in Databricks system.access.audit table.

        Args:
            api_key: Optional API key (PAT)
            api_base: Optional API base URL
            headers: Optional existing headers

        Returns:
            Tuple of (api_base, headers)
        rd   application/jsonr   )rQ   	useragentlitellmrR   rS   a  If the Databricks base URL and API key are not set, the databricks-sdk Python library must be installed. Please install the databricks-sdk, set {LLM_PROVIDER}_API_BASE and {LLM_PROVIDER}_API_KEY environment variables, or provide the base URL and API key as arguments.rT   )	rW   rQ   rx   with_partnerrX   rY   authenticaterZ   r
   )r[   r   rO   r6   rQ   rx   r\   databricks_auth_headerss           r   _get_databricks_credentialsz*DatabricksBase._get_databricks_credentials  s    " An.@A	A ""9- / 1W&7&>&>&C&C%DDV#WH &,,99; ( A4@@W$$ 		%H 		s   A"A- -Bendpoint_type)chat_completions
embeddingscustom_endpointc                 F   ddl m} t        j                  d      }t        j                  d      }	|t        j                  d      }|r<|	r:|r8|j	                  d       | j                  |||	      }
|xs i }d|
 |d<   d	|d
<   n=|;|s9|du rt        dd      |j	                  d       | j                  |||      \  }}|&|rt        dd      | j                  |||      \  }}|dj                  |      d	d}n$|"|j                  ddj                  |      i       |d| |d<   | j                  |      |d<   |j	                  d| j                  |              |dk(  r|durdj                  |      }||fS |dk(  r|durdj                  |      }||fS )a!  
        Validate and configure the Databricks environment.

        Authentication priority:
        1. OAuth M2M (DATABRICKS_CLIENT_ID + DATABRICKS_CLIENT_SECRET) - Recommended
        2. PAT (DATABRICKS_API_KEY) - Supported for development
        3. Databricks SDK automatic auth - Fallback (uses unified auth)

        Args:
            api_key: Personal access token (PAT)
            api_base: Databricks workspace URL with /serving-endpoints
            endpoint_type: Type of endpoint (chat_completions or embeddings)
            custom_endpoint: Whether using a custom endpoint URL
            headers: Existing headers dict
            custom_user_agent: Optional custom user agent to prefix

        Returns:
            Tuple of (api_base, headers) with authentication configured
        r   )verbose_loggerDATABRICKS_CLIENT_IDDATABRICKS_CLIENT_SECRETDATABRICKS_API_BASEz-Using OAuth M2M authentication for DatabrickszBearer Authorizationrw   rd   TrS   zMissing API Key - A call is being made to LLM Provider but no key is set either in the environment variables ({LLM_PROVIDER}_API_KEY) or via paramsrT   z'Using Databricks SDK for authentication)rO   r   r6   zMissing API Base - A call is being made to LLM Provider but no api base is set either in the environment variables ({LLM_PROVIDER}_API_KEY) or via paramsz	Bearer {})r   rd   z
User-AgentzDatabricks request headers: r   z{}/chat/completionsr   z{}/embeddings)litellm._loggingr   osgetenvdebugru   r
   r}   formatupdaterN   r?   )r[   r   rO   r~   r   r6   r@   r   r^   r_   ri   s              r   databricks_validate_environmentz.DatabricksBase.databricks_validate_environment5  s   8 	4 II45			"<= yy!67H8  !PQ44Xy-XLmG)0'?GO$&8GN#_W$&) # r  $$%NO$($D$D%w %E %!' ) # x 
 %)$D$D%w %E %!' ?!,!3!3G!< 2G
 "1C1CG1LMN)0	':GO$ !% 6 67H I 	*4+J+J7+S*TU	
 ..?$3N,33H=H    l*d/J&--h7H  r   r   )r   r   r   __doc__recompile
IGNORECASEr&   classmethodr   r,   r   r%   r?   staticmethodr   rN   r]   ru   r(   r   r}   r   boolr   r   r   r   r   r      s0    
3R]]	C_U	2BMM	BOTBJJ:BMMJ	

 BJJ@"--P	
 
-r}}	=?PQBJJ?O	
$ / / / /b !c3h !DcN ! !F ,$Xc] ,$c ,$ ,$\hsm  .8*8* 8* 	8*
 
8*t,},08,HPQU,	sDy	,j ,0^!#^! 3-^! ?@	^!
 "$^! $^! $C=^! 
sDy	^!r   r   )r   r   r   typingr   r   r   r   r   )litellm.llms.base_llm.chat.transformationr   r
   r   r   r   r   <module>r      s4   
 
 	 6 6 F	* 	{! {!r   