
    R-jQ6                       d Z ddlZddlm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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mZmZ ddlm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"m#Z# dd	l$m%Z% dd
l&m'Z' ddl m(Z) ddl*Z*ddl+m,Z, ddl+m-Z- ddl.Z.ddl/m0Z0 ddl1Z1ddl2m3Z3 ddl2m4Z4 ddl2m5Z5 ddl6m7Z7 ddl6m8Z8 ddl6m9Z: ddl6m;Z; ddl6m<Z< 	 ddl=m>Z? dZB	 ddlCZCdZBerddlEmFZF ddlGmHZH  e
j                  d      ZJdZKdZLd ZMdZNd!ZOd"d#hZP G d$ d%eQ      ZRd&eeS   fd'ZTd(eUeSeSf   d&dfd)ZVd*e7d+e7d&e7fd,ZWd(eUeSeSf   d-eeeXeYf      d&dfd.ZZd/eSd0eSd&eSfd1Z[d2eeSdf   d&ee#eSf   fd3Z\d4e#d&e#fd5Z]d6eeeXeYf      d&eeX   fd7Z^e G d8 d9             Z_ G d: d;      Z9d<Z`d=Zad>Zbd!ZcdZdd?Zed*ee;   d&e3j                  fd@Zg G dA dBe*j                        Zi G dC dDe*j                        Zk G dE dF      ZldGdFd4e!j                  j                  jF                  d&eSfdHZodGdFd4e!j                  j                  jF                  d&eSfdIZpy# e@$ r
 ddlAm>Z? Y }w xY w# eD$ r Y w xY w)JzBase client for calling HTTP APIs sending and receiving JSON.

The BaseApiClient is intended to be a private module and is subject to change.
    N)	Generator)	dataclass)AnyAsyncIteratorIteratorOptionalTYPE_CHECKINGTupleUnion)urlparse)
urlunparseCredentials)mtls)AuthorizedSession)
exceptions)	BaseModel)ValidationError)CaseInsensitiveDict   )_common)errors)version)HttpOptions)HttpOptionsOrDict)HttpResponse)HttpRetryOptions)ResourceScope)connectFT)CIMultiDictProxyAsyncAuthorizedSessionzgoogle_genai._api_clienti   i  @       useuc                       e Zd ZdZy)EphemeralTokenAPIKeyErrorz)Error raised when the API key is invalid.N)__name__
__module____qualname____doc__     f/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/google/genai/_api_client.pyr(   r(   b   s    1r.   r(   returnc                      t         j                  j                  dd      } t         j                  j                  dd      }| r|rt        j	                  d       | xs |xs dS )zGets the API key from environment variables, prioritizing GOOGLE_API_KEY.

  Returns:
      The API key string if found, otherwise None. Empty string is considered
      invalid.
  GOOGLE_API_KEYNGEMINI_API_KEYzEBoth GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.)osenvirongetloggerwarning)env_google_api_keyenv_gemini_api_keys     r/   get_env_api_keyr;   h   sX     zz~~&6=zz~~&6=.
NNO 
	91	9T9r.   headersc                 r   dt         j                   }dt        j                   j                         d   z   }| d| }d| v r|| d   vr| d| d   z   | d<   n"d| v r|| d   vr| d    d| | d<   n	d| vr|| d<   d| v r|| d   vr| d| d   z   | d<   yd| v r|| d   vr| d    d| | d<   yd| vr|| d<   yy)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_values       r/   append_library_version_headersrE   y   sD   %g&9&9%:;-#++"3"3"5a"88.)?!N+;<g
w|4
434A69NNGLw>9N#N&|45Q~6FGGL7"0GLW$
w':;
;  
 "W-@%AA   W$
(; <
< &'
(.)9:   ')#7G  *r.   optionspatch_optionsc           	      |   | j                         }|j                  xs i }|j                  xs i }i |||_        t        j                  j	                         }|D ]<  }|dk(  r	t        ||d       }|t        |||       &t        ||t        | |             > |j                  t        |j                         |S )Nr<   )
model_copyr<   r   model_fieldskeysgetattrsetattrrE   )rF   rG   copy_optionoptions_headerspatch_options_headershttp_options_keyskeypatch_values           r/   patch_http_optionsrT      s     ""$+''-2/'//52+
 "..335c
i-d3Kk3,k3 56  $";#6#67	r.   timeout_in_secondsc                 V    |r'd| vr"t        t        j                  |            | d<   yyy)z8Populates the server timeout header in the headers dict.zX-Server-TimeoutN)strmathceil)r<   rU   s     r/   populate_server_timeout_headerrZ      s1     .g="%dii0B&C"DG >r.   base_urlpathc                     t        |       }|j                  j                  d      r|j                  d d n|j                  }|j                  d      r|dd  n|}t	        |j                  |dz   |z               S )N/r   )r\   )r   r\   endswith
startswithr   _replace)r[   r\   parsed_base	base_paths       r/   join_url_pathre      s~    "+ 
			"	"3	' s 
 __S)abt$	K((i#o.D(E	FFr.   projectc                 t    t         j                  j                  dg      \  }}| 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)rf   credentialsloaded_project_ids      r/   	load_authro      sQ    #);;#6#6>? $7 $ +  
G	
J  
g	r.   rm   c                 >    ddl m} | j                   |              | S )Nr   )Request)google.auth.transport.requestsrq   refresh)rm   rq   s     r/   refresh_authrt      s    4gi 	r.   timeoutc                     | r| dz  }|S d}|S )z Converts the timeout to seconds.g     @@Nr-   )ru   rU   s     r/   get_timeout_in_secondsrw      s*      !6) 
 	r.   c                   h    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<   y)HttpRequestr<   urlmethoddataNru   )r)   r*   r+   dictrW   __annotations__r   objectbytesru   r   floatr-   r.   r/   ry   ry      sA    S>
