
    Lh                     4   U d Z ddlZddlmZmZ ddlmZ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mZmZmZmZmZmZ ddlmZ ddlmZ ej8                  rddlZddlZdd	l m!Z! dd
l mZ ddl mZ  e
jD                  d      Z#ejH                  dk\  r+ejJ                  Z&ej,                  ejJ                  fZ'ddlm(Z( nejR                  Z&ej,                  fZ'ddl*m(Z( ej8                  rddl+m,Z- ddl.m/Z0 n/eZ-ejb                  e2d<   eZ0ejb                  e2d<   	 ddl+m,Z- ddl.m/Z0 ddddZ4e4jk                         D  ci c]  \  } }|| 
 c}} Z6dede7ejp                     de9fdZ:ddde!jv                  de<de<d e=de<f
d!Z>de!jv                  d"e<de<fd#Z?d$e!jv                  d%e9de<fd&Z@d'ej                  deBej                     fd(ZCd$e!jv                  d"e<dee<   fd)ZDd*edej                  fd+ZFd,ej                  dej                  fd-ZId.eej                  eej                     f   deBej                     fd/ZJd0eej                  eBej                     f   deBej                     fd1ZLd2ej                  dej                  fd3ZMd2ej                  dej                  fd4ZNd2ej                  dej                  fd5ZPd6eej                     dej                  fd7ZSd8eeeBej                     ej                  eBej                     f      deBej                     fd9ZTd:eeee<ef         deeBej                        fd;ZVeej                  ej                  ej                  f   ZYd<eeYej                  df   dej                  fd=ZZde!jv                  d>eeBej                     eBej                     eYf   deeBe<   eBej                     f   fd?Z[d>eeej                  ej                  ej                  f      deBej                     fd@Z^dAej                  ddfdBZ_dCeddfdDZ`dAedee!jv                     ddfdEZa	 dpdFdGdAej                  dee!jv                     dHeej                     dIe9ddf
dJZbdKedee!jv                     dej                  fdLZddCeej                  ef   de(ej                     fdMZfdee!jv                     dCeej                  ef   deej                     fdNZgdCeej                  ef   deej                     fdOZjdCej                  deej                     fdPZlde!jv                  dCedeeej^                  ef      fdQZmde!jv                  dCeBe   deBej^                     fdRZnde!jv                  dSe<de<fdTZode!jv                  dUej                  dej                  fdVZrde!jv                  dUej                  dej                  fdWZudXee<ej                  f   dej                  fdYZxdXeye<ef   deye<ef   fdZZzde!jv                  dSe<de<fd[Z{d\e<de<fd]Z|d^Z}d_Z~d`ZdaZd$e!jv                  dbej                  defdcZdSeee<ej                  ej                  ej                  f      de<fddZdee<deej                  e<f   fdfZd<ej                  dej                  fdgZd>eeej                     ej                  f   deBej                     fdhZ	 	 dqdieeeej                     ej                  f      dje9dej                  fdkZdleej                  eej                     f   dej                  fdmZdneBej                     deBeye<ef      fdoZy# e3$ r dZ-dZ0Y cw xY wc c}} w )rz"Transformers for Google GenAI SDK.    N)IterableMapping)EnumEnumMeta)AnyGenericAliasListOptionalSequenceUnion   )mcp_to_gemini_tool)get_value_by_path)_api_client)_common)typeszgoogle_genai._transformers)   
   )	TypeGuard)ClientSession)ToolMcpClientSessionMcpToolexactMatchSpecbleuSpec	rougeSpec)exact_matchbleu
rouge_specobjclsreturnc                 z     t         t              st        |d      syt         fd|j                  D              S )a  Checks if an object has all of the fields of a Pydantic model.

  This is a duck-typing alternative to `isinstance` to solve dual-import
  problems. It returns False for dictionaries, which should be handled by
  `isinstance(obj, dict)`.

  Args:
    obj: The object to check.
    cls: The Pydantic model class to duck-type against.

  Returns:
    True if the object has all the fields defined in the Pydantic model, False
    otherwise.
  model_fieldsFc              3   6   K   | ]  }t        |        y wN)hasattr).0fieldr    s     M/var/www/html/venv/lib/python3.12/site-packages/google/genai/_transformers.py	<genexpr>z#_is_duck_type_of.<locals>.<genexpr>^   s     ?UWS% ?s   )
