o
    pkjlq                     @   s8  U d 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mZmZmZ ddlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ejdkrsddlmZ nej Zej!rddl"m#Z$ ddl%m&Z' ne	Z$eje(d< e	Z'eje(d< edddZ)dZ*e+dZ,dej-dej.fddZ/dee0ej1f dee0 fddZ2dee0ej1f dee0 fddZ3	dddee0ej4f deej5 dej5fd d!Z6		"dedeej- d#e7de8e9 fd$d%Z:deej- d&e8e9 ddfd'd(Z;			"dfdeej- d)ee<e0ef  d*e7de<e0ee
d+e	f ef f fd,d-Z=d.ej>dej>fd/d0Z?d.ee<e0e@f e8e@ e@f dee<e0e@f e8e@ e@f fd1d2ZAd3e	de7fd4d5ZBd6e	d3e	d7e0d8e0de	f
d9d:ZCd.ej>d;e
d+e	f dej>fd<d=ZDd.ej>d>e
d+e	f de	fd?d@ZEd.ej>d>e
d+e	f de	fdAdBZFdCejGdDe<e0ee
d+e	f ef f de8ejH fdEdFZIdCejGdDe<e0ee
d+e	f ef f de8ejH fdGdHZJ	dddeej- de7fdIdJZK	dddeej- de9fdKdLZLdeej. ddfdMdNZM	dddeej- de7fdOdPZN	dddeej- deej. fdQdRZO		"dedeej- d#e7dePeej. e<e0ef f fdSdTZQdUeejRejSf dVejGdeejRejSf fdWdXZT		dgdYee0ejUe0 ejVf dZeejW d[ee0 dePejXe9e0f fd\d]ZY	dddeej- de7fd^d_ZZdeee<e0e	f e)f  d`ee) dae0de)fdbdcZ[dS )hzNExtra utils depending on types that are shared between sync and async modules.    N)	AnyCallableDictOptionalTypeTypeVarUnionget_args
get_origin   )_common)
_mcp_utils)_transformers)errors)types)version)McpToGenAiToolAdapter)   
   )	UnionTypeClientSession)ToolMcpClientSessionMcpToolCz_common.BaseModel)boundr   zgoogle_genai.modelsconfigreturnc                 C   s   t | trtjdi | S | S )N )
isinstancedictr   GenerateContentConfig)r   r   r   W/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/google/genai/_extra_utils.py%_create_generate_content_config_model;   s   
r$   srcc                 C   sn   t | tr| dr| S t | tr"| dr"| d r | d d S dS t | tjr5| jr5| jr3| jd S dS dS )z9Extracts the first GCS URI from the source, if available.zgs://gcs_urir   N)r    str
startswithr!   getr   BatchJobSourcer&   r%   r   r   r#   _get_gcs_uriD   s   r,   c                 C   sP   t | tr| dr| S t | tr| dr| d S t | tjr&| jr&| jS dS )z8Extracts the BigQuery URI from the source, if available.zbq://bigquery_uriN)r    r'   r(   r!   r)   r   r*   r-   r+   r   r   r#   _get_bigquery_uriQ   s   r.   c                 C   s   |du rt  }d}|jst }d| |_|jsEt| }t| }|r5|dr5|dd  d|_|S |rE|p<t }| d| |_|S )zBFormats the destination uri based on the source uri for Vertex AI.Ngenai_batch_job_z.jsonliz/dest_dest_)	r   CreateBatchJobConfigdisplay_namer   timestamped_unique_namedestr,   r.   endswith)r%   r   unique_namegcs_source_uribigquery_source_urir   r   r#   format_destination^   s    r9   Fis_agent_platformc                 C   sx   | sg S t | }g }|r|js|S t|jD ]#\}}t|tjs!qt|ddr,|| t|ddr9|s9|| q|S )z9Checks if the config contains any AFC incompatible tools.function_declarationsNmcp_servers)r$   tools	enumerater    r   r   getattrappend)r   r:   config_modelincompatible_tools_indexesindextoolr   r   r#   "find_afc_incompatible_tool_indexesx   s   