(
+d3;&''!'8E?!r.   ry   c            	       4   e Zd Z	 	 ddeeeef   ej                  def   dee	ef   dee	e
f   fdZddZde	fd	Zede	fd
       Zdee	ddf   fdZdee	   fdZdeee
e	f   ddf   fdZdeeef   ddfdZdee   fdZdee   fdZede	de	fd       Zy)r   Nr<   zCIMultiDictProxy[str]response_streambyte_streamc           	      `   t        |t              r|| _        nt        |t        j                        rC|j                         D ci c]#  }|dj                  |j                  |            % c}| _        nt        |t              r*|j                         D ci c]  \  }}||
 c}}| _        nZt        |      j                  dk(  rB|j                         D ci c]#  }|dj                  |j                  |            % c}| _        d| _        || _        || _        y c c}w c c}}w c c}w )Nz, r       )
isinstancer}   r<   httpxHeadersrK   joinget_listr   itemstyper)   getallstatus_coder   r   )selfr<   r   r   rR   values         r/   __init__zHttpResponse.__init__   s    '4 dl	GU]]	+;B<<>;IC#tyy))#./
/>dl 
G0	13:==?C?ZS%c5j?Cdl	g		#5	59@9G##tyy,-
-dl  D*D"D Ds   (D D%(D+r0   c                 0    | j                         | _        | S N)async_segmentssegment_iteratorr   s    r/   	__aiter__zHttpResponse.__aiter__  s     //1DKr.   c                 z   K   	 | j                   j                          d {   S 7 # t        $ r t        w xY wwr   )r   	__anext__StopIterationStopAsyncIterationr   s    r/   r   zHttpResponse.__anext__  s:     ((224444 s    ;( &( ;( 8;c                     t        | j                  t              sy | j                  r| j                  d   sy| j                  | j                  d         S )Nr    )r   r   list_load_json_from_responser   s    r/   jsonzHttpResponse.json  sL     d**D1t';';A'>(()=)=a)@AAr.   c              #     K   t        | j                  t              r)| j                  D ]  }|r| j                  |      ni   y | j                  g E d {    y | j	                         D ]  }| j                  |        y 7 .wr   )r   r   r   r   _iter_response_stream)r   chunks     r/   segmentszHttpResponse.segments*  sy     $&&-''%6;d++E2C (				%mm --/%++E22 0 s   ABB/Bc                8  K   t        | j                  t              r*| j                  D ]  }|r| j                  |      ni   y | j                  g 2 3 d {   }| | j	                         2 3 d {   }| j                  |       7 86 y 7 6 y wr   )r   r   r   r   _aiter_response_stream)r   r   cs      r/   r   zHttpResponse.async_segments6  s     $&&-''%6;d++E2C (				%  446 3++E22R36sN   ABBBBB4B8B9B<BBBBBc              #      K   t        | j                  t              r| j                  E d {    y | j                  g E d {    y t        d      7 '7 w)Nz8Byte segments are not supported for streaming responses.)r   r   r   rl   r   s    r/   byte_segmentszHttpResponse.byte_segmentsC  sQ     $""D)!!!!				!mm
D 	 "s!   *AAAAAAresponse_payloadc                     t        | d       t        |       D ]$  }t        j                  t	        | |            ||<   & y )Nr   )delattrdircopydeepcopyrL   )r   r   	attributes      r/   _copy_to_dictzHttpResponse._copy_to_dictN  s6    D$%Y	$(MM'$	2J$Ky! r.   c              #     K   t        | j                  t        j                        sPt        | j                  t        j                        s,t        dt        | j                        j                   d      d}d}g }t        | j                  t        j                        r| j                  j                         }n| j                  j                  d      }|D ]y  }|s|rdj                  |       g }|j                  d      r|j                  |t        d      d	        L|D ]  }|d
k(  r|dz  }|dk(  s|dz  } ||z  }|dk(  st| d}{ |r| |rdj                  |       y	y	w)z,Iterates over chunks retrieved from the API.zFExpected self.response_stream to be an httpx.Response object, but got .r   r   T)decode_unicode
data: N{r   })r   r   r   Responserequests	TypeErrorr   r)   
iter_linesr   ra   appendlen)r   r   balancedata_bufferr   liner   s          r/   r   z"HttpResponse._iter_response_streamT  sn     	4''8d**H,=,=>$../889< 
 EGK$&&7,,779o,,77t7Lo		+&
&+ 
	"4H/0
 !8
Q,'#X
Q,'	  tme	A3  8 kIIk"" s   D9E3<E3%E3c                "  K   t        | j                  t        j                        xs, t        xr$ t        | j                  t
        j                        }|s,t        dt        | j                        j                   d      d}d}g }t        | j                  t        j                        r	 | j                  j                         2 3 d{   }|s|rdj                  |       g }$|j                  d      r|j                  |t        d      d        S|D ]  }|dk(  r|d	z  }|d
k(  s|d	z  } ||z  }|dk(  s{| d}t        r-t        | j                  t
        j                        r	 	 | j                  j                   j#                  t$               d{   }|sn|j'                  d      j)                         }|s|rdj                  |       g }p|j                  d      r|j                  |t        d      d        |D ]  }|dk(  r|d	z  }|d
k(  s|d	z  } ||z  }|dk(  r| d}|r| |rdj                  |       | j                  j+                          yyy7 6 |r| |rdj                  |       | j                  j                          d{  7   y# | j                  j                          d{  7   w xY w7 G# | j                  j+                          w xY ww)z;Asynchronously iterates over chunks retrieved from the API.z`Expected self.response_stream to be an httpx.Response or aiohttp.ClientResponse object, but got r   r   r   Nr   r   r   r   r   )max_line_lengthutf-8)r   r   r   r   has_aiohttpaiohttpClientResponser   r   r)   aiter_linesr   ra   r   r   aclosecontentreadlineREAD_BUFFER_SIZEdecoderstriprelease)r   is_valid_responser   r   r   r   r   
line_bytess           r/   r   z#HttpResponse._aiter_response_stream  s    "4#7#7H P
4#7#79O9OP  4''(112!5  EGK$&&7!,..::< 	$IIk**k __X&tCMN34
 aCxlgclg	  4-%\KE 
g44*'!1199BB. C  * ""7+224$IIk**k __X&tCMN34
 aCxlgclg	  4-%\KEC F +		+&
& 	$$&[G	<4 +		+&
& ""))+++d""))+++N 	$$&s   B+L.K JJ JA K 1K K ,L8.K0 &K-'BK0 -6K0 #L JK !L>K?LK*#K&$K**L-K0 0LLresponsec                     	 t        j                  |      S # t         j                  $ r}t        j                  d|       |d}~ww xY w)zFLoads JSON from the response, or raises an error if the parsing fails.z0Failed to parse response as JSON. Raw response: N)r   loadsJSONDecodeErrorr   UnknownApiResponseError)clsr   es      r/   r   z%HttpResponse._load_json_from_response  sL    ZZ!! **<XJ
Gs    AAA)NN)r0   r   )r)   r*   r+   r   r}   rW   r   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r   r   r   r   r   classmethodr   r-   r.   r/   r   r      s<    *.'+#
sCx.
--
!
# S#X# e$#:s  	BC 	B 	B
3	#tT/2 
33M#$6 3	YuUCZ'8$'DE 	LDf,= L$ L1#Xc] 1#fb'M#,> b'H c c  r.   r      g      ?g      N@)i  i  i  i  i  i  c                 (   | t        j                  d      ddS | j                  dk(  rd| _        t        j                  | j                  xs t              }| j                  xs t
        t        j                  fd      }t        j                  | j                  xs t        | j                  xs t        | j                  xs t        | j                  xs t              }||d|t        j                   t"        t$        j&                        dS )a  Returns the retry args for the given http retry options.

  Args:
    options: The http retry options to use for the retry configuration. If None,
      the 'never retry' stop strategy will be used.

  Returns:
    The arguments passed to the tenacity.(Async)Retrying constructor.
  r   T)stopreraiser   c                     t        | t        j                        xr | j                  v xs* t        | t        j
                  t        j                  f      S r   )r   r   APIErrorcoder   TimeoutExceptionConnectError)r   retriable_codess    r/   <lambda>zretry_args.<locals>.<lambda>  sE    Av/MAFFo4M E	A..0B0BC	DEr.   )initialmaxexp_basejitter)r   retryr   waitbefore_sleep)tenacitystop_after_attemptattempts_RETRY_ATTEMPTShttp_status_codes_RETRY_HTTP_STATUS_CODESretry_if_exceptionwait_exponential_jitterinitial_delay_RETRY_INITIAL_DELAY	max_delay_RETRY_MAX_DELAYr   _RETRY_EXP_BASEr   _RETRY_JITTERbefore_sleep_logr7   loggingINFO)rF   r   r   r   r   s       @r/   
retry_argsr   	  s     _//2tDDG		$	$W%5%5%H	I$--I1I/

%
%E% 
	)	)##;';



//2?^^,}	
$ //E
 r.   c                   4     e Zd ZdZdeddf fdZddZ xZS )SyncHttpxClientzSync httpx client.kwargsr0   Nc                 H    |j                  dd       t        |   di | yzInitializes the httpx client.follow_redirectsTNr-   
