o
    iI                     @   s  U d Z ddlZddlmZmZ ddlmZmZ ddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlmZmZmZmZmZmZ ddlmZ ddlmZ dd	lmZ ejr`ddlZddl Z dd
l!m"Z" ddl!mZ ddl!mZ e
#dZ$ej%dkrej&Z'ejej&fZ(ddlm)Z) nej*Z'ejfZ(ddl+m)Z) ejrddl,m-Z. ddl/m0Z1 n*eZ.ej2e3d< eZ1ej2e3d< zddl,m-Z. ddl/m0Z1 W n e4y   dZ.dZ1Y nw ddddZ5dd e56 D Z7ddde"j8de9de9de:d e9f
d!d"Z;de"j8d#e9d e9fd$d%Z<d&e"j8d'e=d e9fd(d)Z>d*ej?d e@ej? fd+d,ZAd&e"j8d#e9d ee9 fd-d.ZBd/ed ejCfd0d1ZDd2ejEd ejFfd3d4ZGd5eejEeejE f d e@ejF fd6d7ZHd8eejIe@ejI f d e@ejC fd9d:ZJd;ejId ejCfd<d=ZKd;ejId ejCfd>d?ZLd;ejMd ejCfd@dAZNdBeejO d ejPfdCdDZQdEeee@ejO ejOe@ejP f  d e@ejP fdFdGZRdHeeee9ef   d ee@ejS  fdIdJZTeejUejVejOf ZWdKeeWejVdf d ejUfdLdMZXde"j8dNee@ejU e@ejV eWf d ee@e9 e@ejU f fdOdPZYdNeeejZej[ejUf  d e@ejU fdQdRZ\dSej?d dfdTdUZ]dVed dfdWdXZ^dSedee"j8 d dfdYdZZ_	dd[d\dSej?dee"j8 d]eej? d^e=d df
d_d`Z`daedee"j8 d ejafdbdcZbdVeejcef d e)ej? fdddeZddee"j8 dVeejcef d eeja fdfdgZedVeejfef d eejg fdhdiZhdVejid eejg fdjdkZjde"j8dVed eeej0ef  fdldmZkde"j8dVe@e d e@ej0 fdndoZlde"j8dpe9d e9fdqdrZmde"j8dsejnd ejofdtduZpde"j8dsejqd ejrfdvdwZsdxee9ejtf d ejufdydzZvdxewe9ef d ewe9ef fd{d|Zxde"j8dpe9d e9fd}d~Zyde9d e9fddZzdZ{dZ|dZ}dZ~d&e"j8dej?d efddZdpeee9ejejejf  d e9fddZde9d eeje9f fddZdKejd ejUfddZdNeeej ejf d e@ejU fddZ		[ddeeeej ejf  de=d ejfddZdeejEeejE f d ejfddZde@ej d e@ewe9ef  fddZd#e9d e=fddZdS )z"Transformers for Google GenAI SDK.    N)IterableMapping)EnumEnumMeta)AnyGenericAliasListOptionalSequenceUnion   )mcp_to_gemini_tool)get_value_by_path)is_duck_type_of)_api_client)_common)typeszgoogle_genai._transformers)   
   )	TypeGuard)ClientSession)ToolMcpClientSessionMcpToolexactMatchSpecbleuSpec	rougeSpec)exact_matchbleu
rouge_specc                 C   s   i | ]\}}||qS  r    ).0kvr    r    X/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/google/genai/_transformers.py
<dictcomp>I       r%      )collection_hierarchy_depthclientresource_namecollection_identifierr(   returnc                C   s   | | d o| d| dd |k}| jrX| dr!|S | dr/d| j d| S | | drDd| j d| j d| S |rVd| j d| j d| d| S |S |ra| 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_identifierr    r    r$   _resource_nameL   s$   E

 r6   modelc                 C   s   |st dd|v sd|v sd|v rt d| jrC|ds(|ds(|dr*|S d	|v r>|d	d
\}}d| d| S d| S |drJ|S |drQ|S d| S )Nzmodel is required.z..?&zinvalid model parameter.r.   models/publishers/r-   r   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr2   r0   split)r)   r7   	publishermodel_idr    r    r$   t_model   s*   



r@   
api_clientbase_modelsc                 C   s   | j r	|rdS dS |rdS dS )Nzpublishers/google/modelsmodelstunedModels)r2   )rA   rB   r    r    r$   t_models_url   s   rE   responsec                 C   s   | sg S |  d}|d ur|S |  d}|d ur|S |  d}|d ur%|S |  dd ur5|  dd u r5g S td td|  g S )NrC   rD   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)rF   rC   tuned_modelspublisher_modelsr    r    r$   t_extract_models   s&   


rP   c                 C   sj   t | |}|s	d S |dr| jrd| j d| j d| S |dr3| jr3d| j d| j d| S |S )Nr;   r.   r/   r-   r:   z/publishers/google/)r@   r0   r2   r3   r4   )rA   r7   r    r    r$   t_caches_model   s   
rQ   imagec                 C   sz   d}t  }| jdkrt| ddr| jdv rd}|jdd t }| j||fi | | }d|	  }t
j||d	S )
NPNGJPEGfilename )1LRGBRGBXCMYKkeep)qualityimage/)data	mime_type)dictformatgetattrmodeupdateioBytesIOsavegetvaluelowerr   Blob)rR   image_formatsave_paramsimage_ioimage_bytesr`   r    r    r$   pil_to_blob  s   