isinstancedictr'   allr$   )r    r!   s   ` r*   _is_duck_type_ofr/   K   s4     T'#~"> 
?c.>.>?	??       )collection_hierarchy_depthclientresource_namecollection_identifierr2   c                   |j                  | d       xr | d| j                  d      dz   |k(  }| j                  r|j                  d      r|S |j                  d      rd| j                   d| S |j                  | d      rd| j                   d| j                   d| S |r"d| j                   d| j                   d| d| S |S |r| d| S |S )a|  Prepends resource name with project, location, collection_identifier if needed.

  The collection_identifier will only be prepended if it's not present
  and the prepending won't violate the collection hierarchy depth.
  When the prepending condition doesn't meet, returns the input
  resource_name.

  Args:
    client: The API client.
    resource_name: The user input resource name to be completed.
    collection_identifier: The collection identifier to be prepended. See
      collection identifiers in https://google.aip.dev/122.
    collection_hierarchy_depth: The collection hierarchy depth. Only set this
      field when the resource has nested collections. For example,
      `users/vhugo1802/events/birthday-dinner-226`, the collection_identifier is
      `users` and collection_hierarchy_depth is 4. See nested collections in
      https://google.aip.dev/122.

  Example:

    resource_name = 'cachedContents/123'
    client.vertexai = True
    client.project = 'bar'
    client.location = 'us-west1'
    _resource_name(client, 'cachedContents/123',
      collection_identifier='cachedContents')
    returns: 'projects/bar/locations/us-west1/cachedContents/123'

  Example:

    resource_name = 'projects/foo/locations/us-central1/cachedContents/123'
    # resource_name = 'locations/us-central1/cachedContents/123'
    client.vertexai = True
    client.project = 'bar'
    client.location = 'us-west1'
    _resource_name(client, resource_name,
      collection_identifier='cachedContents')
    returns: 'projects/foo/locations/us-central1/cachedContents/123'

  Example:

    resource_name = '123'
    # resource_name = 'cachedContents/123'
    client.vertexai = False
    _resource_name(client, resource_name,
      collection_identifier='cachedContents')
    returns 'cachedContents/123'

  Example:
    resource_name = 'some/wrong/cachedContents/resource/name/123'
    resource_prefix = 'cachedContents'
    client.vertexai = False
    # client.vertexai = True
    _resource_name(client, resource_name,
      collection_identifier='cachedContents')
    returns: 'some/wrong/cachedContents/resource/name/123'

  Returns:
    The completed resource name.
  /r   	projects/z
locations//locations/)
startswithcountvertexaiprojectlocation)r3   r4   r5   r2   $should_prepend_collection_identifiers        r*   _resource_namer@   a   s!   J 
"
"&;%<A#>
?? $ ##1]O
4
:
:3
?!
C	#$	 ' __,		!	!,	/(-99		!	!%:$;1"=	>(FOO3DAm_UU	-(FOO3DAF[E\\]^k]lmm+%&a77r0   modelc                 @   |st        d      | j                  r[|j                  d      s"|j                  d      s|j                  d      r|S d|v r|j                  dd      \  }}d| d| S d| S |j                  d      r|S |j                  d	      r|S d| S )
Nzmodel is required.r8   models/publishers/r7   r   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr<   r:   split)r3   rA   	publishermodel_ids       r*   t_modelrI      s    	
)
**__%I&M*l	!KKQ/i9+XhZ88(00	"l			.	)lugr0   
api_clientbase_modelsc                 *    | j                   r|ryy|ryy)Nzpublishers/google/modelsmodelstunedModels)r<   )rJ   rK   s     r*   t_models_urlrO      s     'r0   responsec                 *   | sg S | j                  d      }||S | j                  d      }||S | j                  d      }||S | j                  d      | j                  d      g S t        j                  d       t        j                  d|        g S )NrM   rN   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)rP   rM   tuned_modelspublisher_modelss       r*   t_extract_modelsr[      s     
I/7||H/E&M5=\\-5P,9A: ! ll=!-
,,}
%
-I
NN67
LLDhOIr0   c                    t        | |      }|sy |j                  d      r+| j                  rd| j                   d| j                   d| S |j                  d      r+| j                  rd| j                   d| j                   d| S |S )NrD   r8   r9   r7   rC   z/publishers/google/)rI   r:   r<   r=   r>   )rJ   rA   s     r*   t_caches_modelr]     s     *e
$%	
m$)<)< J&&'{:3F3F2GqP 	"z':':z))*+j6I6I5JJ]^c]deeLr0   imgc                    	 dd l }|j                  }t        j                         }|t        | |j                        s| j                  dk(  r| j                  |d       d}n| j                  |d       d}|j                  d       |j                         }t        j                  ||      S # t        $ r d }Y w xY w)	Nr   RGBAPNG)formatz	image/pngJPEGz
image/jpeg)	mime_typedata)PIL.PngImagePluginPngImagePluginImportErrorioBytesIOr,   PngImageFilemodesaveseekreadr   Blob)r^   PILrg   bytesiord   re   s         r*   pil_to_blobrs     s    ''N JJL' 
S.55
6	V	HHWUH#IHHWVH$I	,,q/	$	id	33! 
 Ns   B0 0B>=B>function_responsec                     | st        d      t        | t              rt        j                  j                  |       S t        | t        j                        r| S t        dt        |              )Nzfunction_response is required.zOCould not parse input as FunctionResponse. Unsupported function_response type: )	rE   r,   r-   r   FunctionResponsemodel_validater/   	TypeErrortype)rt   s    r*   t_function_responserz   .  sp     

