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

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

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

  Returns:
    True if the object has all the fields defined in the Pydantic model, False
    otherwise.
  model_fieldsFc              3   6   K   | ]  }t        |        y wNhasattr).0fieldr    s     X/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/google/genai/_transformers.py	<genexpr>z#_is_duck_type_of.<locals>.<genexpr>^   s     FEGC'F   c              3   6   K   | ]  }t        |        y wr&   r'   )r)   fobj_privates     r+   r,   z#_is_duck_type_of.<locals>.<genexpr>d   s     PAQ/Pr-   )	
isinstancedictr(   allr$   pydantic	BaseModeltype
ValueError)r    r!   all_matchedr0   s   `  @r+   _is_duck_type_ofr9   K   s     T'#~"> FS5E5EFF+	C););<EkPc9O9OPPk 
  s   .B 	BB   )collection_hierarchy_depthclientresource_namecollection_identifierr;   c                   |j                  | d       xr | d| j                  d      dz   |k(  }| j                  r|j                  d      r|S |j                  d      rd| j                   d| S |j                  | d      rd| j                   d| j                   d| S |r"d| j                   d| j                   d| d| S |S |r| d| S |S )a|  Prepends resource name with project, location, collection_identifier if needed.

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

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

  Example:

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

  Example:

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

  Example:

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

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

  Returns:
    The completed resource name.
  /r   	projects/z
locations//locations/)
startswithcountvertexaiprojectlocation)r<   r=   r>   r;   $should_prepend_collection_identifiers        r+   _resource_namerI   j   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.rA   models/publishers/r@   r   z/models/zpublishers/google/models/ztunedModels/)r7   rE   rC   split)r<   rK   	publishermodel_ids       r+   t_modelrT      s    	
)
**	U]cUlcUl
/
00__%I&M*l	!KKQ/i9+XhZ88(00	"l			.	)lugrJ   
api_clientbase_modelsc                 *    | j                   r|ryy|ryy)Nzpublishers/google/modelsmodelstunedModels)rE   )rU   rV   s     r+   t_models_urlrZ      s     'rJ   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 )NrX   rY   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)r[   rX   tuned_modelspublisher_modelss       r+   t_extract_modelsrf      s     
I/7||H/E&M5=\\-5P,9A: ! ll=!-
,,}
%
-I
NN67
LLDhOIrJ   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 )NrP   rA   rB   r@   rO   z/publishers/google/)rT   rC   rE   rF   rG   )rU   rK   s     r+   t_caches_modelrh     s     *e
$%	
m$)<)< J&&'{:3F3F2GqP 	"z':':z))*+j6I6I5JJ]^c]deeLrJ   imgc                    	 dd l }|j                  }t        j                         }|t        | |j                        s| j                  dk(  r| j                  |d       d}n| j                  |d       d}|j                  d       |j                         }t        j                  ||      S # t        $ r d }Y w xY w)	Nr   RGBAPNG)formatz	image/pngJPEGz
image/jpeg)	mime_typedata)PIL.PngImagePluginPngImagePluginImportErrorioBytesIOr1   PngImageFilemodesaveseekreadr   Blob)ri   PILrr   bytesioro   rp   s         r+   pil_to_blobr~      s    ''N JJL' 
S.55
6	V	HHWUH#IHHWVH$I	,,q/	$	id	33! 
 Ns   B0 0B>=B>function_responsec                     | st        d      t        | t              rt        j                  j                  |       S t        | t        j                        r| S t        dt        |              )Nzfunction_response is required.zOCould not parse input as FunctionResponse. Unsupported function_response type: )	r7   r1   r2   r   FunctionResponsemodel_validater9   	TypeErrorr6   )r   s    r+   t_function_responser   9  sp     

5
66!4(!!001BCC)5+A+AB
	$$():$;#<	> rJ   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.)r7   r1   r   r   )r   r[   s     r+   t_function_responsesr   I  sJ     

7
88"H-:LMh)MM 2344 Ns   Ablobsc                 v    t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w r&   )r1   listt_blob)r   blobs     r+   t_blobsr   W  s4     t%*+TF4L++5M? ,   6r   c                    | st        d      t        | t        j                        r| S t	        | t
              rt        j                  j                  |       S d| j                  j                  j                         v r4	 dd l
}|j                  j                  }|t	        | |      rt        |       S t        dt        |              # t        $ r d }Y =w xY w)Nzblob is required.imager   z6Could not parse input as Blob. Unsupported blob type: )r7   r9   r   r{   r1   r2   r   	__class____name__lower	PIL.ImageImagers   r~   r   r6   )r   r|   	PIL_Images      r+   r   r   `  s    	
(
))dEJJ'Kd::$$T**''--//))//i D)!<>tDzlK	   is    C
 
