
    Li:                        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!m"Z" ddl#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(m+Z+ ddl,m-Z- ddl,m.Z. ddl,m/Z0 ddl,m1Z1 	 ddl2m3Z4 dZ7	 ddl8Z8dZ7erddl:m;Z;  e
jx                  d      Z=dZ>dZ?dZ@dZAdZB G d deC      ZDdeeE   fdZFd eGeEeEf   ddfd!ZHd"e-d#e-de-fd$ZId eGeEeEf   d%eeeJeKf      ddfd&ZLd'eEd(eEdeEfd)ZMd*eeEdf   dee"eEf   fd+ZNd,e"de"fd-ZOd.eeeJeKf      deeJ   fd/ZPe G d0 d1             ZQ G d2 d3      Z/d4ZRd5ZSd6ZTdZUdZVd7ZWd"ee1   de)j                  fd8ZY G d9 d:e#j                        Z[ G d; d<e#j                        Z] G d= d>      Z^y# e5$ r
 ddl6m3Z4 Y #w xY w# e9$ r Y &w xY w)?zBase client for calling HTTP APIs sending and receiving JSON.

The BaseApiClient is intended to be a private module and is subject to change.
    N)	Generator)	dataclass)AnyAsyncIteratorIteratorOptionalTupleTYPE_CHECKINGUnion)urlparse)
urlunparse)Credentials)	BaseModel)ValidationError   )_common)errors)version)HttpOptions)HttpOptionsOrDict)HttpResponse)HttpRetryOptionsconnectFT)CIMultiDictProxyzgoogle_genai._api_clienti   i  @       c                       e Zd ZdZy)EphemeralTokenAPIKeyErrorz)Error raised when the API key is invalid.N)__name__
__module____qualname____doc__     V/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/google/genai/_api_client.pyr   r   W   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_keyr2   ]   sX     zz~~&6=zz~~&6=.
NNO 
	91	9T9r%   headersc                    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<   d| v r|| d   vr| d| d   z   | 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)r3   library_labellanguage_labelversion_header_values       r&   append_library_version_headersr<   n   s    %g&9&9%:;-#++"3"3"5a"88.)?!N+;<g
gl&;
;34A69NNGL7"0GLW$
g.A&B
B  
 "W-@%AA   ')#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 )Nr3   )
model_copyr3   r   model_fieldskeysgetattrsetattrr<   )r=   r>   copy_optionoptions_headerspatch_options_headershttp_options_keyskeypatch_values           r&   patch_http_optionsrK      s     ""$+''-2/'//52+
 "..335 7c
i-d3Kk3,k3 567 $";#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)r3   rL   s     r&   populate_server_timeout_headerrQ      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   )rS   )r   rS   endswith
startswithr   _replace)rR   rS   parsed_base	base_paths       r&   join_url_pathr\      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)r]   credentialsloaded_project_ids      r&   	load_authrf      sQ    #);;#6#6>? $7 $ +  
G	
J  
g	r%   rd   c                 >    ddl m} | j                   |              | S )Nr   )Request)google.auth.transport.requestsrh   refresh)rd   rh   s     r&   refresh_authrk      s    4gi 	r%   timeoutc                     | r| dz  }|S d}|S )z Converts the timeout to seconds.g     @@Nr$   )rl   rL   s     r&   get_timeout_in_secondsrn      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)HttpRequestr3   urlmethoddataNrl   )r    r!   r"   dictrN   __annotations__r   objectbytesrl   r   floatr$   r%   r&   rp   rp      sA    S>
(
+d3;&''!'8E?!r%   rp   c            	       2   e Zd Z	 	 ddeeeef   ej                  d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   Nr3   zCIMultiDictProxy[str]response_streambyte_streamc           	         t        |t              r|| _        nt        |t        j                        rC|j                         D ci c]#  }|dj                  |j                  |            % c}| _        nZt        |      j                  dk(  rB|j                         D ci c]#  }|dj                  |j                  |            % c}| _        d| _        || _        || _        y c c}w c c}w )Nz, r      )
isinstancert   r3   httpxHeadersrB   joinget_listtyper    getallstatus_coderz   r{   )selfr3   rz   r{   rI   s        r&   __init__zHttpResponse.__init__   s     '4 dl	GU]]	+;B<<>47#tyy))#./
/dl 
g		#5	59@25#tyy,-
-dl  D*D"Ds   (C& (C+r'   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                 ^    | j                   d   sy| j                  | j                   d         S )Nr    )rz   _load_json_from_responser   s    r&   jsonzHttpResponse.json  s/    "(()=)=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~   rz   listr   _iter_response_stream)r   chunks     r&   segmentszHttpResponse.segments	  s     $&&-'' D%6;d++E2CD				%mm --/ 3%++E223 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~   rz   r   r   _aiter_response_stream)r   r   cs      r&   r   zHttpResponse.async_segments  s     $&&-'' D%6;d++E2CD				%   446 3 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   rc   r   s    r&   byte_segmentszHttpResponse.byte_segments"  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deepcopyrC   )r   r   	attributes      r&   _copy_to_dictzHttpResponse._copy_to_dict-  s=    D$%Y L	$(MM'$	2J$Ky!Lr%   c              #     K   t        | j                  t        j                        s,t	        dt        | j                        j                   d      d}d}| j                  j                         D ]U  }|s|j                  d      r|t        d      d  (|D ]  }|dk(  r|dz  }|d	k(  s|dz  } ||z  }|dk(  sP| d}W |r| 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   data: N{r   })
r~   rz   r   Response	TypeErrorr   r    
iter_linesrX   len)r   r   balanceliner   s        r&   r   z"HttpResponse._iter_response_stream3  s     d**ENN;$../889< 
 EG$$//1  
	"3x=>""
  !8