5
66!4(!!001BCC)5+A+AB
	$$():$;#<	> r0   function_responsesc                     | st        d      t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w )Nz function_responses are required.)rE   r,   r   rz   )r{   rP   s     r*   t_function_responsesr}   >  sJ     

7
88"H-:LMh)MM 2344 Ns   Ablobsc                 v    t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w r&   )r,   listt_blob)r~   blobs     r*   t_blobsr   L  s4     t%*+TF4L++5M? ,   6r   c                    | st        d      t        | t        j                        r| S t	        | t
              rt        j                  j                  |       S d| j                  j                  j                         v r4	 dd l
}|j                  j                  }|t	        | |      rt        |       S t        dt        |              # t        $ r d }Y =w xY w)Nzblob is required.imager   z6Could not parse input as Blob. Unsupported blob type: )rE   r/   r   rp   r,   r-   rw   	__class____name__lower	PIL.ImageImagerh   rs   rx   ry   )r   rq   	PIL_Images      r*   r   r   U  s    	
(
))dEJJ'Kd::$$T**''--//))//i D)!<>tDzlK	   is    C
 
CCc                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzimage/Unsupported mime type: r   rd   r:   rE   r   s    r*   t_image_blobr   o  @    	$	^^11(;K,T^^,>?@@r0   c                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzaudio/r   r   r   s    r*   t_audio_blobr   v  r   r0   partc                    | t        d      t        | t              rt        j                  |       S t        | t        j                        rX| j                  r| j                  st        d      t        j                  j                  | j                  | j                        S t        | t              r 	 t        j                  j                  |       S t        | t        j                        r| S d| j                  j                   j#                         v rH	 dd l}|j&                  j&                  }|+t        | |      rt        j                  t+        |             S t        d	t-        |              # t        j                  $ r6 t        j                  t        j                  j                  |             cY S w xY w# t(        $ r d }Y w xY w)
Nzcontent part is required.)textz$file uri and mime_type are required.)file_urird   )	file_datar   r   )inline_datazUnsupported content part type: )rE   r,   strr   Partr/   Fileurird   from_urir-   rw   pydanticValidationErrorFileDatar   r   r   r   r   rh   rs   ry   r   rq   r   s      r*   t_partr   }  sg   	\
0
11c::4  dEJJ'884>>=>>::DNNKKdGZZ&&t,, dEJJ'K''--//))//i D)!<ZZK$5664T$ZLABB ## GZZ%.."?"?"EFFG  is%   7E7 G 7AG ?G GGpartsc                     | t        | t              r| st        d      t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w )Nzcontent parts are required.)r,   r   rE   r   )r   r   s     r*   t_partsr     sP     ]z%.u
2
33t%*+TF4L++5M? ,s   Apredictionsc           
          | sy g }| D ]Z  }|j                  d      s|j                  t        j                  t        j                  |d   d   |d   d                      \ |S )Nr   gcsUri
imageBytes)gcs_uriimage_bytes)r   )rU   appendr   GeneratedImager   )r   images
predictions      r*   t_image_predictionsr     sq     
& 	j~~gmm


KK$W-h7(1,?	 
-r0   contentc                    | t        d      t        | t        j                        r| S t	        | t
              r 	 t        j                  j                  |       S t        | t        j                        r t        j                  t        |       g      S t        | t        j                        r:| j                  rt        j                  | g      S t        j                  | g      S t        j                  |       S # t        j                  $ rJ t        |       }|j                  rt        j                  |g      cY S t        j                  |g      cY S w xY w)Nzcontent is required.r   )rE   r/   r   Contentr,   r-   rw   r   r   r   function_callModelContentUserContentr   r   )r   possible_parts     r*   	t_contentr     s'    _
+
,,gu}}-N]]))'22 guzz*F7O#455guzz*    	'+ gY/
 
			)) ## Wom (( 

M?
3   7s   C> >AEEEcontentsc                    t        |t              r|D cg c]  }t        |       }}nt        |      g}| j                  rg }|D ]  }|t        |t              rt
        j                  j                  |      }|j                  B|j                  D ]?  }|j                  r|j                  |j                         +t        j                  d       A  |S |S c c}w )Nz/Non-text part found, only returning text parts.)r,   r   r   r<   r-   r   r   rw   r   r   r   rV   rW   )r3   r   r   transformed_contents
text_partsr   s         r*   t_contents_for_embedr     s     $>FG7Ig.GG%h/0__J' 	Q		gt$MM009'==$mm Qdyy		*nnNP	Q	Q % Hs   Cc                 V   | t        | t              r| st        d      t        | t              st        |       gS g }g }dt        t
        j                  t        f   dt        t
        j                     fd}dt
        j                  dt        fddt        t
        j                     dt        ffddt        t
        j                     d	t        t
        j                     dd ffd