setdefaultsuperr   r   r  	__class__s     r/   r   zSyncHttpxClient.__init__/  $    
($/	Gvr.   c                     	 | j                   ry	 	 | j                          y# t        $ r Y w xY w# t        $ r Y yw xY w)zCloses the httpx client.N)	is_closed	Exceptioncloser   s    r/   __del__zSyncHttpxClient.__del__4  sK    	 

jjl  
  
s   " 1 	..	==r0   Nr)   r*   r+   r,   r   r   r  __classcell__r
  s   @r/   r  r  ,  s    s t 

r.   r  c                   4     e Zd ZdZdeddf fdZddZ xZS )AsyncHttpxClientzAsync httpx client.r  r0   Nc                 H    |j                  dd       t        |   di | yr  r  r	  s     r/   r   zAsyncHttpxClient.__init__D  r  r.   c                     	 | j                   ry 	 	 t        j                         j	                  | j                                y # t        $ r Y >w xY w# t        $ r Y y w xY wr   )r  r  asyncioget_running_loopcreate_taskr   r   s    r/   r  zAsyncHttpxClient.__del__I  s_    	 
 ,,T[[];  
  
s"   A 1A 	AA	AAr  r  r  s   @r/   r  r  A  s    s t 
	r.   r  c                      e Zd ZdZ	 	 	 	 	 	 d7dee   dee   deej                  j                  j                     dee   dee   dee   fd	Zd
efdZd
efdZd
ed   fdZeded
eej*                  ej*                  f   fd       Zeded
ej*                  fd       Zeded
ej*                  fd       Zd
efdZd
efdZd
efdZd
ej:                  fdZd
eeef   fdZ 	 d8dedede!ee"f   dee   d
e#f
dZ$	 d9de#ded
e%fdZ&	 	 d:de#dee   ded
e%fdZ'	 d9de#ded
e%fd Z(	 	 d:de#dee   ded
e%fd!Z)d
ej*                  fd"Z*	 d8dedede!ee"f   dee   d
e+f
d#Z,	 d8dedede!ee"f   dee   d
e-e+ddf   f
d$Z.	 d8dedede!ee"f   dee   d
e+f
d%Z/	 d8dedede!ee"f   dee   d
ef
d&Z0dd'd(eee1jd                  f   d)ed*e3dee   d
e%f
d+Z4dd'd,e1jd                  d)ed*e3dee   d
e%f
d-Z5dd'dedee   d
eee6f   fd.Z7dd'd(eee1jd                  f   d)ed*e3dee   d
e%f
d/Z8dd'd,ee1jd                  e9jt                  e   f   d)ed*e3dee   d
e%f
d0Z;dd'dedee   d
eee6f   fd1Z<d2ejz                  d
dfd3Z>d;d4Z?d;d5Z@d;d6ZAy)<BaseApiClientz8Client for calling HTTP APIs sending and receiving JSON.Nvertexaiapi_keyrm   rf   locationhttp_optionsc                 h   || _         d | _        | j                   t        j                  j	                  dd       }t        j                  j	                  dd       }d }	||j                         dv }	d }
||j                         dv }
|	|
|	|
k7  rt        j                  d       |	|	| _         n	|
|
| _         |s|r|rt        d      |r|rt        d      t               }t        |t              r	 t        j                  |      }n|rt        j                  |t              r|}|j                   r|j"                  st        d      t        j                  j	                  d	d       }t        j                  j	                  d
d       }t%               }|xs || _        |xs || _        |xs || _        || _        t               | _        t1        j2                         | _        d | _        d | _        | j                   r|r|rt:        j=                  d       d | _        no|s|r&|r$t:        j=                  d       d | _        d | _        nE|s|r|rt:        j=                  d       d | _        n"|s|r|rt:        j=                  d       d | _        |j"                  r|j"                  nd | _        | j(                  sB| j*                  s6| j                  sd| _        n"| j                  j?                  d      rd| _        | j&                  s?| j*                  s3| j                  s'tA        d       \  }| _        | j,                  s|| _        | j&                  xr | j(                  xs | j*                  }|s| j                  st        d      | j*                  s| j(                  dk(  r| j                  sd| j.                  _        n| j(                  tB        v r,| j                  s d| j(                   d| j.                  _        nv| j                  rK| j                  j?                  d      s0|r|s,|s*| j                  | j.                  _        d | _        d | _        nd| j(                   d| j.                  _        d| j.                  _"        n9| j*                  st        d      d| j.                  _        d| j.                  _"        ddi| j.                  _#        | j*                  rX| j*                  jI                         | _        | j.                  jF                  #| j*                  | j.                  jF                  d<   |rtK        | j.                  |      | _        n5| j.                  jF                  tM        | j.                  jF                         | jO                  | j.                        \  }}|| _(        d | _)        | jU                         rd | _+        nB| j.                  jX                  r| j.                  jX                  | _+        nt[        d&i || _+        | j]                         rd | _/        nB| j.                  j`                  r| j.                  j`                  | _/        ntc        d&i || _/        | j.                  j`                  r| j.                  j`                  | _/        ntc        d&i || _/        d | _2        | jg                         r	 dd l4}| j.                  jj                  r| j.                  jj                  | _2        | jm                  | j.                        | _7        | j]                         rkd | jn                  d!<   | j.                  jp                  ts        d"      nts        | j.                  jp                        | jn                  d#<   d$| jn                  d%<   tw        | j.                  jx                        }| j{                  | j.                        | _>        t        j                  d&i || _A        t        j                  d&i || _C        y # t        $ r}t        d      |d }~ww xY w# tt        $ r Y w xY w)'NGOOGLE_GENAI_USE_ENTERPRISEGOOGLE_GENAI_USE_VERTEXAI)true1zWarning: Both GOOGLE_GENAI_USE_ENTERPRISE and GOOGLE_GENAI_USE_VERTEXAI are set with conflicting values. The value of GOOGLE_GENAI_USE_ENTERPRISE will be used.zNProject/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_optionsz9base_url must be set when base_url_resource_scope is set.GOOGLE_CLOUD_PROJECTGOOGLE_CLOUD_LOCATIONzoThe 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.globalz.googleapis.comrf   z<Project or API key must be set when using the Vertex AI API.z"https://aiplatform.googleapis.com/zhttps://aiplatform.z.rep.googleapis.com/zhttps://z-aiplatform.googleapis.com/v1beta1zNo API key was provided. Please pass a valid API key. Learn how to create an API key at https://ai.google.dev/gemini-api/docs/api-key.z*https://generativelanguage.googleapis.com/v1betazContent-Typezapplication/jsonzx-goog-api-keyr   Tsslinfmax_allowed_timer   total_attemptsr-   )Dr  custom_base_urlr4   r5   r6   lowerwarningswarnrl   r   r   r}   model_validater   r   is_duck_type_ofbase_url_resource_scoper[   r;   rf   r   r  _credentials_http_options	threadingLock_sync_auth_lock_async_auth_lock_async_auth_lock_creation_lockr7   infor`   ro   _MULTI_REGIONAL_LOCATIONSapi_versionr<   striprT   rE   _ensure_httpx_ssl_ctx_async_httpx_client_args_authorized_session_use_google_auth_sync_httpx_clienthttpx_clientr  _use_google_auth_async_async_httpx_clienthttpx_async_clientr  _aiohttp_session_use_aiohttpr   aiohttp_client_ensure_aiohttp_ssl_ctx"_async_client_session_request_argsru   r   ImportErrorr   retry_options_ensure_websocket_ssl_ctx_websocket_ssl_ctxr   Retrying_retryAsyncRetrying_async_retry)r   r  r  rm   rf   r   r!  env_enterprise_strenv_vertexai_strenv_enterpriseenv_vertexaivalidated_http_optionsr   env_projectenv_locationenv_api_keyhas_sufficient_authclient_argsasync_client_argsr   retry_kwargss                        r/   r   zBaseApiClient.__init__X  sr    DMD}}::>>*GN(CTJn		'+113}Dl		%'--/=@ 
$&,B	
 
	#&#$ 	8  
  )],%8!,!;!;L!I 
