o
    i                     @   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 ejrZd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.m/Z0 n*eZ-ej1e2d< eZ0ej1e2d< zddl+m,Z- ddl.m/Z0 W n e3y   dZ-dZ0Y nw ddddZ4dd e45 D Z6dede7ej8 de9fddZ:ddd e!j;d!e<d"e<d#e=de<f
d$d%Z>d e!j;d&e<de<fd'd(Z?d)e!j;d*e9de<fd+d,Z@d-ejAdeBejA fd.d/ZCd)e!j;d&e<dee< fd0d1ZDd2edejEfd3d4ZFd5ejGdejHfd6d7ZId8eejGeejG f deBejH fd9d:ZJd;eejKeBejK f deBejE fd<d=ZLd>ejKdejEfd?d@ZMd>ejKdejEfdAdBZNd>ejOdejEfdCdDZPdEeejQ dejRfdFdGZSdHeeeBejQ ejQeBejR f  deBejR fdIdJZTdKeeee<ef   deeBejU  fdLdMZVeejWejXejQf ZYdNeeYejXdf dejWfdOdPZZd e!j;dQeeBejW eBejX eYf deeBe< eBejW f fdRdSZ[dQeeej\ej]ejWf  deBejW fdTdUZ^dVejAddfdWdXZ_dYeddfdZd[Z`dVed ee!j; ddfd\d]Za	dd^d_dVejAd ee!j; d`eejA dae9ddf
dbdcZbdded ee!j; dejcfdedfZddYeejeef de(ejA fdgdhZfd ee!j; dYeejeef deejc fdidjZgdYeejhef deeji fdkdlZjdYejkdeeji fdmdnZld e!j;dYedeeej/ef  fdodpZmd e!j;dYeBe deBej/ fdqdrZnd e!j;dse<de<fdtduZod e!j;dvejpdejqfdwdxZrd e!j;dvejsdejtfdydzZud{ee<ejvf dejwfd|d}Zxd{eye<ef deye<ef fd~dZzd e!j;dse<de<fddZ{de<de<fddZ|dZ}dZ~dZdZd)e!j;dejAdefddZdseee<ejejejf  de<fddZde<deeje<f fddZdNejdejWfddZdQeeej ejf deBejW fddZ		^ddeeeej ejf  de9dejfddZdeejGeejG f dejfddZdeBej deBeye<ef  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)_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   `/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/google/genai/_transformers.py
<dictcomp>H       r$   objclsreturnc                    s   t  ts
t|dsdS t fdd|jD }|s?t  tjr?z| tfddt jD }W |S  ty>   Y dS w |S )a  Checks if an object has all of the fields of a Pydantic model.

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

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

  Returns:
    True if the object has all the fields defined in the Pydantic model, False
    otherwise.
  model_fieldsFc                 3       | ]}t  |V  qd S Nhasattr)r    field)r&   r   r#   	<genexpr>^       z#_is_duck_type_of.<locals>.<genexpr>c                 3   r*   r+   r,   )r    f)obj_privater   r#   r/   d   r0   )	
isinstancedictr-   allr)   pydantic	BaseModeltype
ValueError)r&   r'   all_matchedr   )r&   r2   r#   _is_duck_type_ofK   s   r;      )collection_hierarchy_depthclientresource_namecollection_identifierr=   c                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_namej   s$   E

 rJ   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.rB   models/publishers/rA   r   z/models/zpublishers/google/models/ztunedModels/)r9   rF   rD   split)r>   rK   	publishermodel_idr   r   r#   t_model   s*   



rS   
api_clientbase_modelsc                 C   s   | j r	|rdS dS |rdS dS )Nzpublishers/google/modelsmodelstunedModels)rF   )rT   rU   r   r   r#   t_models_url   s   rX   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 )NrV   rW   publisherModelshttpHeadersjsonPayloadz!Cannot determine the models type.z1Cannot determine the models type for response: %s)getloggerwarningdebug)rY   rV   tuned_modelspublisher_modelsr   r   r#   t_extract_models   s&   


rc   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 )NrO   rB   rC   rA   rN   z/publishers/google/)rS   rD   rF   rG   rH   )rT   rK   r   r   r#   t_caches_model  s   
rd   imgc                 C   s   z	dd l }|j}W n ty   d }Y nw t }|d ur#t| |js(| jdkr2| j|dd d}n	| j|dd d}|	d |
 }tj||dS )	Nr   RGBAPNG)formatz	image/pngJPEGz
image/jpeg)	mime_typedata)PIL.PngImagePluginPngImagePluginImportErrorioBytesIOr3   PngImageFilemodesaveseekreadr   Blob)re   PILrm   bytesiorj   rk   r   r   r#   pil_to_blob   s$   



ry   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: )	r9   r3   r4   r   FunctionResponsemodel_validater;   	TypeErrorr8   )rz   r   r   r#   t_function_response9  s   
r~   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   )r~   )r    rY   r   r   r#   
<listcomp>R      z(t_function_responses.<locals>.<listcomp>)r9   r3   r
   r~   r   r   r   r#   t_function_responsesI  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   [  r   zt_blobs.<locals>.<listcomp>)r3   listr   )r   r   r   r#   t_blobsW     

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.imager   z6Could not parse input as Blob. Unsupported blob type: )r9   r;   r   rv   r3   r4   r|   	__class____name__lower	PIL.ImageImagern   ry   r}   r8   )r   rw   	PIL_Imager   r   r#   r   `  s$   
r   c                 C   .   t | } | jr| jdr| S td| j)Nzimage/Unsupported mime type: r   rj   rD   r9   r   r   r   r#   t_image_blobz     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_urirj   )	file_datar   r   )inline_datazUnsupported content part type: )r9   r3   strr   Partr;   Fileurirj   from_urir4   r|   r6   ValidationErrorFileDatar   r   r   r   r   rn   ry   r8   r   rw   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>)r3   r   r9   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 )Nr   gcsUri
imageBytes)gcs_uriimage_bytes)r   )r]   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   )r9   r;   r   Contentr3   r4   r|   r6   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.)r3   r   r   rF   r4   r   r   r|   r   r   r   r^   r_   )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 )NTFr   r   )r3   r   r;   r   r   r   r4   r|   r6   r   r   r   r   r   r   r   rn   r   r   r   r#   _is_part  s>   