CCc                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzimage/Unsupported mime type: r   ro   rC   r7   r   s    r+   t_image_blobr   z  @    	$	^^11(;K,T^^,>?@@rJ   c                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzaudio/r   r   r   s    r+   t_audio_blobr     r   rJ   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_uriro   )	file_datar   r   )inline_datazUnsupported content part type: )r7   r1   strr   Partr9   Fileuriro   from_urir2   r   r4   ValidationErrorFileDatar   r   r   r   r   rs   r~   r6   r   r|   r   s      r+   t_partr     sg   	\
0
11c::4  dEJJ'884>>=>>::DNNKKdGZZ&&t,, dEJJ'K''--//))//i D)!<ZZK$5664T$ZLABB ## GZZ%.."?"?"EFFG  is%   7E7 G 7AG ?G GGpartsc                     | t        | t              r| st        d      t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w )Nzcontent parts are required.)r1   r   r7   r   )r   r   s     r+   t_partsr     sP     ]z%.u
2
33t%*+TF4L++5M? ,s   Apredictionsc           
          | sy g }| D ]Z  }|j                  d      s|j                  t        j                  t        j                  |d   d   |d   d                      \ |S )Nr   gcsUri
imageBytes)gcs_uriimage_bytes)r   )r`   appendr   GeneratedImager   )r   images
predictions      r+   t_image_predictionsr     sq     
& 	j~~gmm


KK$W-h7(1,?	 
-rJ   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   )r7   r9   r   Contentr1   r2   r   r4   r   r   function_callModelContentUserContentr   r   )r   possible_parts     r+   	t_contentr     s'    _
+
,,gu}}-N]]))'22 guzz*F7O#455guzz*    	'+ gY/
 
			)) ## Wom (( 

M?
3   7s   C> >AEEEcontentsc                    t        |t              r|D cg c]  }t        |       }}nt        |      g}| j                  rg }|D ]  }|t        |t              rt
        j                  j                  |      }|j                  B|j                  D ]?  }|j                  r|j                  |j                         +t        j                  d       A  |S |S c c}w )Nz/Non-text part found, only returning text parts.)r1   r   r   rE   r2   r   r   r   r   r   r   ra   rb   )r<   r   r   transformed_contents
text_partsr   s         r+   t_contents_for_embedr     s     $>FG7Ig.GG%h/0__J' 	Q		gt$MM009'==$mm Qdyy		*nnNP	Q	Q % Hs   Cc                 V   | t        | t              r| st        d      t        | t              st        |       gS g }g }dt        t
        j                  t        f   dt        t
        j                     fd}dt
        j                  dt        fddt        t
        j                     dt        ffddt        t
        j                     d	t        t
        j                     dd ffd
dt        t
        j                     d	t        t
        j                     dt
        j                  dd ffd}| D ]  }t        |t
        j                        st        |t              rQ ||       t        |t              r&|j                  t        j                  |             l|j                  |       ~ ||      r ||||       t        |t              r/|j                  t
        j                  j!                  |             t        dt#        |               ||       |S )Nzcontents are required.r   r"   c                 ^   t        | t              s4t        | t        j                        st        | t        j
                        ryt        | t              r$| sy	 t        j
                  j                  |        yd| j                  j                  j                         v r*	 dd l}|j                  j                  }|t        | |      ryy# t        j                  $ r= 	 t        j                  j                  |        Y y# t        j                  $ r Y Y yw xY ww xY w# t         $ r d }Y pw xY w)NTFr   r   )r1   r   r9   r   r   r   r2   r   r4   r   r   r   r   r   r   r   rs   r   s      r+   _is_partzt_contents.<locals>._is_part  s     	4D%**-D%**-$

!!$' $..))//11IIOO	 
	:dI#>% %% 	
..
'
'
-'' 			  	s<   C !D DD  DDDDD,+D,c                     | j                    S r&   )r   )r   s    r+   _is_user_partz!t_contents.<locals>._is_user_part2  s    !!!!rJ   r   c                 ,    t        fd| D              S )Nc              3   .   K   | ]  } |        y wr&    )r)   r   r   s     r+   r,   z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>6  s     5t}T"5s   )r3   )r   r   s    r+   _are_user_partsz#t_contents.<locals>._are_user_parts5  s    5u555rJ   resultaccumulated_partsc                     |sy | j                   |      rt        j                  |      nt        j                  |             g |d d  y )Nr   )r   r   r   r   )r   r   r   s     r+   $_append_accumulated_parts_as_contentz8t_contents.<locals>._append_accumulated_parts_as_content8  sM     
MM,- 	 12&78
 arJ   current_partc                     t        |      } |       |      k(  r|j                  |       y  | |       |g|d d  y r&   )r   r   )r   r   r   r   r   r   s      r+   _handle_current_partz(t_contents.<locals>._handle_current_partE  sH    
 ,'L\"o6G&HH|,*63DE*^rJ   r   zUnsupported content type: )r1   r   r7   r   r   r   PartUnionDictr   r   r   boolr   r9   r   r   r2   r   r6   )	r   r   r   r   r   r   r   r   r   s	         @@@r+   
t_contentsr      s   
 *Xt4X
-
..	Hd	#h   "&(*#%%%s*+#$$%#J"%** " "6T%**- 6$ 65==!ejj) 
,5==!
,ejj)
, ''
, 	
,&  Eg/:gt3L*63DE	GT	"e''g67g	'	6#4g>	GT	"mmEMM009:3DM?CDDE 'v/@A	-rJ   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"
        }
      }
  r6   NnullTnullableanyOfr   r   )r`   removelenitems)r   itemkeyvals       r+   handle_null_fieldsr   l  s    X ZZ'F:v&w 	4DLF2!zw/0vg1$ /!,224 hc3F3KWo rJ   originc                     t        d|        )z2Raises an error if the schema type is unsupported.Unsupported schema type: )r7   r   s    r+   "_raise_for_unsupported_schema_typer     s    .vh788rJ   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.)rE   r`   r7   )r   r<   s     r+   '_raise_for_unsupported_mldev_propertiesr     sE     oo
