
    [Thp                        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e!jh                  de5de5de6de5f
dZ7de!jh                  de5de5fdZ8de!jh                  de9de5fdZ:d ejv                  de<ejv                     fd!Z=de!jh                  de5dee5   fd"Z>d#edej~                  fd$Z@d%ej                  dej                  fd&ZCd'eej                  eej                     f   de<ej                     fd(ZDd)eej                  e<ej                     f   de<ej~                     fd*ZFd+ej                  dej~                  fd,ZGd+ej                  dej~                  fd-ZHd+ej                  dej~                  fd.ZJd/eej                     dej                  fd0ZMd1eee<ej                     ej                  e<ej                     f      de<ej                     fd2ZNd3eeee5ef         dee<ej                        fd4ZPeej                  ej                  ej                  f   ZSd5eeS   dej                  fd6ZTde!jh                  d7ee<ej                     e<ej                     eSf   dee<e5   e<ej                     f   fd8ZUd7eeej                  ej                  ej                  f      de<ej                     fd9ZXd:ejv                  ddfd;ZYd<eddfd=ZZd:edee!jh                     ddfd>Z[	 did?d@d:ejv                  dee!jh                     dAeejv                     dBe9ddf
dCZ\dDedee!jh                     dej                  fdEZ^d<eej                  ef   de(ejv                     fdFZ`dee!jh                     d<eej                  ef   deej                     fdGZad<eej                  ef   deej                     fdHZdd<ej                  deej                     fdIZfde!jh                  d<edeeej^                  ef      fdJZgde!jh                  d<e<e   de<ej^                     fdKZhde!jh                  dLe5de5fdMZide!jh                  dNej                  dej                  fdOZlde!jh                  dNej                  dej                  fdPZodQee5ej                  f   dej                  fdRZrdQese5ef   dese5ef   fdSZtde!jh                  dLe5de5fdTZudUe5de5fdVZvdWZwdXZxdYZydZZzde!jh                  d[ejv                  defd\Z{dLeee5ej                  ej                  ej                  f      de5fd]Zd^e5deej                   e5f   fd_Zd5ej                  dej                  fd`Zd7eeej                     ej                  f   de<ej                     fdaZ	 	 djdbeeeej                     ej                  f      dce9dej
                  fddZdeeej                  eej                     f   dej                  fdfZdge<ej                     de<ese5ef      fdhZy# e3$ r dZ-dZ0Y w xY w)kz"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   )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        _/home/www/backend.miabetepe.com/venv/lib/python3.12/site-packages/google/genai/_transformers.py_resource_namer+   C   s!   J 
"
"&;%<A#>
?? $ ##1]O
4
:
:3
?!
C	#$	 ' __,		!	!,	/(-99		!	!%:$;1"=	>(FOO3DAm_UU	-(FOO3DAF[E\\]^k]lmm+%&a77    modelc                 @   |st        d      | j                  r[|j                  d      s"|j                  d      s|j                  d      r|S d|v r|j                  dd      \  }}d| d| S d| S |j                  d      r|S |j                  d	      r|S d| S )
Nzmodel is required.r"   models/publishers/r!   r   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr&   r$   split)r   r-   	publishermodel_ids       r*   t_modelr5      s    	
)
**__%I&M*l	!KKQ/i9+XhZ88(00	"l			.	)lugr,   
api_clientbase_modelsc                 *    | j                   r|ryy|ryy)Nzpublishers/google/modelsmodelstunedModels)r&   )r6   r7   s     r*   t_models_urlr;      s     'r,   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 )Nr9   r:   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)r<   r9   tuned_modelspublisher_modelss       r*   t_extract_modelsrG      s     
I/7||H/E&M5=\\-5P,9A: ! ll=!-
,,}
%
-I
NN67
LLDhOIr,   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 )Nr0   r"   r#   r!   r/   z/publishers/google/)r5   r$   r&   r'   r(   )r6   r-   s     r*   t_caches_modelrI      s     *e
$%	
m$)<)< J&&'{:3F3F2GqP 	"z':':z))*+j6I6I5JJ]^c]deeLr,   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BytesIO
isinstancePngImageFilemodesaveseekreadr   Blob)rJ   PILrS   bytesiorP   rQ   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: )r1   rW   dictr   FunctionResponsemodel_validate	TypeErrortype)ra   s    r*   t_function_responserh     sp     

