
    +j                        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 dd	lmZ ej        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
j#        d          Z$ej%        dk    rej&        Z'ej        ej&        fZ(ddlm)Z) nej*        Z'ej        fZ(ddl+m)Z) ej        rddl,m-Z. ddl/m0Z1 n5eZ.ej2        e3d<   eZ1ej2        e3d<   	 ddl,m-Z. ddl/m0Z1 n# e4$ r dZ.dZ1Y nw xY wddddZ5d e56                                D             Z7ddde"j8        de9de9de:de9f
d Z;de"j8        d!e9de9fd"Z<d#e"j8        d$e=de9fd%Z>d&ej?        de@ej?                 fd'ZAd#e"j8        d!e9dee9         fd(ZBd)edejC        fd*ZDd+ejE        dejF        fd,ZGd-eejE        eejE                 f         de@ejF                 fd.ZHd/eejI        e@ejI                 f         de@ejC                 fd0ZJd1ejI        dejC        fd2ZKd1ejI        dejC        fd3ZLd1ejM        dejC        fd4ZNd5eejO                 dejP        fd6ZQd7eee@ejO                 ejO        e@ejP                 f                  de@ejP                 fd8ZRd9eeee9ef                           dee@ejS                          fd:ZTeejU        ejV        ejO        f         ZWd;eeWejV        df         dejU        fd<ZXde"j8        d=ee@ejU                 e@ejV                 eWf         dee@e9         e@ejU                 f         fd>ZYd=eeejZ        ej[        ejU        f                  de@ejU                 fd?Z\d@ej?        ddfdAZ]dBeddfdCZ^d@edee"j8                 ddfdDZ_	 dqdEddFd@ej?        dee"j8                 dGeej?                 dHe=dIee`e:                  ddfdJZadKedee"j8                 dejb        fdLZcdBeejd        ef         de)ej?                 fdMZedee"j8                 dBeejd        ef         deejb                 fdNZfdBeejg        ef         deejh                 fdOZidBejj        deejh                 fdPZkde"j8        dBedeeej0        ef                  fdQZlde"j8        dBe@e         de@ej0                 fdRZmde"j8        dSe9de9fdTZnde"j8        dUejo        dejp        fdVZqde"j8        dUejr        dejs        fdWZtdXee9eju        f         dejv        fdYZwdXexe9ef         dexe9ef         fdZZyde"j8        dSe9de9fd[Zzd\e9de9fd]Z{d^Z|d_Z}d`Z~daZd#e"j8        dbej?        defdcZdSeee9ej        ej        ej        f                  de9fddZdee9deej        e9f         fdfZd;ej        dejU        fdgZd=eeej                 ej        f         de@ejU                 fdhZ	 	 drdieeeej                 ej        f                  dje=dej        fdkZdleejE        eejE                 f         dej        fdmZdne@ej                 de@exe9ef                  fdoZd!e9de=fdpZdS )sz"Transformers for Google GenAI SDK.    N)IterableMapping)EnumEnumMeta)AnyGenericAliasListOptionalSequenceUnion   )mcp_to_gemini_tool)get_value_by_path)is_duck_type_of)_api_client)_common)typeszgoogle_genai._transformers)   
   )	TypeGuard)ClientSession)ToolMcpClientSessionMcpToolexactMatchSpecbleuSpec	rougeSpec)exact_matchbleu
rouge_specc                     i | ]\  }}||	S  r"   ).0kvs      ^/home/wildlama/visual-decline/.venv/lib/python3.11/site-packages/google/genai/_transformers.py
<dictcomp>r'   I   s    LLLDAq1aLLL       )collection_hierarchy_depthclientresource_namecollection_identifierr*   returnc                   |                     | d           o | d|                     d          dz   |k    }| j        r|                     d          r|S |                     d          rd| j         d| S |                     | 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)r+   r,   r-   r*   $should_prepend_collection_identifiers        r&   _resource_namer9   L   sO   J 
"
"&;#>#>#>
?
?? $ #
4
4]
4
4
:
:3
?
?!
C	#$	 ' _ ,, 			!	!,	/	/ 999-999		!	!%:"="="=	>	> UUUFOUUmUUU	- mmmFOmmF[mm^kmmm+ %77777r(   modelc                    |st          d          d|v sd|v sd|v rt          d          | j        rk|                    d          s*|                    d          s|                    d          r|S d	|v r!|                    d	d
          \  }}d| d| S d| S |                    d          r|S |                    d          r|S d| S )Nzmodel is required.z..?&zinvalid model parameter.r1   models/publishers/r0   r   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr5   r3   split)r+   r:   	publishermodel_ids       r&   t_modelrD      s   	 +
)
*
**	U]]cUllcUll
/
0
00_ %%
1I&&
1 M**
1
 l	!KKQ//i8988h8880000	"" l			.	)	) lur(   
