o
    %g{                     @   s  d Z ddlZddlZddlZddlmZ ddlZddlZddlZddl	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mZ ddlZddlZddlmZ ddlmZ ddlZddlmZmZm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' e	(dZ)dZ*de+e,e,f ddfddZ-de%de%de%fddZ.de,de,de,fddZ/dee,df deee,f fddZ0dedefd d!Z1eG d"d# d#Z2G d$d% d%e!jZ3G d&d' d'Z4G d(d) d)ej5Z6G d*d+ d+ej7Z8G d,d- d-Z9dS ).zBase client for calling HTTP APIs sending and receiving JSON.

The BaseApiClient is intended to be a private module and is subject to change.
    N)	dataclass)AnyAsyncIteratorOptionalTupleUnion)urlparse
urlunparse)Credentials)Request)	BaseModelFieldValidationError   )_common)errors)version)HttpOptionsHttpOptionsDictHttpOptionsOrDictzgoogle_genai._api_clienti   headersreturnc                 C   s   dt j }dtj  d  }| d| }d| v r,|| d vr,| d  d| 7  < nd| vr4|| d< d| v rK|| d vrK| d  d| 7  < dS d| vrU|| d< dS dS )z1Appends the telemetry header to the headers dict.zgoogle-genai-sdk/z
gl-python/r    z
user-agentzx-goog-api-clientN)r   __version__syssplit)r   library_labellanguage_labelversion_header_value r   Z/mnt/skqttb/ctump_chatbot/chatbot/lib/python3.10/site-packages/google/genai/_api_client.py_append_library_version_headers1   s   r!   optionspatch_optionsc                 C   s   |   }|jpi }|jpi }i |||_tj }|D ]!}|dkr#qt||d }|d ur4t||| qt||t| | q|jd urHt|j |S )Nr   )
model_copyr   r   model_fieldskeysgetattrsetattrr!   )r"   r#   copy_optionoptions_headerspatch_options_headershttp_options_keyskeypatch_valuer   r   r    _patch_http_optionsF   s&   




r/   base_urlpathc                 C   sZ   t | }|jdr|jd d n|j}|dr|dd  n|}t|j|d | dS )N/r   )r1   )r   r1   endswith
startswithr	   _replace)r0   r1   parsed_base	base_pathr   r   r    _join_url_pathb   s   
r9   projectc                 C   s0   t jjdgd\}}| s|} | std|| fS )z-Loads google auth credentials and project id.z.https://www.googleapis.com/auth/cloud-platform)scopesz@Could not resolve project using application default credentials.)googleauthdefault
ValueError)r:   credentialsloaded_project_idr   r   r    
_load_authm   s   
rB   r@   c                 C   s   |  t  | S N)refreshr   )r@   r   r   r    _refresh_auth~   s   rE   c                   @   sV   e Zd ZU eeef ed< eed< eed< eeeef ef ed< dZ	e
e ed< dS )HttpRequestr   urlmethoddataNtimeout)__name__
__module____qualname__dictstr__annotations__r   objectbytesrJ   r   floatr   r   r   r    rF      s   
 rF   c                   @   sF   e Zd ZU edddZeeeef  ed< edddZ	ee
 ed< dS )BaseResponseNz!The http headers of the response.)r>   descriptionhttp_headersz!The json payload of the response.json_payload)rK   rL   rM   r   rV   r   rN   rO   rP   rW   r   r   r   r   r    rT      s   
 rT   c                	   @   s   e Zd Z		ddeeeef ejf deeef deee	f fddZ
dd Zd	d
 ZedefddZdd Zdee fddZdd Zdeeef fddZdS )HttpResponseNr   response_streambyte_streamc                 C   s   d| _ || _|| _|| _d S )N   )status_coder   rY   rZ   )selfr   rY   rZ   r   r   r    __init__   s   