'11,L+ 	66&// 
E 
 **..!7>K::>>"94@L!#K)kDL,DM)kDL#D$D %>>+D48DBFD' }}	A	
 KWB	
 x[B	
 K[M	
  $,, !
)
)  mm,,##"$-!!**+<="$- ll,,&&$-d$;!T\  )$
!\\;dmmL )=)=J
 	
 ,,$--83$$(J#
--4
4&& "$--0DE 	# 

&&//0ABh7 '+&:&:# t}}o%@A 	# (1d$\\>
 	

 %Qd!'/d$"02D!ED||\\'')dl				#	#	/7;||""#34-


4d 
			#	#	/&t'9'9'A'AB%)%?%?&"K" %6D!<@D!!#d				(	(--::d*9[9d""$!%d				.	.!%!3!3!F!Fd!1!F4E!Fd,,!%!3!3!F!Fd!1!F4E!Fd aeD,,"&"4"4"C"C$
 ((););< 	/ &&(;?$
1
1%
8 !!))1 INI7<  ((8 
1
12D
E
 GH$
1
12B
C d00>>?L"<<T=O=OPD##3l3DK ..>>DM  8/0a78@  s+   3` C`% 	`"``"%	`10`1r0   c                    t        t        d      syt        | j                  xr[ t        j                         xrE t        j
                         xr/ | j                  j                  xs | j                  j                         S )Nshould_use_client_certF)	hasattrr   boolr  rf  has_default_client_cert_sourcer9  rH  rb  r   s    r/   rF  z#BaseApiClient._use_google_auth_syncZ  sr    412 	
'')	
//1	
 ++Mt/A/A/M/M
	 r.   c                     t        t        xrc | j                  xrU t        t        d      xrC t	        j
                         xr- t	        j                         xr | j                  j                         S )Nrf  )	rh  r   r  rg  r   rf  ri  r9  rK  r   s    r/   rI  z$BaseApiClient._use_google_auth_asyncf  sm     	6MM	6D23	6 '')	6 //1		6
 ""555 r.   )zaiohttp.ClientSessionr"   c                 ,  K   | j                   G| j                         r7	 ddlm} ddlm}  G d d|      } | ||             | _         | j                   S | j                         s| j                   :| j                   j                  s$| j                   j                  j                         rM G d dt        j                        } G d d	t        j                        } | |d
      dt              | _         | j                   S # t        $ r Y w xY ww)z#Returns the aiohttp client session.r   r   r!   c            
       `     e Zd ZdZd fdZdedededeeef   ddf
d	Ze	de
fd
       Z xZS )HBaseApiClient._get_aiohttp_session.<locals>._RefreshableAsyncCredentialszJAdapter to use the client's sync credentials in an AsyncAuthorizedSession.c                 0    t         |           || _        y r   )r  r   _client)r   clientr
  s     r/   r   zQBaseApiClient._get_aiohttp_session.<locals>._RefreshableAsyncCredentials.__init__}  s    G!DLr.   requestr{   rz   r<   r0   Nc                   K   | j                   j                          d {   }d| |d<   | j                   j                  rE| j                   j                  j                  r$| j                   j                  j                  |d<   y y y 7 hw)NBearer Authorizationx-goog-user-project)ro  _async_access_tokenr8  quota_project_id)r   rq  r{   rz   r<   tokens         r/   before_requestzWBaseApiClient._get_aiohttp_session.<locals>._RefreshableAsyncCredentials.before_request  s}      ,,::<<E)0'8GO$))LL-->> ,,++<< +, ? * =s   BB	A)Bc                 r    | j                   j                  sy| j                   j                  j                   S NF)ro  r8  expiredr   s    r/   validzNBaseApiClient._get_aiohttp_session.<locals>._RefreshableAsyncCredentials.valid  s+    <<,,||008888r.   )rp  r  )r)   r*   r+   r,   r   r   rW   r}   ry  r   rh  r}  r  r  s   @r/   _RefreshableAsyncCredentialsrm  z  s[    
Z" *-47BFsCx. 9T 9 9r.   r~  c                        e Zd ZefdeddfdZy)@BaseApiClient._get_aiohttp_session.<locals>.AiohttpClientSession	_warningsr0   Nc                 `    | j                   s"| dd}| j                  | j                  |d<   y y y )NzUnclosed client session)client_sessionmessagesource_traceback)closed_source_traceback)r   r  contexts      r/   r  zHBaseApiClient._get_aiohttp_session.<locals>.AiohttpClientSession.__del__  s?    "&4G %%1,0,B,Bg() 2 r.   r)   r*   r+   r3  r   r  r-   r.   r/   AiohttpClientSessionr    s    +3 	CS 	C 	Cr.   r  c                        e Zd ZefdeddfdZy)?BaseApiClient._get_aiohttp_session.<locals>.AiohttpTCPConnectorr  r0   Nc                    | j                   ry | j                  sy | j                  j                         D cg c]  }t        |       }}| j	                          | |dd}| j
                  | j
                  |d<   y y c c}w )NzUnclosed connector)	connectorconnectionsr  r  )_closed_connsvaluesrepr_closer  )r   r  r   connsr  s        r/   r  zGBaseApiClient._get_aiohttp_session.<locals>.AiohttpTCPConnector.__del__  s    \\$(KK$6$6$89$8q47$8%9
++-"-'
 ##/*.*@*@G&' 0 :s   A>r  r-   r.   r/   AiohttpTCPConnectorr    s    +3 	AS 	A 	Ar.   r  )limitT)r  	trust_envread_bufsize)rL  rI  google.auth.aio.credentialsr   "google.auth.aio.transport.sessionsr"   rQ  r  _loopr  r   ClientSessionTCPConnectorr   )r   AsyncCredentialsr"   r~  r  r  s         r/   _get_aiohttp_sessionz"BaseApiClient._get_aiohttp_sessionp  s    
 $)D)D)F!OM	9+; 	94 !77STX7Y Z$$$ &&(%  ''  &&002	C!6!6 	CA 4 4 A$ 3'a0'd    [  s)   D5D B0D	DDDDrF   c                    d| j                   }| j                  }|r|j                        n|r|j                        nd}|sdt        j                  t
        j                  j                  dt        j                               t
        j                  j                  d            }dt        t        j                     dt        j                  dt        j                  ffd	} |||       |||      fS )
zEnsures the SSL context is present in the HTTPX client args.

    Creates a default SSL context if one is not provided.

    Args:
      options: The http options to check for SSL context.

    Returns:
      A tuple of sync/async httpx client args.
    verifyNSSL_CERT_FILESSL_CERT_DIRcafilecapathargsctxr0   c                 $   | r| j                        s| xs i j                         } || <   | j                         }|j                         D ]?  }|t        j                  t        j
                  j                        j                  vs=||= A |S -  Sets the SSL context in the client args if not set.

      Does not override the SSL context if it is already set.

      Args:
        args: The client args to to check for SSL context.
        ctx: The SSL context to set.

      Returns:
        The client args with the SSL context included.
      )r6   r   inspect	signaturer   Clientr   
parametersr  r  copied_argsrR   r  s       r/   
_maybe_setz7BaseApiClient._ensure_httpx_ssl_ctx.<locals>._maybe_set  s     &)
  "VIIKk!!##g''(=(=>III# $ r.   )rb  rc  r6   r-  create_default_contextr4   r5   certifiwherer   r   
StringDict
SSLContext)rF   r  
async_argsr  r  r  s        @r/   rC  z#BaseApiClient._ensure_httpx_ssl_ctx  s     FD**J  	   ^^F+  
 &&A/c
w))*^^ 
		4 	4:s# r.   c                    d| j                   }|r|j                        nd}|sdt        j                  t        j
                  j                  dt        j                               t        j
                  j                  d            }dt        t        j                     dt        j                  dt        j                  ffd	} |||      S )
  Ensures the SSL context is present in the async client args.

    Creates a default SSL context if one is not provided.

    Args:
      options: The http options to check for SSL context.

    Returns:
      An async aiohttp ClientSession._request args.
    r-  Nr  r  r  r  r  r0   c                 $   | r| j                        s| xs i j                         } || <   | j                         }|j                         D ]?  }|t        j                  t        j
                  j                        j                  vs=||= A |S r  )r6   r   r  r  r   r  _requestr  r  s       r/   r  z9BaseApiClient._ensure_aiohttp_ssl_ctx.<locals>._maybe_set  s     &)
  "VIIKk!!##$$W%:%:%C%CDOOP # $ r.   rc  r6   r-  r  r4   r5   r  r  r   r   r  r  rF   r  r  r  r  s       @r/   rO  z%BaseApiClient._ensure_aiohttp_ssl_ctx  s     F**J$.*..
 DC&&A/c