api_clientbase_modelsc                 (    | j         r|rdS dS |rdS dS )Nzpublishers/google/modelsmodelstunedModels)r5   )rE   rF   s     r&   t_models_urlrJ      s4      	 ''X X]r(   responsec                 f   | sg S |                      d          }||S |                      d          }||S |                      d          }||S |                      d          |                      d          g S t                              d           t                              d|            g S )NrH   rI   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)rK   rH   tuned_modelspublisher_modelss       r&   t_extract_modelsrV      s     
 I/7||H/E/E&M5=\\-5P5P,9A: : ! ll=!!-
,,}
%
%
-I
NN6777
LLDhOOOIr(   c                     t          | |          }|sd S |                    d          r| j        rd| j         d| j         d| S |                    d          r| j        rd| j         d| j         d| S |S )Nr?   r1   r2   r0   r>   z/publishers/google/)rD   r3   r5   r6   r7   )rE   r:   s     r&   t_caches_modelrX      s     *e
$
$%	 4
m$$ )<  	QJ&PP:3FPPPP 	"" z': ez)eej6Iee^ceeeLr(   imagec                 b   d}t                      }| j        dk    r2t          | dd          r!| j        dv rd}|                    d           t          j                    } | j        ||fi | |                                }d|	                                 }t          j        ||	          S )
NPNGJPEGfilename )1LRGBRGBXCMYKkeep)qualityimage/)data	mime_type)dictformatgetattrmodeupdateioBytesIOsavegetvaluelowerr   Blob)rY   image_formatsave_paramsimage_ioimage_bytesrh   s         r&   pil_to_blobrx     s    , $+lf
%R
(
( 
*9
9
9Lv&&&Z\\(%*X|33{333!!##+-|))++--)			:	:	::r(   function_responsec                    | st          d          t          | t                    rt          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: )	r@   
isinstanceri   r   FunctionResponsemodel_validater   	TypeErrortype)ry   s    r&   t_function_responser     s     
 7
5
6
66!4(( !001BCCC(%*@AA 
	>$():$;$;	> 	>  r(   function_responsesc                     | st          d          t          | t                    rd | D             S t          |           gS )Nz function_responses are required.c                 ,    g | ]}t          |          S r"   )r   )r#   rK   s     r&   
<listcomp>z(t_function_responses.<locals>.<listcomp>.  s!    MMMh))MMMr(   )r@   r{   r   r   r   s    r&   t_function_responsesr   %  sU     
 9
7
8
88"H-- 5MM:LMMMM 23344r(   blobsc                 d    t          | t                    rd | D             S t          |           gS )Nc                 ,    g | ]}t          |          S r"   )t_blob)r#   blobs     r&   r   zt_blobs.<locals>.<listcomp>7      +++TF4LL+++r(   )r{   listr   )r   s    r&   t_blobsr   3  s8     t ++U++++5MM?r(   r   c                    | st          d          t          | t          j                  r| S t	          | t
                    rt          j                            |           S d| j        j        	                                v rE	 dd l
}|j        j        }n# t          $ r d }Y nw xY w|t	          | |          rt          |           S t          dt          |                      )Nzblob is required.rY   r   z6Could not parse input as Blob. Unsupported blob type: )r@   r   r   rs   r{   ri   r}   	__class____name__rr   	PIL.ImageImageImportErrorrx   r~   r   )r   PIL	PIL_Images      r&   r   r   <  s    	 *
(
)
))T5:&& Kd +:$$T***'--////)/ii   iii D)!<!<KtDzzKK	 	 s   B B#"B#c                     t          |           } | j        r| j                            d          r| S t          d| j                  )Nrf   Unsupported mime type: r   rh   r3   r@   r   s    r&   t_image_blobr   V  L    	$	^ 11(;; K?T^??@@@r(   c                     t          |           } | j        r| j                            d          r| S t          d| j                  )Nzaudio/r   r   r   s    r&   t_audio_blobr   ]  r   r(   partc                    | t          d          t          | t                    rt          j        |           S t          | t          j                  rH| j        r| j        st          d          t          j        	                    | j        | j                  S t          | t                    rg	 t          j                            |           S # t          j        $ r5 t          j        t          j                            |                     cY S w xY wt          | t          j                  r| S d| j        j                                        v rX	 dd l}|j        j        }n# t(          $ r d }Y nw xY w|2t          | |          r"t          j        t+          |                     S t          d	t-          |                      )
Nzcontent part is required.)textz$file uri and mime_type are required.)file_urirh   )	file_datarY   r   )inline_datazUnsupported content part type: )r@   r{   strr   Partr   Fileurirh   from_uriri   r}   pydanticValidationErrorFileDatar   r   rr   r   r   r   rx   r   r   r   r   s      r&   t_partr   d  s   	\
0
1
11c !:4    T5:&& L8 ?4> ?=>>>:DNKKKd GGZ&&t,,,# G G GZ%."?"?"E"EFFFFFFGT5:&& K'--////)/ii   iii D)!<!<ZK$5$56666AT$ZZAABBBs%   4C ADDE( (E76E7partsc                     | t          | t                    r| st          d          t          | t                    rd | D             S t          |           gS )Nzcontent parts are required.c                 ,    g | ]}t          |          S r"   )r   )r#   r   s     r&   r   zt_parts.<locals>.<listcomp>  r   r(   )r{   r   r@   r   r   s    r&   t_partsr     s^     ]z%..]u]
2
3
33t ++U++++5MM?r(   predictionsc           
          | sd S g }| D ]k}|                     d          rT|                    t          j        t          j        |d         d         |d         d                                        l|S )NrY   gcsUri