zHttpResponse.__init__c                 C   s   |   | _| S rC   )async_segmentssegment_iteratorr]   r   r   r    	__aiter__   s   
zHttpResponse.__aiter__c                    s(   z	| j  I d H W S  ty   tw rC   )r`   	__anext__StopIterationStopAsyncIterationra   r   r   r    rc      s   zHttpResponse.__anext__r   c                 C   s   | j d sdS t| j d S )Nr    )rY   jsonloadsra   r   r   r    rg      s   
zHttpResponse.jsonc                 c   s    t | jtr| jD ]}|rt|ni V  q
d S | jd u r%g E d H  d S | j D ]!}|rKt |ts8|d}|drE|t	dd  }t|V  q*d S )Nutf-8data: )

isinstancerY   listrg   rh   
iter_linesrO   decoder5   len)r]   chunkr   r   r    segments   s    




zHttpResponse.segmentsc                 C  s   t | jtr| jD ]}|rt|ni V  q
d S | jd u r-g 2 z	3 d H W }|V  q 6 d S t| jdra| j 2 z%3 d H W }|r]t |tsJ|d}|	drW|t
dd  }t|V  q86 d S td)Naiter_linesri   rj   z!Error parsing streaming response.)rk   rY   rl   rg   rh   hasattrrr   rO   rn   r5   ro   r?   )r]   rp   cr   r   r    r_      s(   




zHttpResponse.async_segmentsc                 c   s>    t | jtr| jE d H  d S | jd u rg E d H  d S td)Nz8Byte segments are not supported for streaming responses.)rk   rZ   rl   r?   ra   r   r   r    byte_segments   s   
zHttpResponse.byte_segmentsresponse_payloadc                 C   s0   t | d t| D ]}tt| |||< q	d S )Nr`   )delattrdircopydeepcopyr'   )r]   rv   	attributer   r   r    _copy_to_dict   s   
zHttpResponse._copy_to_dict)NN)rK   rL   rM   r   rN   rO   httpxHeadersr   rR   r^   rb   rc   propertyrg   rq   r   r_   ru   rQ   r|   r   r   r   r    rX      s$    