rE   rB   c                 C   s|   |sdS d}t | tjr| jrt| j}nt | tr&| dg }|r&t|}t||kr<dtt	|}t
d| dS dS )zMLogs a warning if any tools are incompatible with automatic function calling.Nr   r=   z, zTools at indices [%s] are not compatible with automatic function calling (AFC). AFC is disabled. If AFC is intended, please include python callables in the tool list, and do not include function declaration and MCP server in the tool list.)r    r   r"   r=   lenr!   r)   joinmapr'   loggerwarning)r   rB   original_tools_lengthr=   indices_strr   r   r#   "log_afc_incompatible_tools_warning   s$   

rM   mcp_to_genai_tool_adaptersis_caller_method_async.c                 C   s   i }| s|S t | }|jr1|jD ] }t|r0t|r+|s+td|j d|j d|||j< q|rU|s:td| D ]\}}|	|rOt
d| dq>|| |S )z'Returns a function map from the config.z	Function zh is a coroutine function, which is not supported for automatic function calling. Please manually invoke z to get the function response.z3MCP tools are not supported in synchronous methods.Tool $ is already defined for the request.)r$   r=   callableinspectiscoroutinefunctionr   UnsupportedFunctionError__name__itemsr)   
ValueErrorupdate)r   rN   rO   function_maprA   rD   	tool_name_r   r   r#   get_function_map   s8   





r]   argsc                 C   s   dd |   D S )z:Converts float values in dict with no decimal to integers.c                 S      i | ]	\}}|t |qS r   ,convert_number_values_for_function_call_args.0keyvaluer   r   r#   
<dictcomp>       zEconvert_number_values_for_dict_function_call_args.<locals>.<dictcomp>)rW   r^   r   r   r#   1convert_number_values_for_dict_function_call_args   s   ri   c                 C   sR   t | tr|  rt| S t | trdd |  D S t | tr'dd | D S | S )z2Converts float values with no decimal to integers.c                 S   r_   r   r`   rb   r   r   r#   rf      rg   z@convert_number_values_for_function_call_args.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r   r`   )rc   re   r   r   r#   
<listcomp>   s    z@convert_number_values_for_function_call_args.<locals>.<listcomp>)r    float
is_integerintr!   rW   listrh   r   r   r#   ra      s   

ra   
annotationc                 C   s.   zt | ot| tjW S  ty   Y dS w NF)rS   isclass
issubclasspydantic	BaseModel	TypeError)ro   r   r   r#   is_annotation_pydantic_model   s   rv   re   
param_name	func_namec                    s  t | tr3t|r3z|di | W S  tjy2 } ztd d  d|  d| d| 
d }~ww t | trOt|tkrOt	|d  fdd| D S t | trmt|tkrmt	|\} fd	d
| 
 D S t|ttfv rt	|D ]/}t	|rt|tu st | |st | trt|rz
t| | W   S  tjy   Y qyw qytd d  d|  d| d	t | tr|tu r| S t | |std d  d|  d| d	| S )NzFailed to parse parameter z for function z> from function call part because function call argument value z- is not compatible with parameter annotation z, due to error r   c                    s   g | ]	}t | qS r   convert_if_exist_pydantic_model)rc   item)rx   	item_typerw   r   r#   rj     s    z3convert_if_exist_pydantic_model.<locals>.<listcomp>c                    s    i | ]\}}|t | qS r   ry   )rc   kv)rx   rw   
value_typer   r#   rf     s    z3convert_if_exist_pydantic_model.<locals>.<dictcomp>z- cannot be converted to parameter annotation .r   )r    r!   rv   rs   ValidationErrorr    UnknownFunctionCallArgumentErrorrn   r
   r	   rW   r   r   rz   rm   rk   )re   ro   rw   rx   er\   argr   )rx   r|   rw   r   r#   rz      s   

rz   functionc                 C   sL   t |}|j}i }|j D ]\}}|| v r#t| | |j||||< q|S N)rS   	signaturerV   
parametersrW   rz   ro   )r^   r   r   rx   converted_argsrw   paramr   r   r#   convert_argument_from_function6  s   
r   function_to_invokec                 C   sX   t | |}z|di |W S  ty+ } ztd|j d| d|  d| d }~ww NzFailed to invoke function z with converted arguments z, from model returned function call argument z because of error r   r   	Exceptionr   FunctionInvocationErrorrV   r^   r   r   r   r   r   r#   invoke_function_from_dict_argsG  s   