dt        t
        j                     d	t        t
        j                     dt
        j                  dd ffd}| D ]  }t        |t
        j                        st        |t              rQ ||       t        |t              r&|j                  t        j                  |             l|j                  |       ~ ||      r ||||       t        |t              r/|j                  t
        j                  j!                  |             t        dt#        |               ||       |S )Nzcontents are required.r   r"   c                 ^   t        | t              s4t        | t        j                        st        | t        j
                        ryt        | t              r$| sy	 t        j
                  j                  |        yd| j                  j                  j                         v r*	 dd l}|j                  j                  }|t        | |      ryy# t        j                  $ r= 	 t        j                  j                  |        Y y# t        j                  $ r Y Y yw xY ww xY w# t         $ r d }Y pw xY w)NTFr   r   )r,   r   r/   r   r   r   r-   rw   r   r   r   r   r   r   r   r   rh   r   s      r*   _is_partzt_contents.<locals>._is_part  s     	4D%**-D%**-$

!!$' $..))//11IIOO	 
	:dI#>% %% 	
..
'
'
-'' 			  	s<   C !D DD  DDDDD,+D,c                     | j                    S r&   )r   )r   s    r*   _is_user_partz!t_contents.<locals>._is_user_part'  s    !!!!r0   r   c                 ,    t        fd| D              S )Nc              3   .   K   | ]  } |        y wr&    )r(   r   r   s     r*   r+   z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>+  s     5t}T"5s   )r.   )r   r   s    r*   _are_user_partsz#t_contents.<locals>._are_user_parts*  s    5u555r0   resultaccumulated_partsc                     |sy | j                   |      rt        j                  |      nt        j                  |             g |d d  y )Nr   )r   r   r   r   )r   r   r   s     r*   $_append_accumulated_parts_as_contentz8t_contents.<locals>._append_accumulated_parts_as_content-  sM     
MM,- 	 12&78
 ar0   current_partc                     t        |      } |       |      k(  r|j                  |       y  | |       |g|d d  y r&   )r   r   )r   r   r   r   r   r   s      r*   _handle_current_partz(t_contents.<locals>._handle_current_part:  sH    
 ,'L\"o6G&HH|,*63DE*^r0   r   zUnsupported content type: )r,   r   rE   r   r   r   PartUnionDictr   r   r   boolr   r/   r   r   r-   rw   ry   )	r   r   r   r   r   r   r   r   r   s	         @@@r*   
t_contentsr     s   
 *Xt4X
-
..	Hd	#h   "&(*#%%%s*+#$$%#J"%** " "6T%**- 6$ 65==!ejj) 
,5==!
,ejj)
, ''
, 	
,&  Eg/:gt3L*63DE	GT	"e''g67g	'	6#4g>	GT	"mmEMM009:3DM?CDDE 'v/@A	-r0   schemac                     | j                  dd      dk(  r	d| d<   | d= yd| v rl| d   D ]c  }d|v s|d   dk(  sd| d<   | d   j                  ddi       t        | d         dk(  s>| d   d   j                         D ]
  \  }}|| |<    | d= e yy)	a  Process null fields in the schema so it is compatible with OpenAPI.

  The OpenAPI spec does not support 'type: 'null' in the schema. This function
  handles this case by adding 'nullable: True' to the null field and removing
  the {'type': 'null'} entry.

  https://swagger.io/docs/specification/v3_0/data-models/data-types/#null

  Example of schema properties before and after handling null fields:
    Before:
      {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "total_area_sq_mi": {
          "anyOf": [
            {
              "type": "integer"
            },
            {
              "type": "null"
            }
          ],
          "default": None,
          "title": "Total Area Sq Mi"
        }
      }

    After:
      {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "total_area_sq_mi": {
          "type": "integer",
          "nullable": true,
          "default": None,
          "title": "Total Area Sq Mi"
        }
      }
  ry   NnullTnullableanyOfr   r   )rU   removelenitems)r   itemkeyvals       r*   handle_null_fieldsr   a  s    X ZZ'F:v&w 	4DLF2!zw/0vg1$ /!,224 hc3F3KWo r0   originc                     t        d|        )z2Raises an error if the schema type is unsupported.Unsupported schema type: )rE   r   s    r*   "_raise_for_unsupported_schema_typer     s    .vh788r0   c                 ~    |r;|j                   s.| j                  d      s| j                  d      rt        d      y y y )NadditionalPropertiesadditional_propertiesz8additionalProperties is not supported in the Gemini API.)r<   rU   rE   )r   r3   s     r*   '_raise_for_unsupported_mldev_propertiesr     sE     oo
**+
,ZZ/0 O
PP 1  r0   Torder_propertiesdefsr   c                R   | j                  d      dk(  r| d= t        |        dD ]  \  }}| j                  |d      x}|| |<   ! 9| j                  di       j                         D ]  \  }}t	        |        t        |        | j                  dd      x}	&| j                  |	j                  d      d	             d
t        j                  dt        j                  ffd}
| j                  d      x}|D cg c]
  } |