zt_contents.<locals>._is_partc                 S   s   | j  S r+   )r   )r   r   r   r#   _is_user_part2  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#   r/   6  s    z6t_contents.<locals>._are_user_parts.<locals>.<genexpr>)r5   r   r   r   r#   _are_user_parts5  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_content8  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_partE  s
   
z(t_contents.<locals>._handle_current_partr   zUnsupported content type: )r3   r   r9   r   r   r   PartUnionDictr   r   r   boolr   r;   r   r   r4   r|   r8   )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"
        }
      }
  r8   NnullTnullableanyOfr   r   )r]   removelenitems)r   itemkeyvalr   r   r#   handle_null_fieldsl  s   ,

r   originc                 C   s   t d|  )z2Raises an error if the schema type is unsupported.Unsupported schema type: )r9   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.)rF   r]   r9   )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   )poprP   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#   r   (  r   z"process_schema.<locals>.<listcomp>r8   constSTRINGenumzLiteral values must be strings.OBJECT
propertiesr   r   r   r   ARRAYr   r   c                    r   r   r   )r    prefixr   r   r#   r   N  r   )r]   r   r   r   r   r   updaterP   r   
StringDictr3   r   valuer   upperr9   r   r   keysr4   )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#   r   a  r%   z!_process_enum.<locals>.<listcomp>)r8   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#   Placeholdere     
 r  r   r
  )r3   r   intr   r}   r  r8   r   r   r6   r7   model_json_schemar   r   Schemar|   )r   r>   is_integer_enumr  str_membersstr_enumr  enum_schemar   r  r#   _process_enumQ  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+   )r3   r   )r    r   r   r   r#   r/   r  s    

z(_is_type_dict_str_any.<locals>.<genexpr>)r3   r4   r5   r   r   r   r#   _is_type_dict_str_anyn  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   )r3   r4   r  r   r   r  r|   r   r  r;   r   
model_dumpr   r8   
issubclassr6   r7   r  VersionedUnionTypetyping
get_origin_UNION_TYPESr9   )r>   r   r   r  r   r   r#   t_schemaw  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   SpeechConfigr3   r   VoiceConfigPrebuiltVoiceConfigr4   r|   r9   r8   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'  r3   r4   r|   multi_speaker_voice_configr9   )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   r3   r4   r|   )r>   r   r   r   r#   t_tool  s   
r6  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   r6  r0  r   )r>   r   function_tooltoolstooltransformed_toolr   r   r#   t_tools  s$   



