
    ÁjXy                       d dl m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mZmZ d dlmZmZ d dlmZmZ d dlZddlmZmZmZmZ ddlmZmZ dd	lmZm Z  dd
l!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0  ee0d      Z1 ee/d      Z2erd dl3m4Z5 dZ6dZ7eg e8f   Z9eg df   Z: e
deejv                  ejx                  f         Z= e
dee$e   e%e   f         Z> G d d      Z? G d de,e=e>f         Z@	 	 	 	 	 	 	 	 	 	 	 	 d%dZA	 	 	 	 	 	 	 	 d&dZBd'd ZC G d! d"e@ejv                  e$e   f   e      ZD G d# d$e@ejx                  e%e   f   e       ZEy)(    )annotationsN)	TYPE_CHECKINGAnyUnionMappingTypeVarCallableSequence	Awaitablecast)partialcached_property)Selfoverride   )HeadersTimeoutNotGiven	not_given)asyncifyis_given)	AnthropicAsyncAnthropic)FinalRequestOptions)StreamAsyncStream)AnthropicError)MiddlewareInput)DEFAULT_MAX_RETRIES
BaseClientmerge_headers   )refresh_credentialsload_default_credentialsgoogle_cloud)extra)Credentialsznhttps://claude.googleapis.com/v1alpha/projects/{project}/locations/{location}/workspaces/{workspace_id}/invokeglobalzstr | Awaitable[str]_HttpxClientT)bound_DefaultStreamTc                       e Zd ZdZddZddZy)_GoogleCredentialsStateu  Holder for the Google credentials object, its refresh lock, and the project
    ADC resolved.

    Shared between a client and its ``copy()``/``with_options()`` clones (when the
    credential configuration is inherited) so a lazily-loaded ADC credential is
    minted once — not once per clone — and concurrent loads/refreshes are
    serialized: google-auth credential objects are not safe to ``refresh()``
    concurrently.
    c                R    t        j                         | _        || _        d | _        y N)	threadingLock_lockcredentialsadc_project)selfr3   s     I/tmp/pip-target-k_scjv0h/lib/python/anthropic/lib/google_cloud/_client.py__init__z _GoogleCredentialsState.__init__:   s     ^^%
5@'+    c                ~   | j                   5  | j                  t               \  | _        | _        nA| j                  j                  s| j                  j
                  st        | j                         | j                  j
                  }|st        d      t        |t              sJ |cddd       S # 1 sw Y   yxY w)zJReturn a valid access token, loading ADC / refreshing as needed. Blocking.NzKCould not resolve a GCP access token from the configured Google credentials)
r2   r3   _load_adc_credentialsr4   expiredtoken_refresh_credentialsr   
isinstancestr)r5   r<   s     r6   r<   z_GoogleCredentialsState.token?   s    ZZ 
	'5J5L2 $"2!!))1A1A1G1G$T%5%56$$**E$%rsseS)))
	 
	 
	s   BB33B<N)r3   GoogleCredentials | NonereturnNonerA   r?   )__name__
__module____qualname____doc__r7   r<    r8   r6   r-   r-   /   s    ,
r8   r-   c                      e Zd ZU dZded<   ded<   ded<   ded<   d	ed
<   d	ed<   eedd              Zej                  dd       Zedd       Z	ddZ
y)BaseGoogleCloudClientzMarker base so ``_is_base_client()`` keeps these clients off the first-party
    credential-discovery chain (it matches only the exact ``Anthropic`` /
    ``AsyncAnthropic`` classes). Auth is handled entirely by this helper.