**+
,ZZ/0 O
PP 1  rJ   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   )poprQ   process_schema)r   refr<   r   r   s     r+   _recursez process_schema.<locals>._recurse   sF    ~~fd++8		'*2./j:vt>NOrJ   r   r6   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   )r`   r   r  r   r  r   updaterQ   r   
StringDictr1   r   valuer   upperr7   r   r   keysr2   )r   r<   r   r   	from_nameto_namer  _r   r  r  r   schema_typer  r
  name
additionalr   prefixesprefixs    ```                r+   r  r    s   F ZZ44w)&&9
 i It,,9fWo 
\::gr"D : 
fd5E	 V
 ZZ%%c2
MM$syy)"-./7-- '2D2D  

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

6"+T"##KS!##%K **W
%
hwfVn
/899Hjj..
;":#3#3#56 0
$
#J/
40 j 
!A
% .&*:??+<&="#jj!788
E 
J	%)1*)=%& 
& F
 gG$$1 fWoJJ}--:>FGFx/Gf] ; E FL Hs   
JJ$r  c           	      .   d}| D ]g  }t        |j                  t              rd} t        |j                  t              r;t	        d|j
                   dt        |j                                | |r@| D cg c]  }t        |j                         }}t        | j                  |t              }| G fddt        j                        }|j                         }t        ||       |d   d	   }t        j                  j                  |      S c c}w )
NFTzEnum member z( value must be a string or integer, got )r6   c                       e Zd ZU W  ed<   y)"_process_enum.<locals>.PlaceholderplaceholderNr   
__module____qualname____annotations__)enum_to_processs   r+   Placeholderr  e  s	      rJ   r"  r
  r  )r1   r  intr   r   r  r6   r   r   r4   r5   model_json_schemar  r   Schemar   )	r  r<   is_integer_enummemberstr_membersstr_enumr"  enum_schemar!  s	           @r+   _process_enumr+  Q  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&   )r1   r   )r)   r   s     r+   r,   z(_is_type_dict_str_any.<locals>.<genexpr>r  s      *"jc*s   )r1   r2   r3   r   s    r+   _is_type_dict_str_anyr.  n  s,     
FD	! 
c *&,* ' rJ   c                 <   sy t        t              r6t              r+t        |        t        j
                  j                        S t        t              rt        |       S t        t        j
                        rqt              t        t	        j
                               k(  rt               j                  d      }t        ||        t        j
                  j                  |      S t        t              set        t              rUt        t        j                         r;j#                         }t        ||        t        j
                  j                  |      S t        t              s;t        t              s+t        t$              st'        j(                        t*        v r^ G fddt        j                         }|j#                         }t        ||        |d   d   }t        j
                  j                  |      S t-        d       )NT)exclude_unsetc                       e Zd ZU W  ed<   y)t_schema.<locals>.Placeholderr  Nr  r   s   r+   r"  r2    s	    rJ   r"  r
  r  r   )r1   r2   r.  r  r   r%  r   r   r+  r9   r   
model_dumpr   r6   
issubclassr4   r5   r$  VersionedUnionTypetyping
get_origin_UNION_TYPESr7   )r<   r   r   r"  s    `  r+   t_schemar9  w  s    
"7"?66"<<&&v..!((fell+F|tELLN++ )0T2F66"<<&&v..
 V\