|       c}| d<   y| j                  d      }t        |t              r|j                  }t        |t              r|j                         }| j                  d      }||dk(  r
|g| d<   | d= nt        d      |dk(  r| j                  d      x}jt!        |j                               D ]  \  }} |
|      ||<    t#        |j                               dkD  r"r d| vrt!        |j%                               | d<   | j                  d      x}t        |t&              r |
|      | d<   yyy|dk(  rL| j                  d      x} |
|      | d<   | j                  d      x}|D cg c]
  } |
|       c}| d<   yyyc c}w c c}w )a{  Updates the schema and each sub-schema inplace to be API-compatible.

  - Inlines the $defs.

  Example of a schema before and after (with mldev):
    Before:

    `schema`

    {
        'items': {
            '$ref': '#/$defs/CountryInfo'
        },
        'title': 'Placeholder',
        'type': 'array'
    }


    `defs`

    {
      'CountryInfo': {
        'properties': {
          'continent': {
              'title': 'Continent',
              'type': 'string'
          },
          'gdp': {
              'title': 'Gdp',
              'type': 'integer'}
          },
        }
        'required':['continent', 'gdp'],
        'title': 'CountryInfo',
        'type': 'object'
      }
    }

    After:

    `schema`
     {
        'items': {
          'properties': {
            'continent': {
              'title': 'Continent',
              'type': 'string'
            },
            'gdp': {
              'title': 'Gdp',
              'type': 'integer'
            },
          }
          'required':['continent', 'gdp'],
          'title': 'CountryInfo',
          'type': 'object'
        },
        'type': 'array'
    }
  titlePlaceholderLiteralEnum))r   r   )any_ofr   )prefix_itemsprefixItems)property_orderingpropertyOrderingNz$defsr   $refdefs/
sub_schemar"   c                 |    | j                  dd      x}|j                  d      d      } t        |        | S )z@Returns the processed `sub_schema`, resolving its '$ref' if any.r   Nr   r   r   )poprF   process_schema)r   refr3   r   r   s     r*   _recursez process_schema.<locals>._recurse  sF    ~~fd++8		'*2./j:vt>NOr0   r   ry   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   )rU   r   r   r   r   r   updaterF   r   
StringDictr,   r   valuer   upperrE   r   r   keysr-   )r   r3   r   r   	from_nameto_namer  _r   r   r   r   schema_typer   r  name
additionalr   prefixesprefixs    ```                r*   r   r     s   F ZZ44w)&&9
 i It,,9fWo 
\::gr"D : 
fd5E	 V
 ZZ%%c2
MM$syy)"-./7-- '2D2D  

7##f0>DE
x
+EF7O


6"+T"##KS!##%K **W
%
hwfVn
/899Hjj..
;":#3#3#56 0
$
#J/
40 j 
!A
% .&*:??+<&="#jj!788
E 
J	%)1*)=%& 
& F
 gG$$1 fWoJJ}--:>FGFx/Gf] ; E FL Hs   
JJ$r   c           	      .   d}| D ]g  }t        |j                  t              rd} t        |j                  t              r;t	        d|j
                   dt        |j                                | |r@| D cg c]  }t        |j                         }}t        | j                  |t              }| G fddt        j                        }|j                         }t        ||       |d   d	   }t        j                  j                  |      S c c}w )
NFTzEnum member z( value must be a string or integer, got )ry   c                       e Zd ZU W  ed<   y)"_process_enum.<locals>.PlaceholderplaceholderNr   
__module____qualname____annotations__)enum_to_processs   r*   Placeholderr  Z  s	      r0   r  r  r  )r,   r  intr   rx   r  ry   r   r   r   	BaseModelmodel_json_schemar   r   Schemarw   )	r   r3   is_integer_enummemberstr_membersstr_enumr  enum_schemar  s	           @r*   _process_enumr#  F  s     / f&,,$oc* &6<< !# 	 /3783v||$8K8DMM;S9HO!H&& ! --/+f%L)-8+		$	$[	11 9s   8Dc                 J    t        | t              xr t        d | D              S )zEVerifies the schema is of type dict[str, Any] for mypy type checking.c              3   <   K   | ]  }t        |t                y wr&   )r,   r   )r(   r   s     r*   r+   z(_is_type_dict_str_any.<locals>.<genexpr>g  s      *"jc*s   )r,   r-   r.   r   s    r*   _is_type_dict_str_anyr&  c  s,     
FD	! 
c *&,* ' r0   c                 <   sy t        t              r6t              r+t        |        t        j
                  j                        S t        t              rt        |       S t        t        j
                        rqt              t        t	        j
                               k(  rt               j                  d      }t        ||        t        j
                  j                  |      S t        t              set        t              rUt        t        j                         r;j#                         }t        ||        t        j
                  j                  |      S t        t              s;t        t              s+t        t$              st'        j(                        t*        v r^ G fddt        j                         }|j#                         }t        ||        |d   d   }t        j
                  j                  |      S t-        d       )NT)exclude_unsetc                       e Zd ZU W  ed<   y)t_schema.<locals>.Placeholderr  Nr  r   s   r*   r  r*    s	    r0   r  r  r  r   )r,   r-   r&  r   r   r  rw   r   r#  r/   r   
model_dumpr   ry   
issubclassr   r  r  VersionedUnionTypetyping
get_origin_UNION_TYPESrE   )r3   r   r   r  s    `  r*   t_schemar1  l  s    
"7"?66"<<&&v..!((fell+F|tELLN++ )0T2F66"<<&&v..
 V\