Q,'#X
Q,'	 tme	A-2 k s   B,C/CCc                $  K   t        | j                  t        j                        xs, t        xr$ t        | j                  t
        j                        }|s,t        dt        | j                        j                   d      d}d}t        | j                  t        j                        rz	 | j                  j                         2 3 d{   }|s|j                  d      r|t        d      d  /|D ]  }|dk(  r|dz  }|d	k(  s|dz  } ||z  }|dk(  sW| d}_t        rt        | j                  t
        j                        r	 	 | j                  j                  j                          d{   }|snt|j!                  d
      j#                         }|sR|j                  d      r|t        d      d  u|D ]  }|dk(  r|dz  }|d	k(  s|dz  } ||z  }|dk(  r| d}|r| | j                  j%                          yyy7 N6 |r| | j                  j                          d{  7   y# | j                  j                          d{  7   w xY w7 # | 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   zutf-8)r~   rz   r   r   has_aiohttpaiohttpClientResponser   r   r    aiter_linesrX   r   aclosecontentreadlinedecoderstriprelease)r   is_valid_responser   r   r   r   
line_bytess          r&   r   z#HttpResponse._aiter_response_streamY  s    "4#7#7H P
4#7#79O9OP  4''(112!5  EG$&&7,..::< 	 	$ __X&s8}~&&
  aCxlgclg	 4-%\KE 
g44#'!1199BBDD*""7+224$ __X&s8}~&&
  aCxlgclg	 4-%\KE9 < + 	$$&M=	<. + ""))+++d""))+++ E@ 	$$&s   B)J,I H
HH<I I I %*J(I1 8I/9A!I1  I1 ;JHI #J IJI,%I(&I,,J/I1 1JJ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)r'   r   )r    r!   r"   r   rt   rN   r   r   r   rw   r   r   r   propertyr   r   r   r   r   r   rv   r   r   r   r   classmethodr   r$   r%   r&   r   r      s3   
 *.'+	#T#s(^U]]4KKL# S#X# e$	#,s  BC B B

3	#tT/2 
33M#$6 3	YuUCZ'8$'DE 	LDf,= L$ L$Xc] $LU'M#,> U'n c c  r%   r      g      ?g      N@)i  i  i  i  i  i  c                    | t        j                  d      ddS 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reraisec                 X    t        | t        j                        xr | j                  v S r   )r~   r   APIErrorcode)r   retriable_codess    r&   <lambda>zretry_args.<locals>.<lambda>  s     
1foo.L166_3L 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_logr.   loggingINFO)r=   r   r   r   r   s       @r&   
retry_argsr     s     _//2tDD		$	$W%5%5%H	I$--I1I/

%
%L% 
	)	)##;';



//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.kwargsr'   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__  sK    	 

jjl  
  
