Ë
    uPêj$8  ã                   ór   — d Z ddlZddlZddlmZmZmZ ddl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ÚFinalÚLiteral)ÚurlsplitÚ
urlunsplit)ÚBaseLLMExceptionc                   ó   — e Zd Zy)ÚDatabricksExceptionN)Ú__name__Ú
__module__Ú__qualname__© ó    úi/home/oem/CyberBrain26-unified/.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dz  defd„«       Zdedz  defd„Zdedededefd„Zdedz  dedz  dedz  deeef   fd„Z	 ddedz  dedz  ded   dedz  dedz  dedz  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>N   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_data2   sî   ø€ ð ˆ<Øä�dœCÔ ØˆFØ(+×(>Ñ(>ò :Ñ$�˜Ø Ÿ™ [°&Ó9‘ð:àˆMä�dœDÔ!Ø ˆHØ"Ÿj™j›lò E‘
��UØŸI™I›K�	Üó ð&ôô ð %1�H˜S’Mà$'×$=Ñ$=¸eÓ$D�H˜S’Mð!Eð" ˆOä�dœDÔ!Ø@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_loggingd   s}   € ñ ØˆIàˆò$
Ðð "Ÿ-™-›/ò 	&‰JˆC�Ø�y‰y‹{Ð/Ñ/Ü�u“: ’?Ø',¨R¨a y k°Ð$?�H˜S’Mà$0�H˜S’Mà %�˜’ð	&ð ˆ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Ñ6°sÓ;¸AÑ>×DÑDÓF‘à0�ñ  × 4Ñ 4°S¸"Ó =× EÑ EÀcÈ2Ó N× VÑ VÔ XØ&˜ 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   € ð ÐðÝ:á+:Ó+<Ð!Ø/×6Ñ6×;Ñ;Ð<Ð<NÐO�Ø�ð ˆøô ò Ü)Ø #ðHôð ðús	   „'. ®AÚ	client_idÚclient_secretc                 óŒ  — ddl }t        |«      }t        |j                  |j                  dddf«      }|› 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|	› �¬«      ‚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   NrE   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)Úrequestsr   r   ÚschemeÚnetlocÚpostÚRequestExceptionr
   rU   ÚtextÚjson)r[   rO   r^   r_   rj   Úapi_base_partsÚworkspace_urlÚ	token_urlÚresponseÚeÚ
token_datas              r   Ú_get_oauth_m2m_tokenz#DatabricksBase._get_oauth_m2m_tokenË   sû   € ó. 	ä (¨Ó 2ˆÜ)¨>×+@Ñ+@À.×BWÑBWÐY[Ð]_ÐacÐ*dÓeˆØ+˜_¨NÐ;ˆ	ð	Ø&Ÿm™mØà"6Ø'ñð   Ð/Ø'Ð)LÐMØð ,ó 	ˆHð  ×Ñ 3Ò&Ü%Ø$×0Ñ0Ø:¸8¿=¹=¸/ÐJôð ð
 %ŸM™M›Oˆ
Ø˜.Ñ)Ð)øð ×(Ñ(ò 	Ü%ØØ:¸1¸#Ð>ôð ûð	ú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   rz   Úwith_partnerrX   rY   ÚauthenticaterZ   r
   )r[   r   rO   r6   rQ   rz   r\   Údatabricks_auth_headerss           r   Ú_get_databricks_credentialsz*DatabricksBase._get_databricks_credentials  s¯   € ð" ÒA˜nÐ.@ÐAˆð	ßAð ×"Ñ" 9Ô-á'6Ó'8ÐàÒWÐ&7×&>Ñ&>×&CÑ&CÐ%DÐDVÐ#WˆHàˆØAR×AYÑAY×AfÑAfÓAhÐ'Ø@Ð4Ð@¸Ð@�à˜WÐ$Ð$øÜò 		Ü%ØðHôð ð		ús   ŠA"A- Á-BÚendpoint_type)Úchat_completionsÚ
embeddingsÚcustom_endpointc                 óâ  — 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|› �d	dœ}n|�|j                  dd|› �i«       |�d|› �|d<   | j                  |«      |d<   |j	                  d| j                  |«      «       |dk(  r|dur	|› d�}||fS |dk(  r	|dur|› d�}||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 ÚAuthorizationry   rd   TrS   z“Missing 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   z™Missing 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 params)r‰   rd   z
User-AgentzDatabricks request headers: %sr�   z/chat/completionsr‚   z/embeddings)Úlitellm._loggingr…   ÚosÚgetenvÚdebugrw   r
   r   ÚupdaterN   r?   )r[   r   rO   r€   rƒ   r6   r@   r…   r^   r_   ri   s              r   Údatabricks_validate_environmentz.DatabricksBase.databricks_validate_environment.  s  € õ8 	4ô Ÿ9™9Ð%;Ó<ˆ	Ü!Ÿy™yÐ)CÓDˆð ÐÜ—y‘yÐ!6Ó7ˆHá™©8à× Ñ Ð!PÔQØ"&×";Ñ";¸HÀiÐQ^Ó"_ˆLØ’m ˆGØ)0°°Ð'?ˆG�OÑ$Ø&8ˆG�NÒ#Øˆ_¡WØ $Ñ&Ü)Ø #ð rôð ð ×$Ñ$Ð%NÔOØ$(×$DÑ$DØ%¨wÀð %Eó %Ñ!�˜'ð ÐÙÜ)Ø #ð xôð ð
 %)×$DÑ$DØ%¨wÀð %Eó %Ñ!�˜'ð ˆ?à#*¨7¨)Ð!4Ø 2ñ‰Gð
 Ð"Ø—‘ °7¸7¸)Ð1DÐEÔFàÐØ)0°°	Ð':ˆG�OÑ$ð !%× 6Ñ 6Ð7HÓ Iˆ�Ñð 	×ÑÐ=¸t×?^Ñ?^Ð_fÓ?gÔhàÐ.Ò.°?È$Ñ3NØ"˜Ð#4Ð5ˆHð ˜Ð Ð ð ˜lÒ*¨ÀdÑ/JØ"˜ ;Ð/ˆHà˜Ð Ð r   r   )r   r   r   Ú__doc__ÚreÚcompileÚ