w))*^^ 
		8 j#&&r.   c                    d| j                   }|r|j                        nd}|sdt        j                  t        j
                  j                  dt        j                               t        j
                  j                  d            }dt        t        j                     dt        j                  dt        j                  ffd	} |||      S )
r  r-  Nr  r  r  r  r  r0   c                    | r| j                        s| xs i j                         } || <   | j                         }|j                         D ]1  }|t        j                  t              j
                  vs)|dk7  s/||= 3 |S )r  r-  )r6   r   r  r  
ws_connectr  r  s       r/   r  z;BaseApiClient._ensure_websocket_ssl_ctx.<locals>._maybe_setW  s{     &)
  "VIIKk!!##g''
3>>>3%<# $ r.   r  r  s       @r/   rS  z'BaseApiClient._ensure_websocket_ssl_ctx;  s     F**J$.*..
 DC &&A/c
w))*^^ 
		2 j#&&r.   c                     t         xrE | j                  j                  xs i j                  d      d u xr | j                  j                  d u S )N	transport)r   r9  rc  r6   rK  r   s    r/   rM  zBaseApiClient._use_aiohttpr  sS     	 	<117R<<[I	< 22d:	r.   c                    | j                   xr | j                  xs | j                  }| j                  r|s| j                  S t	        | j
                  j                        }|j                  d      j                         S )Nwss)scheme)	rf   r   r  r1  r   r9  r[   rb   geturl)r   ra  	url_partss      r/   _websocket_base_urlz!BaseApiClient._websocket_base_url|  sk    <<9DMMJdll$7 !!!++445IU+2244r.   c                    | j                   5  | j                  s1t        | j                        \  | _        }| j                  s|| _        | j                  rt	        | | j                        cddd       S t        d      # 1 sw Y   yxY w)z/Retrieves the access token for the credentials.r*  N0Could not resolve API token from the environment)r<  r8  ro   rf   get_token_from_credentialsRuntimeError)r   rf   s     r/   _access_tokenzBaseApiClient._access_token  sp    			%.t||%D"7|| $,			)$0A0AB 
	 MNN 
	s   AB6BB
c                 x  K   | j                   {| j                  t        j                         | _        | j                  4 d{    | j                   t        j                         | _         ddd      d{    | j                   S | j                   S 7 Q7 # 1 d{  7  sw Y   | j                   S xY ww)a[  Lazily initializes and returns an asyncio.Lock for async authentication.

    This method ensures that a single `asyncio.Lock` instance is created and
    shared among all asynchronous operations that require authentication,
    preventing race conditions when accessing or refreshing credentials.

    The lock is created on the first call to this method. An internal async lock
    is used to protect the creation of the main authentication lock to ensure
    it's a singleton within the client instance.

    Returns:
        The asyncio.Lock instance for asynchronous authentication operations.
    N)r=  r>  r  r;  r   s    r/   _get_async_auth_lockz"BaseApiClient._get_async_auth_lock  s      $		,	,	4.5lln+444  ("),,.$
 54    4   	 54444    sH   AB:BB:&B.B:9B:B:B:B7 B#!B7(B:c                   K   | j                   s| j                          d{   }|4 d{    | j                   sHt        j                  t        | j
                         d{   \  | _         }| j
                  s|| _        ddd      d{    | j                   rt        | | j                          d{   S t        d      7 7 7 h7 ?# 1 d{  7  sw Y   OxY w7 ,w)z>Retrieves the access token for the credentials asynchronously.Nr*  r  )r8  r  r  	to_threadro   rf    async_get_token_from_credentialsr  )r   async_auth_lockrf   s      r/   rv  z!BaseApiClient._async_access_token  s     "7799o    -4->->. (
$$
W "DL ! 3



  
 KLL% : 
( !sr    C*C
C*CC*5C&C'CC*C)C*;C(<C*C*CC*C%CC%!C*http_methodr\   request_dictc                    |j                         D cg c]  }|j                  d      s| }}|D ]  }||=  |rQt        |t              rt	        | j
                  |      }n6t	        | j
                  t        j                  |            }n| j
                  }d}| j                  r|dk(  r|j                  d      rd}| j                  rt|j                  d      sc|sa| j                  s| j                  rI| j                  r|j                  t        j                  k(  s d| j                   d| j                   d|z   }|j                  d| }	n|j                   d| }	|j                  |j                  st!        d	      |j                  }
t#        |d
      r,|j$                  r t'        j(                  ||j$                         |
}| j                  r$| j                  r| j                  s| j*                  r7|j                  t        j                  k(  rt-        |
|      }nBt-        |
|	      }n5| j                  r)|j                  t        j                  k(  rt-        |
|      }| j*                  r&| j*                  j                  d      rt/        d      t1        |j2                        }|j4                  t!        d      t7        |j4                  |       t9        |||j4                  ||      S c c}w )N_Fr6   zpublishers/google/modelsTz	projects/z/locations/r^   zBase URL must be set.
extra_bodyzauth_tokens/z4Ephemeral tokens can only be used with the live API.zRequest headers must be set.r{   rz   r<   r|   ru   )rK   ra   r   r   rT   r9  r5  r  rf   r   r1  r7  r   
COLLECTIONrA  r[   rl   rg  r  r   recursive_dict_updater  re   r(   rw   ru   r<   rZ   ry   )r   r  r\   r  r!  rR   keys_to_deletepatched_http_optionsquery_vertex_base_modelsversioned_pathr[   rz   rU   s                r/   _build_requestzBaseApiClient._build_request  s    &2%6%6%8P%8cCNN3<Oc%8NP
s
  	L+	.1 

  2 : :< H 
 "//$5 OO67!%,(\\T]]  $<<''( k$--BTId''/4&zn.::;1TFCn 	%%-#,,.//%..h 	$l3 ++##
,77 C  LLT]]<< 
6
6%%& Hd+

 	 88M<T<TT(D)c||//?%
