o
    0XxiX                     @   sn  d 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mZmZmZ ddlZdd	lm Z  dd
lm!Z! ddl"m#Z#m$Z$m%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*eG dd dZ+eG dd dZ,G dd dZ-G dd dZ.dS ) z=Base client for calling HTTP APIs sending and receiving JSON.    N)	dataclass)AnyOptionalTuple	TypedDictUnion)urlparse
urlunparse)AuthorizedSession)	BaseModel
ConfigDictFieldValidationError   )errors)version)HttpOptionsHttpOptionsDictHttpOptionsOrDict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   W/home/air/biblejyuku/back/venv/lib/python3.10/site-packages/google/genai/_api_client.py_append_library_version_headers*   s   r    optionspatch_optionsc                 C   s   t  }||  | D ]/\}}t|tr3t||d tr3i ||< || | |  || | q|d ur;|||< qt|d  |S )Nr   )r   updateitems
isinstancedictgetr    )r!   r"   copy_option	patch_keypatch_valuer   r   r   _patch_http_options?   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   )r-   )r   r-   endswith
startswithr	   _replace)r,   r-   parsed_base	base_pathr   r   r   _join_url_pathV   s   
r5   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__r&   str__annotations__r   objectbytesr:   r   floatr   r   r   r   r6   a   s   
 r6   c                   @   s8   e Zd ZU eeef ed< edeeef fddZdS )BaseResponsehttp_headersr   c                 C   s   t | tr| S d| jiS )NhttpHeaders)r%   r&   rD   selfr   r   r   r&   p   s   

zBaseResponse.dictN)r;   r<   r=   r&   r>   r?   propertyr   r   r   r   r   rC   l   s   
 rC   c                	   @   s   e Zd Z		ddeee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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   rJ   rK   segmentssegment_iterator)rG   r   rJ   rK   r   r   r   __init__y   s
   zHttpResponse.__init__c                 C   s   | S Nr   rF   r   r   r   	__aiter__      zHttpResponse.__aiter__c                    s"   zt | jW S  ty   tw rQ   )nextrO   StopIterationStopAsyncIterationrF   r   r   r   	__anext__   s   zHttpResponse.__anext__r   c                 C   s   | j d sdS t| j d S )Nr    )rJ   jsonloadsrF   r   r   r   rY      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 ]}|rD|dr;|tdd  }tt|dV  q*d S )Ns   data: zutf-8)	r%   rJ   listrY   rZ   
iter_linesr1   lenr>   )rG   chunkr   r   r   rN      s   