r;  r  c                 C   s   t | |ddS )NcachedContents)r@   )rJ   )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rh   r   bq://bigqueryrh   bigquery_urifiles/)	file_namezUnsupported source: r   )r3   r4   r   BatchJobSourcer;   sumr   rG  r@  rI  rF   r9   r   r   rD   )r>   r>  vertex_sourcesmldev_sourcesr   r   r#   t_batch_job_source  sN   





rN  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   )
r3   r4   r   EmbeddingsBatchJobSourcer;   rK  r@  rI  r9   r8   )r>   r>  rM  r   r   r#   t_embedding_batch_job_source.  s   
rP  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|  )	NrA  rB  rC  rD  rE  rF  zUnsupported destination: r   )r3   r4   r   BatchJobDestinationr   rD   r9   r;   )rQ  r   r   r#   t_batch_job_destinationE  s$   



rS  c                 C   sX   |  di  dg }|s| S |D ]}| di }|sqd|v r)| d| d<  | S q| S )NinlinedResponsesrY   	embeddinginlinedEmbedContentResponses)r]   r   )rQ  inline_responsesrY   inner_responser   r   r#   t_recv_batch_job_destination^  s   rY  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/[^/]+$rA   r   zInvalid batch job name: .z:^projects/[^/]+/locations/[^/]+/batchPredictionJobs/[^/]+$)rF   rematchrP   r9   isdigit)r>   r  mldev_patternvertex_patternr   r   r#   t_batch_job_nameo  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   )ra  r   r   r#   t_job_state  s   rp  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.
rY   )
r]   !LRO_POLLING_INITIAL_DELAY_SECONDSLRO_POLLING_TIMEOUT_SECONDSRuntimeErrorrequesttimesleepminLRO_POLLING_MULTIPLIER!LRO_POLLING_MAXIMUM_DELAY_SECONDS)rT   rq  r  	operationtotal_secondsdelay_secondsrw  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://rH  r   z	[a-z0-9]+z&Could not extract file name from URI: r   )r;   r   r   r  Videor   GeneratedVideovideor9   r3   r   r8   rD   rP   r[  r\  group)r  suffixr\  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   JobStaterc  rg  ri  rk  r   r   )r  ra  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`)r3   r4   r   r   r|   r;   r9   r8   )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>)r3   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  	Exceptionr9   r8   )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`)r9   r   LiveClientToolResponser   r  r8   )r  r  r   r   r#   t_tool_response  s   r  metricsc           	      C   s   g }| D ]n}i }ddg|d< t |dg }|dkri |d< nN|dkr(i |d< nE|d	r:|d
d}d|i|d< n3t|drf|jrfd|ji}t |dg}|rS||d< t |dg}|rad|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   
rouge_typer   prompt_templatemetric_prompt_templatejudge_model_system_instructionsystem_instructionreturn_raw_outputcustom_output_format_configpointwise_metric_specz0Unsupported metric type or invalid metric name: )getvr   rD   replacer-   r  r9   r   )	r  metrics_payloadmetricmetric_payload_itemmetric_namer  pointwise_specr  r  r   r   r#   	t_metrics'  sB   




r  r+   )NT)__doc__base64collections.abcr   r   r   r   r   r1  ro   loggingr[  sysr|  r   builtin_typesr   r   r   r   r	   r
   r   
_mcp_utilsr   r   r   r  TYPE_CHECKINGr   rw   r6   r  r   	getLoggerr^   version_info	UnionTyper  r"  r   _UnionGenericAliastyping_extensionsmcpr   r   	mcp.typesr   r   Typer  rn   metric_name_sdk_api_mapr   metric_name_api_sdk_mapr8   r7   r   r;   BaseApiClientr   r  rJ   rS   rX   r   r   rc   rd   rv   ry   FunctionResponseOrDictr{   r~   r   BlobImageUnionDictr   r   r   
BlobOrDictr   r   r   r   r   r   r   r   ContentDictContentTyper   r   ContentListUnionContentListUnionDictr   r   r   r   r   r  r  SchemaUnionDictr  r#  SpeechConfigUnionDictr'  r*  SpeechConfigOrDictr-  r6  r;  r=  BatchJobSourceUnionDictrJ  rN  EmbeddingsBatchJobSourceOrDictrO  rP  BatchJobDestinationOrDictrR  rS  r4   rY  r`  rp  rx  r  ry  r  r  r   r  r  r  r  r  ContentOrDictr  r  r  r  r  r  MetricSubclassr  r   r   r   r#   <module>   s"   

$
]





	




l;

 

	
0




2

"

"