imageBytes)gcs_urirw   )rY   )rP   appendr   GeneratedImager   )r   images
predictions      r&   t_image_predictionsr     s     
 4& 	 	j~~g mm

K$W-h7(1,?       
-r(   contentc                    | t          d          t          | t          j                  r| S t	          | t
                    rw	 t          j                            |           S # t          j        $ rE t          |           }|j
        rt          j        |g          nt          j        |g          cY S w xY wt          | t          j                  r#t          j        t          |           g          S t          | t          j                  r3| j
        rt          j        | g          nt          j        | g          S t          j        |           S )Nzcontent is required.r   )r@   r   r   Contentr{   ri   r}   r   r   r   function_callModelContentUserContentr   r   )r   possible_parts     r&   	t_contentr     sb    _
+
,
,,Wem,, N 	]))'222#   Woom (8%
M?
3
3
3
3 777   Wej)) 6F7OO#45555Wej))   	0'++++gY///
 
		)	)	))s   A# #AB76B7contentsc                    t          |t                    rd |D             }nt          |          g}| j        rg }|D ]}|t          |t                    rt
          j                            |          }|j        F|j        D ]>}|j	        r|
                    |j	                   $t                              d           ?|S |S )Nc                 ,    g | ]}t          |          S r"   )r   r#   r   s     r&   r   z(t_contents_for_embed.<locals>.<listcomp>  s     GGG7Ig..GGGr(   z/Non-text part found, only returning text parts.)r{   r   r   r5   ri   r   r   r}   r   r   r   rQ   rR   )r+   r   transformed_contents
text_partsr   r   s         r&   t_contents_for_embedr     s     $ 1GGhGGG%h//0_  J' 	Q 	Q		gt$$ 	:M0099'=$m Q Qdy Q	****nnOPPPPr(   c                    | 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                    r` ||           t          |t                    r)|                    t          j        |                     ||                    |            ||          r ||||           t          |t                    r3|                    t
          j                            |                     t          dt#          |                      ||           |S )Nzcontents are required.r   r.   c                 \   t          | t                    s4t          | t          j                  st          | t          j                  rdS t          | t                    rs| sdS 	 t          j                            |            dS # t          j	        $ r; 	 t          j
                            |            Y dS # t          j	        $ r Y Y dS w xY ww xY wd| j        j                                        v r8	 dd l}|j        j        }n# t           $ r d }Y nw xY w|t          | |          rdS dS )NTFrY   r   )r{   r   r   r   r   r   ri   r}   r   r   r   r   r   rr   r   r   r   r   s      r&   _is_partzt_contents.<locals>._is_part  sl    	44,, 4,,
 T$  u
