
    Li^                        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j4                  dk\  rddlmZ nej8                  Zej:                  rddlmZ  ddl!m"Z# n/eZ ejH                  e%d<   eZ#ejH                  e%d<   	 ddlmZ  ddl!m"Z# dZ' ejP                  d      Z)dejT                  dejV                  fdZ,dee-ej\                  f   de
e-   fdZ/dee-ej\                  f   de
e-   fdZ0	 d=dee-ejb                  f   de
ejd                     dejd                  fdZ3	 d=de
ejT                     de4e5   fdZ6	 	 	 d>de
ejT                     de
e7e-ef      de8de7e-eedef   ef   f   fdZ9dejt                  dejt                  fd Z;dee7e-e<f   e4e<   e<f   dee7e-e<f   e4e<   e<f   fd!Z=d"ede8fd#Z>d$ed"ed%e-d&e-def
d'Z?dejt                  d(edef   dejt                  fd)Z@dejt                  d*edef   defd+ZAdejt                  d*edef   defd,ZBd-ej                  d.e7e-eedef   ef   f   de4ej                     fd/ZEd-ej                  d.e7e-eedef   ef   f   de4ej                     fd0ZF	 d=de
ejT                     de8fd1ZG	 d=de
ejT                     de5fd2ZH	 d=de
ejT                     de8fd3ZI	 d=de
ejT                     de
ejV                     fd4ZJ	 d=de
ejT                     deKe
ejV                     e7e-ef   f   fd5ZLd6eej                  ej                  f   d7ej                  deej                  ej                  f   fd8ZO	 	 d?d9ee-ej                  e-   ej                  f   d:e
ej                     d;e
e-   deKej                  e5e-f   fd<ZTy# e&$ r dZ dZ#Y %w xY w)@zNExtra 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                 P    t        | t              rt        j                  di | S | S )N )
isinstancedictr   GenerateContentConfig)r   s    W/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/google/genai/_extra_utils.py%_create_generate_content_config_modelr    <   s'     &&000M    srcc                 0   t        | t              r| j                  d      r| S t        | t              r | j	                  d      r| d   r| d   d   S dS t        | t
        j                        r)| j                  r| j                  r| j                  d   S dS y)z9Extracts the first GCS URI from the source, if available.zgs://gcs_urir   N)r   str
startswithr   getr   BatchJobSourcer$   r"   s    r   _get_gcs_urir*   E   s     ScnnW5J#t!3 #I3y>!8D8#u++, [[3;;q>2d2	r!   c                     t        | t              r| j                  d      r| S t        | t              r| j	                  d      r| d   S t        | t
        j                        r| j                  r| j                  S y)z8Extracts the BigQuery URI from the source, if available.zbq://bigquery_uriN)r   r%   r&   r   r'   r   r(   r,   r)   s    r   _get_bigquery_urir-   R   se     ScnnW5J#t!8~#u++,1A1A	r!   c                 ^   |t        j                         }d}|j                  st        j                         }d| |_        |j
                  s^t        |       }t        |       }|r |j                  d      r|dd  d|_        |S |r$|xs t        j                         }| 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_uris        r   format_destinationr9   _   s    
 ^'')F+			113K,[M:F	!#&N+C0.11(;%cr*+51fk
 
-	 
D7#B#B#Dk*+6+?fk	-r!   c                     | sg S t        |       }g }|r|j                  s|S t        |j                        D ]>  \  }}t        |t        j
                        s!|j                  s.|j                  |       @ |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tools        r   "find_afc_incompatible_tool_indexesrC   y   sw     
I6v>,*,	\//%%|112 /keT$

#(B(B ''./ 
$#r!   mcp_to_genai_tool_adaptersis_caller_method_async.c                    i }| s|S t        |       }|j                  rs|j                  D ]d  }t        |      st        j                  |      r2|s0t        j                  d|j                   d|j                   d      |||j                  <   f |r`|st        j                  d      |j                         D ]%  \  }}|j                  |      st        d| d       |j                  |       |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   rD   rE   function_mapr?   rB   	tool_name_s           r   get_function_maprT      s    OQ,	6v>,"" +	$&&t,5K//$-- )'EG 
 '+T]]#+  !++
?  388: 
	1			)	$I;BC
 	


 23	r!   argsc                 h    | j                         D ci c]  \  }}|t        |       c}}S c c}}w )z:Converts float values in dict with no decimal to integers.)rN   ,convert_number_values_for_function_call_argsrU   keyvalues      r   1convert_number_values_for_dict_function_call_argsr[      s9     



#u 
7>>
  
s   .c                 >   t        | t              r| j                         rt        |       S t        | t              r-| j                         D ci c]  \  }}|t        |       c}}S t        | t              r| D cg c]  }t        |       c}S | S c c}}w c c}w )z2Converts float values with no decimal to integers.)r   float
is_integerintr   rN   rW   listrX   s      r   rW   rW      s     e!2t9d **,C 	9%@@  dIM@E4U;  
+
s   B=B
annotationc                     	 t        j                  |       xr t        | t        j                        S # t
        $ r Y yw xY w)NF)rJ   isclass