r   c                    s`   t | |}z|di |I d H W S  ty/ } ztd|j d| d|  d| d }~ww r   r   r   r   r   r#   $invoke_function_from_dict_args_asyncU  s    

r   responserZ   c           
      C   s   g }| j durtt| j d jtjrt| j d jjdurt| j d jjD ]R}|js'q!|jj}|durs|jjdurs|| }t	|jj}zt|t
sLdt||i}W n tye } zdt|i}W Y d}~nd}~ww tjj||d}	||	 q!|S )6Returns the function response parts from the response.Nr   resulterrornamer   )
candidatesr    contentr   Contentpartsfunction_callr   r^   ri   r   r   r   r'   Partfrom_function_responser@   )
r   rZ   func_response_partspartrx   funcr^   func_responser   func_response_partr   r   r#   get_function_response_partsc  s:   



r   c                    sf  g }| j durt| j d jtjr| j d jjdur| j d jjD ]}|js(q"|jj}|dur|| }|jjdur>|jjni }t	|}zFt|t
rm|tj||dI dH }t|dt|dd}	|	rhd|i}
n!d|i}
nt|r}dt||I dH i}
ndtt||I dH i}
W n ty } zdt|i}
W Y d}~nd}~ww tjj||
d	}|| q"|S )
r   Nr   )r   r^   is_errorisErrorFr   r   r   )r   r    r   r   r   r   r   r   r^   ri   r   	call_toolFunctionCallr?   rS   rT   r   asyncio	to_threadr   r   r'   r   r   r@   )r   rZ   r   r   rx   r   raw_argsr^   mcp_tool_responser   r   r   r   r   r   r#   !get_function_response_parts_async  s`   







r   c                 C   s   | sdS t | }|r(|jr(|jjdur(t|jjdkr(td|jj d dS |jr1|jjdu r3dS |jjrV|jjdurVd|jjv rVt|jjdkrVtd|jj d	 |jjS )
z6Returns whether automatic function calling is enabled.FNr   z6max_remote_calls in automatic_function_calling_config zu is less than or equal to 0. Disabling automatic function calling. Please set max_remote_calls to a positive integer.Tmaximum_remote_callsz`automatic_function_calling.disable` is set to `True`. And `automatic_function_calling.maximum_remote_calls` is a positive number a9  . Disabling automatic function calling. If you want to enable automatic function calling, please set `automatic_function_calling.disable` to `False` or leave it unset, and set `automatic_function_calling.maximum_remote_calls` to a positive integer or leave `automatic_function_calling.maximum_remote_calls` unset.)r$   automatic_function_callingr   rm   rI   rJ   disablemodel_fields_setr   rA   r   r   r#   should_disable_afc  sH   r   c                 C   sD   | st S 	 t| rtdt| }|jr|jjd u rt S t|jjS )NzUautomatic function calling is not enabled, but SDK is trying to get max remote calls.)_DEFAULT_MAX_REMOTE_CALLS_AFCr   rX   r$   r   r   rm   r   r   r   r#   get_max_remote_calls_afc  s   r   c                 C   sL   | r	| j r	| j jsdS | j}|r|jnd}| j jj}|r"|s$tddS dS )z9Raises an error if the config is not compatible with AFC.NFav  Running in streaming mode with stream_function_call_arguments enabled, this feature is not compatible with automatic function calling (AFC). Please set config.automatic_function_calling.disable to True to disable AFC or leave config.tool_config. function_calling_config.stream_function_call_arguments to be empty or set to False to disable streaming function call arguments.)tool_configfunction_calling_configr   r   stream_function_call_argumentsrX   )r   
afc_configdisable_afc_configstream_function_callr   r   r#   'raise_error_for_afc_incompatible_config
  s    r   c                 C   s$   | sdS t | }|jsdS |jj S )NT)r$   r   ignore_call_historyr   r   r   r#   should_append_afc_history#  s   
r   c                 C   sx   | sdS t | }|jddid}|j|_|jr:t|jr:|jdu r)tji d|_|jjdu r3i |j_t	|jj |S )zVReturns a parsed config with an appended MCP header if MCP tools or sessions are used.Nr=   rY   )headers)
r$   
model_copyr=   r   has_mcp_tool_usagehttp_optionsr   HttpOptionsr   set_mcp_usage_header)r   rA   config_model_copyr   r   r#   parse_config_for_mcp_usage.  s   
r   c           
         s&  i }t | }|sd|fS |jddid}|jrg |_t s*|j|j ||fS zddlm} W n tyA   t	ddi }Y nw |jD ]I}t