!!$'''t%   	
.
'
'
-
-
-' 	 	 			 $.)//1111IO		   			 
	:dI#>#>	t5s<   &B CB99CCCC5D DDc                     | j          S N)r   )r   s    r&   _is_user_partz!t_contents.<locals>._is_user_part  s    !!!r(   r   c                 :    t          fd| D                       S )Nc              3   .   K   | ]} |          V  d S r   r"   )r#   r   r   s     r&   	<genexpr>z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>  s-      55t}}T""555555r(   )all)r   r   s    r&   _are_user_partsz#t_contents.<locals>._are_user_parts  s&    5555u555555r(   resultaccumulated_partsc                     |sd S |                       |          rt          j        |          nt          j        |                     g |d d <   d S )Nr   )r   r   r   r   )r   r   r   s     r&   $_append_accumulated_parts_as_contentz8t_contents.<locals>._append_accumulated_parts_as_content  sx      f
MM?,--	9 12222&7888  
 aaar(   current_partc                     t          |          } |           |          k    r|                    |           d S  | |           |g|d d <   d S r   )r   r   )r   r   r   r   r   r   s      r&   _handle_current_partz(t_contents.<locals>._handle_current_part!  sw    
 ,''L}\""oo6G&H&HHH|,,,,,**63DEEE*^r(   r   zUnsupported content type: )r{   r   r@   r   r   r   PartUnionDictr   r   r   boolr   r   r   r   ri   r}   r   )	r   r   r   r   r   r   r   r   r   s	         @@@r&   
t_contentsr     s   
 *Xt44X
-
.
..	Hd	#	# !h   "&(*#%%s*+#$%# # # #J"%* " " " " "6T%*- 6$ 6 6 6 6 6 65=!ej)      
,5=!
,ej)
, '
, 	
, 
, 
, 
, 
, 
, 
, 
,&  E Egw.. E*Wd2K2K E**63DEEE	GT	"	" e'g6667777g	'		 E6#4g>>>>	GT	"	" EmmEM0099::::CDMMCCDDD&&v/@AAA	-r(   schemac                 b   |                      dd          dk    r
d| d<   | d= dS d| v r| d         D ]}}d|v ru|d         dk    rid| d<   | d                             ddi           t          | d                   dk    r.| d         d                                         D ]
\  }}|| |<   | d= |dS dS )	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"
        }
      }
  r   NnullTnullableanyOfr   r   )rP   removelenitems)r   itemkeyvals       r&   handle_null_fieldsr   H  s    X ZZ''F:v&w  	4DLF22!zw/000vg1$$ /!,2244  hc3F3KKWo  r(   originc                 &    t          d|            )z2Raises an error if the schema type is unsupported.Unsupported schema type: )r@   r   s    r&   "_raise_for_unsupported_schema_typer     s    7v77888r(   c                     |r@|j         s;|                     d          s|                     d          rt          d          d S d S d S )NadditionalPropertiesadditional_propertiesztadditionalProperties is only supported in Gemini Enterprise Agent Platform mode, , not in Gemini Developer API mode.)r5   rP   r@   )r   r+   s     r&   '_raise_for_unsupported_mldev_propertiesr     s     MoM **+
,
,	M
 ZZ/00M   L  M  M  MM M M M M Mr(   Torder_propertiesvisited_dicts_pathdefsr   r   c                   t                      t          |           v rdS                     t          |                      |                     d          dk    r| d= t	          |            dD ]"\  }}|                     |d          x}|| |<   #D|                     di                                           D ]\  }}	t          |	           t          |            |                     dd          x}
4| 	                    |

                    d          d	                             d
t          j        dt          j        ffd|                     d          x}5fd|D             | d<                       t          |                      dS |                     d          }t          |t                    r|j        }t          |t"                    r|                                }|                     d          }||dk    r
|g| d<   | d= nt'          d          |dk    r|                     d          x}t)          |                                          D ]\  }}	 |	          ||<   t+          |                                          dk    r*r(d| vr$t)          |                                          | d<   |                     d          x}#t          |t.                    r |          | d<   nS|dk    rM|                     d          x} |          | d<   |                     d          x}fd|D             | d<                       t          |                      dS )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'
    }
  NtitlePlaceholderLiteralEnum))r   r   )any_ofr   )prefix_itemsprefixItems)property_orderingpropertyOrderingz$defsr   $refdefs/
sub_schemar.   c                     |                      dd          x}4|                    d          d                  } t          |           v ri S t          |            | S )z@Returns the processed `sub_schema`, resolving its '$ref' if any.r  Nr  r  r   )poprA   idprocess_schema)r  refr+   r   r   r   s     r&   _recursez process_schema.<locals>._recurse  s|    ~~fd+++8		'**2./j	J-	-	-	)-    r(   r   c                 &    g | ]} |          S r"   r"   )r#   r  r  s     r&   r   z"process_schema.<locals>.<listcomp>  s#    EEE
xx
++EEEr(   r   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r  r  r   ARRAYr   r   c                 &    g | ]} |          S r"   r"   )r#   prefixr  s     r&   r   z"process_schema.<locals>.<listcomp>@  s#    GGGFxx//GGGr(   )setr	  addrP   r   r  r   r
  r   rm   rA   r   
StringDictr   r{   r   valuer   upperr@   r   r   keysri   )r   r+   r   r   r   	from_nameto_namer  _r  r  r   schema_typer  r  name
additionalr   prefixesr  s    ````              @r&   r
  r
    s   H ZZ%%%
FF$$$ZZ444w)&&999
  i It,,,9fWo	\::gr""D 
 
: 


+/     V
 ZZ%%%c2
MM$syy))"-.///7- '2D           

7###f0EEEEfEEEF7Objj)))
F

6""+T"" $#KS!! &##%%K **W

%
hwfVn
//8999Hjj...
;":#3#3#5#566 0 0
$
#8J//
4
j  
!
!A
%
% & ..&*:??+<+<&=&="#jj!7888
E 
J	%	% >)1*)=)=%&gG$$$1 fWoJJ}---:GGGGhGGGf]BvJJ'''''r(   r  c           	      
   d}| D ]e}t          |j        t                    rd}t          |j        t                    s,t	          d|j         dt          |j                             f| |r*d | D             }t          | j        |t                    }| G fddt          j
                  }|                                }t          ||           |d	         d
         }t          j                            |          S )NFTzEnum member z( value must be a string or integer, got c                 6    g | ]}t          |j                  S r"   )r   r  )r#   members     r&   r   z!_process_enum.<locals>.<listcomp>T  s"    8883v|$$888r(   )r   c                       e Zd ZU  ed<   dS )"_process_enum.<locals>.PlaceholderplaceholderNr   