s   " 1 	..	==r'   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   r'   Nc                 H    |j                  dd       t        |   di | yr   r   r   s     r&   r   zAsyncHttpxClient.__init__  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__  s_    	 
 ,,T[[];  
  
s"   A 1A 	AA	AAr   r   r   s   @r&   r  r    s    s t 
	r%   r  c                      e Zd ZdZ	 	 	 	 	 	 d4dee   dee   deej                  j                  j                     dee   dee   dee   fd	Zd5d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j4                  fdZd
eeef   fdZ	 d6dededeee f   dee   d
e!f
dZ"	 d7de!ded
e#fdZ$	 	 d8de!dee   ded
e#fdZ%	 d7de!ded
e#fdZ&	 	 d8de!dee   ded
e#fdZ'd
ej$                  fdZ(	 d6dededeee f   dee   d
e)f
d Z*	 d6dededeee f   dee   d
e+e)ddf   f
d!Z,	 d6dededeee f   dee   d
e)f
d"Z-	 d6dededeee f   dee   d
ef
d#Z.dd$d%eee/j`                  f   d&ed'e1dee   d
e#f
d(Z2dd$d)e/j`                  d&ed'e1dee   d
e#f
d*Z3dd$dedee   d
eee4f   fd+Z5dd$d%eee/j`                  f   d&ed'e1dee   d
e#f
d,Z6dd$d)ee/j`                  e7jp                  e   f   d&ed'e1dee   d
e#f
d-Z9dd$dedee   d
eee4f   fd.Z:d/ejv                  d
dfd0Z<d9d1Z=d9d2Z>d9d3Z?y):BaseApiClientz8Client for calling HTTP APIs sending and receiving JSON.Nvertexaiapi_keyrd   r]   locationhttp_optionsc                    || _         d | _        | j                   7t        j                  j	                  dd      j                         dv rd| _         |s|r|rt        d      |r|rt        d      t               }t        |t              r	 t        j                  |      }nt        |t              r|}t        j                  j	                  dd       }	t        j                  j	                  d	d       }
t               }|xs |	| _        |xs |
| _        |xs || _        || _        t               | _        t%        j&                         | _        d | _        d | _        | j                   r |r|rt.        j1                  d
       d | _        no|
s|	r&|r$t.        j1                  d       d | _        d | _        nE|s|r|rt.        j1                  d       d | _        n"|
s|	r|rt.        j1                  d       d | _        |j2                  r|j2                  nd | _        | j                  s| j                  s| j                  sd| _        | j                  s?| j                  s3| j                  s't5        d       \  }| _        | j                   s|| _        | j                  xr | j                  xs | j                  }|s| j                  st        d      | j                  s| j                  dk(  rd| j"                  _        n[| j                  r0|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                  j;                         | _        | j"                  j8                  #| j                  | j"                  j8                  d<   |rt=        | j"                  |      | _        n5| j"                  j8                  t?        | j"                  j8                         | jA                  | j"                        \  }}|| _!        | j"                  jD                  r| j"                  jD                  | _#        ntI        di || _#        | j"                  jJ                  r| j"                  jJ                  | _&        ntO        di || _&        | jQ                         r%	 dd l)}| jU                  | j"                        | _+        d | _-        t]        | j"                  j^                        }| ja                  | j"                        | _1        te        jf                  di || _4        te        jj                  di || _6        y # t        $ r}t        d      |d }~ww xY w# tX        $ r Y w xY w)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_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.globalr]   z<Project or API key must be set when using the Vertex AI API.z"https://aiplatform.googleapis.com/zhttps://z-aiplatform.googleapis.com/v1beta1zMissing key inputs argument! To use the Google AI API, provide (`api_key`) arguments. To use the Google Cloud API, provide (`vertexai`, `project` & `location`) arguments.z*https://generativelanguage.googleapis.com/v1betazContent-Typezapplication/jsonzx-goog-api-keyr   r$   )7r	  custom_base_urlr+   r,   r-   lowerrc   r   r~   rt   model_validater   r2   r]   r  r
  _credentials_http_options	threadingLock_sync_auth_lock_async_auth_lock_async_auth_lock_creation_lockr.   inforR   rf   api_versionr3   striprK   r<   _ensure_httpx_ssl_ctx_async_httpx_client_argshttpx_client_httpx_clientr   httpx_async_client_async_httpx_clientr  _use_aiohttpr   _ensure_aiohttp_ssl_ctx"_async_client_session_request_argsImportError_aiohttp_sessionr   retry_options_ensure_websocket_ssl_ctx_websocket_ssl_ctxr   Retrying_retryAsyncRetrying_async_retry)r   r	  r
  rd   r]   r  r  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__  sJ    DMD}}	3S	9	?	?	A F 
  	8  
  )],%8!,!;!;L!I 
L+	.+ **..!7>K::>>"94@L!#K)kDL,DM)kDL#D$D %>>+D48DBFD' }}	A	
 KWB	
 x[B	
 K[M	
  $,, !
)
)  ]]4<<8L8L"$- ll,,&&$-d$;!T\  )$
!\\;dmmL )=)=
 	
 
(2(J#'h7 '+&:&:# t}}o%@A 	# (1d$\\G
 	

 %Qd!'/d$"02D!ED||\\'')dl				#	#	/7;||""#34-


4d 
			#	#	/&t'9'9'A'AB%)%?%?&"K" %6D!&&--::d*9[9d,,!%!3!3!F!Fd!1!F4E!Fd262N2N3
/ >BDd00>>?L"<<T=O=OPD##3l3DK ..>>Dm  8/0a78Z  s*   W '$W# 	W WW #	W/.W/r'   c                    K   | j                   | j                   j                  r5t        j                  t        j                  d      dt
              | _         | j                   S w)z#Returns the aiohttp client session.r   )limitT)	connector	trust_envread_bufsize)r/  closedr   ClientSessionTCPConnectorREAD_BUFFER_SIZEr   s    r&   _get_aiohttp_sessionz"BaseApiClient._get_aiohttp_session  sU     $(=(=(D(D%33((q1'd
    s   A$A&r=   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ctxr'   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.
      )r-   r   inspect	signaturer   Clientr   
parametersrP  rQ  copied_argsrI   rJ  s       r&   
_maybe_setz7BaseApiClient._ensure_httpx_ssl_ctx.<locals>._maybe_set  s     &)
  "VIIKk!!# #g''(=(=>III# r%   )r<  r=  r-   sslcreate_default_contextr+   r,   certifiwherer   r   
StringDict
SSLContext)r=   rP  
async_argsrQ  r[  rJ  s        @r&   r%  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\  NrK  rL  rM  rP  rQ  r'   c                 $   | r| j                        s| xs i j                         } || <   | j                         }|j                         D ]?  }|t        j                  t        j
                  j                        j                  vs=||= A |S rS  )r-   r   rU  rV  r   rE  _requestrX  rY  s       r&   r[  z9BaseApiClient._ensure_aiohttp_ssl_ctx.<locals>._maybe_set@  s     &)
  "VIIKk!!# #$$W%:%:%C%CDOOP # r%   r=  r-   r\  r]  r+   r,   r^  r_  r   r   r`  ra  r=   rb  rQ  r[  rJ  s       @r&   r,  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 )
