o
    YiI                     @   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McpToolZexactMatchSpecZbleuSpecZ	rougeSpec)exact_matchbleu
rouge_specc                 C   s   i | ]\}}||qS  r   ).0kvr   r   T/home/kim/smarthome/.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%   Z$should_prepend_collection_identifierr   r   r!   _resource_nameL   s$   E

 r2   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/)
ValueErrorr/   r-   split)r&   r3   Z	publisherZ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)r/   )r;   r<   r   r   r!   t_models_url   s   r?   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 )Nr=   r>   ZpublisherModelsZhttpHeadersZjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)r@   r=   Ztuned_modelsZpublisher_modelsr   r   r!   t_extract_models   s&   


rE   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 )Nr7   r+   r,   r*   r6   z/publishers/google/)r:   r-   r/   r0   r1   )r;   r3   r   r   r!   t_caches_model   s   
rF   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 )
NZPNGZJPEGfilename )1LRGBZRGBXZCMYKZkeep)Zqualityimage/)data	mime_type)dictformatgetattrmodeupdateioBytesIOsavegetvaluelowerr   Blob)rG   Zimage_formatZsave_paramsZimage_ioimage_bytesrO   r   r   r!   pil_to_blob  s   


r\   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: )	r8   
isinstancerP   r   FunctionResponsemodel_validater   	TypeErrortype)r]   r   r   r!   t_function_response  s   
rc   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   )rc   )r   r@   r   r   r!   
<listcomp>.      z(t_function_responses.<locals>.<listcomp>)r8   r^   r
   rc   rd   r   r   r!   t_function_responses%  s
   

ri   blobsc                 C   "   t | trdd | D S t| gS )Nc                 S   re   r   )t_blob)r   blobr   r   r!   rf   7  rg   zt_blobs.<locals>.<listcomp>)r^   listrl   )rj   r   r   r!   t_blobs3     

ro   rm   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.rG   r   z6Could not parse input as Blob. Unsupported blob type: )r8   r   r   rZ   r^   rP   r`   	__class____name__rY   	PIL.ImageImageImportErrorr\   ra   rb   )rm   PIL	PIL_Imager   r   r!   rl   <  s$   
rl   c                 C   .   t | } | jr| jdr| S td| j)NrM   Unsupported mime type: rl   rO   r-   r8   rm   r   r   r!   t_image_blobV     r|   c                 C   rx   )Nzaudio/ry   rz   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.)Zfile_urirO   )	file_datarG   r   )Zinline_datazUnsupported content part type: )r8   r^   strr   Partr   FileurirO   Zfrom_urirP   r`   pydanticValidationErrorFileDatarq   rr   rY   rs   rt   ru   r\   rb   r   rv   rw   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   re   r   )r   r   r   r   r   r!   rf     rg   zt_parts.<locals>.<listcomp>)r^   rn   r8   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 )NrG   ZgcsUriZ
imageBytes)gcs_urir[   )rG   )rA   appendr   GeneratedImagert   )r   ZimagesZ
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   )r8   r   r   Contentr^   rP   r`   r   r   r   function_callModelContentUserContentr   r   )r   Z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   re   r   )r   r   r   r   r   r!   rf     rg   z(t_contents_for_embed.<locals>.<listcomp>z/Non-text part found, only returning text parts.)r^   rn   r   r/   rP   r   r   r`   r   r   r   rB   rC   )r&   r   Ztransformed_contentsZ
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 )NTFrG   r   )r^   r   r   r   r   r   rP   r`   r   r   r   rq   rr   rY   rs   rt   ru   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: )r^   rn   r8   r   r   r   PartUnionDictr   r   r   boolr   r   r   r   rP   r`   rb   )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"
        }
      }
  rb   NnullTZnullableanyOfr   r   )rA   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: )r8   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.)r/   rA   r8   )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'
    }
  titleZPlaceholderLiteralEnum))r   r   )any_ofr   )Z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   )popr9   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!   rf     rg   z"process_schema.<locals>.<listcomp>rb   constSTRINGenumzLiteral values must be strings.ZOBJECT