__module____qualname____annotations__)enum_to_processs   r&   Placeholderr'  X  s               r(   r.  r  r(  )r{   r  intr   r~   r   r   r   r   r   	BaseModelmodel_json_schemar
  r   Schemar}   )	r  r+   is_integer_enumr%  str_membersstr_enumr.  enum_schemar-  s	           @r&   _process_enumr7  D  sE    /  f&,$$ ooc** # # #6<  # #   / 884888KDM;S999HO! ! ! ! ! ! !H& ! ! ! --//+f%%%L)-8+		$	$[	1	11r(   c                 ^    t          | t                    ot          d | D                       S )zEVerifies the schema is of type dict[str, Any] for mypy type checking.c              3   @   K   | ]}t          |t                    V  d S r   )r{   r   )r#   r   s     r&   r   z(_is_type_dict_str_any.<locals>.<genexpr>e  s=       * *"jc* * * * * *r(   )r{   ri   r   r   s    r&   _is_type_dict_str_anyr:  a  sC     
FD	!	! 
c * *&,* * * ' ' r(   c                    sd S t          t                    r>t                    r/t          |            t          j                                      S t          t                    rt          |           S t          t          j                  rt                    t          t	          j                              k    rt                                         d          }t          ||            t          j                            |          S t          t                    srt          t                    r]t          t          j                  rC                                }t          ||            t          j                            |          S t          t                    sEt          t                    s0t          t$                    st'          j                  t*          v rk G fddt          j                  }|                                }t          ||            |d         d         }t          j                            |          S t-          d           )NT)exclude_unsetc                       e Zd ZU  ed<   dS )t_schema.<locals>.Placeholderr(  Nr)  r   s   r&   r.  r>    s         r(   r.  r  r(  r   )r{   ri   r:  r
  r   r2  r}   r   r7  r   r   
