
    עiI                     "   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
jF                  d      Z$ejJ                  dk\  r+ejL                  Z'ej,                  ejL                  fZ(ddlm)Z) nejT                  Z'ej,                  fZ(ddl+m)Z) ej:                  rddl,m-Z. ddl/m0Z1 n/eZ.ejd                  e3d<   eZ1ejd                  e3d<   	 ddl,m-Z. ddl/m0Z1 ddddZ5e5jm                         D  ci c]  \  } }|| 
 c}} Z7ddde"jp                  de9de9de:de9f
dZ;de"jp                  d e9de9fd!Z<d"e"jp                  d#e=de9fd$Z>d%ej~                  de@ej~                     fd&ZAd"e"jp                  d e9dee9   fd'ZBd(edej                  fd)ZDd*ej                  dej                  fd+ZGd,eej                  eej                     f   de@ej                     fd-ZHd.eej                  e@ej                     f   de@ej                     fd/ZJd0ej                  dej                  fd1ZKd0ej                  dej                  fd2ZLd0ej                  dej                  fd3ZNd4eej                     dej                  fd5ZQd6eee@ej                     ej                  e@ej                     f      de@ej                     fd7ZRd8eeee9ef         dee@ej                        fd9ZTeej                  ej                  ej                  f   ZWd:eeWej                  df   dej                  fd;ZXde"jp                  d<ee@ej                     e@ej                     eWf   dee@e9   e@ej                     f   fd=ZYd<eeej                  ej                  ej                  f      de@ej                     fd>Z\d?ej~                  ddfd@Z]dAeddfdBZ^d?edee"jp                     ddfdCZ_	 dodDdEd?ej~                  dee"jp                     dFeej~                     dGe=ddf
dHZ`dIedee"jp                     dej                  fdJZbdAeej                  ef   de)ej~                     fdKZddee"jp                     dAeej                  ef   deej                     fdLZedAeej                  ef   deej                     fdMZhdAej                  deej                     fdNZjde"jp                  dAedeeej`                  ef      fdOZkde"jp                  dAe@e   de@ej`                     fdPZlde"jp                  dQe9de9fdRZmde"jp                  dSej                  dej                  fdTZpde"jp                  dSej                  dej                  fdUZsdVee9ej                  f   dej                  fdWZvdVewe9ef   dewe9ef   fdXZxde"jp                  dQe9de9fdYZydZe9de9fd[Zzd\Z{d]Z|d^Z}d_Z~d"e"jp                  d`ej~                  defdaZdQeee9ej                   ej                  ej                  f      de9fdbZdce9deej                  e9f   fddZd:ej                  dej                  fdeZd<eeej                     ej                  f   de@ej                     fdfZ	 	 dpdgeeeej                     ej                  f      dhe=dej                  fdiZdjeej                  eej                     f   dej                  fdkZdle@ej                     de@ewe9ef      fdmZd e9de=fdnZy# e4$ r dZ.dZ1Y Tw xY wc c}} w )qz"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_spec   )collection_hierarchy_depthclientresource_namecollection_identifierr"   returnc                   |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)r#   r$   r%   r"   $should_prepend_collection_identifiers        [/sites/domain-asset-master/.venv/lib/python3.12/site-packages/google/genai/_transformers.py_resource_namer2   L   s!   J 
"
"&;%<A#>
?? $ ##1]O
4
:
:3
?!
C	#$	 ' __,		!	!,	/(-99		!	!%:$;1"=	>(FOO3DAm_UU	-(FOO3DAF[E\\]^k]lmm+%&a77    modelc                 n   |st        d      d|v sd|v sd|v r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.z..?&zinvalid model parameter.r)   models/publishers/r(   r   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr-   r+   split)r#   r4   	publishermodel_ids       r1   t_modelr>      s    	
)
**	U]cUlcUl
/
00__%I&M*l	!KKQ/i9+XhZ88(00	"l			.	)lugr3   
api_clientbase_modelsc                 *    | j                   r|ryy|ryy)Nzpublishers/google/modelsmodelstunedModels)r-   )r?   r@   s     r1   t_models_urlrD      s     'r3   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 )NrB   rC   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)rE   rB   tuned_modelspublisher_modelss       r1   t_extract_modelsrP      s     
I/7||H/E&M5=\\-5P,9A: ! ll=!-
,,}
%
-I
NN67
LLDhOIr3   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 )Nr9   r)   r*   r(   r8   z/publishers/google/)r>   r+   r-   r.   r/   )r?   r4   s     r1   t_caches_modelrR      s     *e
$%	
m$)<)< J&&'{:3F3F2GqP 	"z':':z))*+j6I6I5JJ]^c]deeLr3   imagec                 Z   d}t               }| j                  dk(  r/t        | dd      r"| j                  dv rd}|j	                  d       t        j                         } | j                  ||fi | |j                         }d|j                          }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)rS   image_formatsave_paramsimage_ioimage_bytesrb   s         r1   pil_to_blobrr     s    , $+llf
%R
(
**9
9Lv&ZZ\(%**X|3{3!!#+|))+,-)			::r3   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: )	r:   
isinstancerc   r   FunctionResponsemodel_validater   	TypeErrortype)rs   s    r1   t_function_responserz     sp     

5
66!4(!!001BCC(%*@*@A
	$$():$;#<	> r3   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.)r:   ru   r   rz   )r{   rE   s     r1   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 N)ru   listt_blob)r~   blobs     r1   t_blobsr   3  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.rS   r   z6Could not parse input as Blob. Unsupported blob type: )r:   r   r   rm   ru   rc   rw   	__class____name__rl   	PIL.ImageImageImportErrorrr   rx   ry   )r   PIL	PIL_Images      r1   r   r   <  s    	
(
))T5::&Kd::$$T**''--//))//i D)!<>tDzlK	   is    C
 
CCc                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nr`   Unsupported mime type: r   rb   r+   r:   r   s    r1   t_image_blobr   V  @    	$	^^11(;K,T^^,>?@@r3   c                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzaudio/r   r   r   s    r1   t_audio_blobr   ]  r   r3   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_urirb   )	file_datarS   r   )inline_datazUnsupported content part type: )r:   ru   strr   Partr   Fileurirb   from_urirc   rw   pydanticValidationErrorFileDatar   r   rl   r   r   r   rr   ry   r   r   r   s      r1   t_partr   d  sg   	\
0
11c::4  T5::&884>>=>>::DNNKKdGZZ&&t,, T5::&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.)ru   r   r:   r   )r   r   s     r1   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 )NrS   gcsUri
imageBytes)gcs_urirq   )rS   )rJ   appendr   GeneratedImager   )r   images
predictions      r1   t_image_predictionsr     sq     
& 	j~~gmm


KK$W-h7(1,?	 
-r3   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   )r:   r   r   Contentru   rc   rw   r   r   r   function_callModelContentUserContentr   r   )r   possible_parts     r1   	t_contentr     s'    _
+
,,Wemm,N]]))'22 Wejj)F7O#455Wejj)    	'+ 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.)ru   r   r   r-   rc   r   r   rw   r   r   r   rK   rL   )r#   r   r   transformed_contents
text_partsr   s         r1   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)NTFrS   r   )ru   r   r   r   r   r   rc   rw   r   r   r   r   r   rl   r   r   r   r   s      r1   _is_partzt_contents.<locals>._is_part  s     	44,4,$

!!$' $..))//11IIOO	 
	:dI#>% %% 	
..
'
'
-'' 			  	s<   C !D DD  DDDDD,+D,c                     | j                    S r   )r   )r   s    r1   _is_user_partz!t_contents.<locals>._is_user_part  s    !!!!r3   r   c                 ,    t        fd| D              S )Nc              3   .   K   | ]  } |        y wr    ).0r   r   s     r1   	<genexpr>z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>  s     5t}T"5s   )all)r   r   s    r1   _are_user_partsz#t_contents.<locals>._are_user_parts  s    5u555r3   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     r1   $_append_accumulated_parts_as_contentz8t_contents.<locals>._append_accumulated_parts_as_content  sM     
MM,- 	 12&78
 ar3   current_partc                     t        |      } |       |      k(  r|j                  |       y  | |       |g|d d  y r   )r   r   )r   r   r   r   r   r   s      r1   _handle_current_partz(t_contents.<locals>._handle_current_part!  sH    
 ,'L\"o6G&HH|,*63DE*^r3   r   zUnsupported content type: )ru   r   r:   r   r   r   PartUnionDictr   r   r   boolr   r   r   r   rc   rw   ry   )	r   r   r   r   r   r   r   r   r   s	         @@@r1   
t_contentsr     s   
 *Xt4X
-
..	Hd	#h   "&(*#%%%s*+#$$%#J"%** " "6T%**- 6$ 65==!ejj) 
,5==!
,ejj)
, ''
, 	
,&  Egw.*Wd2K*63DE	GT	"e''g67g	'	6#4g>	GT	"mmEMM009:3DM?CDDE 'v/@A	-r3   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   )rJ   removelenitems)r   itemkeyvals       r1   handle_null_fieldsr   H  s    X ZZ'F:v&w 	4DLF2!zw/0vg1$ /!,224 hc3F3KWo r3   originc                     t        d|        )z2Raises an error if the schema type is unsupported.Unsupported schema type: )r:   r   s    r1   "_raise_for_unsupported_schema_typer     s    .vh788r3   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-   rJ   r:   )r   r#   s     r1   '_raise_for_unsupported_mldev_propertiesr     sE     oo
**+
,ZZ/0 O
PP 1  r3   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   )popr;   process_schema)r   refr#   r   r   s     r1   _recursez process_schema.<locals>._recurse  sF    ~~fd++8		'*2./j:vt>NOr3   r   ry   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   )rJ   r   r   r   r   r   rg   r;   r   
StringDictru   r   valuer   upperr:   r   r   keysrc   )r   r#   r   r   	from_nameto_namer  _r   r   r   r   schema_typer   r  name
additionalr   prefixesprefixs    ```                r1   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   r1   Placeholderr  A  s	      r3   r  r  r  )ru   r  intr   rx   r  ry   r   r   r   	BaseModelmodel_json_schemar   r   Schemarw   )	r  r#   is_integer_enummemberstr_membersstr_enumr  enum_schemar  s	           @r1   _process_enumr%  -  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   )ru   r   )r   r   s     r1   r   z(_is_type_dict_str_any.<locals>.<genexpr>N  s      *"jc*s   )ru   rc   r   r   s    r1   _is_type_dict_str_anyr(  J  s,     
FD	! 
c *&,* ' r3   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   r1   r  r,  x  s	    r3   r  r  r  r   )ru   rc   r(  r   r   r  rw   r   r%  r   r   
model_dumpr   ry   
issubclassr   r  r  VersionedUnionTypetyping
get_origin_UNION_TYPESr:   )r#   r   r   r  s    `  r1   t_schemar3  S  s    
"7"?66"<<&&v..!((VU\\*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8r3   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   SpeechConfigru   r   VoiceConfigPrebuiltVoiceConfigrc   rw   r:   ry   r   s    r1   t_speech_configr;    s     
VU//0M&&"'";";v"N
 
 ,,V444T&\NCDDr3   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   r8  ru   rc   rw   multi_speaker_voice_configr:   )r   speech_configs     r1   t_live_speech_configr?    s]     VU//0M&&55f=M--9