rd  r\  NrK  rL  rM  rP  rQ  r'   c                    | r| j                        s| xs i j                         } || <   | j                         }|j                         D ]1  }|t        j                  t              j
                  vs)|dk7  s/||= 3 |S )rT  r\  )r-   r   rU  rV  
ws_connectrX  rY  s       r&   r[  z;BaseApiClient._ensure_websocket_ssl_ctx.<locals>._maybe_setz  s     &)
  "VIIKk!!# #g''
3>>>3%<# r%   rg  rh  s       @r&   r1  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   r  r=  r-   r)  r   s    r&   r+  zBaseApiClient._use_aiohttp  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)	r]   r  r
  r  r   r  rR   rY   geturl)r   r;  	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| j                  j                  s| j                  j
                  st        | j                         | j                  j
                  st        d      | j                  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  0Could not resolve API token from the environmentN)r  r  rf   r]   expiredtokenrk   RuntimeError)r   r]   s     r&   _access_tokenzBaseApiClient._access_token  s    			 O%.t||%D"7|| $,			$$D,=,=,C,C
t((
)  &&OP
P  &&O O MNNO Os   CC#C##C,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 1 1  ("),,.$
1 1    4   	1 1 1 1 1    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| j                   j                  s| j                   j                  s| j                          d{   }|4 d{    | j                   j                  s| j                   j                  s,t        j                  t        | j                          d{    ddd      d{    | j                   j                  st        d      | j                   j                  S t        d      7 y7 q7 ;7 # 1 d{  7  sw Y   $xY w7 7 7 |7 n# 1 d{  7  sw Y   ~xY ww)z>Retrieves the access token for the credentials asynchronously.Nr  ru  )
r  r{  r  	to_threadrf   r]   rv  rw  rk   rx  )r   async_auth_lockr]   s      r&   _async_access_tokenz!BaseApiClient._async_access_token  s    "7799o  	# 	#   -4->->. (
$$
W "DL	# 	# 				"	"$*;*;*A*A $ 9 9 ;;" 	E 	E&&d.?.?.E.E##L$2C2CDDD	E 	E
 $$MNN$$$KLL5 :	#
(	# 	# 	# 	# <	E E	E 	E 	E 	Es    GF
GFG5F'&F!'F'GF$AG!F="
G,F?-G0AGGG	GGAGG!F'$G'F:-F0.F:5	G?GGGGGGGhttp_methodrS   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                  rK|j                  d      s:|s8| j                  s| j                  r 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$                  rt'        |
|	      }| j$                  r&| j$                  j                  d      rt)        d      t+        |j,                        }|j.                  t        d      t1        |j.                  |       t3        |||j.                  ||      S c c}w )N_Fr-   zpublishers/google/modelsTz	projects/z/locations/rU   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.rr   rq   r3   rs   rl   )rB   rX   r~   r   rK   r  r  r	  r]   r  r#  rR   rc   hasattrr  r   recursive_dict_updater  r
  r\   r   rn   rl   r3   rQ   rp   )r   r  rS   r  r  rI   keys_to_deletepatched_http_optionsquery_vertex_base_modelsversioned_pathrR   rq   rL   s                r&   _build_requestzBaseApiClient._build_request  sZ    &2%6%6%8PcCNN3<OcPN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]]<<