issubclasspydantic	BaseModel	TypeError)ra   s    r   is_annotation_pydantic_modelrh      sC    ??:& :H&&,  
 s   03 	??rZ   
param_name	func_namec                 :   t        | t              rt        |      r		  |d	i | S t        | t              r<t        |      t        k(  r*t        |      d   }| D cg c]  }t        ||||       c}S t        | t              rPt        |      t        k(  r>t        |      \  }}| j                         D 	
ci c]  \  }	}
|	t        |
|||       c}
}	S t        |      t        t        fv rt        |      D ]W  }t        |      rt        |      t        u s)t        | |      st        | t              s<t        |      sH	 t        | |||      c S  t        j                  d| d| d|  d| d	      t        | t              r
|t        u r| S t        | |      s"t        j                  d| d| d|  d| d	      | S # t        j                  $ r)}t        j                  d| d| d|  d| d| 
      d }~ww xY wc c}w c c}
}	w # t        j                  $ r Y &w xY w)
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   z- cannot be converted to parameter annotation .r   )r   r   rh   re   ValidationErrorr    UnknownFunctionCallArgumentErrorr`   r	   r   convert_if_exist_pydantic_modelrN   r   r   r_   r]   )rZ   ra   ri   rj   e	item_typeitemrS   
value_typekvargs               r   ro   ro      so    t!=j!I %   tJ!74!?$Q'I  	(iYO  tJ!74!?Z(MAz KKMAq 	
*1j*iPP  
y11
# C=Z_4s#%*Fs*K	0S*i  
1
1
$ZL 1;  <q	  s
e 3L	E:	&

1
1
$ZLyk JDDI7 K55?L	C 
 
,k ## 33&zl 3[ 7 \- & '' 	
	s5   F9 G84G=<H9G5$G00G5HHfunctionc                     t        j                  |      }|j                  }i }|j                  j	                         D ](  \  }}|| v st        | |   |j                  ||      ||<   * |S N)rJ   	signaturerM   
parametersrN   ro   ra   )rU   rw   rz   rj   converted_argsri   params          r   convert_argument_from_functionr~      s}     ))).$//557 j%T#B
z





	$nZ  
r!   function_to_invokec                     t        | |      }	  |di |S # t        $ r0}t        j                  d|j                   d| d|  d|       d }~ww xY wNzFailed to invoke function z with converted arguments z, from model returned function call argument z because of error r   r~   	Exceptionr   FunctionInvocationErrorrM   rU   r   r|   rp   s       r   invoke_function_from_dict_argsr   1  sx     2$8JK.///	 

(
(
$%7%@%@$A B  ./ 01!	6 s    	A+A

Ac                    K   t        | |      }	  |di | d {   S 7 # t        $ r0}t        j                  d|j                   d| d|  d|       d }~ww xY wwr   r   r   s       r   $invoke_function_from_dict_args_asyncr   ?  s      2$8JK.#5n5555	 

(
(
$%7%@%@$A B  ./ 01!	6 s0   A"  " A" 	A+AAAresponserQ   c                    g }| j                   .t        | j                   d   j                  t        j                        r| j                   d   j                  j
                  | j                   d   j                  j
                  D ]  }|j                  s|j                  j                  }|)|j                  j                  @||   }t        |j                  j                        }	 t        |t              sdt        ||      i}t        j                  j                  |      }	|j!                  |	        |S # t        $ r}dt        |      i}Y d}~Qd}~ww xY w)6Returns the function response parts from the response.Nr   resulterrornamer   )
candidatesr   contentr   Contentpartsfunction_callr   rU   r[   r   r   r   r%   Partfrom_function_responser>   )
r   rQ   func_response_partspartrj   funcrU   func_responserp   func_response_parts
             r   get_function_response_partsr   M  sM   
 %
X((+33U]]
C


a
 
(
(
.
.
:##A&..44 7$$))i		4#5#5#:#:#FI&@##
	,D"788tDM
 #ZZ>>] ? 
 	""#56)7* 
  	,"CF+-	,s   ,E  	E 	EE c                   K   g }| j                   t        | j                   d   j                  t        j                        r| j                   d   j                  j
                  c| j                   d   j                  j
                  D ]<  }|j                  s|j                  j                  }|*|j                  j                  A||   }t        |j                  j                        }	 t        |t              rD|j                  t        j                  ||             d{   }|j                  rd|i}nVd|i}nQt        j                  |      rdt!        ||       d{   i}n%dt#        j$                  t&        ||       d{   i}t        j,                  j/                  ||      }
|j1                  |
       ? |S 7 7 d7 @# t(        $ r}	dt+        |	      i}Y d}	~	Xd}	~	ww xY ww)r   Nr   )r   rU   r   r   r   )r   r   r   r   r   r   r   r   rU   r[   r   	call_toolFunctionCallisErrorrJ   rK   r   asyncio	to_threadr   r   r%   r   r   r>   )r   rQ   r   r   rj   r   rU   mcp_tool_responser   rp   r   s              r   !get_function_response_parts_asyncr   p  s    
 %
X((+33U]]
C


a
 
(
(
.
.
:##A&..44 "7$$))i		4#5#5#:#:#FI&@##
	,34&*nn""	=' ! !((&(9:m'):;m**40 DT4 PPM
  1 12D$! M #ZZ>>] ? 
 	""#56E"7F 
/! Q  	,"CF+-	,sr   B2G65G6$G619G*G+?G*G+%GGG7G6GGG	G3G.)G6.G33G6c                    | syt        |       }|rs|j                  rg|j                  j                  	 Pt        |j                  j                        dk  r.t        j                  d|j                  j                   d       y|j                  r|j                  j                  y|j                  j                  r~|j                  j                  	 gd|j                  j                  v rOt        |j                  j                        dkD  r-t        j                  d|j                  j                   d       |j                  j                  S )	z6Returns whether automatic function calling is enabled.Fr   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   r?   s     r   should_disable_afcr     sF    
6v>, 

1
1

1
1
F
F
l55JJ
Kq
P
NN	33HHI J>	>  
1
1		0	0	8	8	@ --55

1
1
F
F !		0	0	A	AB
l55JJ
Ka
O
NN	 33HHI JD		D 
	0	0	8	88r!   c                     | st         S 	 t        |       rt        d      t        |       }|j                  r|j                  j
                  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   rO   r    r   r   r_   r   s     r   get_max_remote_calls_afcr     sn     
((J
	  7v>,

1
1		0	0	E	E	M((	\44II	JJr!   c                 f    | syt        |       }|j                  sy|j                  j                   S )NT)r    r   ignore_call_historyr   s     r   should_append_afc_historyr     s5     
6v>,		0	044HH	HHr!   c                    | syt        |       }|j                  ddi      }|j                  |_        |j                  rt        j                  |j                        rw|j
                  t        j                  i       |_        |j
                  j                  i |j
                  _        t        j                  |j
                  j                         |S )zVReturns a parsed config with an appended MCP header if MCP tools or sessions are used.Nr;   rP   )headers)
r    
model_copyr;   r   has_mcp_tool_usagehttp_optionsr   HttpOptionsr   set_mcp_usage_header)r   r?   config_model_copys      r   parse_config_for_mcp_usager     s     
6v>, #--gt_-E(..J99,:L:LM%%-','8'8'D$%%--5/1$$,##$5$B$B$J$JK	r!   c                   K   i }t        |       }|sd|fS |j                  ddi      }|j                  rg |_        |j                  D ]  }t        t	        |t              rt        ||j                          d{         }|j                  j                  |j                         |j                  D ]p  }|j                  s|j                  D ]R  }|j                  s|j                  |j                        rt        d|j                   d      |||j                  <   T r |j                  j                  |        ||fS 7 έw)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   rG   rH   )r   r   r;   r   r   r   
list_toolsextendr=   r   r'   rO   r>   )r   rD   parsed_configparsed_config_copyrB   mcp_to_genai_tool_adapter
genai_toolfunction_declarations           r   parse_config_for_mcp_sessionsr     sh     BD,V4-	+++ %///G!## .		%*T;K*L$9))%
! 	  ''(A(G(GH399 	J--(2(H(H 	$%**-112F2K2KL"2778 9& & 
 . ++?+D+DE		 	  ''-)., 
7	77' *s    A:E<E=AEE"A*Econtentschunkc                     |]|j                   Q|j                   d   j                  }t        j                  |       } t	        | t
              r|| j                  |       | S )zFAppends the contents of the chunk to the contents list and returns it.r   )r   r   t
t_contentsr   r`   r>   )r   r   chunk_contents      r   append_chunk_contentsr   8  sY    
 5++7$$Q'//M||H%H(D!m&?oom$	/r!   fileuser_http_optionsuser_mime_typec           	         d}|}t        | t        j                        r|t        d      t	        | d      rd| j
                  vrt        d      | j                         }| j                  dt        j                         | j                         |z
  }| j                  |t        j                         nt        j                  |       }|rt        j                  j                  |      st        |  d      t        j                  j                  |      }|t!        j"                  |      \  }}|t        d      |r>t        |t$              rt'        j(                  di |}|}d	|_        d