@  00D0L0LM##+566"$$&8 $,," w Qs
   K5K5http_requeststreamc                    d }| j                   r| j                  s| j                  rd| j                          |j                  d<   | j
                  r9| j
                  j                  r#| j
                  j                  |j                  d<   |j                  rt        j                  |j                        nd }n`|j                  rTt        |j                  t              s.|j                  rt        j                  |j                        nd }n|j                  }| j                         rt        |j                        }| j                  Kt!        | j
                  d      | _        t#        j$                         }| j                  j'                  |       | j                  j(                  r-d|v r)d|v r|j+                  dd	      }n|j+                  dd
      }| j                  j-                  |j.                  j1                         |||j                  |j2                  |      }ne| j4                  j7                  |j.                  |j                  ||j                  |j2                        }| j4                  j9                  ||      }t:        j<                  j?                  |       tA        |j                  |r|      S |jB                  g      S )Nrs  rt  ru  r   )max_refresh_attemptsgoogleapis.comsandboxsandbox.googleapis.commtls.sandbox.googleapis.commtls.googleapis.com)r{   rz   r|   r<   ru   r  r{   rz   r   r<   ru   r  )"r  rf   r   r  r<   r8  rw  r|   r   dumpsr   r   rF  rW   rz   rE  r   r   default_client_cert_sourceconfigure_mtls_channel_is_mtlsreplacerq  r{   upperru   rG  build_requestsendr   r   raise_for_responser   text)r   r  r  r|   rz   client_cert_sourcer   httpx_requests           r/   _request_oncezBaseApiClient._request_once-  sp   
 )-D}}$,,$--078J8J8L7M.Nl?+			t00AA.. 	23 /;.?.?TZZ))*Td			,++U32>2C2CL--.$""$!!#  !c		!	!	)#4!"$
  "<<>  77	
 
	!	!	*	*/?3/F&(E# ,.CD#))11$$**,&&&& 2 h ((66$$&&&& 7 m ##((v(Fh
OO&&x0f( 3;==/ r.   c                    |rgt        |t              rt        di |n|}|j                  r>t	        |j                        }t        j                  di |} || j                  ||      S | j                  | j                  ||      S Nr-   )	r   r}   r   rR  r   r   rU  r  rV  r   r  r!  r  parameter_modelrd  r   s          r/   r  zBaseApiClient._requestj  s      d+ 
%
%  
	&	&!/"?"?@!!1L1T''v>>;;t))<@@r.   c                 "  K   d }| j                   r| j                  s| j                  rmd| j                          d {    |j                  d<   | j
                  r9| j
                  j                  r#| j
                  j                  |j                  d<   |j                  rUt        |j                  t              s/t        j                  |j                        j                  d      }n|j                  }|r*| j                         ro| j                          d {   | _        |j                   }| j#                         rzt%        j&                         }| j                  j)                  |       d {    | j                  j*                  r-d|v r)d|v r|j-                  dd      }n|j-                  dd	      }	  | j                  j.                  d|j0                  ||j                  |t3        j4                  |j6                  
      d| j8                   d {   }tV        jX                  j[                  |       d {    t]        |d      r|j^                  }ta        |j                  |      S | jb                  je                  |j0                  |j                   ||j                  |j6                        }| jb                  jg                  ||       d {   }	tV        jX                  j[                  |	       d {    ta        |	j                  |	      S | j                         r| j                          d {   | _        |j                   }| j#                         rzt%        j&                         }| j                  j)                  |       d {    | j                  j*                  r-d|v r)d|v r|j-                  dd      }n|j-                  dd	      }	  | j                  j.                  d|j0                  ||j                  |t3        j4                  |j6                  
      d| j8                   d {   }tV        jX                  j[                  |       d {    |}
t]        |
d      r|
j^                  }
ta        |
j                  |
ji                          d {   g      S | jb                  j/                  |j0                  |j                   |j                  ||j6                         d {   }	tV        jX                  j[                  |	       d {    ta        |	j                  |	jh                  g      S 7 7 :7 7 ># t2        j:                  t2        j<                  t2        j>                  t2        j@                  tB        jD                  f$ r}tG        jH                  dtK        jL                  dd      z          d {  7   tN        jQ                  d|z         | jS                  | jT                        | _        | j                          d {  7  | _         | j                  j.                  d|j0                  ||j                  |t3        j4                  |j6                  
      d| j8                   d {  7  }Y d }~d }~ww xY w7 j7 7 7 r7 7 v7 R7 # t2        j:                  t2        j<                  t2        j>                  t2        j@                  tB        jD                  f$ rl}tG        jH                  dtK        jL                  dd      z          d {  7   tN        jQ                  d|z         | jS                  | jT                        | _        | j                          d {  7  | _         | j                  j.                  d|j0                  ||j                  |t3        j4                  |j6                  
      d| j8                   d {  7  }tV        jX                  j[                  |       d {  7   |}t]        |d      r|j^                  }ta        |j                  |ji                          d {  7  g      cY d }~S d }~ww xY w7 7 ]w)Nrs  rt  ru  r   r  r  r  r  r  totalr  r   r   	   z!Retrying due to aiohttp error: %s	_responser  r  r{   rz   r<   r   ru   r-   )5r  rf   r   rv  r<   r8  rw  r|   r   r   r   r  encoderM  r  rL  rz   rI  r   r  r  r  r  rq  r{   r   ClientTimeoutru   rP  ClientConnectorErrorClientConnectorDNSErrorClientOSErrorServerDisconnectedErrorauth_exceptionsTransportErrorr  sleeprandomrandintr7   r?  rO  r9  r   r   raise_for_async_responserg  r  r   rJ  r  r  r  )r   r  r  r|   rz   r  r   r   r  client_responseunwrapped_responseunwrapped_retry_responses               r/   _async_request_oncez!BaseApiClient._async_request_once~  s     !D }}$,,$--$22445
6 ?+ 
		t00AA.. 	23 ))51zz,++,33G<  				&*&?&?&A A&&(#>>@
%%<<    ""++0@C0GCKK*,Ic KK 02GHc	840088 !(("**++,2F2FG 77 (@ oo66x@@@8[) ''(H,,h77 00>>&&   (( (( ? 
 !% 8 8 = = !> !
 
 oo66GGGO33_EE				&*&?&?&A A&&(#>>@
%%<<    ""++0@C0GCKK*,Ic KK 02GHc0	840088 !(("**++,2F2FG 77 ( 88B
B
B$,
'5!3!=!= ((1C1H1H1J+J*K J !% 8 8 @ @&&   (( (( !A !
 
 oo66GGGO33o6J6J5KLL{ 5 !B ((++!!++**
 	 a&..A"667
7
7
++9A=
> **4+=+=> 
1 )-(A(A(C"C"C$
840088 !(("**++,2F2FG 77  (	0 	A
 	H !B C ,K ((++!!++**
 	 a&..A"667
7
7
++9A=
> **4+=+=> 
1 )-(A(A(C"C"C$
840088 !(("**++,2F2FG 77  ( 88B
B
B*2
"-{;'?'I'I$&..-224445 9	D
 	Hs  ;bUC bUAb6U7Ab?A!U!  U!U! %"bZ1Bb"Z4#&b	Z7
>bZ:	Ab Z=!Ab)A![	 
[ &[	 1[2A[	 3[
4[	 <Abb		&b/b0&bbbU! !AZ.1/Z) W#!AZ)1X42A+Z)Z Z)#b)Z..b4b7b:b=b [	 [	 [	 	Ab/b	]
Ab^A+b`	'b.`1/Ab1a42	b;b<bbbbc                 >  K   |rot        |t              rt        di |n|}|j                  rFt	        |j                        }t        j                  di |} || j                  ||       d {   S | j                  | j                  ||       d {   S 7 )7 wr  )	r   r}   r   rR  r   r   rW  r  rX  r  s          r/   _async_requestzBaseApiClient._async_request%  s       d+ 
%
%  
	&	&!/"?"?@&&66433\6JJJ""  ,   Ks$   A-B/B0$BBBBc                     t        | j                  t              r| j                  j                         }|S | j                  }|S r   )r   r9  r   
model_dump)r   copieds     r/   get_read_only_http_optionsz(BaseApiClient.get_read_only_http_options:  s?    $$$i0!!,,.f M !!fMr.   c                     | j                  ||||      }| j                  ||d      }|j                  r|j                  d   nd}t        |j                  |      S )NFr  r   r   r<   body)r  r  r   SdkHttpResponser<   )r   r  r\   r  r!  r  r   response_bodys           r/   rq  zBaseApiClient.requestA  se     &&T<L }}\<}FH'/'?'?  #R  8#3#3-HHr.   c              #   &  K   | j                  ||||      }| j                  ||d      }|j                         D ]  }t        j                  |      }	 |j                  d      rUt        j                  |      }	t        j                  j                  |	j                  di       j                  d      |	|       t        |j                   |        y # t        j                  j                  $ r t        j                  d|z         Y Sw xY ww)NTr  	{"error":errorr   1Failed to decode chunk that contains an error: %sr  )r  r  r   r   r  ra   r   r   r   raise_errorr6   decoderr   r7   debugr  r<   )
r   r  r\   r  r!  r  session_responser   
chunk_dump
chunk_jsons
             r/   request_streamedzBaseApiClient.request_streamedQ  s      &&T<L }}\<}M!**,::e$j  -zz*-*