*
VT
"
VX//
0%%'F66"<<&&v..&	FD	!	F.	/			6	"l	2h((  **,F66"L!-0F<<&&v...vh788r0   c                 h   | sy t        | t        j                        r| S t        | t              r>t        j                  t        j
                  t        j                  |                   S t        | t              rt        j                  j                  |       S t        dt        |              )N)
voice_name)prebuilt_voice_config)voice_configzUnsupported speechConfig type: )r/   r   SpeechConfigr,   r   VoiceConfigPrebuiltVoiceConfigr-   rw   rE   ry   r   s    r*   t_speech_configr9    s     
fe001M&&"'";";v"N
 
 ,,V444T&\NCDDr0   c                     t        | t        j                        r| }t        | t              rt        j                  j                  |       }j                  t        d      |S )Nz<multi_speaker_voice_config is not supported in the live API.)r/   r   r6  r,   r-   rw   multi_speaker_voice_configrE   )r   speech_configs     r*   t_live_speech_configr=    s]     fe001M&&55f=M--9
F  
r0   c                 l   |sy t        j                  |      st        j                  |      r6t        j                  t        j
                  j                  | |      g      S t        t        |t              rt        |      S t        |t              rt        j                  j                  |      S |S )N)r3   callablefunction_declarations)inspect
isfunctionismethodr   r   FunctionDeclarationfrom_callabler   r/   r   r,   r-   rw   )r3   r   s     r*   t_toolrG    s     
7#3#3F#;::%%33 4 
  /@f%%&$::$$V,,Mr0   c                 6   |sg S t        j                  g       }g }|D ]Z  }t        | |      }||j                  r,|j                   |xj                  |j                  z  c_        J|j	                  |       \ |j                  r|j	                  |       |S )Nr@  )r   r   rG  rA  r   )r3   r   function_tooltoolstooltransformed_tools         r*   t_toolsrM    s     
I**26-
% 'dfd+#

0
011=++22	
+ 	%&' ((	LL	,r0   r  c                     t        | |d      S )NcachedContents)r5   )r@   )r3   r  s     r*   t_cached_content_namerP    s    	<L	MMr0   srcc                    t        |t              rt        j                  di |}t	        |t        j                        r~t        |j                  d u|j                  d ug      }t        |j                  d u|j                  d ug      }| j                  r|s|dk7  rt        d      |S |s|dk7  rt        d      |S t        |t              rt        j                  |      S t        |t              rx|j                  d      rt        j                  d|g      S |j                  d      rt        j                  d	|
      S |j                  d      rt        j                  |      S t        d|       )Nr   zeExactly one of `gcs_uri` or `bigquery_uri` must be set, other sources are not supported in Vertex AI.Exactly one of `inlined_requests`, `file_name`, `inlined_embed_content_requests`, or `embed_content_file_name` must be set, other sources are not supported in Gemini API.)inlined_requestsgs://jsonlrb   r   bq://bigqueryrb   bigquery_urifiles/)	file_namezUnsupported source: r   )r,   r-   r   BatchJobSourcer/   sumr   r[  rT  r]  r<   rE   r   r   r:   )r3   rQ  vertex_sourcesmldev_sourcess       r*   t_batch_job_sourcerb    s    T



%
%Cc5//0	D	 #"2"2$">?N D(T! M 	.A-6
 	
 J 
=A-J
 	

 J#t55#s
~~g!!%  
	 !!  
	!!!  	)#/00r0   c                    t        |t              rt        j                  di |}t	        |t        j                        r7t        |j                  d u|j                  d ug      }|dk7  rt        d      |S t        dt        |             )Nr   rS  zUnsupported source type: r   )
r,   r-   r   EmbeddingsBatchJobSourcer/   r_  rT  r]  rE   ry   )r3   rQ  ra  s      r*   t_embedding_batch_job_sourcere  #  s     T