*
VT
"
VX//
0%%'F66"<<&&v..&	FD	!	F.	/			6	"l	2h((  **,F66"L!-0F<<&&v...vh788rJ   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: )r9   r   SpeechConfigr1   r   VoiceConfigPrebuiltVoiceConfigr2   r   r7   r6   r   s    r+   t_speech_configrA    s     
fe001M&&"'";";v"N
 
 ,,V444T&\NCDDrJ   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.)r9   r   r>  r1   r2   r   multi_speaker_voice_configr7   )r   speech_configs     r+   t_live_speech_configrE    s]     fe001M&&55f=M--9
F  
rJ   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   r9   r   r1   r2   r   )r<   r   s     r+   t_toolrO    s     
7#3#3F#;::%%33 4 
  /@f%%&$::$$V,,MrJ   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 )NrH  )r   r   rO  rI  r   )r<   r   function_tooltoolstooltransformed_tools         r+   t_toolsrU    s     
I**26-
% 'dfd+#

0
011=++22	
+ 	%&' ((	LL	,rJ   r  c                     t        | |d      S )NcachedContents)r>   )rI   )r<   r  s     r+   t_cached_content_namerX    s    	<L	MMrJ   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rm   r   bq://bigqueryrm   bigquery_urifiles/)	file_namezUnsupported source: r   )r1   r2   r   BatchJobSourcer9   sumr   rc  r\  re  rE   r7   r   r   rC   )r<   rY  vertex_sourcesmldev_sourcess       r+   t_batch_job_sourcerj    s    T