//
%
%nnWb)--f5 $4$<$<:NN - \\)) ?*L	
 		s+   ADA&C:D5DDDDc                    K   | j                  ||||      }| j                  ||d       d {   }|j                  r|j                  d   nd}t        |j                  |      S 7 8w)NFr  r!  r  r   r   r  )r  r  r   r  r<   )r   r  r\   r  r!  r  resultr  s           r/   async_requestzBaseApiClient.async_requestn  sv      &&T<L &&!U '  F 281G1GF**1-RM6>>FF	s   ,A)A'9A)c                    K   | j                  ||||      }| j                  ||d       d {   fd} |       S 7 w)NTr,  c                   K   2 3 d {   } t        j                  |       }	 |j                  d      r]t        j                  |      }t        j
                  j                  |j                  di       j                  d      |       d {    t        j                  |       7 7 !# t         j                  j                  $ r t        j                  d|z         Y Vw xY w6 y w)Nr!  r"  r   r#  r  )r   r  ra   r   r   r   raise_error_asyncr6   r%  r   r7   r&  r  r<   )r   r(  r)  r   s      r/   async_generatorz=BaseApiClient.async_request_streamed.<locals>.async_generator  s     ! IZZ&
	"";/J/J//33w+//7   h&6&6ZHHI

 ||++ 	
,,AJN 		 "sU   C/C-B.C-C/A)B2B0B2C/.C-0B225C*'C/)C**C/)r  r  )r   r  r\   r  r!  r  r2  r   s          @r/   async_request_streamedz$BaseApiClient.async_request_streamed  s[      &&T<L ((!T )  HI$ -s   ,AA Ar!  	file_path
upload_urlupload_sizec                    t        |t        j                        r| j                  ||||      S t	        |d      5 }| j                  ||||      cddd       S # 1 sw Y   yxY w)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.
      http_options: The http options to use for the request.

    returns:
          The HttpResponse object from the finalize request.
    r4  rbN)r   ioIOBase
_upload_fdopen)r   r5  r6  r7  r!  files         r/   upload_filezBaseApiClient.upload_file  se    , )RYY'__
Z<    	4 D*k  
 !  s   AA$r>  c                   d}|r|n| j                   }t        |t              r|j                  d      nt	        |dd      }|rFt        |      }t        |      }t        |j                  |j                  |j                              }	 |j                  t              }	d}
|	rt        |	      }
d}|
|z   |k\  r|dz  }t        |t              r|j                  d      n|j                  }|Ft        | j                   t              r| j                   j                  n| j                   j                  }t        |      }t        |t              r|j                  di       nt	        |di       xs i }|rt        |      ni }|j                  |t!        |      t!        |
      d	       t#        ||       d}|t$        k  rp| j&                  j)                  d
|||	|      }|j*                  j                  d      rn4t,        t.        |z  z  }|dz  }t1        j2                  |       |t$        k  rp||
z  }j*                  j                  d      dk7  rn||k  rt5        d      t6        j8                  j;                  |       |j*                  j                  d      dk7  rt5        d      t=        |j*                  |j>                  g      S )a  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.
      http_options: The http options to use for the request.

    returns:
          The HttpResponse object from the finalize request.
    r   r[   Nr  netlocupload
, finalizeru   r<   zX-Goog-Upload-CommandzX-Goog-Upload-OffsetzContent-LengthPOSTr  x-goog-upload-statusr   activeFAll content has been uploaded, but the upload status is not finalized.final6Failed to upload file: Upload status is not finalized.r   ) r9  r   r}   r6   rL   r   r   rb   r  rB  read
CHUNK_SIZEr   ru   rw   updaterW   rZ   MAX_RETRY_COUNTrG  rq  r<   INITIAL_RETRY_DELAYDELAY_MULTIPLIERtimer  rl   r   r   r  r   r  )r   r>  r6  r7  r!  offsetr[   rc   parsed_upload
file_chunk
chunk_sizeupload_commandru   rU   user_headersupload_headersretry_countr   delay_secondss                      r/   r<  zBaseApiClient._upload_fd  s   ( F#/<T5G5GL lD) 	$\:t4 
 X&kz*m

 
  ''0B0B ! j 99Z(jj	_
n	f		+,& d+ 

9
%## 
 
 $,,d3 &&##++ 	
 2': d+ 

9b
)i4: 
 .:tL)rn#1"%f+
O 	
 %^5GHk/)%%--"& . 
  67
+/?/LMq

=! /) 
f					4	5	A		
 	
k r OO&&x023w>OPP((8==/JJr.   c                   | j                  d|i |      }d}|j                  rFt        |j                  t              s t	        j
                  |j                        }n|j                  }| j                  j                  |j                  |j                  |j                  ||j                        }t        j                  j                  |       t        |j                  |j!                         g      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
    r6   r\   r  r!  Nr  r   r   )r  r|   r   r   r   r  rG  rq  r{   rz   r<   ru   r   r   r  r   rM  r   )r   r\   r!  r  r|   r   s         r/   download_filezBaseApiClient.download_file%  s     &&Dr ' L )-D))51zz,++,  !!))""$$$$ * H OO&&x0x}}&7k! r.   c                  K   t        |t        j                        r| j                  ||||       d{   S t	        j
                  |      }|j                  d       d{   }|4 d{    | j                  ||||       d{   cddd      d{    S 7 k7 ?7 67 7 # 1 d{  7  sw Y   yxY ww)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.
      http_options: The http options to use for the request.

    returns:
          The HttpResponse object from the finalize request.
    r4  Nr9  )r   r:  r;  _async_upload_fdanyioPathr=  )r   r5  r6  r7  r!  r>  fds          r/   async_upload_filezBaseApiClient.async_upload_fileL  s     * )RYY'((
Z< )    ZZ	"d4 b**
Kl + 
 
 
 !
 s{   3C B!-C #B#$
C .B%/C 2B+B'B+C B)C #C %C 'B+)C +B=1B42B=9C c          	      ^  K   d}|r|n| j                   }t        |t              r|j                  d      nt	        |dd      }|rFt        |      }t        |      }t        |j                  |j                  |j                              }| j                         r| j                          d{   | _        	 t        |t        j                        r|j                  t               }	n|j                  t                d{   }	d}
|	rt#        |	      }
d}|
|z   |k\  r|dz  }t        |t              r|j                  d      n|j$                  }|Ft        | j                   t              r| j                   j$                  n| j                   j$                  }t'        |      }t        |t              r|j                  di       nt	        |di       xs i }|rt        |      ni }|j)                  |t+        |      t+        |
      d	       t-        ||       d}d}|t.        k  r| j                  j1                  d
||	|t3        j4                  |             d{   }|j6                  j                  d      rn<t8        t:        |z  z  }|dz  }t=        j>                  |       d{    |t.        k  r||
z  }||j6                  j                  d      dk7  rn||k  rtA        d      9tB        jD                  jG                  |       d{    |)|j6                  j                  d      dk7  rtA        d      tI        |j6                  |jK                          d{   g      S 	 t        |t        j                        r|j                  t               }	n|j                  t                d{   }	d}
|	rt#        |	      }
d}|
|z   |k\  r|dz  }t        |t              r|j                  d      n|j$                  }|Ft        | j                   t              r| j                   j$                  n| j                   j$                  }t'        |      }t        |t              r|j                  di       nt	        |di       xs i }|rt        |      ni }|j)                  |t+        |      t+        |
      d	       t-        ||       d}d}|t.        k  r| jL                  j1                  d