rp   function_responsec                 C   sD   | st dt| trtj| S t| tjr| S tdt|  )Nzfunction_response is required.zOCould not parse input as FunctionResponse. Unsupported function_response type: )	r<   
isinstancera   r   FunctionResponsemodel_validater   	TypeErrortype)rq   r    r    r$   t_function_response  s   
rw   function_responsesc                 C   s.   | st dt| trdd | D S t| gS )Nz function_responses are required.c                 S      g | ]}t |qS r    )rw   )r!   rF   r    r    r$   
<listcomp>.      z(t_function_responses.<locals>.<listcomp>)r<   rr   r
   rw   rx   r    r    r$   t_function_responses%  s
   

r}   blobsc                 C   "   t | trdd | D S t| gS )Nc                 S   ry   r    )t_blob)r!   blobr    r    r$   rz   7  r{   zt_blobs.<locals>.<listcomp>)rr   listr   )r~   r    r    r$   t_blobs3     

r   r   c                 C   s   | st dt| tjr| S t| trtj| S d| jj	 v rDz
dd l
}|jj}W n ty6   d }Y nw |d urDt| |rDt| S tdt|  )Nzblob is required.rR   r   z6Could not parse input as Blob. Unsupported blob type: )r<   r   r   rk   rr   ra   rt   	__class____name__rj   	PIL.ImageImageImportErrorrp   ru   rv   )r   PIL	PIL_Imager    r    r$   r   <  s$   
r   c                 C   .   t | } | jr| jdr| S td| j)Nr^   Unsupported mime type: r   r`   r0   r<   r   r    r    r$   t_image_blobV     r   c                 C   r   )Nzaudio/r   r   r   r    r    r$   t_audio_blob]  r   r   partc                 C   s  | d u rt dt| trtj| dS t| tjr-| jr| js#t dtjj	| j| jdS t| t
rNztj| W S  tjyM   tjtj| d Y S w t| tjrV| S d| jj v rz
dd l}|jj}W n tys   d }Y nw |d urt| |rtjt| dS t d	t|  )
Nzcontent part is required.)textz$file uri and mime_type are required.)file_urir`   )	file_datarR   r   )inline_datazUnsupported content part type: )r<   rr   strr   Partr   Fileurir`   from_urira   rt   pydanticValidationErrorFileDatar   r   rj   r   r   r   rp   rv   r   r   r   r    r    r$   t_partd  s4   

r   partsc                 C   s@   | d u st | tr| stdt | trdd | D S t| gS )Nzcontent parts are required.c                 S   ry   r    )r   r!   r   r    r    r$   rz     r{   zt_parts.<locals>.<listcomp>)rr   r   r<   r   r   r    r    r$   t_parts  s
   

r   predictionsc                 C   sP   | sd S g }| D ]}| dr%|tjtj|d d |d d dd q|S )NrR   gcsUri
imageBytes)gcs_uriro   )rR   )rJ   appendr   GeneratedImager   )r   images
predictionr    r    r$   t_image_predictions  s   


r   contentc                 C   s   | d u rt dt| tjr| S t| tr>ztj| W S  tjy=   t	| }|j
r4tj|gd Y S tj|gd Y S w t| tjrMtjt	| gdS t| tjrd| j
r]tj| gdS tj| gdS tj| dS )Nzcontent is required.r   )r<   r   r   Contentrr   ra   rt   r   r   r   function_callModelContentUserContentr   r   )r   possible_partr    r    r$   	t_content  s0   
r   contentsc                 C   s   t |trdd |D }nt|g}| jrGg }|D ]+}|d urDt |tr*tj|}|jd urD|jD ]}|j	r>|
|j	 q2td q2q|S |S )Nc                 S   ry   r    )r   r!   r   r    r    r$   rz     r{   z(t_contents_for_embed.<locals>.<listcomp>z/Non-text part found, only returning text parts.)rr   r   r   r2   ra   r   r   rt   r   r   r   rK   rL   )r)   r   transformed_contents
text_partsr   r   r    r    r$   t_contents_for_embed  s"   




r   c                    s  | d u s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}dtj	dt
fdddttj	 dt
ffd	d
dttj dttj	 dd ffdd dttj dttj	 dtjdd f fdd}| D ]I}t|tjst |tr || t |tr|tj|d qs|| qs||r|||| qst |tr|tj| qstdt|  || |S )Nzcontents are required.r   r,   c                 S   s   t | tst| tjst| tjrdS t | trE| sdS z	tj|  W dS  tj	yD   z
tj
|  W Y dS  tj	yC   Y Y dS w w d| jj v rnz
dd l}|jj}W n tyb   d }Y nw |d urnt | |rndS dS )NTFrR   r   )rr   r   r   r   r   r   ra   rt   r   r   r   r   r   rj   r   r   r   r   r    r    r$   _is_part  s>   


zt_contents.<locals>._is_partc                 S   s   | j  S N)r   )r   r    r    r$   _is_user_part  s   z!t_contents.<locals>._is_user_partr   c                    s   t  fdd| D S )Nc                 3   s    | ]} |V  qd S r   r    r   r   r    r$   	<genexpr>  s    z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>)allr   r   r    r$   _are_user_parts  s   z#t_contents.<locals>._are_user_partsresultaccumulated_partsc                    s>   |sd S |   |rtj|dntj|d g |d d < d S )Nr   )r   r   r   r   )r   r   )r   r    r$   $_append_accumulated_parts_as_content  s   
z8t_contents.<locals>._append_accumulated_parts_as_contentcurrent_partc                    sB   t |}||kr|| d S  | | |g|d d < d S r   )r   r   )r   r   r   r   r   r   r    r$   _handle_current_part!  s
   
z(t_contents.<locals>._handle_current_partr   zUnsupported content type: )rr   r   r<   r   r   r   PartUnionDictr   r   r   boolr   r   r   r   ra   rt   rv   )r   r   r   r   r   r   r    r   r$   
t_contents  sT   


%



r   schemac                 C   s   |  dddkrd| d< | d= dS d| v rO| d D ]7}d|v rN|d dkrNd| d< | d ddi t| d dkrN| d d  D ]\}}|| |< qB| d= qdS dS )	a  Process null fields in the schema so it is compatible with OpenAPI.

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

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

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

    After:
      {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "total_area_sq_mi": {
          "type": "integer",
          "nullable": true,
          "default": None,
          "title": "Total Area Sq Mi"
        }
      }
  rv   NnullTnullableanyOfr   r   )rJ   removelenitems)r   itemkeyvalr    r    r$   handle_null_fieldsH  s   ,

r   originc                 C   s   t d|  )z2Raises an error if the schema type is unsupported.Unsupported schema type: )r<   r   r    r    r$   "_raise_for_unsupported_schema_type  s   r   c                 C   s2   |r|j s| ds| drtdd S d S d S )NadditionalPropertiesadditional_propertiesz8additionalProperties is not supported in the Gemini API.)r2   rJ   r<   )r   r)   r    r    r$   '_raise_for_unsupported_mldev_properties  s   r   Torder_propertiesdefsr   c                   sX  |  ddkr
| d= t|  dD ]\}}| |d }dur#|| |< qdu r?| di  D ]\}}t|d q2t|  | dd }	durY| |	dd	   d
tj	dtj	ffdd |  d }
dur~ fdd|
D | d< dS |  d}t
|tr|j}t
|tr| }|  d}|dur|dkr|g| d< | d= ntd|dkr|  d }durt| D ]
\}} |||< qt| dkrrd| vrt| | d< |  d }durt
|tr || d< dS dS dS |dkr(|  d }dur || d< |  d }dur* fdd|D | d< dS dS dS ) a{  Updates the schema and each sub-schema inplace to be API-compatible.

  - Inlines the $defs.

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

    `schema`

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


    `defs`

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

    After:

    `schema`
     {
        'items': {
          'properties': {
            'continent': {
              'title': 'Continent',
              'type': 'string'
            },
            'gdp': {
              'title': 'Gdp',
              'type': 'integer'
            },
          }
          'required':['continent', 'gdp'],
          'title': 'CountryInfo',
          'type': 'object'
        },
        'type': 'array'
    }
  titlePlaceholderLiteralEnum))r   r   )any_ofr   )prefix_itemsprefixItems)property_orderingpropertyOrderingNz$defsr   $refdefs/
sub_schemar,   c                    s:   |  dd }dur|dd  } t|  d | S )z@Returns the processed `sub_schema`, resolving its '$ref' if any.r   Nr   r   r   )popr=   process_schema)r   ref)r)   r   r   r    r$   _recurse  s   z process_schema.<locals>._recurser   c                       g | ]} |qS r    r    )r!   r   r   r    r$   rz     r{   z"process_schema.<locals>.<listcomp>rv   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   c                    r   r    r    )r!   prefixr   r    r$   rz   *  r{   )rJ   r   r   r   r   r   re   r=   r   
StringDictrr   r   valuer   upperr<   r   r   keysra   )r   r)   r   r   	from_nameto_namer   _r   r   r   schema_typer   r   name
additionalr   prefixesr    )r   r)   r   r   r$   r     sh   C







r   r   c                    s   d}| D ]}t |jtrd}qt |jts#td|j dt|j q|  |r9dd | D }t| j|td}| G  fdd	d	t	j
}| }t|| |d
 d }tj|S )NFTzEnum member z( value must be a string or integer, got c                 S   s   g | ]}t |jqS r    )r   r   )r!   memberr    r    r$   rz   =  r&   z!_process_enum.<locals>.<listcomp>)rv   c                          e Zd ZU  ed< dS )z"_process_enum.<locals>.PlaceholderplaceholderNr   
__module____qualname____annotations__r    enum_to_processr    r$   PlaceholderA     
 r  r   r  )rr   r   intr   ru   r   rv   r   r   r   	BaseModelmodel_json_schemar   r   Schemart   )r   r)   is_integer_enumr  str_membersstr_enumr  enum_schemar    r
  r$   _process_enum-  s*   

r  c                 C   s   t | totdd | D S )zEVerifies the schema is of type dict[str, Any] for mypy type checking.c                 s   s    | ]}t |tV  qd S r   )rr   r   )r!   r   r    r    r$   r   N  s    

z(_is_type_dict_str_any.<locals>.<genexpr>)rr   ra   r   r   r    r    r$   _is_type_dict_str_anyJ  s   r  c                    sF   sd S t  trt rt |  tj S t  tr"t | S t	 tjrGt tt kr6t
   jdd}t||  tj|S t  tsft  trft tjrf  }t||  tj|S t  ts|t  ts|t  ts|t tv rG  fdddtj}| }t||  |d d }tj|S td  )NT)exclude_unsetc                       r  )zt_schema.<locals>.Placeholderr  Nr  r    r   r    r$   r  x  r  r  r   r  r   )rr   ra   r  r   r   r  rt   r   r  r   r   
model_dumpr   rv   
issubclassr   r  r  VersionedUnionTypetyping
get_origin_UNION_TYPESr<   )r)   r   r   r  r    r   r$   t_schemaS  sF   






r  c                 C   sf   | sd S t | tjr| S t| trtjtjtj| dddS t| tr*tj| S t	dt
|  )N)
voice_name)prebuilt_voice_config)voice_configzUnsupported speechConfig type: )r   r   SpeechConfigrr   r   VoiceConfigPrebuiltVoiceConfigra   rt   r<   rv   r   r    r    r$   t_speech_config  s   


r&  c                 C   s<   t | tjr| }t| trtj| }|jd urtd|S )Nz<multi_speaker_voice_config is not supported in the live API.)r   r   r#  rr   ra   rt   multi_speaker_voice_configr<   )r   speech_configr    r    r$   t_live_speech_config  s   

r)  c                 C   sj   |sd S t |st |rtjtjj| |dgdS td ur(t|tr(t	|S t
|tr3tj|S |S )N)r)   callablefunction_declarations)inspect
isfunctionismethodr   r   FunctionDeclarationfrom_callabler   r   r   rr   ra   rt   )r)   r   r    r    r$   t_tool  s   
r2  c                 C   st   |sg S t jg d}g }|D ]!}t| |}|d ur/|jr*|jd ur*| j|j7  _q|| q|jr8|| |S )Nr+  )r   r   r2  r,  r   )r)   r   function_tooltoolstooltransformed_toolr    r    r$   t_tools  s$   



r7  r   c                 C   s   t | |ddS )NcachedContents)r+   )r6   )r)   r   r    r    r$   t_cached_content_name  s   r9  srcc                 C   s  t |trtjdi |}t|tjrFt|jd u|jd ug}t|jd u|j	d ug}| j
r:|s4|dkr8td|S |s@|dkrDtd|S t |trQtj|dS t |trz|drctjd|gdS |drotjd	|d
S |drztj|dS td| )Nr   zeExactly one of `gcs_uri` or `bigquery_uri` must be set, other sources are not supported in Vertex AI.Exactly one of `inlined_requests`, `file_name`, `inlined_embed_content_requests`, or `embed_content_file_name` must be set, other sources are not supported in Gemini API.)inlined_requestsgs://jsonlrb   r   bq://bigqueryrb   bigquery_urifiles/)	file_namezUnsupported source: r    )rr   ra   r   BatchJobSourcer   sumr   rC  r<  rE  r2   r<   r   r   r0   )r)   r:  vertex_sourcesmldev_sourcesr    r    r$   t_batch_job_source  sN   





rJ  c                 C   sd   t |trtjdi |}t|tjr)t|jd u|jd ug}|dkr'td|S tdt	| )Nr   r;  zUnsupported source type: r    )
rr   ra   r   EmbeddingsBatchJobSourcer   rG  r<  rE  r<   rv   )r)   r:  rI  r    r    r$   t_embedding_batch_job_source
  s   
rL  destc                 C   s   t | trtjdi | } | S t | tr3| dr tjd| dS | dr,tjd| dS td|  t| tjr;| S td|  )	Nr=  r>  r?  r@  rA  rB  zUnsupported destination: r    )rr   ra   r   BatchJobDestinationr   r0   r<   r   )rM  r    r    r$   t_batch_job_destination!  s$   



rO  c                 C   sX   |  di  dg }|s| S |D ]}| di }|sqd|v r)| d| d<  | S q| S )NinlinedResponsesrF   	embeddinginlinedEmbedContentResponses)rJ   r   )rM  inline_responsesrF   inner_responser    r    r$   t_recv_batch_job_destination:  s   rU  c                 C   sn   | j sd}t||r|dd S td| dd}t||r)|dd S | r/|S td| d)Nzbatches/[^/]+$r-   r   zInvalid batch job name: .z:^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$)r2   rematchr=   r<   isdigit)r)   r   mldev_patternvertex_patternr    r    r$   t_batch_job_nameK  s   r\  statec                 C   sX   | dkrdS | dkrdS | dkrdS | dkrdS | d	krd
S | dkr$dS | dkr*dS | S )NBATCH_STATE_UNSPECIFIEDJOB_STATE_UNSPECIFIEDBATCH_STATE_PENDINGJOB_STATE_PENDINGBATCH_STATE_RUNNINGJOB_STATE_RUNNINGBATCH_STATE_SUCCEEDEDJOB_STATE_SUCCEEDEDBATCH_STATE_FAILEDJOB_STATE_FAILEDBATCH_STATE_CANCELLEDJOB_STATE_CANCELLEDBATCH_STATE_EXPIREDJOB_STATE_EXPIREDr    )r]  r    r    r$   t_job_state]  s   rl  g      ?g      4@g      @g      ?structc                 C   s   | d }r^d|v r^|}d}t}| ddkrE|tkr&td| d| | jd|i d	}t| ||7 }t|t t	}| ddks| d
 }rYtd| d| d| | dS |S )Nr   z/operations/g        doneTz
Operation z timed out.
GET)http_methodpathrequest_dicterrorz failed with error: z.
rF   )
rJ   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)rA   rm  r   	operationtotal_secondsdelay_secondsrs  r    r    r$   t_resolve_operationv  s.   

r  c                 C   s   t | tjr
| j} nt | tjr| j} nt | tjr&| jd ur$| jj} nd } | d u r.tdt	| t
s=tdt|  d| dra| dd }td|}|d u rZtd|  |d	} | S | drm| 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   )r   r   r   r   Videor   GeneratedVideovideor<   rr   r   rv   r0   r=   rW  rX  group)r   suffixrX  r    r    r$   t_file_name  s0   





r  statusc                 C   sf   | 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r0|  S q#| S )NSTATE_UNSPECIFIEDCREATINGACTIVEFAILED)r   JobStater_  rc  re  rg  r   r   )r  r]  r    r    r$   t_tuning_job_status  s   
r  c                 C   s:   t | trtj| S t| tjr| S tdt|  d)NCould not convert input (type "z") to `types.Content`)rr   ra   r   r   rt   r   r<   rv   )r   r    r    r$   t_content_strict  s   
r  c                 C   r   )Nc                 S   ry   r    )r  r   r    r    r$   rz     r{   z%t_contents_strict.<locals>.<listcomp>)rr   r
   r  r   r    r    r$   t_contents_strict  r   r  turnsturn_completec              
   C   sZ   | d u r
t j|dS zt jt| d|dW S  ty, } ztdt|  d|d }~ww )N)r  r  )r  r  r  z") to `types.LiveClientContent`)r   LiveClientContentr  	Exceptionr<   rv   )r  r  er    r    r$   t_client_content  s   r  inputc              
   C   sV   | s	t d|  z
tjt| ddW S  ty* } zt dt|  d|d }~ww )Nz#A tool response is required, got: 
r|   r  z$") to `types.LiveClientToolResponse`)r<   r   LiveClientToolResponser}   r  rv   )r  r  r    r    r$   t_tool_response  s   r  metricsc           
   	   C   sF  g }| D ]}t |trztj|}W n
 tjy   Y nw t |tjr4| }ddg|d< || qi }ddg|d< t	|dg
 }|dkrMi |d< nN|dkrVi |d< nE|d	rh|d
d}d|i|d< n3t|dr|jrd|ji}t	|dg}|r||d< t	|dg}	|	rd|	i|d< ||d< ntd| || q|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   rV   
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: )rr   ra   r   UnifiedMetricrt   r   r   r  r   getvrj   r0   replacehasattrr  r<   )
r  metrics_payloadmetricunified_metric_payloadmetric_payload_itemmetric_namer  pointwise_specr  r  r    r    r$   	t_metrics  s\   






r  c                 C   s   d| v r| dkpd| v S )Ngeminizgemini-embedding-001maasr    )r7   r    r    r$   t_is_vertex_embed_content_modelI  s   r  r   )NT)__doc__base64collections.abcr   r   r   r   r   r-  rf   loggingrW  sysrx  r   builtin_typesr  r   r   r   r	   r
   r   
_mcp_utilsr   r   r   r  r   TYPE_CHECKINGr   r   r   rV   r   	getLoggerrK   version_info	UnionTyper  r  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer	  r   metric_name_sdk_api_mapr   metric_name_api_sdk_mapBaseApiClientr   r  r6   r@   r   rE   r   r   rP   rQ   rk   rp   FunctionResponseOrDictrs   rw   r}   BlobImageUnionDictr   r   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)  r2  r7  r9  BatchJobSourceUnionDictrF  rJ  EmbeddingsBatchJobSourceOrDictrK  rL  BatchJobDestinationOrDictrN  rO  ra   rU  r\  rl  rt  r|  ru  r{  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  r  r    r    r    r$   <module>   s$   


]





	




l;

 

	
0




2

"

"



F