o
    pkj׫                     @   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 dd
lmZ ejrfd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< ddddZ4dd e45 D Z6ddde"j7de8de8d e9d!e8f
d"d#Z:de"j7d$e8d!e8fd%d&Z;d'e"j7d(e<d!e8fd)d*Z=d+ej>d!e?ej> fd,d-Z@d'e"j7d$e8d!ee8 fd.d/ZAd0ed!ejBfd1d2ZCd3ejDd!ejEfd4d5ZFd6eejDeejD f d!e?ejE fd7d8ZGd9eejHe?ejH f d!e?ejB fd:d;ZId<ejHd!ejBfd=d>ZJd<ejHd!ejBfd?d@ZKd<ejLd!ejBfdAdBZMdCeejN d!ejOfdDdEZPdFeee?ejN ejNe?ejO f  d!e?ejO fdGdHZQdIeeee8ef   d!ee?ejR  fdJdKZSeejTejUejNf ZVdLeeVejUdf d!ejTfdMdNZWde"j7dOee?ejT e?ejU eVf d!ee?e8 e?ejT f fdPdQZXdOeeejYejZejTf  d!e?ejT fdRdSZ[dTej>d!dfdUdVZ\dWed!dfdXdYZ]dTedee"j7 d!dfdZd[Z^	dd\dd]dTej>dee"j7 d^eej> d_e<d`ee_e9  d!dfdadbZ`dcedee"j7 d!ejafdddeZbdWeejcef d!e)ej> fdfdgZddee"j7 dWeejcef d!eeja fdhdiZedWeejfef d!eejg fdjdkZhdWejid!eejg fdldmZjde"j7dWed!eeej0ef  fdndoZkde"j7dWe?e d!e?ej0 fdpdqZlde"j7dre8d!e8fdsdtZmde"j7duejnd!ejofdvdwZpde"j7duejqd!ejrfdxdyZsdzee8ejtf d!ejufd{d|Zvdzewe8ef d!ewe8ef fd}d~Zxde"j7dre8d!e8fddZyde8d!e8fddZzdZ{dZ|dZ}dZ~d'e"j7dej>d!efddZdreee8ejejejf  d!e8fddZde8d!eeje8f fddZdLejd!ejTfddZdOeeej ejf d!e?ejT fddZ		\ddeeeej ejf  de<d!ejfddZdeejDeejD f d!ejfddZde?ej d!e?ewe8ef  fddZd$e8d!e<fddZdWed!efddZdS )z"Transformers for Google GenAI SDK.    N)IterableMapping)EnumEnumMeta)AnyGenericAliasListOptionalSequenceUnion   )
_mcp_utils)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/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/google/genai/_transformers.py
<dictcomp>D       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_nameG   s$   E

 r8   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.r0   models/publishers/r/   r   z/models/zpublishers/google/models/ztunedModels/)
ValueErrorr4   r2   split)r+   r9   	publishermodel_idr"   r"   r&   t_model   s*   



rB   
api_clientbase_modelsc                 C   s   | j r	|rdS dS |rdS dS )Nzpublishers/google/modelsmodelstunedModels)r4   )rC   rD   r"   r"   r&   t_models_url   s   rG   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 )NrE   rF   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)rH   rE   tuned_modelspublisher_modelsr"   r"   r&   t_extract_models   s&   


rR   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=   r0   r1   r/   r<   z/publishers/google/)rB   r2   r4   r5   r6   )rC   r9   r"   r"   r&   t_caches_model   s   
rS   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)rT   image_formatsave_paramsimage_ioimage_bytesrb   r"   r"   r&   pil_to_blob   s   


rr   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>   
isinstancerc   r   FunctionResponsemodel_validater   	TypeErrortype)rs   r"   r"   r&   t_function_response  s   
ry   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"   )ry   )r#   rH   r"   r"   r&   
<listcomp>)      z(t_function_responses.<locals>.<listcomp>)r>   rt   r
   ry   rz   r"   r"   r&   t_function_responses   s
   

