o
    ưi6                  
   @   s  d Z ddlZddlZddlmZmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZmZmZ ddlmZ dd	lmZ d
ZdZdZe
 ZG dd deZdee fddZdefddZdefddZdefddZ			d&dee dee dee defddZ			d&dee dee dee defddZ dedededeee!f fdd Z"dedededeee!f fd!d"Z#d#ej$deee!f fd$d%Z%dS )'z
GigaChat OAuth Authenticator

Handles OAuth 2.0 token management for GigaChat API.
Based on official GigaChat SDK authentication flow.
    N)OptionalTuple)verbose_logger)InMemoryCache)BaseLLMException)HTTPHandler_get_httpx_clientget_async_httpx_clientget_secret_str)LlmProvidersz1https://ngw.devices.sberbank.ru:9443/api/v2/oauthZGIGACHAT_API_PERSi`  c                   @   s   e Zd ZdZdS )GigaChatAuthErrorzGigaChat authentication error.N)__name__
__module____qualname____doc__ r   r   Z/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/gigachat/authenticator.pyr   &   s    r   returnc                   C   s   t dpt dS )z*Get GigaChat credentials from environment.ZGIGACHAT_CREDENTIALSZGIGACHAT_API_KEYr
   r   r   r   r   _get_credentials,   s   r   c                   C      t dptS )z6Get GigaChat auth URL from environment or use default.GIGACHAT_AUTH_URL)r   r   r   r   r   r   _get_auth_url1      r   c                   C   r   )z3Get GigaChat scope from environment or use default.GIGACHAT_SCOPE)r   r   r   r   r   r   
_get_scope6   r   r   c                   C   s   t ddidS )z7Get cached httpx client with SSL verification disabled.
ssl_verifyF)params)r   r   r   r   r   _get_http_client;   s   r   credentialsscopeauth_urlc                 C   s   | pt  } | stddd|pt }|pt }d| dd  }t|}|r<|\}}t d |t k r<t	d |S t
| ||\}}td	|t t d  d }|d	kratj|||f|d
 |S )ae  
    Get valid access token, using cache if available.

    Args:
        credentials: Base64-encoded credentials (client_id:client_secret)
        scope: API scope (GIGACHAT_API_PERS, GIGACHAT_API_CORP, etc.)
        auth_url: OAuth endpoint URL

    Returns:
        Access token string

    Raises:
        GigaChatAuthError: If authentication fails
      eGigaChat credentials not provided. Set GIGACHAT_CREDENTIALS or GIGACHAT_API_KEY environment variable.status_codemessagegigachat_token:N     "Using cached GigaChat access tokenr   ttl)r   r   r   r   _token_cache	get_cachetimeTOKEN_EXPIRY_BUFFER_MSr   debug_request_token_syncmax	set_cacher   r    r!   	cache_keycachedtoken
expires_atZttl_secondsr   r   r   get_access_token@   s(   




r:   c                    s   | pt  } | stddd|pt }|pt }d| dd  }t|}|r=|\}}t d |t k r=t	d |S t
| ||I dH \}}td	|t t d  d }|d	kretj|||f|d
 |S )z"Async version of get_access_token.r"   r#   r$   r'   Nr(   r)   r*   r   r+   )r   r   r   r   r-   r.   r/   r0   r   r1   _request_token_asyncr3   r4   r5   r   r   r   get_access_token_asyncr   s*   




r<   c              
   C   s   d|  t t dd}d|i}td|  zt }|j|||dd}|  t|W S  t	j
yH } zt|jjd|jj d	d
}~w t	jy_ } ztddt | d	d
}~ww )z
    Request new access token from GigaChat OAuth endpoint (sync).

    Returns:
        Tuple of (access_token, expires_at_ms)
    Basic !application/x-www-form-urlencodedAuthorizationZRqUIDzContent-Typer    &Requesting GigaChat access token from    headersdatatimeout GigaChat authentication failed: r$   N  (GigaChat authentication request failed: )struuiduuid4r   r1   r   postraise_for_status_parse_token_responsehttpxHTTPStatusErrorr   responser%   textRequestErrorr   r    r!   rD   rE   clientrR   er   r   r   r2      s0   

r2   c              
      s   d|  t t dd}d|i}td|  zttjddid}|j|||d	d
I dH }|	  t
|W S  tjyR } zt|jjd|jj dd}~w tjyi } ztddt | dd}~ww )z%Async version of _request_token_sync.r=   r>   r?   r    rA   r   F)Zllm_providerr   rB   rC   NrG   r$   rH   rI   )rJ   rK   rL   r   r1   r	   r   ZGIGACHATrM   rN   rO   rP   rQ   r   rR   r%   rS   rT   rU   r   r   r   r;      s8   

r;   rR   c                 C   sj   |   }|dp|d}|dp|d}|s#tdd| dt|tr,t|}td ||fS )	zParse OAuth token response.tokaccess_tokenexpr9   rH   zInvalid token response: r$   z+GigaChat access token obtained successfully)jsongetr   
isinstancerJ   intr   r1   )rR   rE   rY   r9   r   r   r   rO      s   

rO   )NNN)&r   r/   rK   typingr   r   rP   Zlitellm._loggingr   Zlitellm.caching.cachingr   Z)litellm.llms.base_llm.chat.transformationr   Z&litellm.llms.custom_httpx.http_handlerr   r   r	   Zlitellm.secret_managers.mainr   Zlitellm.types.utilsr   r   r   r0   r-   r   rJ   r   r   r   r   r:   r<   r^   r2   r;   ResponserO   r   r   r   r   <module>   s~    
3
$

%

 #