c
 ||//?%
@  00D0L0LM##+566"$$&8 $,," W Qs
   I,I,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                  }|r| j                  j                  |j                  |j                  ||j                  |j                         }| j                  j#                  ||      }t$        j&                  j)                  |       t+        |j                  |r|      S |j,                  g      S | j                  j/                  |j                  |j                  |j                  ||j                         }t$        j&                  j)                  |       t+        |j                  |r|      S |j,                  g      S )NBearer Authorizationx-goog-user-projectrr   rq   r   r3   rl   r  rr   rq   r3   r   rl   )r	  r]   r  ry  r3   r  quota_project_idrs   r   dumpsr~   rw   r(  build_requestrr   rq   rl   sendr   r   raise_for_responser   textrequest)r   r  r  rs   httpx_requestr   s         r&   _request_oncezBaseApiClient._request_onceM  s   
 )-D}}$,,$--078J8J8L7M.Nl?+			t00AA.. 	23 /;.?.?TZZ))*Td			,++U32>2C2CL--.$""$((66$$&&&& 7 m ##((v(Fhoo((2


H 5=]]O  ##++$$&&&& , h oo((2


H 5=]]O r%   c                    |rgt        |t              rt        di |n|}|j                  r>t	        |j                        }t        j                  di |} || j                  ||      S | j                  | j                  ||      S Nr$   )	r~   rt   r   r0  r   r   r3  r  r4  r   r  r  r  parameter_modelr>  r   s          r&   rf  zBaseApiClient._request|  s      d+ 
%
%  
	&	&!/"?"?@!!1L1T''v>>;;t))<@@r%   c                   K   d }| j                   r| j                  s| j                  rd| j                          d {    |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                  }|r| j                         r| j                          d {   | _        	  | j                  j                  d|j                   |j"                  |j                  |t%        j&                  |j(                        d| j*                   d {   }tD        jF                  jI                  |       d {    tK        |j                  |      S | jL                  jO                  |j                   |j"                  ||j                  |j(                  
      }| jL                  jQ                  ||       d {   }tD        jF                  jI                  |       d {    tK        |j                  |      S | j                         r| j                          d {   | _        	  | j                  j                  d|j                   |j"                  |j                  |t%        j&                  |j(                        d| j*                   d {   }tD        jF                  jI                  |       d {    tK        |j                  |jS                          d {   g      S | jL                  j                  |j                   |j"                  |j                  ||j(                         d {   }tD        jF                  jI                  |       d {    tK        |j                  |jR                  g      S 7 7 7 |# t$        j,                  t$        j.                  t$        j0                  t$        j2                  f$ r}t5        j6                  dt9        j:                  dd      z          d {  7   t<        j?                  d	|z         | jA                  | jB                        | _        | j                          d {  7  | _         | j                  j                  d|j                   |j"                  |j                  |t%        j&                  |j(                        d| j*                   d {  7  }Y d }~d }~ww xY w7 7 $7  7 7 R7 .7 	# t$        j,                  t$        j.                  t$        j0                  t$        j2                  f$ r\}t5        j6                  dt9        j:                  dd      z          d {  7   t<        j?                  d	|z         | jA                  | jB                        | _        | j                          d {  7  | _         | j                  j                  d|j                   |j"                  |j                  |t%        j&                  |j(                        d| j*                   d {  7  }tD        jF                  jI                  |       d {  7   tK        |j                  |jS                          d {  7  g      cY d }~S d }~ww xY w7 X7 4w)Nr  r  r  r   r  r   r   	   z!Retrying due to aiohttp error: %sr  r  r  r$   )*r	  r]   r  r  r3   r  r  rs   r   r  r~   rw   r+  rH  r/  r  rr   rq   r   ClientTimeoutrl   r-  ClientConnectorErrorClientConnectorDNSErrorClientOSErrorServerDisconnectedErrorr  sleeprandomrandintr.   r"  r,  r  r   r   raise_for_async_responser   r*  r  r  r  )r   r  r  rs   r   r   r  client_responses           r&   _async_request_oncez!BaseApiClient._async_request_once  s     )-D }}$,,$--$22445
6 ?+ 
		t00AA.. 	23 /;.?.?TZZ))*Td			,++U32>2C2CL--.$""$				&*&?&?&A A	840088 !(("""**++L4H4HI 77 (> oo66x@@@H,,h77 00>>&&   (( (( ? 
 !% 8 8 = = !> !
 
 oo66GGGO33_EE				&*&?&?&A A"	I840088 !(("""**++L4H4HI 77 ( 88B
B
Bh..x}}1F0GH
H6 !% 8 8 @ @&&   (( (( !A !
 
 oo66GGGO33o6J6J5KLLe 5  !B ((++!!++	
 	 a&..A"667
7
7
++9A=
> **4+=+=> 
1 )-(A(A(C"C"C$
840088 !(("""**++L4H4HI 77  (	. 	A
 	H !B C1F((++!!++	
 	I a&..A"667
7
7
++9A=
> **4+=+=> 
1 )-(A(A(C"C"C$
840088 !(("""**++L4H4HI 77  ( 88B
B
Bh..x}}1F1F0GH
H/	I4
 	Hs  ;]P6D]
P9	]A+P?  P<P? "]'V(B]*V+&]V=]V	]A+V  V&V  ,V-'V  V
V  A])]*&]]&]9]<P? ?AV/V0R31AVTA5V7U:8V=]V]]]]V  V  V   A\>"/\9XA\9"Y%#A5\9['\9 \(\9)\,*	\93\>4]9\>>]]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~   rt   r   r0  r   r   r5  r  r6  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~   r  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   r3   body)r  rf  rz   SdkHttpResponser3   )r   r  rS   r  r  r  r   response_bodys           r&   r  zBaseApiClient.request(  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  rf  r   r   r  rX   r   r   r   raise_errorr-   decoderr   r.   debugr  r3   )
r   r  rS   r  r  r  session_responser   
chunk_dump
chunk_jsons
             r&   request_streamedzBaseApiClient.request_streamed8  s      &&T<L }}\<}M!**, O::e$j  -zz*-*