zHttpResponse.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.)r%   rK   r[   
ValueErrorrF   r   r   r   byte_segments   s   
zHttpResponse.byte_segmentsresponse_payloadc                 C   s0   t | d t| D ]}tt| |||< q	d S )NrO   )delattrdircopydeepcopygetattr)rG   ra   	attributer   r   r   _copy_to_dict   s   
zHttpResponse._copy_to_dict)NN)r;   r<   r=   r&   r>   r   r   rA   rP   rR   rW   rH   rY   rN   r`   r@   rh   r   r   r   r   rI   w   s"    



rI   c                   @   sP  e Zd ZdZ						d;deedf deedf dejj	j
deedf deedf defd	d
Zdd Z	d<dededeeef dedef
ddZ	d=ded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fddZ	d<dededeeef defddZ	d<dededeeef defd d!Z	d<dededeeef dedeeef f
d"d#Z	d<dededeeef d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d.d/Z!dedefd0d1Z"d&eeejf d'ed(edefd2d3Z#d+ejd'ed(edefd4d5Z$defd6d7Z%d8e&fd9d:Z'dS )>	ApiClientz8Client for calling HTTP APIs sending and receiving JSON.Nvertexaiapi_keycredentialsprojectlocationhttp_optionsc              
   C   sV  || _ | j d u rtjdd dv rd| _ |s|r |r td|r(|r(tdt|trHzt	| W n t
yG } ztd| d }~ww t|trQ| }tjdd }tjd	d }	tjd
d }
|pi|| _|pn|	| _|ps|
| _|| _t | _| 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j d | _| jr| js| jstd| js| jdkrd| jd< n
d| j d| jd< d| jd< n| jstdd| jd< d| jd< ddi| jd< | jr| j| jd d< |r"t| j|| _d S t| jd  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/r,   zhttps://z-aiplatform.googleapis.com/v1beta1api_versionzMissing 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/jsonr   zx-goog-api-key)rj   osenvironr'   lowerr_   r%   r&   r   model_validater   
model_dumprm   rn   rk   _credentialsr   _http_optionslogginginfogoogleauthdefaultr+   r    )rG   rj   rk   rl   rm   rn   ro   eenv_projectenv_locationenv_api_keyr   r   r   rP      s   	






zApiClient.__init__c                 C   s   t | jd }|jdd S )Nr,   wss)scheme)r   r   r2   geturl)rG   	url_partsr   r   r   _websocket_base_url1  s   zApiClient._websocket_base_urlhttp_methodr-   request_dictr   c                 C   s   dd |  D }|D ]}||= q|r(t|tr!t| j| }n
t| j|}n| j}d}| jr;|dkr;|dr;d}| jrU|dsU|sU| jsUd| j	 d| j
 d	| }t|d
 |d d	 | }	|dd }
|
ro|
d }
nd }
t||	|d ||
dS )Nc                 S   s   g | ]	}| d r|qS )_)r1   ).0keyr   r   r   
<listcomp>=  s    z,ApiClient._build_request.<locals>.<listcomp>Fr'   zpublishers/google/modelsTz	projects/z/locations/r.   r,   ry   r:   g     @@r   )r8   r7   r   r9   r:   )keysr%   r   r+   r   r   rj   r1   rk   rm   rn   r5   r'   r6   )rG   r   r-   r   ro   keys_to_deleter   patched_http_optionsquery_vertex_base_modelsr7   timeout_in_secondsr   r   r   _build_request5  sV   


zApiClient._build_requestFhttp_requeststreamc                 C   s   | j rH| jsH| jstjjdgd\| _}t| j}||_|j|j	
 |j|j|jr/t|jnd |jd}tj| t|j|rC|S |jgS | ||S )N.https://www.googleapis.com/auth/cloud-platformscopes)r   r9   r:   )rj   rk   r   r   r   r   r
   r   requestr8   upperr7   r   r9   rY   dumpsr:   r   APIErrorraise_for_responserI   text_request_unauthorized)rG   r   r   r   authed_sessionresponser   r   r   _requestn  s*   

zApiClient._requestc                 C   sv   d }|j rt|j tst|j }n|j }t }|j|j|j	|j
||j|d}tj| t|j
|r6|S |jgS )Nr8   r7   r   r9   r:   r   )r9   r%   rA   rY   r   requestsSessionr   r8   r7   r   r:   r   r   r   rI   r   )rG   r   r   r9   http_sessionr   r   r   r   r     s(   
zApiClient._request_unauthorizedc                    sT   | j r| jstjjdgd\| _}tj| j||dI d H S tj| j||dI d H S )Nr   r   r   )rj   r   r   r   r   asyncio	to_threadr   )rG   r   r   r   r   r   r   _async_request  s    zApiClient._async_requestc                 C   s.   t  }t| jtr| j | _|| j |S rQ   )r   r%   r   r   r   r#   )rG   copiedr   r   r   get_read_only_http_options  s
   z$ApiClient.get_read_only_http_optionsc           	      C   s<   |  ||||}| j|dd}|j}|st|jj}|S |S )NFr   )r   r   rY   rC   r   r&   )	rG   r   r-   r   ro   r   r   json_responsebase_responser   r   r   r     s   zApiClient.requestc                 c   s8    |  ||||}| j|dd}| D ]}|V  qd S )NTr   )r   r   rN   )rG   r   r-   r   ro   r   session_responser^   r   r   r   request_streamed  s   zApiClient.request_streamedc           	         sD   |  ||||}| j|ddI d H }|j}|s t|jj}|S |S )NFr   r   )r   r   rY   rC   r   r&   )	rG   r   r-   r   ro   r   resultr   r   r   r   r   async_request  s   zApiClient.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 rQ   r   )r^   r   r   r   async_generator  s   z9ApiClient.async_request_streamed.<locals>.async_generator)r   r   )rG   r   r-   r   ro   r   r   r   r   r   async_request_streamed  s   z ApiClient.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 response json object from the finalize request.
    rbN)r%   ioIOBase
_upload_fdopen)rG   r   r   r   filer   r   r   upload_file  s
   $zApiClient.upload_filer   c           
      C   s   d}	 | d}d}|rt|}d}|| |kr|d7 }td||t|t|d|d}| j|d	d
}	||7 }|	jd dkr?n||krOtd|	j d|	j q|	jd dkrctd|	j d|	j |	jS )ay  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 response json object from the finalize request.
    r   Ti   uploadz
, finalizePOST)zX-Goog-Upload-CommandzX-Goog-Upload-OffsetzContent-Length)r8   r7   r   r9   Fr   zX-Goog-Upload-StatusactivezGAll content has been uploaded, but the upload status is not finalized. z, body: finalz@Failed to upload file: Upload status is not finalized. headers: )readr]   r6   r>   r   r   r_   rY   )
rG   r   r   r   offset
file_chunk
chunk_sizeupload_commandr   r   r   r   r   r     sP   
zApiClient._upload_fdc                 C   s"   | j d|i |d}| |jd S )Downloads 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'   )r-   r   ro   r   )r   _download_file_requestrK   )rG   r-   ro   r   r   r   r   download_fileO  s   
zApiClient.download_filec                 C   sr   d }|j rt|j tstj|j td}n|j }t }|j|j	|j
|j||jdd}tj| t|j|jgdS )N)clsFr   )rK   )r9   r%   rA   rY   r   RequestJsonEncoderr   r   r   r8   r7   r   r:   r   r   r   rI   content)rG   r   r9   r   r   r   r   r   r   ^  s    	z ApiClient._download_file_requestc                       t | j|||I dH 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 response json object from the finalize request.
    N)r   r   r   )rG   r   r   r   r   r   r   async_upload_filev  s   
zApiClient.async_upload_filec                    r   )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 response json object from the finalize request.
    N)r   r   r   )rG   r   r   r   r   r   r   _async_upload_fd  s   
zApiClient._async_upload_fdc                    s   t | j||I dH S )r   N)r   r   r   )rG   r-   ro   r   r   r   async_download_file  s   

zApiClient.async_download_fileresponse_modelc                 C   s   d S rQ   r   )rG   r   r   r   r   _verify_response  rS   zApiClient._verify_response)NNNNNNrQ   )F)(r;   r<   r=   __doc__r   boolr>   r   r   rl   Credentialsr   rP   r   r&   r@   r6   r   rI   r   r   r   r   r   r   r   r   r   r   r   intr   r   r   r   r   r   r   r   r   r   r   r   r   ri      s   




v	

<













6


ri   )/r   r   rd   dataclassesr   datetimer   rY   r   r{   r   typingr   r   r   r   r   urllib.parser   r	   google.authr   google.auth.credentialsgoogle.auth.transport.requestsr
   pydanticr   r   r   r   r   rX   r   r   typesr   r   r   r&   r>   r    r+   r5   r6   rC   rI   ri   r   r   r   r   <module>   sF   


A