rX   c                       4   e Zd ZdZdeddf fddZd	ddZ  ZS )
SyncHttpxClientzSync httpx client.kwargsr   Nc                    "   | dd t jdi | dS zInitializes the httpx client.follow_redirectsTNr   
setdefaultsuperr^   r]   r   	__class__r   r    r^         zSyncHttpxClient.__init__c                 C   s.   | j rdS z|   W dS  ty   Y dS w )zCloses the httpx client.N)	is_closedclose	Exceptionra   r   r   r    __del__   s   zSyncHttpxClient.__del__r   NrK   rL   rM   __doc__r   r^   r   __classcell__r   r   r   r    r          r   c                       r   )
AsyncHttpxClientzAsync httpx client.r   r   Nc                    r   r   r   r   r   r   r    r^     r   zAsyncHttpxClient.__init__c                 C   s8   | j rd S zt |   W d S  ty   Y d S w rC   )r   asyncioget_running_loopcreate_taskacloser   ra   r   r   r    r     s   zAsyncHttpxClient.__del__r   r   r   r   r   r    r     r   r   c                   @   s`  e Zd ZdZ						d;dee dee deejj	j
 dee dee dee fd	d
Zdd ZdefddZdefddZ	d<dededeeef dee def
ddZ	d=dededefddZ	d=dedefddZdeeef fddZ	d<dededeeef dee fd d!Z	d<dededeeef dee fd"d#Z	d<dededeeef dee deeef f
d$d%Z	d<dededeeef dee fd&d'Zd(eeejf d)ed*e defd+d,Z!d-ejd)ed*e defd.d/Z"defd0d1Z#d(eeejf d)ed*e defd2d3Z$d-eeje%j&f d)ed*e defd4d5Z'defd6d7Z(d8e)j*fd9d:Z+dS )>BaseApiClientz8Client for calling HTTP APIs sending and receiving JSON.Nvertexaiapi_keyr@   r:   locationhttp_optionsc              
   C   s  || _ | j d u rtjdd dv rd| _ |s|r |r td|r(|r(tdt }t|trKzt	|}W n t
yJ } ztd| d }~ww t|trR|}tjdd }	tjd	d }
tjd
d }|pj|	| _|po|
| _|pt|| _|| _t | _zt | _W n ty   tt  t | _Y nw | j r|rtd d | _n/|
s|	r|rtd d | _d | _n|s|r|rtd d | _n|
s|	r|rtd d | _| js| jstd d\}| _| js|| _| jr| js| jstd| js| jdkrd| j_n	d| j d| j_d| j_n| jstdd| j_d| j_ddi| j_| jr>| jjd ur>| j| jjd< |rIt| j|| _n| jjd urVt| jj t | _t  | _!d S )NGOOGLE_GENAI_USE_VERTEXAI0)true1TzNProject/location and API key are mutually exclusive in the client initializer.zICredentials and API key are mutually exclusive in the client initializer.zInvalid http_options: GOOGLE_CLOUD_PROJECTGOOGLE_CLOUD_LOCATIONGOOGLE_API_KEYzoThe user provided Google Cloud credentials will take precedence over the API key from the environment variable.zrThe user provided Vertex AI API key will take precedence over the project/location from the environment variables.zqThe user provided project/location will take precedence over the Vertex AI API key from the environment variable.zyThe project/location from the environment variables will take precedence over the API key from the environment variables.r:   zIProject and location or API key must be set when using the Vertex AI API.globalz"https://aiplatform.googleapis.com/zhttps://z-aiplatform.googleapis.com/v1beta1zMissing key inputs argument! To use the Google AI API,provide (`api_key`) arguments. To use the Google Cloud API, provide (`vertexai`, `project` & `location`) arguments.z*https://generativelanguage.googleapis.com/v1betazContent-Typezapplication/jsonzx-goog-api-key)"r   osenvirongetlowerr?   r   rk   rN   model_validater   r:   r   r   _credentials_http_optionsr   Lock
_auth_lockRuntimeErrorset_event_loopnew_event_looploggerinforB   r0   api_versionr   r/   r!   r   _httpx_clientr   _async_httpx_client)r]   r   r   r@   r:   r   r   validated_http_optionseenv_projectenv_locationenv_api_keyr   r   r    r^     s   	







zBaseApiClient.__init__c                 C   s   t | jj}|jdd S )Nwss)scheme)r   r   r0   r6   geturl)r]   	url_partsr   r   r    _websocket_base_url  s   z!BaseApiClient._websocket_base_urlr   c                 C   sd   | j st| jd\| _ }| js|| _| j r.| j js| j js"t| j  | j js*td| j jS td)z/Retrieves the access token for the credentials.r   0Could not resolve API token from the environment)r   rB   r:   expiredtokenrE   r   r]   r:   r   r   r    _access_token  s   
zBaseApiClient._access_tokenc              	      s  | j s8| j4 I dH " | j s#tjt| jdI dH \| _ }| js#|| _W d  I dH  n1 I dH s3w   Y  | j r~| j jsC| j jsr| j4 I dH  | j jsS| j js]tt| j I dH  W d  I dH  n1 I dH smw   Y  | j jszt	d| j jS t	d)z>Retrieves the access token for the credentials asynchronously.Nr   r   )
r   r   r   	to_threadrB   r:   r   r   rE   r   r   r   r   r    _async_access_token  s*   ((z!BaseApiClient._async_access_tokenhttp_methodr1   request_dictc                 C   s8  dd |  D }|D ]}||= q|r)t|trt| j|}nt| jt|}n| j}d}| jr<|dkr<|dr<d}| jrV|dsV|sV| jsVd| j	 d| j
 d	| }|jd u rad	| }	n|j d	| }	|jd u sq|jsutd
|j}
t|
|	}|j}|r|d }nd }|jd u rtdt|||j||dS )Nc                 S   s   g | ]	}| d r|qS )_)r5   ).0r-   r   r   r    
<listcomp>  s    z0BaseApiClient._build_request.<locals>.<listcomp>Fr   zpublishers/google/modelsTz	projects/z/locations/r2   zBase URL must be set.g     @@zRequest headers must be set.)rH   rG   r   rI   rJ   )r&   rk   r   r/   r   r   r   r5   r   r:   r   r   r0   r?   r9   rJ   r   rF   )r]   r   r1   r   r   keys_to_deleter-   patched_http_optionsquery_vertex_base_modelsversioned_pathr0   rG   timeout_in_secondsr   r   r    _build_request  sn   




zBaseApiClient._build_requestFhttp_requeststreamc                 C   s$  d }| j r,| js,d|   |jd< | jr | jjr | jj|jd< |jr)t|jnd }n|jrDt	|jt
sA|jr>t|jnd }n|j}|rp| jj|j|j||j|jd}| jj||d}tj| t|j|rk|S |jgS | jj|j|j|j||jd}tj| t|j|r|S |jgS NzBearer Authorizationzx-goog-user-project)rH   rG   contentr   rJ   r   rH   rG   r   r   rJ   )r   r   r   r   r   quota_project_idrI   rg   dumpsrk   rR   r   build_requestrH   rG   rJ   sendr   APIErrorraise_for_responserX   textrequestr]   r   r   rI   httpx_requestresponser   r   r    _request  sN   

zBaseApiClient._requestc                    sD  d }| j r0| js0d|  I d H  |jd< | jr$| jjr$| jj|jd< |jr-t|jnd }n|jrHt	|jt
sE|jrBt|jnd }n|j}|rz| jj|j|j||j|jd}| jj||dI d H }tj|I d H  t|j|ru|S |jgS | jj|j|j|j||jdI d H }tj|I d H  t|j|r|S |jgS r   )r   r   r   r   r   r   rI   rg   r   rk   rR   r   r   rH   rG   rJ   r   r   r   raise_for_async_responserX   r   r   r   r   r   r    _async_requestM  sX   

zBaseApiClient._async_requestc                 C   s$   t | jtr| j }|S | j}|S rC   )rk   r   r   
model_dump)r]   copiedr   r   r    get_read_only_http_options~  s
   
z(BaseApiClient.get_read_only_http_optionsc                 C   s@   |  ||||}| j|dd}|j}|st|jdjddS |S )NFr   rV   Tby_alias)r   r   rg   rT   r   r   )r]   r   r1   r   r   r   r   json_responser   r   r    r     s   zBaseApiClient.requestc                 c   s8    |  ||||}| j|dd}| D ]}|V  qd S )NTr   )r   r   rq   )r]   r   r1   r   r   r   session_responserp   r   r   r    request_streamed  s   zBaseApiClient.request_streamedc                    sH   |  ||||}| j|ddI d H }|j}|s"t|jdjddS |S )NFr   r   r   Tr   )r   r   rg   rT   r   r   )r]   r   r1   r   r   r   resultr   r   r   r    async_request  s   zBaseApiClient.async_requestc                    s8   |  ||||}| j|ddI d H   fdd}| S )NTr   c                    s     2 z	3 d H W } | V  q6 d S rC   r   )rp   r   r   r    async_generator  s   z=BaseApiClient.async_request_streamed.<locals>.async_generator)r   r   )r]   r   r1   r   r   r   r   r   r   r    async_request_streamed  s   z$BaseApiClient.async_request_streamed	file_path
upload_urlupload_sizec                 C   sV   t |tjr| |||S t|d}| |||W  d   S 1 s$w   Y  dS )a  Transfers a file to the given URL.

    Args:
      file_path: The full path to the file or a file like object inherited from
        io.BytesIO. If the local file path is not found, an error will be
        raised.
      upload_url: The URL to upload the file to.
      upload_size: The size of file content to be uploaded, this will have to
        match the size requested in the resumable upload request.

    returns:
          The HttpResponse object from the finalize request.
    rbN)rk   ioIOBase
_upload_fdopen)r]   r   r   r   filer   r   r    upload_file  s
   $zBaseApiClient.upload_filer  c           	      C   s   d}	 | t}d}|rt|}d}|| |kr|d7 }| jjd||t|t|d|d}||7 }|jd d	kr:n	||krBtd
q|jd dkrNtdt|j|j	gdS )ax  Transfers a file to the given URL.

    Args:
      file: A file like object inherited from io.BytesIO.
      upload_url: The URL to upload the file to.
      upload_size: The size of file content to be uploaded, this will have to
        match the size requested in the resumable upload request.

    returns:
          The HttpResponse object from the finalize request.
    r   Tupload
, finalizePOSTzX-Goog-Upload-CommandzX-Goog-Upload-OffsetzContent-Length)rH   rG   r   r   x-goog-upload-statusactiveFAll content has been uploaded, but the upload status is not finalized.final6Failed to upload file: Upload status is not finalized.rY   )
read
CHUNK_SIZEro   r   r   rO   r   r?   rX   r   	r]   r  r   r   offset
file_chunk
chunk_sizeupload_commandr   r   r   r    r    s>   

zBaseApiClient._upload_fdc                 C   s   | j d|i |d}d}|jrt|jtst|j}n|j}| jj|j|j	|j
||jd}tj| t|j
| gdjd S zDownloads the file data.

    Args:
      path: The request path with query params.
      http_options: The http options to use for the request.

    returns:
          The file bytes
    r   )r1   r   r   Nr   )rZ   r   )r   rI   rk   rR   rg   r   r   r   rH   rG   r   rJ   r   r   r   rX   r  rZ   r]   r1   r   r   rI   r   r   r   r    download_file  s*   
zBaseApiClient.download_filec              	      s   t |tjr| |||I dH S t|}|dI dH }|4 I dH  | |||I dH W  d  I dH  S 1 I dH s?w   Y  dS )a  Transfers a file asynchronously to the given URL.

    Args:
      file_path: The full path to the file. If the local file path is not found,
        an error will be raised.
      upload_url: The URL to upload the file to.
      upload_size: The size of file content to be uploaded, this will have to
        match the size requested in the resumable upload request.

    returns:
          The HttpResponse object from the finalize request.
    Nr   )rk   r   r  _async_upload_fdanyioPathr  )r]   r   r   r   r  fdr   r   r    async_upload_file4  s   
0zBaseApiClient.async_upload_filec           	         s   d}	 t |tjr|t}n|tI dH }d}|r t|}d}|| |kr,|d7 }| jjd|||t|t|ddI dH }||7 }|j	
d	d
krNn	||krVtdq|j	
d	dkrctdt|j	|jgdS )a  Transfers a file asynchronously to the given URL.

    Args:
      file: A file like object inherited from io.BytesIO.
      upload_url: The URL to upload the file to.
      upload_size: The size of file content to be uploaded, this will have to
        match the size requested in the resumable upload request.

    returns:
          The HttpResponse object from the finalized request.
    r   TNr  r  r  r	  )rH   rG   r   r   r
  r  r  r  r  r  )rk   r   r  r  r  ro   r   r   rO   r   r   r?   rX   r   r  r   r   r    r  N  sD   
zBaseApiClient._async_upload_fdc                    s   | j d|i |d}d}|jrt|jtst|j}n|j}| jj|j|j	|j
||jdI dH }tj|I dH  t|j
| gdjd S r  )r   rI   rk   rR   rg   r   r   r   rH   rG   r   rJ   r   r   r   rX   r  rZ   r  r   r   r    async_download_file  s,   
z!BaseApiClient.async_download_fileresponse_modelc                 C   s   d S rC   r   )r]   r   r   r   r    _verify_response  s   zBaseApiClient._verify_response)NNNNNNrC   )F),rK   rL   rM   r   r   boolrO   r<   r=   r@   r
   r   r^   r   r   r   rN   rQ   rF   r   rX   r   r   r   r   r   r   r   r   r   r   r  intr  r  r  r  r  	AsyncFiler  r  r   r   r!  r   r   r   r    r     s
   
 "

Q
/
1










2"

8%r   ):r   r  r   ry   dataclassesr   datetimer   rg   loggingr   r   typingr   r   r   r   r   urllib.parser   r	   google.authr<   google.auth.credentialsr
   google.auth.transport.requestsr   r}   pydanticr   r   r   rf   r   r   r   typesr   r   r   	getLoggerr   r  rN   rO   r!   r/   r9   rB   rE   rF   rT   rX   Clientr   AsyncClientr   r   r   r   r   r    <module>   sV   

"

[