//
%
%nnWb)--f5 $4$<$<:NNO \\)) ?*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  rz   r  r3   )r   r  rS   r  r  r  resultr  s           r&   async_requestzBaseApiClient.async_requestU  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)NT)r  r  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  rX   r   r   r   raise_error_asyncr-   r  r   r.   r  r  r3   )r   r  r  r   s      r&   async_generatorz=BaseApiClient.async_request_streamed.<locals>.async_generators  s     ! I 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  rS   r  r  r  r  r   s          @r&   async_request_streamedz$BaseApiClient.async_request_streamedf  sS      &&T<L ((l4(PPHI$ ) Qs   +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.
    r  rbN)r~   ioIOBase
_upload_fdopen)r   r  r  r  r  files         r&   upload_filezBaseApiClient.upload_file  sn    , )RYY'__
Z<    	4  
D*k  

 
 
s   AA$r  c                   d}	 |j                  t              }d}|rt        |      }d}||z   |k\  r|dz  }|r|n| j                  }t	        |t
              r|j                  d      n|j                  }	|	Ft	        | j                  t
              r| j                  j                  n| j                  j                  }	t        |	      }
|t        |      t        |      d}t        ||
       d}|t        k  rp| j                  j                  d||||
      }|j                  j                  d      rn4t        t         |z  z  }|d	z  }t#        j$                  |       |t        k  rp||z  }j                  j                  d      d
