o
    ưi                     @   sp   d dl mZ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 er-d dlmZ neZG dd dZdS )    )TYPE_CHECKINGAnyDictOptionalTupleUnionN)get_async_httpx_client)LlmProviders)#GenerateContentContentListUnionDictc                   @   s   e Zd ZdedefddZddedee defdd	Z				
	ddee dee deeeef  dedeeeef  de	eeef ef fddZ
			ddededee dee deeeejf  deeef fddZdS )GoogleAIStudioTokenCountercontentsreturnc           
      C   sz   ddl }ddlm} |s|S ||}|D ]%}|d }|D ]}d|v r9|d }|di |}	d|	_|	jdd|d< qq|S )	a{  
        Clean up contents to remove unsupported fields for the Gemini API.

        The Google Gemini API doesn't recognize the 'id' field in function responses,
        so we need to remove it to prevent 400 Bad Request errors.

        Args:
            contents: The contents to clean up

        Returns:
            Cleaned contents with unsupported fields removed
        r   N)FunctionResponsepartsZfunctionResponseT)Zexclude_none )copyZgoogle.genai.typesr   deepcopyidZ
model_dump)
selfr   r   r   cleaned_contentscontentr   partZfunction_response_dataZfunction_response_partr   r   _/home/app/Keep/.python/lib/python3.10/site-packages/litellm/llms/gemini/count_tokens/handler.py_clean_contents_for_gemini_api   s$   

	z9GoogleAIStudioTokenCounter._clean_contents_for_gemini_apiNmodelapi_basec                 C   s   |pd}| d| dS )zV
        Construct the URL for the Google Gen AI Studio countTokens endpoint.
        z)https://generativelanguage.googleapis.comz/v1beta/models/z:countTokensr   )r   r   r   base_urlr   r   r   _construct_url4   s   z)GoogleAIStudioTokenCounter._construct_url api_keyheaderslitellm_paramsc                    s8   ddl m} | j||||d}| j||d}||fS )zg
        Returns a Tuple of headers and url for the Google Gen AI Studio countTokens endpoint.
        r   )GoogleGenAIConfig)r   r    r   r!   )r   r   )Z/litellm.llms.gemini.google_genai.transformationr"   validate_environmentr   )r   r   r   r    r   r!   r"   urlr   r   r   r#   ;   s   z/GoogleAIStudioTokenCounter.validate_environmenttimeoutc              
      s  | j ||i ||dI dH \}}| |}	d|	i}
ttjd}z|j|||
dI dH }|  | }|W S  tj	yZ } zd|j
j d|j
j }tj|d||j
jd	|d}~w tjyv } zd
t| }tj|d|d|d}~w ty } zdt| }t||d}~ww )a  
        Count tokens using Google Gen AI Studio countTokens endpoint.

        Args:
            contents: The content to count tokens for (Google Gen AI format)
                    Example: [{"parts": [{"text": "Hello world"}]}]
            model: The model name (e.g. "gemini-1.5-flash")
            api_key: Optional Google API key (will fall back to environment)
            api_base: Optional API base URL (defaults to Google Gen AI Studio)
            timeout: Optional timeout for the request
            **kwargs: Additional parameters

        Returns:
            Dict containing token count information from Google Gen AI Studio API.
            Example response:
            {
                "totalTokens": 31,
                "totalBillableCharacters": 96,
                "promptTokensDetails": [
                    {
                        "modality": "TEXT",
                        "tokenCount": 31
                    }
                ]
            }

        Raises:
            ValueError: If API key is missing
            litellm.APIError: If the API call fails
            litellm.APIConnectionError: If the connection fails
            Exception: For any other unexpected errors
        )r   r   r    r   r!   Nr   )llm_provider)r$   r    jsonz Google Gen AI Studio API error: z - gemini)messager&   r   status_codez(Request to Google Gen AI Studio failed: )r)   r&   r   z(Unexpected error during token counting: )r#   r   r   r	   ZGEMINIpostraise_for_statusr'   httpxZHTTPStatusErrorresponser*   textlitellmZAPIErrorRequestErrorstrZAPIConnectionError	Exception)r   r   r   r   r   r%   kwargsr    r$   r   request_bodyZasync_httpx_clientr.   resulte	error_msgr   r   r   acount_tokensR   sX   +
	
z(GoogleAIStudioTokenCounter.acount_tokens)N)NNNr   N)NNN)__name__
__module____qualname__r   r   r2   r   r   r   r   r#   r   floatr-   Timeoutr9   r   r   r   r   r      sJ    $	

r   )typingr   r   r   r   r   r   r-   r0   Z&litellm.llms.custom_httpx.http_handlerr   Zlitellm.types.utilsr	   Zlitellm.types.google_genai.mainr
   r   r   r   r   r   <module>   s     