model_dumpr   r   
issubclassr   r0  r1  VersionedUnionTypetyping
get_origin_UNION_TYPESr@   )r+   r   r   r.  s    `  r&   t_schemarE  j  sZ    
 4 /"7"?"? /66"""<&&v...!! )(((VU\** /F||tELNN++++ )000T22F66"""<&&v...
 V\
*
*/ VT
"
"	/
 VX/
0
0/ %%''F66"""<&&v...&&/	FD	!	!/ 
F.	/	// 
	6	"	"l	2	2      h(    **,,F66"""L!-0F<&&v...7v77888r(   c                    | sd S t          | t          j                  r| S t          | t                    r;t          j        t          j        t          j        |                               S t          | t                    rt          j                            |           S t          dt          |                      )N)
voice_name)prebuilt_voice_config)voice_configzUnsupported speechConfig type: )r   r   SpeechConfigr{   r   VoiceConfigPrebuiltVoiceConfigri   r}   r@   r   r   s    r&   t_speech_configrM    s     
 4VU/00 M &"'";v"N"N"N
 
 
   
  5,,V444CT&\\CCDDDr(   c                     t          | t          j                  r| }t          | t                    rt          j                            |           }|j        t          d          |S )Nz<multi_speaker_voice_config is not supported in the live API.)r   r   rJ  r{   ri   r}   multi_speaker_voice_configr@   )r   speech_configs     r&   t_live_speech_configrQ    sl     VU/00 M >&55f==M-9
F   
r(   c                    |sd S t          j        |          st          j        |          r5t          j        t          j                            | |          g          S t          $t          |t                    rt          |          S t          |t                    rt          j                            |          S |S )N)r+   callablefunction_declarations)inspect
isfunctionismethodr   r   FunctionDeclarationfrom_callabler   r   r   r{   ri   r}   )r+   r   s     r&   t_toolr[    s     
 4 7#3F#;#; :%33 4  
    vw??f%%%&$ :$$V,,,Mr(   c                    |sg S t          j        g           }g }|D ]}t          | |          }||j        rc|j        \|xj        |j        z  c_        |                                }d |_        |                    d          r|                    |           ~|                    |           |j        r|                    |           |S )NrT  T)exclude_none)r   r   r[  rU  
model_copyr?  r   )r+   r   function_tooltoolstooltransformed_tool	tool_copys          r&   t_toolsrd    s     
 I*2666-
% ' 'dfd++#

0'1=++2	
++ %//11	*.	'T22 	"
,,y
!
!
!%&&&(  	LL	,r(   r   c                 &    t          | |d          S )NcachedContents)r-   )r9   )r+   r   s     r&   t_cached_content_namerg    s    	<L	M	M	MMr(   srcc                 x   t          |t                    rt          j        di |}t	          |t          j                  r~t          |j        d u|j        d u|j        d ug          }t          |j	        d u|j
        d ug          }| j        r|s|dk    rt          d          n|s|dk    rt          d          |S t          |t                    rt          j        |          S t          |t                    r|                    d          rt          j        d|g          S |                    d          rt          j        d	|
          S t!          j        d|          rt          j        d|          S |                    d          rt          j        |          S t          d|           )Nr   zExactly one of `gcs_uri` or `bigquery_uri`, or `vertex_dataset_name` must be set, other sources are not supported in Gemini Enterprise Agent Platform.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rj   r   bq://bigqueryrj   bigquery_uriz/^projects/[^/]+/locations/[^/]+/datasets/[^/]+$zvertex-dataset)rj   vertex_dataset_namefiles/)	file_namezUnsupported source: r"   )r{   ri   r   BatchJobSourcer   sumr   rr  rs  rk  ru  r5   r@   r   r   r3   rematch)r+   rh  vertex_sourcesmldev_sourcess       r&   t_batch_job_sourcer|    s5    T &


%
%
%
%CS%.// 0Kt#D(#4/	
 N D(T!  M  
	 
.A--M
 
 	
 . 
 
=A--J
 
 	

 J#t 5555#s 
~~g !%    
	 	  !    
Dc	J	J !!!    
	!	! !    	/#//000r(   c                 ,   t          |t                    rt          j        di |}t	          |t          j                  r6t          |j        d u|j        d ug          }|dk    rt          d          |S t          dt          |                     )Nr   rj  zUnsupported source type: r"   )
r{   ri   r   EmbeddingsBatchJobSourcer   rw  rk  ru  r@   r   )r+   rh  r{  s      r&   t_embedding_batch_job_sourcer  .  s     T 0

(
/
/3
/
/CS%899 >D(T!  M H  
 J
<c<<
=
==r(   destc                    t          | t                    rt          j        di | } | S t          | t                    rh|                     d          rt          j        d|           S |                     d          rt          j        d|           S t          d|            t          | t          j                  r| S t          d|            )	Nrl  rm  rn  ro  rp  rq  zUnsupported destination: r"   )r{   ri   r   BatchJobDestinationr   r3   r@   r   )r  s    r&   t_batch_job_destinationr  E  s     d 9$,,t,,DK$ 9w ;&    
	!	! ;&   
 9499:::tU677 9K
777
8
88r(   c                     |                      di                                dg           }|s| S |D ]9}|                     di           }|sd|v r|                     d          | d<    n:| S )NinlinedResponsesrK   	embeddinginlinedEmbedContentResponses)rP   r  )r  inline_responsesrK   inner_responses       r&   t_recv_batch_job_destinationr  ^  s    XX0"5599"  
 K"  h\\*b11N n$$-1XX6H-I-Id)*e % 
+r(   c                 P   | j         sEd}t          j        ||          r|                    d          d         S t	          d| d          d}t          j        ||          r|                    d          d         S |                                r|S t	          d| d          )Nzbatches/[^/]+$r0   r  zInvalid batch job name: .z:^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$)r5   rx  ry  rA   r@   isdigit)r+   r   mldev_patternvertex_patterns       r&   t_batch_job_namer  o  s    	 ;%M	xt$$ ;ZZ__R  9$999:::P.Xnd## 9::c??2||~~ 9K
7777
8
88r(   statec                 v    | dk    rdS | dk    rdS | dk    rdS | dk    rdS | d	k    rd
S | dk    rdS | dk    rdS | 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"   )r  s    r&   t_job_stater    s    
'''""%%%%%%'''  $$$'''  %%%Lr(   g      ?g      4@g      @g      ?structc                    |                     d          x}rd|v r|}d}t          }|                     d          dk    r|t          k    rt          d| d|           |                     d|i 	          }t          j        |           ||z  }t          |t          z  t                    }|                     d          dk    |                     d
          x}rt          d| d| d|           |                     d          S |S )Nr   z/operations/g        doneTz
Operation z timed out.
GET)http_methodpathrequest_dicterrorz failed with error: z.
rK   )
rP   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)rE   r  r   	operationtotal_secondsdelay_secondsr  s          r&   t_resolve_operationr    sJ    jj   d n&<&<$*IM5M
--

4
'
'	4	4	4FFF9FFGGG$$$R %  i j}$m
0
0
+ m --

4
'
' g&&&u 
Ft
F
F
F
F9
F
F   ==$$$Mr(   c                    t          | t          j                  r| j        } nRt          | t          j                  r| j        } n0t          | t          j                  r| j        | j        j        } nd } | t          d          t          | t                    s t          dt          |            d          |                     d          rZ|                     d          d         }t          j        d|          }|t          d|            |                    d	          } n0|                     d          r|                     d          d         } | S )
NzFile name is required.z"Could not convert object of type `z` to a file name.zhttps://rt  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )r   r   r   r   Videor   GeneratedVideovideor@   r{   r   r   r3   rA   rx  ry  group)r   suffixry  s      r&   t_file_namer    sP    T5:&& 9DDtU[)) 8DDtU122 zZ^ddd	\
-
.
..	D#		 
JT$ZZJJJ   
__Z   #ZZ!!!$FH[&))E}FFFGGG;;q>>DDx   #::h"D	+r(   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    r|c S | S )NSTATE_UNSPECIFIEDCREATINGACTIVEFAILED)r   JobStater  r  r  r  r   r  )r  r  s     r&   t_tuning_job_statusr    s    """>//>++>-->**  	U[		V	#	# 
$Mr(   c                     t          | t                    rt          j                            |           S t          | t          j                  r| S t          dt          |            d          )NCould not convert input (type "z") to `types.Content`)r{   ri   r   r   r}   r   r@   r   )r   s    r&   t_content_strictr    si     =''000w.. N
N$w--NNN  r(   c                 d    t          | t                    rd | D             S t          |           gS )Nc                 ,    g | ]}t          |          S r"   )r  r   s     r&   r   z%t_contents_strict.<locals>.<listcomp>  s!    >>>'W%%>>>r(   )r{   r   r  r   s    r&   t_contents_strictr    s;     (## (>>X>>>>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  	Exceptionr@   r   )r  r  es      r&   t_client_contentr    s     ]"????	"///#    
   
	$$u++ 	$ 	$ 	$  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`)r@   r   LiveClientToolResponser   r  r   )r  r  s     r&   t_tool_responser    s     
 E