||	||       d{   }|(|j6                  r|j6                  j                  d      rn4t8        t:        |z  z  }|dz  }tO        j>                  |       |t.        k  r||
z  }||j6                  j                  d      dk7  rn||k  rtA        d      +tB        jD                  jG                  |       d{    |)|j6                  j                  d      dk7  rtA        d      tI        |j6                  |jJ                  g      S 7 d7 7 7 p7 
7 7 i7 $7 iw)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.
      http_options: The http options to use for the request.

    returns:
          The HttpResponse object from the finalized request.
    r   r[   NrA  rC  rD  ru   r<   rE  rF  r   )r{   rz   r|   r<   ru   zX-Goog-Upload-Statusr   rH  rI  rJ  rK  rL  r  rG  )(r9  r   r}   r6   rL   r   r   rb   r  rB  rM  r  rL  r:  r;  rM  rN  r   ru   rw   rO  rW   rZ   rP  rq  r   r  r<   rQ  rR  r  r  rl   r   r   r  r   r  rJ  rS  )r   r>  r6  r7  r!  rT  r[   rc   rU  rV  rW  rX  ru   rU   rY  rZ  r[  r   r\  r  s                       r/   rc  zBaseApiClient._async_upload_fdm  s2    ( F#/<T5G5GL lD) 	$\:t4 
 X&kz*m

 
  ''0B0B ! j $($=$=$??ddBII&yy,*!YYz22*
:*!+-
L
(. <. Y'&& 	
 ? D..5   ((%%-- 
 4G< ,- Y+,	26<" 	
 0<l+%3$'K!*o
 	
 	'~7IJO+0088$++2DE 9  ( !!"89-1A;1NO-

+m,
,
, O+ 	*   $$%;<H
&   H OO44X>>>

""#9:gED
 	
 


8==?-B,C 
 dBII&yy,*!YYz22*
:*!+-
L
(. ,- Y'%% 	
 ? D..5   ((%%-- 
 4G< ,- Y+,	26<" 	
 0<l+%3$'K!*o
 	
 	'~7IJO+"&":":"B"B $( #C # / )!))!))--.DE-1A;1NO-

+
**]
#! O+$ 	*'''++,BCxO
&  E N OO44_EEE

%%%))*@AWLD
 	
 

!
!O4H4H3I C @
 3J - ? .C 3J< Fs   B-X-/X0AX-XEX-XAX-,X-X-;AX-XAX-(X"
)AX-<X%=EX-X(A!X-'AX-X+AX-X-X-X-X-"X-%X-(X-+X-c          	      P  K   | j                  d|i |      }d}|j                  rUt        |j                  t              s/t	        j
                  |j                        j                  d      }n|j                  }| j                         r| j                          d{   | _	        | j                  j                  |j                  |j                  |j                  |t        j                  |j                                d{   }t"        j$                  j'                  |       d{    t)        |j                  |j+                          d{   g      j,                  d   S | j.                  j                  |j                  |j                  |j                  ||j                   	       d{   }t"        j$                  j'                  |       d{    t)        |j                  |j+                         g      j,                  d   S 7 z7 7 7 7 h7 Cw)
r^  r6   r_  Nr   r   r  r`  r   r  )r  r|   r   r   r   r  r  rM  r  rL  rq  r{   rz   r<   r   r  ru   r   r   r  r   rM  r   rJ  )r   r\   r!  r  r|   r   r  s          r/   async_download_filez!BaseApiClient.async_download_file8  s     &&Dr ' L !D))51zz,++,33G<  $($=$=$??d,,44$$&&''l.B.BC 5  h OO44X>>>


x}})>(?A 
 #66>>$$&&&& ?  o OO44_EEE

!
!0D0D0F/GA 1 @ ? *? Fsn   BH&HA(H&H&H&.H/'H&H 
A"H&9H":&H& H$!8H&H&H& H&"H&$H&response_modelc                      y r   r-   )r   rk  s     r/   _verify_responsezBaseApiClient._verify_responser  s    r.   c                     | j                   j                  s&| j                  r| j                  j                          | j                  r| j                  j                          yy)zCloses the API client.N)r9  rH  rG  r  rE  r   s    r/   r  zBaseApiClient.closeu  sM     **t/A/A
 
$$&  r.   c                   K   | j                   j                  s"| j                  j                          d{    | j                  r:| j                   j
                  s#| j                  j                          d{    yyy7 K7 	w)zCloses the API async client.N)r9  rK  rJ  r   rL  rN  r  r   s    r/   r   zBaseApiClient.aclose~  sp      00$$++---T%7%7%F%F!!''))) &G .)s"   4BBAB:B;BBc                     	 | j                   j                  s| j                          	 t	        j
                         j                  | j                                y# t        $ r Y >w xY w# t        $ r Y yw xY w)zCloses the API client when the object is garbage collected.

    ADK uses this client so cannot rely on the genai.[Async]Client.__del__
    for cleanup.
    N)r9  rH  r  r  r  r  r  r   r   s    r/   r  zBaseApiClient.__del__  sh    ,,

 ,,T[[];	  

  
s"   &A 1A* 	A'&A'*	A65A6)NNNNNNr   )Fr{  r  )Br)   r*   r+   r,   r   rh  rW   ri   rj   rm   r   r   r   rF  rI  r   r  staticmethodr   r
   r   r  rC  rO  rS  rM  r  r  r  r;  r  r   rv  r}   r   ry   r  r   r  r  r  r  r  r  rq  r   r*  r.  r3  r:  r;  intr?  r<  r   ra  rg  rd  	AsyncFilerc  rj  r   rm  r  r   r  r-   r.   r/   r  r  U  s   @ "&#CG# $26@?@? }@? FKK33??@	@?
 }@? @? ./@?D
T 
d S!>?S!j ??W!3!334? ?B 1'{ 1'w7I7I 1' 1'f 4' 4'9K9K 4' 4'lD 53 5OS O!',, !2MsCx M8 37ii i f%	i
 ./i i\ ;; ; 	;@ 37	AA ./A 	A
 A* 7<eM%eM/3eMeMT 37	 ./ 	
 *'*<*<  37II I f%	I
 ./I I* 37OO O f%	O
 ./O $,-OD 37GG G f%	G
 ./G G, 37!! ! f%	!
 ./! !R 37
sBII~&
 
 	
 ./
 
L 37aKIIaK aK 	aK ./aK aKN 37	%% ./	%
 S%Z%Z 37
sBII~&
 
 	
 ./
 
N 37I"))U__S112I I 	I ./I I^ 37	55 ./	5
 S%Z5t	W->-> 	4 	'*r.   r  rp  c                     |j                   s|j                  st        |       |j                  st        d      |j                  S )=Refreshes the authentication token for the given credentials.r  )r|  rx  rt   r  )rp  rm   s     r/   r  r    s>    
  1 1			
I
JJ			r.   c                   K   |j                   s|j                  sm| j                          d{   }|4 d{    |j                   s|j                  s"t        j                  t
        |       d{    ddd      d{    |j                  st        d      |j                  S 7 |7 s7 ;7 -# 1 d{  7  sw Y   =xY ww)ru  Nr  )r|  rx  r  r  r  rt   r  )rp  rm   r  s      r/   r  r    s     
  1 1"7799O			K$5$5k::: 
 
		
I
JJ			 : 	; sf   ,CB+
CB-C6B33B/4B38CB1(C-C/B31C3C9B<:CC)qr,   r  collections.abcr   r   dataclassesr   r  r:  r   r   rX   r4   r  r-  r@   r:  rS  typingr   r   r   r   r	   r
   r   urllib.parser   r   r3  rd  r  google.authri   google.auth.credentialsr   google.auth.transportr   rr   r   r   r  r   pydanticr   r   r   requests.structuresr   r   r   r   r   r   typesr   r   r   r  r   r   websockets.asyncio.clientr   r  ModuleNotFoundErrorwebsockets.clientr   r   rQ  	multidictr    r  r"   	getLoggerr7   rN  r   rP  rQ  rR  r@  rl   r(   rW   r;   r}   rE   rT   r   rr  rZ   re   ro   rt   rw   ry   r   r   r   r   r   r   r  r   r  r  AsyncClientr  r  rj   rm   r  r  r-   r.   r/   <module>r     s  "
  %  !  	    	  
 
   V V V ! #      / & < 5   $  3      $ 2 #  6= +
 (G 
		5	6
   !4L 2
 2:# :"8DcN 8t 8@)48E#s(^E19%s
:K1LE	EGC Gs Gs G%T	* u[#5E/F "k k 
eE3J'(
e_
 " " "~ ~J     !12  w7I7I  Fell *u(( (B BJ2

((44
 	
((44 	EC  6556  s$   I %I# I I #I,+I,