%
%Cc5//0	D	 #"2"2$">?N D(T! M 	.A-6
 	
 J 
=A-J
 	

 J#t55#s
~~g!!%  
	 !!  
	!!!  	)#/00rJ   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   r[  zUnsupported source type: r   )
r1   r2   r   EmbeddingsBatchJobSourcer9   rg  r\  re  r7   r6   )r<   rY  ri  s      r+   t_embedding_batch_job_sourcerm  .  s     T

(
(
/3
/Cc599:D(T! M H 
 J
0c<
==rJ   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|        )	Nr]  r^  r_  r`  ra  rb  zUnsupported destination: r   )r1   r2   r   BatchJobDestinationr   rC   r7   r9   )rn  s    r+   t_batch_job_destinationrq  E  s     d$$,t,DK$w&&  
	!&& 
 24&9::e778K
07
88rJ   c                     | j                  di       j                  dg       }|s| S |D ]2  }|j                  di       }|sd|v s| j                  d      | d<    | S  | S )NinlinedResponsesr[   	embeddinginlinedEmbedContentResponses)r`   r  )rn  inline_responsesr[   inner_responses       r+   t_recv_batch_job_destinationrx  ^  s    XX0"599" 
K" h\\*b1Nn$-1XX6H-Id)*	+ 
+rJ   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/[^/]+$)rE   rematchrQ   r7   isdigit)r<   r  mldev_patternvertex_patterns       r+   t_batch_job_namer  o  s    	%M	xxt$ZZ_R  1$q9::P.XXnd#::c?2||~K
/vQ7
88rJ   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    r+   t_job_stater    s[    
''"%%%%'' $$'' %%LrJ   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.
r[   )
r`   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)rU   r  r  	operationtotal_secondsdelay_secondsr  s          r+   t_resolve_operationr    s    jj  d n&<$*IM5M
--
4
'	4	4Zv]9+FGG$$$R % i jj}$m
0
0
+m --
4
' g&&u&tf0s9+
F  ==$$MrJ   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://rd  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )r9   r   r   r  Videor   GeneratedVideovideor7   r1   r   r6   rC   rQ   r{  r|  group)r  suffixr|  s      r+   t_file_namer    s    dEJJ'99Dekk*88De223zzZZ^^dd	\
-
..	D#	

,T$ZL8IJ  
__Z ZZ!!$FHH[&)E}?vFGG;;q>D 
+ x ::h"D	+rJ   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     r+   t_tuning_job_statusr    s    "">>///>>+++>>--->>*** 	U[[	V	# MrJ   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`)r1   r2   r   r   r   r9   r7   r6   )r   s    r+   t_content_strictr    sR    ==''00/N

)$w-8MN rJ   c                 v    t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w r&   )r1   r   r  )r   r   s     r+   t_contents_strictr    s8     (#5=>'W%>>X&'' ?r   turnsturn_completec                     | t        j                  |      S 	 t        j                  t        |       |      S # t        $ r}t	        dt        |        d      |d }~ww xY w)N)r  )r   )r  r  r  z") to `types.LiveClientContent`)r   LiveClientContentr  	Exceptionr7   r6   )r  r  es      r+   t_client_contentr    sv     ]""??	""/#  
 

)$u+ 7$ 	$ s    ; 	A"AA"inputc                     | st        d|        	 t        j                  t        |             S # t        $ r}t        dt        |        d      |d }~ww xY w)Nz#A tool response is required, got: 
)r   r  z$") to `types.LiveClientToolResponse`)r7   r   LiveClientToolResponser   r  r6   )r  r  s     r+   t_tool_responser    ss     