5
66!4(!!001BCC#U%;%;<
	$$():$;#<	> r,   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.)r1   rW   r   rh   )ri   r<   s     r*   t_function_responsesrk      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)rW   listt_blob)rl   blobs     r*   t_blobsrr   .  s4     t%*+TF4L++5M? ,   6rq   c                 j   	 dd l }|j                  j                  }| st        d      t	        | t
        j                        r| S t	        | t              rt
        j                  j                  |       S |t	        | |      rt        |       S t        dt        |              # t        $ r d }Y w xY w)Nr   zblob is required.z6Could not parse input as Blob. Unsupported blob type: )	PIL.ImageImagerT   r1   rW   r   r]   rc   re   r`   rf   rg   )rq   r^   	PIL_Images      r*   rp   rp   7  s    		I 

(
))ejj!Kd::$$T**z$	:t>tDzlK	  
 Is   B$ $B21B2c                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzimage/Unsupported mime type: rp   rP   r$   r1   rq   s    r*   t_image_blobr|   P  @    	$	^^11(;K,T^^,>?@@r,   c                     t        |       } | j                  r| j                  j                  d      r| S t        d| j                        )Nzaudio/ry   rz   r{   s    r*   t_audio_blobr   W  r}   r,   partc                    	 dd l }|j                  j                  }| t        d      t	        | t
              rt        j                  |       S |+t	        | |      rt        j                  t        |             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 t        dt        |              # t        $ r d }Y Bw xY w)Nr   zcontent part is required.)text)inline_dataz$file uri and mime_type are required.)file_urirP   zUnsupported content part type: )ru   rv   rT   r1   rW   strr   Partr`   FileurirP   from_urirc   re   rg   )r   r^   rw   s      r*   t_partr   ^  s   		I 
\
0
11c::4  z$	:::+d"344ejj!884>>=>>::DNNKKd::$$T**ejj!K4T$ZLABB# 
 Is   E EE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.)rW   ro   r1   r   )r   r   s     r*   t_partsr   w  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 )NimagegcsUri
imageBytes)gcs_uriimage_bytes)r   )rA   appendr   GeneratedImagerv   )r   images
predictions      r*   t_image_predictionsr     sq     
& 	j~~gmm


KK$W-h7(1,?	 
-r,   contentc                 p   | t        d      t        | t        j                        r| S t        | t              r 	 t        j                  j                  |       S t        | t        j                        r:| j                  rt        j                  | g      S t        j                  | g      S t        j                  |       S # t        j                  $ r^ t        j                  j                  |       }|j                  rt        j                  |g      cY S t        j                  |g      cY S w xY w)Nzcontent is required.r   )r1   rW   r   Contentrc   re   pydanticValidationErrorr   function_callModelContentUserContent)r   possible_parts     r*   	t_contentr     s    _
+
,,'N]]))'22 $    	'+ gY/
 
			)) ## jj//8m (( 

M?
3   7s   C AD5D54D5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.)rW   ro   r   r&   rc   r   r   re   r   r   r   rB   rC   )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                   	
 | t        | t              r| st        d      t        | t              st        |       gS 	 dd l}|j
                  j
                  g }g }dt        t        j                  t        f   dt        t        j                     f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 # t        $ r d Y w xY w)Nzcontents are required.r   r   r   c                 @   t        | t              sBt        | t        j                        s(t        |       st        | t        j                        ryt        | t
              r!	 t        j                  j                  |        yy# t        j                  $ r Y yw xY w)NTF)	rW   r   r   r   r   rc   re   r   r   )r   rw   s    r*   _is_partzt_contents.<locals>._is_part  s     	4dEJJ'!jy&AdEJJ'$