F  
r3   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)r#   callablefunction_declarations)inspect
isfunctionismethodr   r   FunctionDeclarationfrom_callabler   r   r   ru   rc   rw   )r#   r   s     r1   t_toolrI    s     
7#3#3F#;::%%33 4 
  vw?f%%&$::$$V,,Mr3   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 )NrB  )r   r   rI  rC  r   )r#   r   function_tooltoolstooltransformed_tools         r1   t_toolsrO    s     
I**26-
% 'dfd+#

0
011=++22	
+ 	%&' ((	LL	,r3   r  c                     t        | |d      S )NcachedContents)r%   )r2   )r#   r  s     r1   t_cached_content_namerR    s    	<L	MMr3   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rd   r   bq://bigqueryrd   bigquery_urifiles/)	file_namezUnsupported source: r   )ru   rc   r   BatchJobSourcer   sumr   r]  rV  r_  r-   r:   r   r   r+   )r#   rS  vertex_sourcesmldev_sourcess       r1   t_batch_job_sourcerd    s    T



%
%CS%../	D	 #"2"2$">?N D(T! M 	.A-6
 	
 J 
=A-J
 	

 J#t55#s
~~g!!%  
	 !!  
	!!!  	)#/00r3   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   rU  zUnsupported source type: r   )
ru   rc   r   EmbeddingsBatchJobSourcer   ra  rV  r_  r:   ry   )r#   rS  rc  s      r1   t_embedding_batch_job_sourcerg  
  s     T