CECC
D
DD'/5III    
   
	)$u++ 	) 	) 	)  s   "9 
A)!A$$A)metricsc                 0   g }| D ]}t          |t                    r6	 t          j                            |          }n# t
          j        $ r Y nw xY wt          |t          j                  r1|                                }ddg|d<   |                    |           i }ddg|d<   t          |dg          
                                }|dk    ri |d<   n|dk    ri |d<   n|                    d	          r|                    d
d          }d|i|d<   njt          |d          rH|j        rAd|j        i}t          |dg          }|r||d<   t          |dg          }	|	rd|	i|d<   ||d<   nt          d|           |                    |           |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  r^   
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: )r{   ri   r   UnifiedMetricr}   r   r   r?  r   getvrr   r3   replacehasattrr  r@   )
r  metrics_payloadmetricunified_metric_payloadmetric_payload_itemmetric_namer  pointwise_specr  r  s
             r&   	t_metricsr  '  sI    O 42 42	FD	!	! 	&55f==&&' 	 	 	
$	 
FE/	0	0 171B1B1D1D 9
45 	5666,.

4/0
 &**0022k		%	%24.//&  +-K((!!'** 
 ((b11
-9:,FL))6,-- 
&2H 
2F4JK!56
 
  	D1C.-
. ()
 
  	!#4;.6