k7  rn||k  rt'        d      t(        j*                  j-                  |       |j                  j                  d      dk7  rt'        d      t/        |j                  |j0                  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   upload
, finalizerl   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.rz   )read
CHUNK_SIZEr   r  r~   rt   r-   rl   rn   rN   rQ   MAX_RETRY_COUNTr(  r  r3   INITIAL_RETRY_DELAYDELAY_MULTIPLIERtimer  rc   r   r   r  r   r  )r   r  r  r  r  offset
file_chunk
chunk_sizeupload_commandrl   rL   upload_headersretry_countr   delay_secondss                  r&   r  zBaseApiClient._upload_fd  s   ( F
99Z(jj	_
n	f		+,&%1\t7I7Il d+ 

9
%## 
 
 $,,d3 &&##++ 	
 2':#1"%f+
On
 %^5GHk/)%%--"& . 
  67
+/?/LMq

=! /) 
f					4	5	A		
 	
a h 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
    r-   rS   r  r  Nr  r{   r   )r  rs   r~   rw   r   r  r(  r  rr   rq   r3   rl   r   r   r  r   r  r{   )r   rS   r  r  rs   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.
    r  Nr  )r~   r  r  _async_upload_fdanyioPathr  )r   r  r  r  r  r  fds          r&   async_upload_filezBaseApiClient.async_upload_file  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          	      N
  K   d}| j                         r| j                          d{   | _        	 t        |t        j
                        r|j                  t              }n|j                  t               d{   }d}|rt        |      }d}||z   |k\  r|dz  }|r|n| j                  }t        |t              r|j                  d      n|j                  }	|	Ft        | j                  t              r| j                  j                  n| j                  j                  }	t        |	      }
|t        |      t        |      d}t        ||
       d}d}|t         k  r| j                  j#                  d|||t%        j&                  |
      	       d{   }|j(                  j                  d
      rn<t*        t,        |z  z  }|dz  }t/        j0                  |       d{    |t         k  r||z  }||j(                  j                  d
      dk7  rn||k  rt3        d      t4        j6                  j9                  |       d{    |)|j(                  j                  d
      dk7  rt3        d      t;        |j(                  |j=                          d{   g      S 	 t        |t        j
                        r|j                  t              }n|j                  t               d{   }d}|rt        |      }d}||z   |k\  r|dz  }|r|n| j                  }t        |t              r|j                  d      n|j                  }	|	Ft        | j                  t              r| j                  j                  n| j                  j                  }	t        |	      }