dd| | d|_        nt'        j(                  d	d
dd| | d      }t        | t.        t        j0                  f      r?|j,                  i |_        t        j                  j3                  |       |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IOBaserO   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_pathrS   r   s	            r   prepare_resumable_uploadr   E  s    *)bii 8  tV	DII	BCCYY[FIIav%JIIfbkk"iioG"''..1&@ABB)J))'2li; 
 #T*++@.?@$L!L*"-!(2<09{L $$.&1%,6@\4=;
	L sBKK()#!68gg6F6Ft6LL23	z9	,,r!   ry   )NNF)NN)U__doc__r   rJ   r   loggingsystypingr   r   r   r   r   r   r	   r   r   re   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(   r1   r9   r`   r_   rC   r   boolrT   
StringDictr[   objectrW   rh   ro   r~   r   r   GenerateContentResponser   r   r   r   r   r   r   tupler   ContentListUnionContentListUnionDictr   r   r   HttpOptionsOrDictr   r   r   r!   r   <module>r     s    U   	  
  M M M  	        , w'')	3'"%FKK%'6;;5)
 !# 			0	1--
  
	sE...	/
c]

	sE...	/
c]
 48	sE(((	)U//0 6 ;?$U667$	#Y$< ;? 	#(!U667! (S''(!!
 !! 
#uXc3h')>>?
?@!H



S&[!4<7
8
4Vd6lF23$	S 	T 	;;;-0;=@;;|


(0c(:"


2:382D


2:382D ++ sE(38"46K"KLLM  
%** F.++.sE(38"46K"KLLM. 
%**.d ;?49U66749	49p ;?KU667KK* ;?IU667I	I ;?U667e))*, ;?)8U667)8
U(()#	#$&)8X
E**E,F,FFG
((
 5!!5#=#==>
 <@$(F-
R[[%ryy0
1F- 7 78F- SMF- 			F-e 
 Gs   <O! !	O.-O.