(
(
/3
/Cc599:D(T! M H 
 J
0c<
==r0   destc                    t        | t              rt        j                  di | } | S t        | t              r^| j                  d      rt        j                  d|       S | j                  d      rt        j                  d|       S t        d|        t        | t        j                        r| S t        d|        )	NrU  rV  rW  rX  rY  rZ  zUnsupported destination: r   )r,   r-   r   BatchJobDestinationr   r:   rE   r/   )rf  s    r*   t_batch_job_destinationri  :  s     d$$,t,DK$w&&  
	!&& 
 24&9::e778K
07
88r0   c                     | j                  di       j                  dg       }|s| S |D ]2  }|j                  di       }|sd|v s| j                  d      | d<    | S  | S )NinlinedResponsesrP   	embeddinginlinedEmbedContentResponses)rU   r   )rf  inline_responsesrP   inner_responses       r*   t_recv_batch_job_destinationrp  S  s    XX0"599" 
K" h\\*b1Nn$-1XX6H-Id)*	+ 
+r0   c                 *   | j                   s;d}t        j                  ||      r|j                  d      d   S t	        d| d      d}t        j                  ||      r|j                  d      d   S |j                         r|S t	        d| d      )Nzbatches/[^/]+$r7   r   zInvalid batch job name: .z:^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$)r<   rematchrF   rE   isdigit)r3   r  mldev_patternvertex_patterns       r*   t_batch_job_namerx  d  s    	%M	xxt$ZZ_R  1$q9::P.XXnd#::c?2||~K
/vQ7
88r0   statec                 Z    | dk(  ry| dk(  ry| dk(  ry| dk(  ry| d	k(  ry
| dk(  ry| dk(  ry| S )NBATCH_STATE_UNSPECIFIEDJOB_STATE_UNSPECIFIEDBATCH_STATE_PENDINGJOB_STATE_PENDINGBATCH_STATE_RUNNINGJOB_STATE_RUNNINGBATCH_STATE_SUCCEEDEDJOB_STATE_SUCCEEDEDBATCH_STATE_FAILEDJOB_STATE_FAILEDBATCH_STATE_CANCELLEDJOB_STATE_CANCELLEDBATCH_STATE_EXPIREDJOB_STATE_EXPIREDr   )ry  s    r*   t_job_stater  v  s[    
''"%%%%'' $$'' %%Lr0   g      ?g      4@g      @g      ?structc                    |j                  d      x}rd|v r|}d}t        }|j                  d      dk7  rt|t        kD  rt        d| d|       | j	                  d|i 	      }t        j                  |       ||z  }t        |t        z  t              }|j                  d      dk7  rt|j                  d
      x}rt        d| d| d|       |j                  d      S |S )Nr  z/operations/g        doneTz
Operation z timed out.
GET)http_methodpathrequest_dicterrorz failed with error: z.
rP   )
rU   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)rJ   r  r  	operationtotal_secondsdelay_secondsr  s          r*   t_resolve_operationr    s    jj  d n&<$*IM5M
--
4
'	4	4Zv]9+FGG$$$R % i jj}$m
0
0
+m --
4
' g&&u&tf0s9+
F  ==$$Mr0   c                    t        | t        j                        r| j                  } nft        | t        j                        r| j
                  } n?t        | t        j                        r%| j                  | j                  j
                  } nd } | t        d      t        | t              st        dt        |        d      | j                  d      rM| j                  d      d   }t        j                  d|      }|t        d|        |j!                  d	      } | S | j                  d      r| j                  d      d   } | S )
NzFile name is required.z"Could not convert object of type `z` to a file name.zhttps://r\  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )r/   r   r   r  Videor   GeneratedVideovideorE   r,   r   ry   r:   rF   rs  rt  group)r  suffixrt  s      r*   t_file_namer    s    dEJJ'99Dekk*88De223zzZZ^^dd	\
-
..	D#	