;E7C
DD''/5I  
 

)$u+ 7) 	) s   2 	AAAmetricsc                    g }| D ]  }i }ddg|d<   t        |dg      j                         }|dk(  ri |d<   n|dk(  ri |d<   n|j                  d	      r|j                  d
d      }d|i|d<   ndt	        |d      rJ|j
                  r>d|j
                  i}t        |dg      }|r||d<   t        |dg      }|rd|i|d<   ||d<   nt        d|       |j                  |        |S )a   Prepares the metric payload for the evaluation request.

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

    Returns:
        The updated request dictionary with the prepared metric payload.
    AVERAGESTANDARD_DEVIATIONaggregation_metricsr  r   exact_match_specr   	bleu_specrouger   
rouge_typer   prompt_templatemetric_prompt_templatejudge_model_system_instructionsystem_instructionreturn_raw_outputcustom_output_format_configpointwise_metric_specz0Unsupported metric type or invalid metric name: )getvr   rC   replacer(   r  r7   r   )	r  metrics_payloadmetricmetric_payload_itemmetric_namer  pointwise_specr  r  s	            r+   	t_metricsr  '  sV    O $2,.

4/0
 &*002k		%24./& +-K(!!'* ((b1
-9:,FL)6,-&2H2H2F4J4JK!56
 1C.-
. ()
 !#4;.6
7 8F34A+O
 	
 01I$2J rJ   r&   )NT)__doc__base64collections.abcr   r   r  r   r   rJ  rt   loggingr{  sysr  r   builtin_typesr6  r   r   r	   r
   r   r   
_mcp_utilsr   r   r   r  TYPE_CHECKINGr   r|   r4   r  r   	getLoggerra   version_info	UnionTyper5  r8  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer   rs   metric_name_sdk_api_mapr   metric_name_api_sdk_mapr6   r5   r   r9   BaseApiClientr   r#  rI   rT   rZ   r  r   rf   rh   r{   r~   FunctionResponseOrDictr   r   r   BlobImageUnionDictr   r   r   
BlobOrDictr   r   r   r   r   r   r   r   ContentDictContentTyper   r   ContentListUnionContentListUnionDictr   r   r   r   r  r%  r+  SchemaUnionDictr.  r9  SpeechConfigUnionDictr>  rA  SpeechConfigOrDictrE  rO  rU  rX  BatchJobSourceUnionDictrf  rj  EmbeddingsBatchJobSourceOrDictrl  rm  BatchJobDestinationOrDictrp  rq  r2   rx  r  r  r  r  r  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  )kvs   00r+   <module>r     s	    )  -   	  	 
    E E * .	    			7	8w$..,, 7 78,00,,,)	3'"%FKK%'6;;5) $ 
 -D,I,I,KLDAq1a4L # D););$<  H '(Z%%ZZ 	Z
 !$Z 	ZzK-- c c 4))8<  	'

>))25c]"4S 4UZZ 4233
 5$$--.	05
 
%
 
 !5))40H0H+IIJ	%**)) ejj 4Au// AEJJ AAu'' AEJJ AC%--. C5:: C<d5&&')<)<d5::>NNO 
%**	(738#456d5''()& EMM5#4#4e6I6IIJ*; 1 1478*
]]*8 %% D'e.?.?)@+MN  49d5==))* 4ie$$e&@&@%--OPi 
%--	iX8w11 8d 8v9s 9t 9
QQ!+";";<Q	Q" *.TH
 "THTH[../TH 7%%
&TH
 TH 
THn2
2$[%>%>?2
\\2:%'',-w!!"-9[../-9%'',--9 ell-9`E%--s23Ee  !E&$$e  ! %%/2eEJJO$%*%%/3Cy	%**2N+";"; N3 N3 N/1%%/1		&	&/1 /1d>%%>		-	-> ##>.9
U444
59
92tCH~ $sCx. "9[66 9c 9c 9$s s & %( !$( !#  ))3:3E3E<
5ejj%++u7K7KKL
MD ennc.A(B  e11 emm (HU00153F3FFG(	%--( 		hu**+U-@-@@A 	
 *$$--.	0
 !!(3%&&'3	$sCx.3S' 
 G Ms   !^ ^	^^