str | Noneworkspace_id_projectr?   	_locationr-   _creds_statebool_base_url_deferred_base_url_overriddenc                    | j                   S r/   )	_base_urlr5   s    r6   base_urlzBaseGoogleCloudClient.base_urlZ   s     ~~r8   c                    d| _         | j                  t        |t        j                        r|      | _        y t        j                  |            | _        y )NF)rQ   _enforce_trailing_slashr>   httpxURLrT   )r5   urls     r6   rV   zBaseGoogleCloudClient.base_url_   sA     #(55ZUYY=Wcl]b]f]fgj]klr8   c                .    | j                   j                  S )zThe ``google.auth`` credentials in use (explicit or lazily-loaded ADC), if any.

        Distinct from ``.credentials``, which is the base client's first-party
        credentials provider and is always ``None`` on this client.
        )rO   r3   rU   s    r6   google_credentialsz(BaseGoogleCloudClient.google_credentialsf   s       ,,,r8   c                    | j                   sy| j                  t        d      | j                  J t        j                  | j                  | j                  | j                        | _        d| _         y)zDerive and set the real base URL once the project is known.

        Called on every request (after the project back-fill from ADC, if any);
        a no-op once the base URL has been derived.
        NzNo `project` was provided and one could not be resolved from Google credentials. Pass the `project` argument, set the `ANTHROPIC_GOOGLE_CLOUD_PROJECT` environment variable, or provide `base_url` directly.projectlocationrL   F)rQ   rM   r   rL   DEFAULT_URL_TEMPLATEformatrN   rV   rU   s    r6   _resolve_deferred_base_urlz0BaseGoogleCloudClient._resolve_deferred_base_urlo   sw     &&==  H    ,,,,33MMDNNIZIZ 4 
 #(r8   N)rA   z	httpx.URL)r[   zhttpx.URL | strrA   rB   )rA   r@   rA   rB   )rD   rE   rF   rG   __annotations__propertyr   rV   setterr]   rd   rH   r8   r6   rJ   rJ   N   sz    M N))   __m m - -(r8   rJ   c                b    | | S |J ||ryt        d      t        j                  |||      S )a  base_url (arg or ``ANTHROPIC_GOOGLE_CLOUD_BASE_URL``, resolved by the caller)
    > derived template.

    Returns ``None`` when derivation must wait for the project to be back-filled
    from Google credentials on the first request (``allow_deferred_project``).
    NzNo `project` was provided. Pass `project`, set the `ANTHROPIC_GOOGLE_CLOUD_PROJECT` environment variable, or provide `base_url` directly.r_   )
ValueErrorrb   rc   rV   r`   ra   rL   allow_deferred_projects        r6   _resolve_base_urlrm      sV      ###!D
 	
  &&wXd&eer8   c                (    | r||t        d      y y )Nzx`skip_auth` is mutually exclusive with `token_provider` and `credentials`; `skip_auth` disables authentication entirely.)rj   	skip_authtoken_providerr3   s      r6   _reject_skip_auth_conflictrr      s+     n0K4K<
 	
 5Lyr8   c                Z    dD ]&  }t        | |d      }t        |t              s!|s$|c S  y)u   Best-effort project from an explicit credentials object — service-account /
    impersonated credentials usually know theirs.)
project_idquota_project_idN)getattrr>   r?   )r3   attrvalues      r6   _project_from_credentialsry      s7     3 T40eS!eL r8   c                  |    e Zd ZU dZded<   ded<   dddddddeedddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Zee	dd
              Z
ee	dd              Ze	dd       ZddZe	dd       Ze	dd       Zddeeeddedeeddddi d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZeZ xZS )AnthropicGoogleCloudag  Synchronous client for the first-party Anthropic API served through Google's
    gateway (Claude Platform on Google Cloud).

    The whole first-party surface is proxied verbatim (no URL or body rewriting), so
    this subclasses the full ``Anthropic`` client. Authentication is a GCP bearer
    token; the deprecated Completions endpoint is not exposed.
    rK   rL   rP   
_skip_authNFr`   ra   rL   rq   r3   rp   rV   timeoutmax_retriesdefault_headersdefault_queryhttp_client
middleware_strict_response_validationc          
        t        |||       || _        || _        t        |      | _        |t
        j                  j                  d      }|t        }|| _	        |t
        j                  j                  d      }|t
        j                  j                  d      }||t        |      }|| _        |t
        j                  j                  d      }|du| _        |t
        j                  j                  d      }||r|t        d      || _        t        || j                  | j                  | j                  | 	      }|du | _        t"        | I  ||nd