r   blobsc                 C   "   t | trdd | D S t| gS )Nc                 S   r{   r"   )t_blob)r#   blobr"   r"   r&   r|   2  r}   zt_blobs.<locals>.<listcomp>)rt   listr   )r   r"   r"   r&   t_blobs.     

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.rT   r   z6Could not parse input as Blob. Unsupported blob type: )r>   r   r   rm   rt   rc   rv   	__class____name__rl   	PIL.ImageImageImportErrorrr   rw   rx   )r   PIL	PIL_Imager"   r"   r&   r   7  s$   
r   c                 C   .   t | } | jr| jdr| S td| j)Nr`   Unsupported mime type: r   rb   r2   r>   r   r"   r"   r&   t_image_blobQ     r   c                 C   r   )Nzaudio/r   r   r   r"   r"   r&   t_audio_blobX  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_urirb   )	file_datarT   r   )inline_datazUnsupported content part type: )r>   rt   strr   Partr   Fileurirb   from_urirc   rv   pydanticValidationErrorFileDatar   r   rl   r   r   r   rr   rx   r   r   r   r"   r"   r&   t_part_  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   r{   r"   )r   r#   r   r"   r"   r&   r|     r}   zt_parts.<locals>.<listcomp>)rt   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 )NrT   gcsUri
imageBytes)gcs_urirq   )rT   )rL   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   Contentrt   rc   rv   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   r{   r"   )r   r#   r   r"   r"   r&   r|     r}   z(t_contents_for_embed.<locals>.<listcomp>z/Non-text part found, only returning text parts.)rt   r   r   r4   rc   r   r   rv   r   r   r   rM   rN   )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 )NTFrT   r   )rt   r   r   r   r   r   rc   rv   r   r   r   r   r   rl   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: )rt   r   r>   r   r   r   PartUnionDictr   r   r   boolr   r   r   r   rc   rv   rx   )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"
        }
      }
  rx   NnullTnullableanyOfr   r   )rL   removelenitems)r   itemkeyvalr"   r"   r&   handle_null_fieldsC  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_propertiesztadditionalProperties is only supported in Gemini Enterprise Agent Platform mode, , not in Gemini Developer API mode.)r4   rL   r>   )r   r+   r"   r"   r&   '_raise_for_unsupported_mldev_properties  s   r   Torder_propertiesvisited_dicts_pathdefsr   r   c                   s  du rt  t| v rdS t|  | ddkr | d= t|  dD ]\}}| |d }dur9|| |< q'du rV| di  D ]\}}	t|	d qHt|  | dd }
durp| 	|

dd	   d
tjdtjffdd | d }dur fdd|D | d< t|  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rt| D ]
\}}	 |	||< qt| dkrrd| vrt| | d< | d }durt|tr || d< n*|dkrG| d }dur2 || d< | d }durG fdd|D | d< t|  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'
    }
  NtitlePlaceholderLiteralEnum))r   r   )any_ofr   )prefix_itemsprefixItems)property_orderingpropertyOrderingz$defsr   $refdefs/
sub_schemar.   c                    sL   |  dd }dur|dd  } t| v ri S t|  d | S )z@Returns the processed `sub_schema`, resolving its '$ref' if any.r   Nr   r   r   )popr?   idprocess_schema)r   ref)r+   r   r   r   r"   r&   _recurse  s   z process_schema.<locals>._recurser   c                       g | ]} |qS r"   r"   )r#   r   r   r"   r&   r|     r}   z"process_schema.<locals>.<listcomp>rx   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   c                    r   r"   r"   )r#   prefixr   r"   r&   r|   ;  r}   )setr   addrL   r   r   r   r   r   rg   r?   r   
StringDictr   rt   r   valuer   upperr>   r   r   keysrc   )r   r+   r   r   r   	from_nameto_namer   _r   r   r   schema_typer   r   name
additionalr   prefixesr"   )r   r+   r   r   r   r&   r     sx   D
 







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&   r|   O  r(   z!_process_enum.<locals>.<listcomp>)rx   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&   PlaceholderS     
 r  r   r  )rt   r   intr   rw   r  rx   r   r   r   	BaseModelmodel_json_schemar   r   Schemarv   )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   )rt   r   )r#   r   r"   r"   r&   r   `  s    

z(_is_type_dict_str_any.<locals>.<genexpr>)rt   rc   r   r   r"   r"   r&   _is_type_dict_str_any\  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    r  r  r   r  r   )rt   rc   r  r   r   r  rv   r   r  r   r   
model_dumpr   rx   
issubclassr   r  r  VersionedUnionTypetyping
get_origin_UNION_TYPESr>   )r+   r   r   r  r"   r   r&   t_schemae  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   SpeechConfigrt   r   VoiceConfigPrebuiltVoiceConfigrc   rv   r>   rx   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)  rt   rc   rv   multi_speaker_voice_configr>   )r   speech_configr"   r"   r&   t_live_speech_config  s   

r/  c                 C   s   |sd S t |st |rtjtjj| |ddgdS t r<zddl	m} t
||r1t|W S W n	 ty;   Y nw t|trGtj|S |S )NT)r+   callableuse_json_schemafunction_declarationsr   r   )inspect
isfunctionismethodr   r   FunctionDeclarationfrom_callabler   _is_mcp_loaded	mcp.typesr   r   r   rt   rc   rv   )r+   r   _McpToolr"   r"   r&   t_tool  s*   


r<  c                 C   s   |sg S t jg d}g }|D ]3}t| |}|d urA|jr<|jd ur<| j|j7  _| }d |_|jddr;|| q|| q|jrJ|| |S )Nr2  T)exclude_none)r   r   r<  r3  
model_copyr  r   )r+   r   function_tooltoolstooltransformed_tool	tool_copyr"   r"   r&   t_tools  s.   