!!$'  %% s   &B BBc                     | j                    S rn   )r   )r   s    r*   _is_user_partz!t_contents.<locals>._is_user_part  s    !!!!r,   r   c                 ,    t        fd| D              S )Nc              3   .   K   | ]  } |        y wrn    ).0r   r   s     r*   	<genexpr>z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>  s     5t}T"5s   )all)r   r   s    r*   _are_user_partsz#t_contents.<locals>._are_user_parts  s    5u555r,   resultaccumulated_partsc                     |sy | j                   |      rt        j                  |      nt        j                  |             g |d d  y )Nr   )r   r   r   r   )r   r   r   s     r*   $_append_accumulated_parts_as_contentz8t_contents.<locals>._append_accumulated_parts_as_content  sM     
MM,- 	 12&78
 ar,   current_partc                     t        |      } |       |      k(  r|j                  |       y  | |       |g|d d  y rn   )r   r   )r   r   r   r   r   r   s      r*   _handle_current_partz(t_contents.<locals>._handle_current_part
  sH    
 ,'L\"o6G&HH|,*63DE*^r,   r   zUnsupported content type: )rW   ro   r1   r   ru   rv   rT   r   r   PartUnionDictr   r   r   boolr   r   r   rc   re   rg   )r   r^   r   r   r   r   r   rw   r   r   r   s          @@@@r*   
t_contentsr     s   
 *Xt4X
-
..	Hd	#h  		I !#&(*%%%s*+$$%("%** " "6T%**- 6$ 65==!ejj) 
,5==!
,ejj)
, ''
, 	
,&  Eg7EMM*gt$*63DE	GT	"e''g67g	'	6#4g>	GT	"mmEMM009:3DM?CDD#E& 'v/@A	-k 
 Is   I	 	II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"
        }
      }
  rg   NnullTnullableanyOfr   r   )rA   removelenitems)r   itemkeyvals       r*   handle_null_fieldsr   5  s    X ZZ'F:v&w 	4DLF2!zw/0vg1$ /!,224 hc3F3KWo r,   originc                     t        d|        )z2Raises an error if the schema type is unsupported.Unsupported schema type: )r1   r   s    r*   "_raise_for_unsupported_schema_typer   p  s    .vh788r,   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&   rA   r1   )r   r   s     r*   '_raise_for_unsupported_mldev_propertiesr   u  sE     oo
**+
,ZZ/0 O
PP 1  r,   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   )popr2   process_schema)r   refr   r   r   s     r*   _recursez process_schema.<locals>._recurse  sF    ~~fd++8		'*2./j:vt>NOr,   r   rg   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   )rA   r   r   r   r   r   updater2   r   
StringDictrW   r   valuer   upperr1   ro   r   keysrc   )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 )rg   c                       e Zd ZU W  ed<   y)"_process_enum.<locals>.PlaceholderplaceholderN__name__
__module____qualname____annotations__)enum_to_processs   r*   Placeholderr   .  s	      r,   r  r   r   )rW   r   intr   rf   r   rg   r   r  r   	BaseModelmodel_json_schemar   r   Schemare   )	r   r   is_integer_enummemberstr_membersstr_enumr  enum_schemar  s	           @r*   _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rn   )rW   r   )r   r   s     r*   r   z(_is_type_dict_str_any.<locals>.<genexpr>;  s      *"jc*s   )rW   rc   r   r   s    r*   _is_type_dict_str_anyr  7  s,     
FD	! 
c *&,* ' r,   c                 <   sy t        t              r6t              r+t        |        t        j
                  j                        S t        t              rt        |       S t        t        j
                        rqt              t        t	        j
                               k(  rt               j                  d      }t        ||        t        j
                  j                  |      S t        t              set        t              rUt        t        j                        r;j!                         }t        ||        t        j
                  j                  |      S t        t              s;t        t              s+t        t"              st%        j&                        t(        v r^ G fddt        j                        }|j!                         }t        ||        |d   d   }t        j
                  j                  |      S t+        d       )NT)exclude_unsetc                       e Zd ZU W  ed<   y)t_schema.<locals>.Placeholderr   Nr   r   s   r*   r  r  e  s	    r,   r  r   r   r   )rW   rc   r  r   r   r
  re   r   r  r   