||rt|| I dH |d}|j|j |jD ]$}|jr|jD ]}	|	jdur||	jrtd	|	j d
|||	j< qjqbqE|j| qE||fS )zReturns a parsed config with MCP sessions converted to GenAI tools.

  Also returns a map of MCP tools to GenAI tool adapters to be used for AFC.
  Nr=   r   r   r   DummySessionr   )r:   rP   rQ   )r   r   r=   r   _is_mcp_loadedextendmcpr   ImportErrortyper    r   
list_toolsr;   r   r)   rX   r@   )
r   r:   rN   parsed_configparsed_config_copy_McpClientSessionrD   mcp_to_genai_tool_adapter
genai_toolfunction_declarationr   r   r#   parse_config_for_mcp_sessionsC  sH   




r   contentschunkc                 C   sH   |dur"|j dur"|j d j}t| } t| tr"|dur"| | | S )zFAppends the contents of the chunk to the contents list and returns it.Nr   )r   r   t
t_contentsr    rn   r@   )r   r   chunk_contentr   r   r#   append_chunk_contentsz  s   

r   fileuser_http_optionsuser_mime_typec           	      C   sf  d}|}t | tjr9|du rtdt| dr d| jvr td|  }| dtj	 |  | }| |tj
 n-t| }|rFtj|sMt|  dtj|}|du r^t|\}}|du rftd|rt |trutjdi |}|}d	|_d
dd| | d|_ntjd	d
dd| | dd}t | ttjfr|jdu ri |_tj| |jd< |||fS )a-  Prepares the HTTP options, file bytes size and mime type for a resumable upload.

  This function inspects a file (from a path or an in-memory object) to
  determine its size and MIME type. It then constructs the necessary HTTP
  headers and options required to initiate a resumable upload session.
  NzfUnknown mime type: Could not determine the mimetype for your file
 please set the `mime_type` argumentmodebz'The file must be opened in binary mode.r   z is not a valid file path.ziUnknown mime type: Could not determine the mimetype for your file
    please set the `mime_type` argument zapplication/json	resumablestart)zContent-TypezX-Goog-Upload-ProtocolzX-Goog-Upload-Commandz#X-Goog-Upload-Header-Content-Lengthz!X-Goog-Upload-Header-Content-Type)api_versionr   zX-Goog-Upload-File-Namer   )r    ioIOBaserX   hasattrr   tellseekosSEEK_ENDSEEK_SETfspathpathisfileFileNotFoundErrorgetsize	mimetypes
guess_typer!   r   r   r   r   r'   PathLikebasename)	r   r   r   
size_bytes	mime_typeoffsetfs_pathr\   r   r   r   r#   prepare_resumable_upload  sb   







r   c                 C   s<   | sdS t | }|jsdS |jD ]}t|ddr dS qdS )zBChecks whether the configuration contains any MCP server requests.Fr<   NT)r$   r=   r?   )r   rA   rD   r   r   r#   has_agent_platform_mcp_servers  s   
r   
config_clsusagec                 C   s  dt j d| }| s| }nt| tr|di | }n| }t|ds%|S t|dd}|du r9t }t|d| t	
tj|}|jpDi }dD ]>}||v rd| || vr||| vrdt j || v ru|| dt j |||< qG||  d| 7  < qG|||< qG||_|S )z(Returns the usage header for the config.zgoogle-genai-sdk/+r   N)z
user-agentzx-goog-api-client r   )public_version__version__r    r!   r   r?   r   r   setattrtypingcastr   replace)r   r   r   usage_headerrA   r   existing_headers
header_keyr   r   r#   get_usage_header  s:   





r  r   rp   )NNF)NN)\__doc__r   rS   r   loggingr   r   sysr  r   r   r   r   r   r   r   r	   r
   rs   r   r   r   r   r   r   r   r   r  	_adaptersr   version_infor   _UnionGenericAliasTYPE_CHECKINGr   r   r   	mcp.typesr   r   __annotations__r   r   	getLoggerrI   GenerateContentConfigOrDictr"   r$   r'   BatchJobSourceOrDictr,   r.   r*   r1   r9   boolrn   rm   rE   rM   r!   r]   
StringDictri   objectra   rv   rz   r   r   r   GenerateContentResponser   r   r   r   r   r   r   r   tupler   ContentListUnionContentListUnionDictr   r   r   HttpOptionsOrDictr   r   r   r  r   r   r   r#   <module>   s  ,


	






$



>






#
:
8





7

J