7 8F344O+OO
 
 	
 01111s   >AAc                     d| v r| dk    pd| v S )Ngeminizgemini-embedding-001maasr"   )r:   s    r&   t_is_vertex_embed_content_modelr  m  s(     %;E%;; 	5	r(   r   )NT)__doc__base64collections.abcr   r   r  r   r   rV  rn   loggingrx  sysr  r   builtin_typesrB  r   r   r	   r
   r   r   
_mcp_utilsr   r   r   r  r   TYPE_CHECKINGr   r   r   r^   r   	getLoggerrQ   version_info	UnionTyperA  rD  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer,  r   metric_name_sdk_api_mapr   metric_name_api_sdk_mapBaseApiClientr   r/  r9   rD   r   rJ   r  r   rV   rX   rs   rx   FunctionResponseOrDictr|   r   r   BlobImageUnionDictr   r   r   
BlobOrDictr   r   r   r   r   r   r   r   ContentDictContentTyper   r   ContentListUnionContentListUnionDictr   r   r   r   r  r
  r2  r7  SchemaUnionDictr:  rE  SpeechConfigUnionDictrJ  rM  SpeechConfigOrDictrQ  r[  rd  rg  BatchJobSourceUnionDictrv  r|  EmbeddingsBatchJobSourceOrDictr~  r  BatchJobDestinationOrDictr  r  ri   r  r  r  r  r  r  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  r  r"   r(   r&   <module>r     s#    ) ( (  - - - - - - - -          				  				 



       E E E E E E E E E E E E E E E E * * * * * * . . . . . . $ $ $ $ $ $	                    		7	8	8w$., 78,0,,))))))	 333333'''''''"%FK%%%'6;555555)))))))	   GGG $  
 ML,C,I,I,K,KLLL  '(Z Z Z%ZZ 	Z
 !$Z 	Z Z Z ZzK- c c    4)8<    	'
   >)25c]   ";s ;uz ; ; ; ;&3
    5$-.	05
 
%
 !5 5 5 5)40H+IIJ	%*   ) ej    4Au/ AEJ A A A AAu' AEJ A A A AC%-. C5: C C C C<d5&')<d5:>NNO 
%*	   (738#456d5'()   & EM5#4e6IIJ*; 1478*
]* * * *8 % D'e.?)@+MN  49d5=))*       4ie$e&@%-OPi 
%-	i i i iX8w1 8d 8 8 8 8v9s 9t 9 9 9 9
MM!+";<M	M M M M" *.l(
 "-1l( l( l(l([./l( 7%
&l(
 l( !S*l( 
l( l( l( l(\2
2$[%>?2
\2 2 2 2:%',-w!"   -9[./-9%',--9 el-9 -9 -9 -9`E%-s23Ee !E E E E&$e !    %/2eEJO$%   *%/3Cy	%*   :N+"; N3 N3 N N N N81%81		&81 81 81 81 81v>%>		-> #> > > >.9
U44
59
9 9 9 92tCH~ $sCx.    "9[6 9c 9c 9 9 9 9$s s    & %( !$( !#  )3:3E   <
5ej%+u7KKL
M   D enc.A(B     e1 em    (HU0153FFG(	%-( ( ( ( 		 hu*+U-@@A 	
    *$-.	0
 !   (C%&'C	$sCx.C C C CL3 4      s   4D 	DD