||	|
||||       d| _        d| _        y)u  Construct a new synchronous Claude Platform on Google Cloud client.

        Auth precedence (first match wins, unless ``skip_auth=True``):
          1. ``token_provider`` — a callable returning a GCP access token, invoked per request.
          2. ``credentials`` — a ``google.auth`` Credentials object, refreshed as needed.
          3. Application Default Credentials (``google.auth.default``).

        Args:
            project: GCP consumer project id (or ``ANTHROPIC_GOOGLE_CLOUD_PROJECT``,
                else ``GOOGLE_CLOUD_PROJECT``). Only needed when the base URL must be
                derived; if omitted there, it is taken from an explicit ``credentials``
                object when it exposes one, or back-filled from ADC on the first request.
            location: GCP location (or ``ANTHROPIC_GOOGLE_CLOUD_LOCATION``). Optional —
                defaults to ``global``, the region the gateway should normally be
                addressed through.
            workspace_id: The Anthropic workspace ID (or ``ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID``).
                Required unless ``skip_auth`` is set with an explicit ``base_url``.
            skip_auth: For pre-authenticated proxies — skips token attachment. A
                workspace ID is still needed to derive the base URL; pass ``base_url``
                to construct without one. Mutually exclusive with the credential
                arguments.
        ro   NANTHROPIC_GOOGLE_CLOUD_LOCATIONANTHROPIC_GOOGLE_CLOUD_PROJECTGOOGLE_CLOUD_PROJECTANTHROPIC_GOOGLE_CLOUD_BASE_URL#ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_IDyNo workspace ID found. Set the `workspace_id` argument or the `ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID` environment variable.rk    rV   r~   r   r   r   r   r   r   rr   r|   _token_providerr-   rO   osenvirongetDEFAULT_LOCATIONrN   ry   rM   rR   rj   rL   rm   rQ   superr7   api_key
auth_tokenr5   r`   ra   rL   rq   r3   rp   rV   r~   r   r   r   r   r   r   resolved_base_url	__class__s                   r6   r7   zAnthropicGoogleCloud.__init__   s   P 	#Y~cno#-3K@zz~~&GHH'H!?jjnn%EFG?jjnn%;<G?{6/<Gzz~~&GHH %-D$8!::>>*OPL x7KN  )-MM^^**'0=
 #4t"; +<*G&R#+'#!(C 	 	
" r8   c                     yzQCompletions endpoint is deprecated and not supported for the Google Cloud client.NrH   rU   s    r6   completionsz AnthropicGoogleCloud.completions2       r8   c                    i S r/   rH   rU   s    r6   auth_headersz!AnthropicGoogleCloud.auth_headers8  s	    
 	r8   c                     y r/   rH   r5   headerscustom_headerss      r6   _validate_headersz&AnthropicGoogleCloud._validate_headers?  s     	r8   c                    | j                   }|G |       }t        j                  |      r)t        t        |      j                          t        d      |S | j                  j                         S )Nzp`token_provider` returned an awaitable. Async token providers are only supported on `AsyncAnthropicGoogleCloud`.)	r   inspectisawaitabler   r   closer   rO   r<   r5   providerr<   s      r6   
_get_tokenzAnthropicGoogleCloud._get_tokenE  sj    ''JE""5)S% &&($@  L  &&((r8   c                    | j                   si| j                  r]| j                  A| j                  5| j                  j                          | j                  j                  | _        | j                          |S r/   )r|   rQ   rM   r   rO   r<   r4   rd   r5   optionss     r6   _prepare_optionsz%AnthropicGoogleCloud._prepare_optionsS  s^    4#:#:}}$)=)=)E !!'') $ 1 1 = =++-r8   c                    | j                   ry |j                  j                  d      y d| j                          |j                  d<   y NAuthorizationzBearer r|   r   r   r   r5   requests     r6   _prepare_requestz%AnthropicGoogleCloud._prepare_request`  sC    ????/; -4T__5F4G+H(r8   r`   ra   rL   rq   r3   rp   rV   r~   r   r   r   r   set_default_headersr   set_default_query_extra_kwargsc               v   ||t        d      ||t        d      | j                  }|t        ||      }n||}| j                  }|i ||}n||}||n| j                  }t        |      xs t        |      }d}d}|rt        |      r|nd}t        |      r|nd}n$|s"| j                  }| j                  j                  }|| j                  sd}n||n| j                  } | j                  d||n| j                  ||n| j                  t        |      r|n| j                  ||||t        |t               r| j"                  n||	xs | j$                  t        |      r|n| j&                  ||t        |
t               r| j(                  n|
| j*                  d|}|s|s| j                  |_        |S )u  Create a new client re-using the current options, with optional overrides.

        Passing either of ``token_provider`` / ``credentials`` replaces the
        inherited credential configuration wholesale — the source not passed is
        cleared, so an explicit lower-precedence credential takes effect.
        ``workspace_id=None`` clears the workspace ID; ``project`` /
        ``location`` overrides re-derive a template-derived base URL.
        NPThe `default_headers` and `set_default_headers` arguments are mutually exclusiveLThe `default_query` and `set_default_query` arguments are mutually exclusiver`   ra   rL   rq   r3   rp   rV   r~   r   r   r   r   r   r   rH   rj   _custom_headersr!   _custom_queryr|   r   r   rO   r3   rR   rV   r   rM   rN   rL   r>   r   r~   _clientr   _middlewarer   r5   r`   ra   rL   rq   r3   rp   rV   r~   r   r   r   r   r   r   r   r   r   paramsresolved_skip_authcredential_overriddennew_token_providernew_credentialsnew_base_urlclients                            r6   copyzAnthropicGoogleCloud.copym  s   8 &+>+Jopp$):)Fkll&&&#G_=G ,)G##$00-0F*&F*3*?YT__ ( 8 QH[<Q3748 3;N3KQU-5k-BkO#!%!5!5"//;;OD$=$= 48L'/';8L 
&2G!)!5X4>>)1,)?TEVEV-'(!$.w$ADLLw#3t||'/'<$BRBR# +5j(+Kt''Q[(,(H(H
 
" %-? #'"3"3Fr8   )r`   rK   ra   rK   rL   rK   rq   zTokenProvider | Noner3   r@   rp   rP   rV   str | httpx.URL | Noner~   !float | Timeout | None | NotGivenr   intr   Mapping[str, str] | Noner   Mapping[str, object] | Noner   httpx.Client | Noner    Sequence[MiddlewareInput] | Noner   rP   rA   rB   re   rA   zdict[str, str]r   r   r   r   rA   rB   rC   r   r   rA   r   r   zhttpx.RequestrA   rB   )"r`   rK   ra   rK   rL   str | None | NotGivenrq   zTokenProvider | None | NotGivenr3   #GoogleCredentials | None | NotGivenrp   bool | NonerV   r   r~   r   r   r   r   +Sequence[MiddlewareInput] | None | NotGivenr   int | NotGivenr   r   r   r   r   r   r   r   r   Mapping[str, Any]rA   r   rD   rE   rF   rG   rf   r   r   r7   r   r   r   rg   r   r   r   r   r   r   with_options__classcell__r   s   @r6   r{   r{      se    
 ###'/304+/5>.4859+/7;,1!g g 	g
 !g -g .g g )g 3g g 2g 3g )g 5g  &*!g" 