IGNORECASEr&   Úclassmethodr   r,   r(   r%   r?   ÚstaticmethodrN   r]   rw   Útupler   r   Úboolr�   r   r   r   r   r      s/  „ ñð 
ˆ�‰Ð3°R·]±]Ó	CÀ_ÐUØ	ˆ�‰Ð2°B·M±MÓ	BÀOÐTàˆB�J‰JÐ:¸B¿M¹MÓJØð	
ð
 ˆB�J‰JÐ@À"Ç-Á-ÓPØð	
ð 
ˆ�‰Ð-¨r¯}©}Ó	=Ð?PÐQàˆB�J‰JÐ?ÀÇÁÓOØð	
ðÐð$ ð/¨ð /°ò /ó ð/ðb ð!°°c¸3°h±ð !ÀDÈÈcÈÁNò !ó ð!ðF ñ)$¨S°4©Zð )$À3ò )$ó ð)$ðV c¨D¡jð °Só ð.5*àð5*ð ð5*ð ð	5*ð
 
ó5*ðn*Ø˜T‘zð*Ø-0°4©Zð*ØBFÈÁ+ð*à	ˆs�DˆyÑ	ó*ðf )-ñ\!à�t‘ð\!ð ˜‘*ð\!ð Ð?Ñ@ð	\!ð
  ™ð\!ð ˜‘ð\!ð  ™:ð\!ð 
ˆs�DˆyÑ	ô\!r   r   )r�   r‹   r‘   Útypingr   r   r   Úurllib.parser   r   Ú)litellm.llms.base_llm.chat.transformationr   r
   r   r   r   r   ú<module>r›      s7   ðñ
ó 
Û 	ß &Ñ &ß -å Fô	Ð*ô 	÷q!ò q!r   