model_dumpr   rg   
issubclassr   r  r	  VersionedUnionTypetyping
get_origin_UNION_TYPESr1   )r   r   r   r  s    `  r*   t_schemar  @  s    
"7"?66"<<&&v..!((%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8r,   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: )
rW   r   SpeechConfigr   VoiceConfigPrebuiltVoiceConfigrc   re   r1   rg   r   s    r*   t_speech_configr&  p  s     
**+M&&"'";";v"N
 
 ,,V444T&\NCDDr,   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.)rW   r   r#  rc   re   multi_speaker_voice_configr1   )r   speech_configs     r*   t_live_speech_configr*    s]     **+M&&55f=M--9
F  
r,   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   rW   r   rc   re   )r   r   s     r*   t_toolr4    s     
7#3#3F#;::%%33 4 
  z&':f%%&$::$$V,,Mr,   c                 6   |sg S t        j                  g       }g }|D ]Z  }t        | |      }||j                  r,|j                   |xj                  |j                  z  c_        J|j	                  |       \ |j                  r|j	                  |       |S )Nr-  )r   r   r4  r.  r   )r   r   function_tooltoolstooltransformed_tools         r*   t_toolsr:    s     
I**26-
% 'dfd+#

0
011=++22	
+ 	%&' ((	LL	,r,   r   c                     t        | |d      S )NcachedContents)r   )r+   )r   r   s     r*   t_cached_content_namer=    s    	<L	MMr,   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rN   r   bq://bigqueryrN   bigquery_urifiles/)	file_namezUnsupported source: r   )rW   rc   r   BatchJobSourcesumr   rH  rA  rJ  r&   r1   ro   r   r$   )r   r>  vertex_sourcesmldev_sourcess       r*   t_batch_job_sourcerO    s    T



%
%CU))*	D	 #"2"2$">?N D(T! M 	.A-6
 	
 J 
=A-J
 	

 J#t55#s
~~g!!%  
	 !!  
	!!!  	)#/00r,   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   )	rW   rc   r   EmbeddingsBatchJobSourcerL  rA  rJ  r1   rg   )r   r>  rN  s      r*   t_embedding_batch_job_sourcerR    s     T

(
(
/3
/CU334D(T! M H 
 J
0c<
==r,   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|        )	NrB  rC  rD  rE  rF  rG  zUnsupported destination: r   )rW   rc   r   BatchJobDestinationr   r$   r1   )rS  s    r*   t_batch_job_destinationrV    s     d$$,t,DK$w&&  
	!&& 
 24&9::$112K
07
88r,   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)rA   r   )rS  inline_responsesr<   inner_responses       r*   t_recv_batch_job_destinationr]  '  s    XX0"599" 
K" h\\*b1Nn$-1XX6H-Id)*	+ 
+r,   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matchr2   r1   isdigit)r   r   mldev_patternvertex_patterns       r*   t_batch_job_namere  8  s    	%M	xxt$ZZ_R  1$q9::P.XXnd#::c?2||~K
/vQ7
88r,   statec                 B    | 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_SUCCEEDEDJOB_STATE_SUCCEEDEDBATCH_STATE_FAILEDJOB_STATE_FAILEDBATCH_STATE_CANCELLEDJOB_STATE_CANCELLEDr   )rf  s    r*   t_job_staterr  J  sC    
''"%%'' $$'' Lr,   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<   )
rA   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)r6   rs  r   	operationtotal_secondsdelay_secondsrz  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  ==$$Mr,   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://rI  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )rW   r   r   r   Videor   GeneratedVideovideor1   r   rg   r$   r2   r`  ra  group)r   suffixra  s      r*   t_file_namer  }  s    ejj!99D$$88D$,,-zzZZ^^dd	\
-
..	D#	