(
(
/3
/CS%889D(T! M H 
 J
0c<
==r3   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|        )	NrW  rX  rY  rZ  r[  r\  zUnsupported destination: r   )ru   rc   r   BatchJobDestinationr   r+   r:   r   )rh  s    r1   t_batch_job_destinationrk  !  s     d$$,t,DK$w&&  
	!&& 
 24&9::tU667K
07
88r3   c                     | j                  di       j                  dg       }|s| S |D ]2  }|j                  di       }|sd|v s| j                  d      | d<    | S  | S )NinlinedResponsesrE   	embeddinginlinedEmbedContentResponses)rJ   r   )rh  inline_responsesrE   inner_responses       r1   t_recv_batch_job_destinationrr  :  s    XX0"599" 
K" h\\*b1Nn$-1XX6H-Id)*	+ 
+r3   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/[^/]+$r(   r   zInvalid batch job name: .z:^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$)r-   rematchr;   r:   isdigit)r#   r  mldev_patternvertex_patterns       r1   t_batch_job_namerz  K  s    	%M	xxt$ZZ_R  1$q9::P.XXnd#::c?2||~K
/vQ7
88r3   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   )r{  s    r1   t_job_stater  ]  s[    
''"%%%%'' $$'' %%Lr3   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.
rE   )
rJ   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)r?   r  r  	operationtotal_secondsdelay_secondsr  s          r1   t_resolve_operationr  v  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  ==$$Mr3   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videor:   ru   r   ry   r+   r;   ru  rv  group)r  suffixrv  s      r1   t_file_namer    s    T5::&99DtU[[)88DtU112zzZZ^^dd	\
-
..	D#	

,T$ZL8IJ  
__Z ZZ!!$FHH[&)E}?vFGG;;q>D 
+ x ::h"D	+r3   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  r{  s     r1   t_tuning_job_statusr    s    "">>///>>+++>>--->>*** 	U[[	V	# Mr3   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`)ru   rc   r   r   rw   r   r:   ry   )r   s    r1   t_content_strictr    sR    ==''00w.N

)$w-8MN r3   c                 v    t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w r   )ru   r   r  )r   r   s     r1   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  	Exceptionr:   ry   )r  r  es      r1   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`)r:   r   LiveClientToolResponser}   r  ry   )r  r  s     r1   t_tool_responser    ss     

;E7C
DD''/5I  
 

)$u+ 7) 	) s   2 	AAAmetricsc                    g }| D ]P  }t        |t              r 	 t        j                  j	                  |      }t        |t        j                        r)|j                         }ddg|d<   |j                  |       wi }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 |S # t
        j                  $ r Y 8w xY w)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  rX   
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: )ru   rc   r   UnifiedMetricrw   r   r   r-  r   getvrl   r+   replacehasattrr  r:   )
r  metrics_payloadmetricunified_metric_payloadmetric_payload_itemmetric_namer  pointwise_specr  r  s
             r1   	t_metricsr    s    O 42	FD	!	&&55f=& 
FE//	0171B1B1D 9
45 	56,.

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42j a '' 	
	s   EE21E2c                 $    d| v xr | dk7  xs d| v S )Ngeminizgemini-embedding-001maasr   )r4   s    r1   t_is_vertex_embed_content_modelr  I  s(     %;E%;; 	5	r3   r   )NT)__doc__base64collections.abcr   r   r  r   r   rD  rh   loggingru  sysr  r   builtin_typesr0  r   r   r	   r
   r   r   
_mcp_utilsr   r   r   r  r   TYPE_CHECKINGr   r   r   rX   r   	getLoggerrK   version_info	UnionTyper/  r2  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer  r   metric_name_sdk_api_mapr   metric_name_api_sdk_mapBaseApiClientr   r  r2   r>   r   rD   r  r   rP   rR   rm   rr   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(  r3  SpeechConfigUnionDictr8  r;  SpeechConfigOrDictr?  rI  rO  rR  BatchJobSourceUnionDictr`  rd  EmbeddingsBatchJobSourceOrDictrf  rg  BatchJobDestinationOrDictrj  rk  rc   rr  rz  r  r  r  r  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  r  )kvs   00r1   <module>r     s	    )  -   	  	 
    E E * . $	    			7	8w$..,, 7 78,00,,,)	3'"%FKK%'6;;5) $ 
 -D,I,I,KLDAq1a4L  '(Z%%ZZ 	Z
 !$Z 	ZzK-- c c 4))8<  	'

>))25c]";s ;uzz ;&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
 !!(C%&&'C	$sCx.CL3 4 U( 
 G Ms   ']; ^;	^^