o
    i^                     @   s  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mZmZm	Z	m
Z
mZmZmZ ddlZddl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 ejdkriddlmZ nejZejr|ddlmZ  ddl!m"Z# n*eZ ej$e%d< eZ#ej$e%d< zddlmZ  ddl!m"Z# W n e&y   dZ dZ#Y nw dZ'e(dZ)dej*dej+fddZ,dee-ej.f de
e- fddZ/dee-ej.f de
e- fddZ0	dTdee-ej1f de
ej2 dej2fddZ3	dTde
ej* de4e5 fddZ6			 dUde
ej* d!e
e7e-ef  d"e8de7e-eed#ef ef f fd$d%Z9d&ej:dej:fd'd(Z;d&ee7e-e<f e4e< e<f dee7e-e<f e4e< e<f fd)d*Z=d+ede8fd,d-Z>d.ed+ed/e-d0e-def
d1d2Z?d&ej:d3ed#ef dej:fd4d5Z@d&ej:d6ed#ef defd7d8ZAd&ej:d6ed#ef defd9d:ZBd;ejCd<e7e-eed#ef ef f de4ejD fd=d>ZEd;ejCd<e7e-eed#ef ef f de4ejD fd?d@ZF	dTde
ej* de8fdAdBZG	dTde
ej* de5fdCdDZH	dTde
ej* de8fdEdFZI	dTde
ej* de
ej+ fdGdHZJ	dTde
ej* deKe
ej+ e7e-ef f fdIdJZLdKeejMejNf dLejCdeejMejNf fdMdNZO		dVdOee-ejPe- ejQf dPe
ejR dQe
e- deKejSe5e-f fdRdSZTdS )WzNExtra utils depending on types that are shared between sync and async modules.    N)AnyCallableDictOptionalUnionget_args
get_origin   )_common)
_mcp_utils)_transformers)errors)types)McpToGenAiToolAdapter)   
   )	UnionType)ClientSession)ToolMcpClientSessionMcpToolr   zgoogle_genai.modelsconfigreturnc                 C   s   t | trtjdi | S | S )N )
isinstancedictr   GenerateContentConfig)r   r   r   _/var/www/html/karishye-ai-python/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_uriE   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_uriR   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    r3   c                 C   sV   | sg S t | }g }|r|js|S t|jD ]\}}t|tjr(|jr(|| q|S )aN  Checks if the config contains any AFC incompatible tools.

  A `types.Tool` object that contains `function_declarations` is considered a
  non-AFC tool for this execution path.

  Args:
    config: The GenerateContentConfig to check for incompatible tools.

  Returns:
    A list of indexes of the incompatible tools in the config.
  )r   tools	enumerater   r   r   function_declarationsappend)r   config_modelincompatible_tools_indexesindextoolr   r   r   "find_afc_incompatible_tool_indexesy   s   

r<   F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   r4   callableinspectiscoroutinefunctionr   UnsupportedFunctionError__name__itemsr#   
ValueErrorupdate)r   r=   r>   function_mapr8   r;   	tool_name_r   r   r   get_function_map   s8   





rL   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>)rF   rM   r   r   r   1convert_number_values_for_dict_function_call_args   s   rX   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   rN   r   rO   rQ   r   r   r   rU      rV   z@convert_number_values_for_function_call_args.<locals>.<dictcomp>c                 S   s   g | ]}t |qS r   rO   )rR   rT   r   r   r   
<listcomp>   s    z@convert_number_values_for_function_call_args.<locals>.<listcomp>)r   float
is_integerintr   rF   listrW   r   r   r   rP      s   

rP   
annotationc                 C   s.   zt | ot| tjW S  ty   Y dS w )NF)rB   isclass
issubclasspydantic	BaseModel	TypeError)r^   r   r   r   is_annotation_pydantic_model   s   rd   rT   
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)rR   item)rf   	item_typere   r   r   rY      s    z3convert_if_exist_pydantic_model.<locals>.<listcomp>c                    s    i | ]\}}|t | qS r   rg   )rR   kv)rf   re   
value_typer   r   rU      s    z3convert_if_exist_pydantic_model.<locals>.<dictcomp>z- cannot be converted to parameter annotation .r   )r   r   rd   ra   ValidationErrorr    UnknownFunctionCallArgumentErrorr]   r   r   rF   r   r   rh   r\   rZ   )rT   r^   re   rf   erK   argr   )rf   rj   re   rm   r   rh      s   

rh   functionc                 C   sL   t |}|j}i }|j D ]\}}|| v r#t| | |j||||< q|S N)rB   	signaturerE   
parametersrF   rh   r^   )rM   rs   ru   rf   converted_argsre   paramr   r   r   convert_argument_from_function   s   
ry   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   ry   	Exceptionr   FunctionInvocationErrorrE   rM   rz   rw   rq   r   r   r   invoke_function_from_dict_args1  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_async?  s    

r   responserI   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   rM   rX   r   r   r}   r!   Partfrom_function_responser7   )
r   rI   func_response_partspartrf   funcrM   func_responserq   func_response_partr   r   r   get_function_response_partsM  s:   



r   c                    sL  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|| }t	|jj}z=t|t
r`|tj||dI dH }|jr[d|i}n!d|i}nt|rpd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   rM   r   r   r   )r   r   r   r   r   r   r   r   rM   rX   r   	call_toolFunctionCallisErrorrB   rC   r   asyncio	to_threadr   r}   r!   r   r   r7   )r   rI   r   r   rf   r   rM   mcp_tool_responser   rq   r   r   r   r   !get_function_response_parts_asyncp  sR   






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   r\   loggerwarningdisablemodel_fields_setr   r8   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   rG   r   r   r   r\   r   r   r   r   get_max_remote_calls_afc  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.Nr4   rH   )headers)
r   
model_copyr4   r   has_mcp_tool_usagehttp_optionsr   HttpOptionsr   set_mcp_usage_header)r   r8   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rhg |_|jD ]I}tdurat|trat|| I dH }|j|j |jD ]"}|jr_|jD ]}|j	r^|
|j	rYtd|j	 d|||j	< qEq=q|j| q||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.
  Nr4   r   r?   r@   )r   r   r4   r   r   r   
list_toolsextendr6   r   r#   rG   r7   )r   r=   parsed_configparsed_config_copyr;   mcp_to_genai_tool_adapter
genai_toolfunction_declarationr   r   r   parse_config_for_mcp_sessions  s8   



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   r]   r7   )r   r   chunk_contentr   r   r   append_chunk_contents8  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IOBaserG   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_pathrK   r   r   r   r   prepare_resumable_uploadE  sb   







r   rt   )NNF)NN)U__doc__r   rB   r   loggingsystypingr   r   r   r   r   r   r   r   r   ra   r   r
   r   r   r   r   r   	_adaptersr   version_infor   _UnionGenericAliasTYPE_CHECKINGmcpr   r   	mcp.typesr   r   Type__annotations__ImportErrorr   	getLoggerr   GenerateContentConfigOrDictr   r   r!   BatchJobSourceOrDictr&   r(   r$   r+   r3   r]   r\   r<   r   boolrL   
StringDictrX   objectrP   rd   rh   ry   r   r   GenerateContentResponser   r   r   r   r   r   r   tupler   ContentListUnionContentListUnionDictr   r   r   HttpOptionsOrDictr   r   r   r   r   r   <module>   s~  $


	





$



>






#
2
8




,
