o
    ưiu                  	   @   s   d dl Z d dlZd dlmZmZmZmZmZ d dlZd dl	Z	d dl
mZ d dlmZmZ d dlmZ d dlmZ d dlmZ d dlmZ G d	d
 d
eZG dd deZ	 ddeeef dedeeef fddZdee fddZG dd deZdS )    N)AnyDictListOptionalUnion)DEFAULT_MAX_RECURSE_DEPTH)BaseLLMModelInfoBaseTokenCounter)BaseLLMExceptionget_secret_str)AllMessageValues)TokenCountResponsec                   @   s   e Zd ZdS )GeminiErrorN)__name__
__module____qualname__ r   r   W/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/gemini/common_utils.pyr      s    r   c                   @   s2  e Zd Z		ddededee dededee dee d	efd
dZe	d	efddZ
ed dee d	ee fddZed dee d	ee fddZeded	ee fddZdeeeef  d	ee fddZ	ddee dee d	ee fddZdededeeejf d	efddZd	ee fddZdS )!GeminiModelInfoNheadersmodelmessagesoptional_paramslitellm_paramsapi_keyapi_basereturnc                 C   s   |S )z.Google AI Studio sends api key in query paramsr   )selfr   r   r   r   r   r   r   r   r   r   validate_environment   s   z$GeminiModelInfo.validate_environmentc                 C   s   dS )NZv1betar   r   r   r   r   api_version"   s   zGeminiModelInfo.api_versionc                 C   s   | pt dpdS )NZGEMINI_API_BASEz)https://generativelanguage.googleapis.comr   )r   r   r   r   get_api_base&   s
   zGeminiModelInfo.get_api_basec                 C   s   | p	t dp	t dS NZGOOGLE_API_KEYZGEMINI_API_KEYr   )r   r   r   r   get_api_key.   s   zGeminiModelInfo.get_api_keyc                 C   s   |  ddS )Ngemini/ )replace)r   r   r   r   get_base_model2   s   zGeminiModelInfo.get_base_modelmodelsc                 C   s4   g }|D ]}|d  dd}d| }|| q|S )Nnamezmodels/r&   r%   )r'   append)r   r)   litellm_model_namesr   Zstripped_model_nameZlitellm_model_namer   r   r   process_model_name6   s   z"GeminiModelInfo.process_model_namec                 C   s   t |}t |}d| j d}|d u s|d u rtdtjj| | d| d}|jdkr=td|j d|	  |	 d	 }| 
|}|S )
N/z/modelszGEMINI_API_BASE or GEMINI_API_KEY/GOOGLE_API_KEY is not set. Please set the environment variable, to query Gemini's `/models` endpoint.z?key=)url   z1Failed to fetch models from Gemini. Status code: z, Response: r)   )r   r"   r$   r!   
ValueErrorlitellmZmodule_level_clientgetstatus_codejsonr-   )r   r   r   Zendpointresponser)   r,   r   r   r   
get_models>   s"   



zGeminiModelInfo.get_modelserror_messager4   c                 C   s   t |||dS )N)r4   messager   )r   )r   r8   r4   r   r   r   r   get_error_classW   s   zGeminiModelInfo.get_error_classc                 C   s   t  S )z
        Factory method to create a token counter for this provider.
        
        Returns:
            Optional TokenCounterInterface implementation for this provider,
            or None if token counting is not supported.
        GoogleAIStudioTokenCounterr    r   r   r   get_token_counter^   s   z!GeminiModelInfo.get_token_counter)NNN)r   r   r   dictstrr   r   r   r   propertyr!   staticmethodr"   r$   r(   r   r-   r7   intr   httpxZHeadersr
   r:   r	   r=   r   r   r   r   r      s^    	
"	

r   datadepthr   c                    s    t kr| S i }t| ts| S |  D ]j\}}t|tr't|d||< qt|tjr4|	 ||< qt|trCt
| d ||< qt|trytdd |D rZdd |D ||< tdd |D rmdd |D ||< q fd	d|D ||< q|||< q|S )
a  Converts unserializable types in dict to json.dumps() compatible types.

    This function is called in models.py after calling convert_to_dict(). The
    convert_to_dict() can convert pydantic object to dict. However, the input to
    convert_to_dict() is dict mixed of pydantic object and nested dict(the output
    of converters). So they may be bytes in the dict and they are out of
    `ser_json_bytes` control in model_dump(mode='json') called in
    `convert_to_dict`, as well as datetime deserialization in Pydantic json mode.

    Returns:
      A dictionary with json.dumps() incompatible type (e.g. bytes datetime)
      to compatible type (e.g. base64 encoded string, isoformat date string).
    ascii   c                 s   s    | ]}t |tV  qd S r>   )
isinstancebytes.0vr   r   r   	<genexpr>   s    z.encode_unserializable_types.<locals>.<genexpr>c                 S   s   g | ]
}t |d qS )rG   )base64urlsafe_b64encodedecoderK   r   r   r   
<listcomp>   s    z/encode_unserializable_types.<locals>.<listcomp>c                 s   s    | ]	}t |tjV  qd S r>   )rI   datetimerK   r   r   r   rN      s    c                 S   s   g | ]}|  qS r   )	isoformatrK   r   r   r   rR      s    c                    s   g | ]	}t | d  qS )rH   )encode_unserializable_typesrK   rF   r   r   rR      s    )r   rI   r?   itemsrJ   rO   rP   rQ   rS   rT   rU   listall)rE   rF   Zprocessed_datakeyvaluer   rV   r   rU   i   s0   






rU   c                   C   s   t dpt dS r#   r   r   r   r   r   get_api_key_from_env   s   r\   c                   @   s   e Zd ZdZ	ddee defddZ				dded	eee	ee
f   d
eee	ee
f   dee	ee
f  dedeee	ee
f   dee
 dee fddZdS )r<   z;Token counter implementation for Google AI Studio provider.Ncustom_llm_providerr   c                 C   s   ddl m} ||jjkS )Nr   )LlmProviders)litellm.types.utilsr^   ZGEMINIr[   )r   r]   r^   r   r   r   should_use_token_counting_api   s   z8GoogleAIStudioTokenCounter.should_use_token_counting_apir&   model_to_user   contents
deploymentrequest_modeltoolssystemc                    s   dd l }ddlm}	 |pi }||di }
||d}|
| |	 jd	i |
I d H }|d urCt|dd|||dd|dS d S )
Nr   r;   r   )r   rb   ZtotalTokensZtokenizer_usedr&   )Ztotal_tokensrd   Z
model_usedZtokenizer_typeoriginal_responser   )copyZ(litellm.llms.gemini.count_tokens.handlerr<   deepcopyr3   updateZacount_tokensr   )r   ra   r   rb   rc   rd   re   rf   rh   r<   Zcount_tokens_params_requestZcount_tokens_paramsresultr   r   r   count_tokens   s*   




z'GoogleAIStudioTokenCounter.count_tokensr>   )Nr&   NN)r   r   r   __doc__r   r@   boolr`   r   r   r   r   rl   r   r   r   r   r<      s:    
	r<   )r   )rO   rS   typingr   r   r   r   r   rD   r2   Zlitellm.constantsr   Z litellm.llms.base_llm.base_utilsr   r	   Z)litellm.llms.base_llm.chat.transformationr
   Zlitellm.secret_managers.mainr   Zlitellm.types.llms.openair   r_   r   r   r   r@   objectrC   rU   r\   r<   r   r   r   r   <module>   s.    V


,