#gR      
  
) 
 
 
I 
I ##.7:C;D!%+/5>+/BK&/488<599=+-%U U 	U
 ,U 8U 9U U )U 3U )U @U $U 2U 6U  3!U" 7#U$ )%U& 
'Un Lr8   r{   c                  |    e Zd ZU dZded<   ded<   dddddddeedddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fd	Zee	dd
              Z
ee	dd              Ze	dd       ZddZe	dd       Ze	dd       Zddeeeddedeeddddi d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZeZ xZS )AsyncAnthropicGoogleCloudzAsynchronous client for the first-party Anthropic API served through Google's
    gateway (Claude Platform on Google Cloud). See ``AnthropicGoogleCloud``.
    rK   rL   rP   r|   NFr}   c          
        t        |||       || _        || _        t        |      | _        |t
        j                  j                  d      }|t        }|| _	        |t
        j                  j                  d      }|t
        j                  j                  d      }||t        |      }|| _        |t
        j                  j                  d      }|du| _        |t
        j                  j                  d      }||r|t        d      || _        t        || j                  | j                  | j                  | 	      }|du | _        t"        | I  ||nd
||	|
||||       d| _        d| _        y)a  Construct a new asynchronous Claude Platform on Google Cloud client.

        ``token_provider`` may be sync or async; sync providers are run off the
        event loop. See ``AnthropicGoogleCloud`` for the full argument and
        auth-precedence docs.
        ro   Nr   r   r   r   r   r   rk   r   r   r   r   s                   r6   r7   z"AsyncAnthropicGoogleCloud.__init__  s   0 	#Y~cno#-3K@zz~~&GHH'H!?jjnn%EFG?jjnn%;<G?{6/<Gzz~~&GHH$,D$8!::>>*OPL x7KN  )-MM^^**'0=
 #4t"; +<*G&R#+'#!(C 	 	
 r8   c                     yr   rH   rU   s    r6   r   z%AsyncAnthropicGoogleCloud.completions"  r   r8   c                    i S r/   rH   rU   s    r6   r   z&AsyncAnthropicGoogleCloud.auth_headers(  s	     	r8   c                     y r/   rH   r   s      r6   r   z+AsyncAnthropicGoogleCloud._validate_headers-  s    r8   c                  K   | j                   }|t        j                  |      r# |        d {   }t        |t              sJ |S  t        |              d {   }t        j                  |      r