,T$ZL8IJ  
__Z ZZ!!$FHH[&)E}?vFGG;;q>D 
+ x ::h"D	+r0   statusc                 `   | dk(  rt         j                  j                  S | dk(  rt         j                  j                  S | dk(  rt         j                  j                  S | dk(  rt         j                  j
                  S t         j                  D ]  }t        |j                        | k(  s|c S  | S )NSTATE_UNSPECIFIEDCREATINGACTIVEFAILED)r   JobStater|  r  r  r  r   r  )r  ry  s     r*   t_tuning_job_statusr    s    "">>///>>+++>>--->>*** 	U[[	V	# Mr0   c                     t        | t              rt        j                  j	                  |       S t        | t        j                        r| S t        dt        |        d      )NCould not convert input (type "z") to `types.Content`)r,   r-   r   r   rw   r/   rE   ry   )r   s    r*   t_content_strictr    sR    ==''00/N

)$w-8MN r0   c                 v    t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w r&   )r,   r   r  )r   r   s     r*   t_contents_strictr    s8     (#5=>'W%>>X&'' ?r   turnsturn_completec                     | t        j                  |      S 	 t        j                  t        |       |      S # t        $ r}t	        dt        |        d      |d }~ww xY w)N)r  )r   )r  r  r  z") to `types.LiveClientContent`)r   LiveClientContentr  	ExceptionrE   ry   )r  r  es      r*   t_client_contentr    sv     ]""??	""/#  
 

)$u+ 7$ 	$ s    ; 	A"AA"inputc                     | st        d|        	 t        j                  t        |             S # t        $ r}t        dt        |        d      |d }~ww xY w)Nz#A tool response is required, got: 
)r{   r  z$") to `types.LiveClientToolResponse`)rE   r   LiveClientToolResponser}   r  ry   )r  r  s     r*   t_tool_responser    ss     

;E7C
DD''/5I  
 

)$u+ 7) 	) s   2 	AAAmetricsc                    g }| D ]  }i }ddg|d<   t        |dg      j                         }|dk(  ri |d<   n|dk(  ri |d<   n|j                  d	      r|j                  d
d      }d|i|d<   ndt	        |d      rJ|j
                  r>d|j
                  i}t        |dg      }|r||d<   t        |dg      }|rd|i|d<   ||d<   nt        d|       |j                  |        |S )a   Prepares the metric payload for the evaluation request.

    Args:
        request_dict: The dictionary containing the request details.
        resolved_metrics: A list of resolved metric objects.

    Returns:
        The updated request dictionary with the prepared metric payload.
    AVERAGESTANDARD_DEVIATIONaggregation_metricsr  r   exact_match_specr   	bleu_specrouger
   
rouge_typer   prompt_templatemetric_prompt_templatejudge_model_system_instructionsystem_instructionreturn_raw_outputcustom_output_format_configpointwise_metric_specz0Unsupported metric type or invalid metric name: )getvr   r:   replacer'   r  rE   r   )	r  metrics_payloadmetricmetric_payload_itemmetric_namer  pointwise_specr  r  s	            r*   	t_metricsr    sV    O $2,.

4/0
 &*002k		%24./& +-K(!!'* ((b1
-9:,FL)6,-&2H2H2F4J4JK!56
 1C.-
. ()
 !#4;.6
7 8F34A+O
 	
 01I$2J r0   r&   )NT)__doc__base64collections.abcr   r   r   r   r   rB  ri   loggingrs  sysr  r   builtin_typesr.  r   r   r	   r
   r   r   
_mcp_utilsr   r   r   r  TYPE_CHECKINGr   rq   r   r  r   	getLoggerrV   version_info	UnionTyper-  r0  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer  rh   metric_name_sdk_api_mapr   metric_name_api_sdk_mapry   r  r   r/   BaseApiClientr   r  r@   rI   rO   r  r   r[   r]   rp   rs   FunctionResponseOrDictrv   rz   r}   BlobImageUnionDictr   r   r   
BlobOrDictr   r   r   r   r   r   r   r   ContentDictContentTyper   r   ContentListUnionContentListUnionDictr   r   r   r   r   r  r#  SchemaUnionDictr&  r1  SpeechConfigUnionDictr6  r9  SpeechConfigOrDictr=  rG  rM  rP  BatchJobSourceUnionDictr^  rb  EmbeddingsBatchJobSourceOrDictrd  re  BatchJobDestinationOrDictrh  ri  r-   rp  rx  r  r  r  r  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  )kvs   00r*   <module>r     s	    )  -   	  	 
    E E * .	    			7	8w$..,, 7 78,00,,,)	3'"%FKK%'6;;5) $ 
 -D,I,I,KLDAq1a4L @# @D););$< @ @6 '(Z%%ZZ 	Z
 !$Z 	ZzK-- c c 0))8<  	'

>))25c]"4S 4UZZ 4233
 5$$--.	05
 
%
 
 !5))40H0H+IIJ	%**)) ejj 4Au// AEJJ AAu'' AEJJ AC%--. C5:: C<d5&&')<)<d5::>NNO 
%**	(738#456d5''()& EMM5#4#4e6I6IIJ*; 1 1478*
]]*8 %% D'e.?.?)@+MN  49d5==))* 4ie$$e&@&@%--OPi 
%--	iX8w11 8d 8v9s 9t 9
QQ!+";";<Q	Q" *.TH
 "THTH[../TH 7%%
&TH
 TH 
THn2
2$[%>%>?2
\\2:%'',-w!!"-9[../-9%'',--9 ell-9`E%--s23Ee  !E&$$e  ! %%/2eEJJO$%*%%/3Cy	%**2N+";"; N3 N3 N/1%%/1		&	&/1 /1d>%%>		-	-> ##>.9
U444
59
92tCH~ $sCx. "9[66 9c 9c 9$s s & %( !$( !#  ))3:3E3E<
5ejj%++u7K7KKL
MD ennc.A(B  e11 emm (HU00153F3FFG(	%--( 		hu**+U-@-@@A 	
 *$$--.	0
 !!(3%&&'3	$sCx.3}& 
 G Ms   !^ ^	^^