|t        |      t        |      d}t        ||
       d}d}|t         k  r| j>                  j#                  d||||
       d{   }|(|j(                  r|j(                  j                  d      rn4t*        t,        |z  z  }|dz  }tA        j0                  |       |t         k  r||z  }||j(                  j                  d      dk7  rn||k  rt3        d      t4        j6                  j9                  |       d{    |)|j(                  j                  d      dk7  rt3        d      t;        |j(                  |j<                  g      S 7 7 7 z7 /7 7 y7 (7 $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   Nr  r  rl   r  r  r   )rr   rq   rs   r3   rl   zX-Goog-Upload-Statusr   r  r  r  r  r  r  r  )!r+  rH  r/  r~   r  r  r  r  r   r  rt   r-   rl   rn   rN   rQ   r  r  r   r  r3   r  r  r  r  rc   r   r   r  r   r  r*  r  )r   r  r  r  r  r  r  r  r  rl   rL   r  r  r   r  r  s                   r&   r  zBaseApiClient._async_upload_fd>  s+    ( F$($=$=$??ddBII&yy,*!YYz22*
:*!+-
L
(.'3|9K9K <. Y'&& 	
 ? D..5   ((%%-- 
 4G<%3%([!*o

 	'~7IJO+0088$++4FG 9  ( !!"89-1A;1NO-

+m,
,
, O+ 	*   $$%;<H
&  u ~ OO44X>>>

""#9:gED
 	
 


8==?-B,C 
 dBII&yy,*!YYz22*
:*!+-
L
(.'3|9K9K ,- Y'%% 	
 ? D..5   ((%%-- 
 4G<%3$'K!*o

 	'~7IJO+"&":":"B"B $( #C # / )!))!))--.DE-1A;1NO-

+
**]
#! O+$ 	*'''++,BCxO
&  { D OO44_EEE

%%%))*@AWLD
 	
 

!
!O4H4H3I o @
 3@ - ? .C 3@< Fs   'T%TAT%<T=DT%TAT%%T&T%4AT%TAT%!T
"AT%5T6DT%<T =A!T%AT%9T#:AT%T%T%T%T%T%T% T%#T%c          	      2  K   | j                  d|i |      }d}|j                  rFt        |j                  t              s t	        j
                  |j                        }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  r-   r  Nr   r  r  r   r  )r  rs   r~   rw   r   r  r+  rH  r/  r  rr   rq   r3   r   r  rl   r   r   r  r   r  r{   r*  )r   rS   r  r  rs   r   r  s          r&   async_download_filez!BaseApiClient.async_download_file  s     &&Dr ' L )-D))51zz,++,  $($=$=$??d,,44$$&&''0D0DE 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8H9&HH 'HH
A"H*H+&HH8HHHHHHresponse_modelc                      y r   r$   )r   r   s     r&   _verify_responsezBaseApiClient._verify_response*  s    r%   c                 f    | j                   j                  s| j                  j                          yy)zCloses the API client.N)r  r'  r(  r   r   s    r&   r   zBaseApiClient.close-  s*     **
  +r%   c                    K   | j                   j                  s"| j                  j                          d{    | j                  r#| j                  j                          d{    yy7 47 w)zCloses the API async client.N)r  r)  r*  r   r/  r   r   s    r&   r   zBaseApiClient.aclose4  s^      00$$++---!!'')))  .)s!   4A/A+-A/$A-%A/-A/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)r  r'  r   r   r  r  r  r   r   s    r&   r   zBaseApiClient.__del__=  sh    ,,

 ,,T[[];	  

  
s"   &A 1A* 	A'&A'*	A65A6)NNNNNN)r'   zaiohttp.ClientSessionr   )F)NFr   )@r    r!   r"   r#   r   boolrN   r`   ra   rd   r   r   r   rH  staticmethodr   r	   r   r`  r%  r,  r1  r+  rs  ry  r  r  r{  r   r   r  rt   rv   rp   r  r   r  rf  r  r  r  r  r  r   r  r  r  r  r  intr  r  rw   r  r  r  	AsyncFiler  r  r   r  r   r   r   r$   r%   r&   r  r    s   @ "&#CG# $26{?{? }{? FKK33??@	{?
 }{? {? ./{?z	! ??W!3!334? ?B 6'{ 6'w7I7I 6' 6'p 4' 4'9K9K 4' 4'lD 53 5OS O$!',, !2MsCx MH 37YY Y f%	Y
 ./Y Y| -- - 	-d 37	AA ./A 	A
 A* 7<zM%zM/3zMzM~ 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%	
 ./ N 37
sBII~&
 
 	
 ./
 
L 37MKIIMK MK 	MK ./MK MKf 37	%% ./	%
 S%Z%Z 37
sBII~&
 
 	
 ./
 
N 37p"))U__S112p p 	p ./p pl 37	55 ./	5
 S%Z5t	W->-> 	4 	!*r%   r  )_r#   r  collections.abcr   r   dataclassesr   rU  r  r   r   rO   r+   r  r\  r7   r  r  typingr   r   r   r   r	   r
   r   urllib.parser   r   r  r^  google.authr`   google.auth.credentialsr   r   pydanticr   r   r   r   r   r   r   typesr   r   r   r  r   websockets.asyncio.clientr   rk  ModuleNotFoundErrorwebsockets.clientr   r   r.  	multidictr   	getLoggerr.   r  rG  r  r  r  rc   r   rN   r2   rt   r<   rK   rx   r  rQ   r\   rf   rk   rn   rp   r   r   r   r   r   r   r`  r   rW  r   AsyncClientr  r  r$   r%   r&   <module>r     s  "
  %  !  	    	  
 
   V V V ! #     /   $      $ 2 #6=
 +
 ( 
		5	6
   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_
 " " "W W|    !12 w7I7I Bell *u(( (u uu  6556  s$   6G ?G# G G #G,+G,