rD  r  c                 C   s   t | |ddS )NcachedContents)r-   )r8   )r+   r  r"   r"   r&   t_cached_content_name  s   rF  srcc                 C   s$  t |trtjdi |}t|tjrJt|jd u|jd u|jd ug}t|j	d u|j
d ug}| jr>|s8|dkr<td|S |sD|dkrHtd|S t |trUtj|dS t |tr|drgtjd|gdS |drstjd	|d
S td|rtjd|dS |drtj|dS td| )Nr   zExactly one of `gcs_uri` or `bigquery_uri`, or `vertex_dataset_name` must be set, other sources are not supported in Gemini Enterprise Agent Platform.Exactly one of `inlined_requests`, `file_name`, `inlined_embed_content_requests`, or `embed_content_file_name` must be set, other sources are not supported in Gemini API.)inlined_requestsgs://jsonlrd   r   bq://bigqueryrd   bigquery_uriz/^projects/[^/]+/locations/[^/]+/datasets/[^/]+$zvertex-dataset)rd   vertex_dataset_namefiles/)	file_namezUnsupported source: r"   )rt   rc   r   BatchJobSourcer   sumr   rP  rQ  rI  rS  r4   r>   r   r   r2   rematch)r+   rG  vertex_sourcesmldev_sourcesr"   r"   r&   t_batch_job_source  s^   





rZ  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   rH  zUnsupported source type: r"   )
rt   rc   r   EmbeddingsBatchJobSourcer   rU  rI  rS  r>   rx   )r+   rG  rY  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|  )	NrJ  rK  rL  rM  rN  rO  zUnsupported destination: r"   )rt   rc   r   BatchJobDestinationr   r2   r>   r   )r]  r"   r"   r&   t_batch_job_destinationE  s$   



r_  c                 C   sX   |  di  dg }|s| S |D ]}| di }|sqd|v r)| d| d<  | S q| S )NinlinedResponsesrH   	embeddinginlinedEmbedContentResponses)rL   r   )r]  inline_responsesrH   inner_responser"   r"   r&   t_recv_batch_job_destination^  s   re  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/[^/]+$)r4   rV  rW  r?   r>   isdigit)r+   r  mldev_patternvertex_patternr"   r"   r&   t_batch_job_nameo  s   rj  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"   )rk  r"   r"   r&   t_job_state  s   rz  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.
rH   )
rL   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)rC   r{  r  	operationtotal_secondsdelay_secondsr  r"   r"   r&   t_resolve_operation  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://rR  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )r   r   r   r  Videor   GeneratedVideovideor>   rt   r   rx   r2   r?   rV  rW  group)r  suffixrW  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   JobStaterm  rq  rs  ru  r   r   )r  rk  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`)rt   rc   r   r   rv   r   r>   rx   )r   r"   r"   r&   t_content_strict  s   
r  c                 C   r   )Nc                 S   r{   r"   )r  r   r"   r"   r&   r|     r}   z%t_contents_strict.<locals>.<listcomp>)rt   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>   rx   )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  rx   )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  rX   
rouge_typer!   prompt_templatemetric_prompt_templatejudge_model_system_instructionsystem_instructionreturn_raw_outputcustom_output_format_configpointwise_metric_specz0Unsupported metric type or invalid metric name: )rt   rc   r   UnifiedMetricrv   r   r   r  r   getvrl   r2   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"   )r9   r"   r"   r&   t_is_vertex_embed_content_modelm  s   r  c                 C   s   | S r   r"   r   r"   r"   r&   t_json_schemav  s   r  r   )NT)__doc__base64collections.abcr   r   r   r   r   r4  rh   loggingrV  sysr  r   builtin_typesr"  r   r   r   r	   r
   r   rX   r   r   r   r   r  r   TYPE_CHECKINGr   r   r   r   	getLoggerrM   version_info	UnionTyper!  r$  r   _UnionGenericAliastyping_extensionsmcpr   r   r:  r   r   Typer  metric_name_sdk_api_mapr   metric_name_api_sdk_mapBaseApiClientr   r  r8   rB   r   rG   r   r   rR   rS   rm   rr   FunctionResponseOrDictru   ry   r   BlobImageUnionDictr   r   r   
BlobOrDictr   r   r   r   r   r   r   r   ContentDictContentTyper   r   ContentListUnionContentListUnionDictr   r   r   r   r   r   r  r  SchemaUnionDictr  r%  SpeechConfigUnionDictr)  r,  SpeechConfigOrDictr/  r<  rD  rF  BatchJobSourceUnionDictrT  rZ  EmbeddingsBatchJobSourceOrDictr[  r\  BatchJobDestinationOrDictr^  r_  rc   re  rj  rz  r  r  r  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  r  r  r"   r"   r"   r&   <module>   s    


]





	




l;


 /

	
0




;

"

"



F	