,T$ZL8IJ  
__Z ZZ!!$FHH[&)E}?vFGG;;q>D 
+ x ::h"D	+r,   statusc                 `   | dk(  rt         j                  j                  S | dk(  rt         j                  j                  S | dk(  rt         j                  j                  S | dk(  rt         j                  j
                  S t         j                  D ]  }t        |j                        | k(  s|c S  | S )NSTATE_UNSPECIFIEDCREATINGACTIVEFAILED)r   JobStateri  JOB_STATE_RUNNINGrm  ro  r   r   )r  rf  s     r*   t_tuning_job_statusr    s    "">>///>>+++>>--->>*** 	U[[	V	# Mr,   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`)rW   rc   r   r   re   r1   rg   )r   s    r*   t_content_strictr    sR    ==''00'5==)N

)$w-8MN r,   c                 v    t        | t              r| D cg c]  }t        |       c}S t        |       gS c c}w rn   )rW   r   r  )r   r   s     r*   t_contents_strictr    s8     (#5=>'W%>>X&'' ?rs   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  	Exceptionr1   rg   )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: 
)ri   r  z$") to `types.LiveClientToolResponse`)r1   r   LiveClientToolResponserk   r  rg   )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   exact_matchexact_match_specbleu	bleu_specrouger    
rouge_type
rouge_spec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: )getvlowerr$   replacehasattrr  r1   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 r,   rn   )NT)__doc__base64collections.abcr   r   r   r   r   r/  rU   loggingr`  sysr  r   builtin_typesr  r   r   r	   r
   r   r   
_mcp_utilsr   r   r   r  TYPE_CHECKINGru   r^   r   r  r   	getLoggerrB   version_info	UnionTyper  r  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer  rT   BaseApiClientr   r  r+   r5   r   r;   r   ro   rG   rI   r]   r`   FunctionResponseOrDictrd   rh   rk   BlobImageUnionDictrr   rp   r|   
BlobOrDictr   r   r   r   r   r   r   r   ContentDictContentTyper   r   ContentListUnionContentListUnionDictr   r   r   r   r   r
  r  SchemaUnionDictr  r  SpeechConfigUnionDictr#  r&  SpeechConfigOrDictr*  r4  r:  r=  BatchJobSourceUnionDictrK  rO  EmbeddingsBatchJobSourceOrDictrQ  rR  BatchJobDestinationOrDictrU  rV  rc   r]  re  rr  r{  r  r|  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  r   r,   r*   <module>r     sQ	    )  -   	  	 
    E E * .	    			7	8w$..,, 7 78,00,,,)	3'"%FKK%'6;;5) '(Z%%ZZ 	Z
 !$Z 	ZzK-- c c 0))8<  	'

>))25c]"4S 4UZZ 4233
 5$$--.	05
 
%
 
 !5))40H0H+IIJ	%**)) ejj 2Au// AEJJ AAu'' AEJJ AC%--. C5:: C2d5&&')<)<d5::>NNO 
%**	(738#456d5''()& EMM5#4#4e6I6IIJ*k"*
]]*4 %% D'e.?.?)@+MN  49d5==))* 4ce$$e&@&@%--OPc 
%--	cL8w11 8d 8v9s 9t 9
QQ!+";";<Q	Q" *.TH
 "THTH[../TH 7%%
&TH
 TH 
THn2
2$[%>%>?2
\\2:%'',-w!!"-9[../-9%'',--9 ell-9`E%--s23Ee  !E&$$e  ! %%/2eEJJO$%*%%/3Cy	%**2N+";"; N3 N3 N/1%%/1		&	&/1 /1d>%%>		-	-> ##>.9
U444
59
92tCH~ $sCx. "9[66 9c 9c 9$s s  %( !$( !#  ))3:3E3E<
5ejj%++u7K7KKL
MD ennc.A(B  e11 emm (HU00153F3FFG(	%--( 		hu**+U-@-@@A 	
 *$$--.	0
 !!(3%&&'3	$sCx.3]% 
 Gs   !\3 3	] ?] 