| d {   }t        |t              sJ |S  t        | j                  j                                d {   S 7 7 e7 H7 
wr/   )	r   r   iscoroutinefunctionr>   r?   r   r   rO   r<   r   s      r6   r   z$AsyncAnthropicGoogleCloud._get_token1  s     ''**84&j(!%--- -(8,..E""5)#eS)))L6Xd//556888 )
 /# 9sE   .CC +CCC;C<?C;C<CCCCc                   K   | j                   s{| j                  ro| j                  S| j                  G t	        | j
                  j                                d {    | j
                  j                  | _        | j                          |S 7 1wr/   )	r|   rQ   rM   r   r   rO   r<   r4   rd   r   s     r6   r   z*AsyncAnthropicGoogleCloud._prepare_optionsB  st     4#:#:}}$)=)=)E 8ht00667999 $ 1 1 = =++-	 :s   ABB2Bc                   K   | j                   ry |j                  j                  d      y d| j                          d {    |j                  d<   y 7 wr   r   r   s     r6   r   z*AsyncAnthropicGoogleCloud._prepare_requestO  sM     ????/; -44??;L5L4M+N(5Ls   >A AAr   c               v   ||t        d      ||t        d      | j                  }|t        ||      }n||}| j                  }|i ||}n||}||n| j                  }t        |      xs t        |      }d}d}|rt        |      r|nd}t        |      r|nd}n$|s"| j                  }| j                  j                  }|| j                  sd}n||n| j                  } | j                  d||n| j                  ||n| j                  t        |      r|n| j                  ||||t        |t               r| j"                  n||	xs | j$                  t        |      r|n| j&                  ||t        |
t               r| j(                  n|
| j*                  d|}|s|s| j                  |_        |S )zCreate a new client re-using the current options, with optional overrides.

        See ``AnthropicGoogleCloud.copy`` for the override semantics.
        Nr   r   r   rH   r   r   s                            r6   r   zAsyncAnthropicGoogleCloud.copy\  s   0 &+>+Jopp$):)Fkll&&&#G_=G ,)G##$00-0F*&F*3*?YT__ ( 8 QH[<Q8<48 3;N3KQU-5k-BkO#!%!5!5"//;;OD$=$= 48L'/';8L 
&2G!)!5X4>>)1,)?TEVEV-'(!$.w$ADLLw#3t||'/'<$BRBR# +5j(+Kt''Q[(,(H(H
 
" %-? #'"3"3Fr8   )r`   rK   ra   rK   rL   rK   rq   zAsyncTokenProvider | Noner3   r@   rp   rP   rV   r   r~   r   r   r   r   r   r   r   r   httpx.AsyncClient | Noner   r   r   rP   rA   rB   re   r   r   rC   r   r   )"r`   rK   ra   rK   rL   r   rq   z$AsyncTokenProvider | None | NotGivenr3   r   rp   r   rV   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rA   r   r   r   s   @r6   r   r     se    
 ###'4804+/5>.4859047;,1!Q Q 	Q
 !Q 2Q .Q Q )Q 3Q Q 2Q 3Q .Q 5Q  &*!Q" 
#Qf        9" 
 
 
O 
O ##.7?H;D!%+/5>04BK&/488<599=+-%Q Q 	Q
 ,Q =Q 9Q Q )Q 3Q .Q @Q $Q 2Q 6Q  3!Q" 7#Q$ )%Q& 
'Qf Lr8   r   )rV   r   r`   rK   ra   r?   rL   rK   rl   rP   rA   r   )rp   rP   rq   object | Noner3   r   rA   rB   )r3   GoogleCredentialsrA   rK   )F
__future__r   r   r   r0   typingr   r   r   r   r   r	   r
   r   r   	functoolsr   r   typing_extensionsr   r   rY   _typesr   r   r   r   _utilsr   r   r   r   r   _modelsr   
_streamingr   r   _exceptionsr   r   r   _base_clientr   r    r!   _extras._google_authr#   r$   r:   r=   google.auth.credentialsr'   r   rb   r   r?   TokenProviderAsyncTokenProviderClientAsyncClientr)   r+   r-   rJ   rm   rr   ry   r{   r   rH   r8   r6   <module>r      s   " 	   c c c . ,  ; ; ( 0 * - ) * J J P   8O 2.I H
 u   S!b"889 uU\\5CTCT5T/UV+5kRUFV9V3WX >4(J}o'EF 4(nf$f f 	f
 f !f f<



 "

 	


 


G0vc{1JKY GTh 5e6G6GUXIY6Y Z\j hr8   