propertiesr   r   r   r   ZARRAYr   r   c                    r   r   r   )r   prefixr   r   r!   rf   *  rg   )rA   r   r   r   r   r   rT   r9   r   
StringDictr^   r   valuer   upperr8   rn   r   keysrP   )r   r&   r   r   	from_nameZto_namer   _r   r   r   Z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!   rf   =  r#   z!_process_enum.<locals>.<listcomp>)rb   c                          e Zd ZU  ed< dS )z"_process_enum.<locals>.PlaceholderplaceholderNrr   
__module____qualname____annotations__r   Zenum_to_processr   r!   PlaceholderA     
 r   r   r   )r^   r   intr   ra   r   rb   r   rr   r   	BaseModelmodel_json_schemar   r   Schemar`   )r   r&   Zis_integer_enumr   Zstr_membersZstr_enumr   Z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   )r^   r   )r   r   r   r   r!   r   N  s    

z(_is_type_dict_str_any.<locals>.<genexpr>)r^   rP   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)Zexclude_unsetc                       r   )zt_schema.<locals>.Placeholderr   Nr   r   r   r   r!   r   x  r   r   r   r   r   )r^   rP   r   r   r   r   r`   r   r   r   r   
model_dumpr   rb   
issubclassr   r   r   VersionedUnionTypetyping
get_origin_UNION_TYPESr8   )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)Z
voice_name)Zprebuilt_voice_config)Zvoice_configzUnsupported speechConfig type: )r   r   SpeechConfigr^   r   ZVoiceConfigZPrebuiltVoiceConfigrP   r`   r8   rb   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   r^   rP   r`   Zmulti_speaker_voice_configr8   )r   Z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   ZFunctionDeclarationfrom_callabler   r   r   r^   rP   r`   )r&   r   r   r   r!   t_tool  s   
r   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   r   r   r   )r&   r   Zfunction_toolZtoolsZtoolZtransformed_toolr   r   r!   t_tools  s$   



r   r   c                 C   s   t | |ddS )NZcachedContents)r(   )r2   )r&   r   r   r   r!   t_cached_content_name  s   r  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rQ   r   bq://bigqueryrQ   bigquery_urifiles/)	file_namezUnsupported source: r   )r^   rP   r   BatchJobSourcer   sumr   r  r  r  r/   r8   rn   r   r-   )r&   r  Zvertex_sourcesmldev_sourcesr   r   r!   t_batch_job_source  sN   





r  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   )
r^   rP   r   EmbeddingsBatchJobSourcer   r  r  r  r8   rb   )r&   r  r  r   r   r!   t_embedding_batch_job_source
  s   
r  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  r	  r
  zUnsupported destination: r   )r^   rP   r   BatchJobDestinationr   r-   r8   r   )r  r   r   r!   t_batch_job_destination!  s$   



r  c                 C   sX   |  di  dg }|s| S |D ]}| di }|sqd|v r)| d| d<  | S q| S )NZinlinedResponsesr@   Z	embeddingZinlinedEmbedContentResponses)rA   r   )r  Zinline_responsesr@   Zinner_responser   r   r!   t_recv_batch_job_destination:  s   r  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/[^/]+$)r/   rematchr9   r8   isdigit)r&   r   Zmldev_patternZ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 )NZBATCH_STATE_UNSPECIFIEDJOB_STATE_UNSPECIFIEDZBATCH_STATE_PENDINGZJOB_STATE_PENDINGZBATCH_STATE_RUNNINGJOB_STATE_RUNNINGZBATCH_STATE_SUCCEEDEDJOB_STATE_SUCCEEDEDZBATCH_STATE_FAILEDJOB_STATE_FAILEDZBATCH_STATE_CANCELLEDZJOB_STATE_CANCELLEDZBATCH_STATE_EXPIREDZJOB_STATE_EXPIREDr   )r  r   r   r!   t_job_state]  s   r"  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)Zhttp_methodpathZ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)r;   r#  r   Z	operationtotal_secondsZdelay_secondsr'  r   r   r!   t_resolve_operationv  s.   

r2  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://r  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )r   r   r   r   Videor   GeneratedVideoZvideor8   r^   r   rb   r-   r9   r  r  group)r   suffixr  r   r   r!   t_file_name  s0   





r7  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 )NZSTATE_UNSPECIFIEDZCREATINGZACTIVEZFAILED)r   JobStater  r  r   r!  r   r   )r8  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`)r^   rP   r   r   r`   r   r8   rb   )r   r   r   r!   t_content_strict  s   
r<  c                 C   rk   )Nc                 S   re   r   )r<  r   r   r   r!   rf     rg   z%t_contents_strict.<locals>.<listcomp>)r^   r
   r<  r   r   r   r!   t_contents_strict  rp   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>  	Exceptionr8   rb   )r?  r@  er   r   r!   t_client_content  s   rD  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: 
rh   r;  z$") to `types.LiveClientToolResponse`)r8   r   LiveClientToolResponseri   rB  rb   )rE  rC  r   r   r!   t_tool_response  s   rG  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.
    ZAVERAGEZSTANDARD_DEVIATIONZaggregation_metricsr   r   Zexact_match_specr   Z	bleu_specZrouger   rI   
rouge_typer   prompt_templateZmetric_prompt_templateZjudge_model_system_instructionsystem_instructionreturn_raw_outputZcustom_output_format_configZpointwise_metric_specz0Unsupported metric type or invalid metric name: )r^   rP   r   ZUnifiedMetricr`   r   r   r   r   getvrY   r-   replacehasattrrJ  r8   )
rH  Zmetrics_payloadZmetricZunified_metric_payloadZmetric_payload_itemZmetric_namerI  Zpointwise_specrK  rL  r   r   r!   	t_metrics  s\   






rP  c                 C   s   d| v r| dkpd| v S )Ngeminizgemini-embedding-001Zmaasr   )r3   r   r   r!   t_is_vertex_embed_content_modelI  s   rR  r   )NT)__doc__base64collections.abcr   r   r   r   r   r   rU   loggingr  sysr,  r   Zbuiltin_typesr   r   r   r   r	   r
   r   Z
_mcp_utilsr   r   r   rM  r   TYPE_CHECKINGrs   rv   r   rI   r   	getLoggerrB   version_info	UnionTyper   r   r   _UnionGenericAliasZtyping_extensionsZmcpr   r   Z	mcp.typesr   r   Typer   ru   Zmetric_name_sdk_api_mapr   Zmetric_name_api_sdk_mapZBaseApiClientr   r   r2   r:   r   r?   r   rn   rE   rF   rZ   r\   ZFunctionResponseOrDictr_   rc   ri   ZBlobImageUnionDictro   rl   r|   Z
BlobOrDictr~   r   r   r   r   r   r   r   ZContentDictZContentTyper   r   ZContentListUnionZContentListUnionDictr   r   r   r   r   r   r   ZSchemaUnionDictr   r   ZSpeechConfigUnionDictr   r   ZSpeechConfigOrDictr   r   r   r  ZBatchJobSourceUnionDictr  r  ZEmbeddingsBatchJobSourceOrDictr  r  ZBatchJobDestinationOrDictr  r  rP   r  r  r"  r(  r0  r)  r/  r2  r   r3  r4  r7  r9  r:  ZContentOrDictr<  r>  rA  rD  rF  rG  ZMetricSubclassrP  rR  r   r   r   r!   <module>   s$   


]





	




l;

 

	
0




2

"

"



F