
    6i                    4   d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	m
Z
 ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZmZmZ ddlmZ erddlmZ d(dZd)dZ	 	 	 	 d*dZ d+dZ!d,dZ"erddlmZ# d-dZ$	 	 	 	 	 	 d.dZ%d/dZ&	 	 	 	 d0dZ'	 	 	 	 d1dZ(	 	 	 	 	 	 d2dZ)	 	 	 	 	 	 d2dZ*	 	 	 	 	 	 d2dZ+	 	 	 	 	 	 d2dZ,	 	 	 	 	 	 d2dZ-	 	 	 	 	 	 d2dZ.	 d3	 	 	 	 	 d4dZ/	 	 	 	 	 	 d5d Z0	 	 	 	 	 	 d5d!Z1	 d3	 	 	 	 	 	 	 d6d"Z2	 d3	 	 	 	 	 	 	 d6d#Z3	 	 	 	 	 	 d7d$Z4	 	 	 	 	 	 d5d%Z5	 	 	 	 	 	 d5d&Z6ejn                  e)e1d'ejp                  e*e0d'ejr                  e-e3d'ejt                  e.e2d'ejv                  e+e5d'ejx                  e,e6d'ejz                  e+e4d'iZ>y)8zGoogle-specific utilities (Gemini, GenAI, VertexAI).

This module contains utilities specific to Google providers,
including reask functions, response handlers, and message formatting.
    )annotationsN)dedent)TYPE_CHECKINGAnyUnion)ChatCompletionMessageParam)	BaseModel   )PartialPartialBase)ConfigurationError)Mode)AudioImagePDF)get_message_contenttypesc                ~    t        | d      r%t        | j                        r| j                         S t        | di       S )aB  
    Safely get the JSON schema from a response model.

    Handles both regular models and Partial-wrapped models by using hasattr
    to check for the model_json_schema method.

    Args:
        response_model: The response model (may be regular or Partial-wrapped)

    Returns:
        The JSON schema dictionary
    model_json_schema)hasattrcallabler   getattrresponse_models    l/root/.openclaw/workspace/visionaryfx/venv/lib/python3.12/site-packages/instructor/providers/gemini/utils.py_get_model_schemar      s@     ~23((9 //11>#6;;    c                    t        | dd      S )a  
    Safely get the name of a response model.

    Handles both regular models and Partial-wrapped models by using getattr
    with a fallback to 'Model'.

    Args:
        response_model: The response model (may be regular or Partial-wrapped)

    Returns:
        The model name
    __name__Model)r   r   s    r   _get_model_namer"   0   s     >:w77r   c                >   | sg S g }| D ]=  }|j                  d      dk(  s|j                  dd      }|s-|j                  |       ? d}|rdj                  t        d|            }t	        d | D              }g }dd	d
}| D ];  }|j                  dd      }||v s||   }	|j                  |	t        |      d       = |rZ|r?|d   }
t        |
j                  d      t              r|
d   j                  dd| d       |S |j                  dd| dgd       |S )a  
    Transform messages from OpenAI format to Gemini format.

    This optimized version reduces redundant processing and improves
    handling of system messages.

    Args:
        messages_chatgpt: Messages in OpenAI format

    Returns:
        Messages in Gemini format
    rolesystemcontent 

Nc              3  J   K   | ]  }|j                  d       dk7  sd  yw)r$   r%      N)get).0ms     r   	<genexpr>z-transform_to_gemini_prompt.<locals>.<genexpr>b   s     QaquuV}7PQs   ##usermodel)r/   	assistantr$   partsr   r3   *)	r+   appendjoinfiltersumr   
isinstancelistinsert)messages_chatgptsystem_promptsmessager&   system_promptmessage_countmessages_geminirole_mapr$   gemini_rolefirst_messages              r   transform_to_gemini_promptrE   @   s]     	 N# /;;v(*kk)R0G%%g.	/ MF4$@A Q#3QQMO H $ {{62&8"4.K""$/B7/KL	 +A.M-++G4d;g&--a1]O11EF
  ""F-PQ>R=S#TUr   c                     y)a  
    Verify that the object does not contain any Union types (except Optional and Decimal).
    Optional[T] is allowed as it becomes Union[T, None].
    Decimal types are allowed as Union[str, float] or Union[float, str].

    Note: As of December 2024, Google GenAI now supports Union types
    (see https://github.com/googleapis/python-genai/issues/447).
    This function is kept for backward compatibility but now returns True
    for all schemas. The validation is no longer necessary.

    Args:
        obj: The schema object to verify (kept for backward compatibility).

    Returns:
        Always returns True since Union types are now supported.
    T )objs    r   verify_no_unionsrI      s    & r   c                    ddl } G d dt              }|j                  | d      }|j                  dd       dfd |      }t	        |      st        d	       |di |j                  d
d
      S )a  
    Map OpenAPI schema to Gemini function call schema.

    Transforms a standard JSON schema to Gemini's expected format:
    - Adds 'format': 'enum' for enum fields
    - Converts Optional[T] (anyOf with null) to nullable fields
    - Preserves Union types (anyOf) as they are now supported by GenAI SDK

    Ref: https://ai.google.dev/api/python/google/generativeai/protos/Schema
    r   Nc                      e Zd ZU dZded<   dZded<   dZded<   dZded<   dZd	ed
<   dZ	ded<   dZ
ded<   dZded<   dZded<   dZded<   y)5map_to_gemini_function_schema.<locals>.FunctionSchemaN
str | Nonedescriptionzlist[str] | Noneenumz
Any | Noneexampleformatzbool | NonenullablezFunctionSchema | Noneitemsrequiredtypezlist[dict[str, Any]] | NoneanyOfz dict[str, FunctionSchema] | None
properties)r    
__module____qualname__rN   __annotations__rO   rP   rQ   rR   rS   rT   rU   rV   rW   rG   r   r   FunctionSchemarL      sk    "&Z&!%%""!
! $+$'+$+%)")j-1*17;
4;r   r[   F)	lazy_load$defsc                   t        | t              r| D cg c]
  } |       c}S t        | t              s| S i }| j                         D ]  \  }}|dk(  r|||<   d|d<   |dk(  rt        |t              rt	        |      dk(  r|D cg c](  }t        |t              r|j                  d      dk(  s|* }}t	        |      dk(  r" |d         }|j                  |       d	|d
<   g }|D ],  }t        |t              sd|v s|j                  |d          . t        |      ddhk(  r |      ||<    |      ||<    |      ||<    |S c c}w c c}w )z+Transform a single schema node recursively.rO   rQ   rV      rU   nullr*   r   TrR   stringnumber)	r9   r:   dictrS   lenr+   updater5   set)	nodeitemtransformedkeyvaluenon_null_itemsactual_typetypes_in_uniontransform_schema_nodes	           r   ro   z<map_to_gemini_function_schema.<locals>.transform_schema_node   s   dD!<@AD)$/AA$%K**,  	@JCf}#(C (.H%Jud$;E
a !&"&tT2txx7G67Q " " ~&!+"7q8I"JK&&{3.2K
+ &(N % @%dD1fn*11$v,?@ >*x.BB+@+GC( ,A+GC(#8#?C A 	@D S B"s   E
-EzYGemini does not support Union types (except Optional). Please change your function schemaT)exclude_noneexclude_unsetrg   r   returnr   rG   )jsonrefr	   replace_refspoprI   
ValueError
model_dump)rH   rt   r[   schemaro   s       @r   map_to_gemini_function_schemarz      s     
< 
< %11#1GF
JJw,\ #6*F F#g
 	
 #F#..DPT.UUr   c                t    ddl m} t        |       }dfd|j                  j	                   |            S )Nr   r   c           
        t        | t              r| D cg c]
  } |       c}S t        | t              s| S ddddddddd	d
	}i }| j                         D ]   \  }} |      ||j	                  ||      <   " |S c c}w )Nany_ofrefdefs	max_items	min_items
max_length
min_lengthmax_propertiesmin_properties)	rV   z$refr]   maxItemsminItems	maxLength	minLengthmaxPropertiesminProperties)r9   r:   rc   rS   r+   )rg   rh   key_map
normalizedrj   rk   	normalizes         r   r   z&map_to_genai_schema.<locals>.normalize   s    dD!045IdO55$%K ##%%--

 &(
**, 	AJC09%0@Jw{{3,-	A) 6s   A=rr   )google.genair   rz   Schemamodel_validate)rH   r   ry   r   s      @r   map_to_genai_schemar      s1    "*3/F0 <<&&y'899r   c           	     T   ddl m}m} | j                         }ddddddd	d
d}|j	                  di       }|j                         D ]#  \  }}||v s|j	                  |      }	|	|	||<   % dd}
|j	                  di       }g |d<   t        |t              r||d<   d}|j                  h}t        |d      r|j                  |j                         | |
|      }|D cg c]#  }||vr|j                  j                  d      r|% }}|D cg c]#  }||vr|j                  j                  d      s|% }}|r|r|n|}dd}|D ]  }|j                  }t        |t              r\||v r||   }nR|rP|j                  j                  d      r5 ||j                        }|!t        ||      rt!        ||      }||v r||   }|d   j#                  ||d        |j%                  d      }d}t        |t              r|j%                  d      }n|t        |d      r|j&                  }|j	                  dd      }||}|||d<   |Ug d}|D ]L  }t        |t              r|j%                  |      }nt        ||      rt!        ||      }nd}|C||vsH|||<   N |S c c}w c c}w )z
    Update keyword arguments for google.genai package from OpenAI format.

    Handles merging of user-provided config with instructor's base config,
    including special handling for thinking_config and other config fields.
    r   HarmBlockThresholdHarmCategorymax_output_tokenstemperaturecandidate_counttop_pstop_sequencesseedpresence_penaltyfrequency_penalty)
max_tokensr   nr   stopr   r   r   generation_configNc                ,   | j                  d      }t        |t              r|D ]  }t        |dd      }|s|D ]  }t        |dd      }|1t        |dd      }t        |t              r|j                  d      r  yt        |dd      }|St        |dd      }t        |t              sq|j                  d      s  y  | j                  d	      }t        |t              r|D ]  }	t        |	t              s|	j                  d
      }t        |t              r yt        |t              rA|D ]<  }
t        |
t              r  yt        |
t              s'|
j                  d      dv s;  y t        |t              s|j                  d      dv s y y)a8  
        Best-effort check for image content in a GenAI request.

        We use this to decide whether to send text vs image harm categories in
        `safety_settings`. The google-genai SDK has separate image categories
        (e.g., `HARM_CATEGORY_IMAGE_HATE`) which are required for image content.
        contentsr3   Ninline_data	mime_typezimage/T	file_datamessagesr&   rU   >   image	image_urlinput_imageF)r+   r9   r:   r   str
startswithrc   r   )genai_kwargsr   r&   r3   partr   r   r   r   r>   rh   s              r   _genai_kwargs_has_image_contentz<update_genai_kwargs.<locals>._genai_kwargs_has_image_content3  s     ##J/h%# ($7! (D")$t"DK".$+Kd$K	%i5):N:N$; $( 'k4 @I ,$+I{D$I	%i5):N:N$; $((	(,  ##J/h%#  !'40!++i0gu-gt, ' (%dE2#'%dD1dhhv6F K 7
 $(( gt,V1D I 2
  + . r   safety_settingsHARM_CATEGORY_JAILBREAKHARM_CATEGORY_IMAGE_c                :    | j                  d      }|dk(  ryd| S )Nr   HATEHARM_CATEGORY_HATE_SPEECHHARM_CATEGORY_)removeprefix)image_category_namesuffixs     r    _map_text_to_image_category_namez=update_genai_kwargs.<locals>._map_text_to_image_category_name  s+    (556LMF2#F8,,r   )category	thresholdconfigthinking_config)automatic_function_callinglabelscached_content)r   dict[str, Any]rs   bool)r   r   rs   rM   )google.genai.typesr   r   copyrv   rS   r9   r:   HARM_CATEGORY_UNSPECIFIEDr   addr   namer   OFFrc   r   r5   r+   r   )kwargsbase_configr   r   
new_kwargsOPENAI_TO_GEMINI_MAPr   
openai_key
gemini_keyvalr   r   excluded_categories	has_imagecimage_categoriestext_categoriessupported_categoriesr   r   r   mapped_namemapped_categoryuser_configuser_thinking_configr   config_fields_to_mergefieldfield_values                                r   update_genai_kwargsr     s<    DJ *$ .0	 #':B?"6"<"<"> .
J**#''
3C*-J'	.:x !nn%6;O%'K!" /4()8%&
 (AAB|67 D DE"3J?	 "
++!!"89 
 
 "
++FF%%&<= 
 
 "+/?o 		- - 	H*..I/40. / 9I8==#;#;<R#S"B8=="QK".7<3U*1,*L*o=(7(HI)*11 (!*	, ..*K+t$*/@A		 W[:K%L*:: !nn%6=O.")8%&
 "

 , 		1E+t,)ooe4e,%k59"&5+C%0E"		1 c

s   !(J (J%c                X   | j                         }dddddd}d|v r;|d   }|j                         D ]#  \  }}||v s|j                  |      }||||<   % d|v rt        |j                  d            |d	<   	 d
dlm}m} |j                  di       }	|	|d<   |j                  |j                  |j                  |j                  |j                  |j                  i}
|
j                         D ]#  \  }}|	j                  |      }|||kD  s||	|<   % |S # t        $ r d
dlm}m} Y w xY w)a.  
    Update keyword arguments for Gemini API from OpenAI format.

    This optimized version reduces redundant operations and uses
    efficient data transformations.

    Args:
        kwargs: Dictionary of keyword arguments to update

    Returns:
        Updated dictionary of keyword arguments
    r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r   )r   rS   rv   rE   r   r   r   ImportErrorgoogle.generativeai.typesr+   r   BLOCK_ONLY_HIGHHARM_CATEGORY_HARASSMENTHARM_CATEGORY_DANGEROUS_CONTENT)r   resultr   
gen_configr   r   r   r   r   r   DEFAULT_SAFETY_THRESHOLDSr   r   currents                 r   update_gemini_kwargsr     sr    [[]F
 *$  f$/0
 ';&@&@&B 	1"J
Z' nnZ0?-0Jz*		1 V7

:8NOz
G jj!2B7O /F
 	..0B0R0R--/A/Q/Q446H6X6X!  9>>@ 2)!%%h/ ?g	1(1OH%2 M9  
	
 	

s   :D D)(D)c                   d}| D ]  }t        |t              rt        |t              s%|j                  d      dk(  s:t        |j                  d      t              r||j                  dd      dz   z  }rt        |j                  d      t              s|j                  dg       D ]  }t        |t              s||dz   z  }  |rt        |       dk(  rt        d      t        j                  d|      rt        d	      |S )
zx
    Extract system messages from a list of messages.

    We expect an explicit system messsage for this provider.
    r'   r$   r%   r&   r(   r*   zUAt least one user message must be included. A system message alone is not sufficient.z{{.*?}}|{%.*?%}z[Jinja templating is not supported in system messages with Google GenAI, only user messages.)	r9   r   rc   r+   r:   rd   rw   research)r   system_messagesr>   rh   s       r   extract_genai_system_messager   "  s     O 
=gs#&{{6"h.gkk)4c:#w{{9b'AF'JJOI 6= 'Ir : =%dC0+tf}<O=
= 3x=A-c
 	
 
yy#_5i
 	
 r   c           
     j   ddl m} g }| D ]$  }t        |t              r?|j	                   |j
                  d|j                  j                  |      g             St        ||j
                        r|j	                  |       {t        ||j                        r|j	                  |       t        |t              r\d|v sJ d|v sJ |d   dk(  r|d   d	vrt        d
|d          t        |d   t              rF|j	                   |j
                  |d   |j                  j                  |d         g             :t        |d   t              sOg }|d   D ]  }t        |t              r,|j	                  |j                  j                  |             ?t        |t        t        t        f      r |j	                  |j                                zt        dt!        |              |j	                   |j
                  |d   |             t        dt!        |              |S )z
    Convert a list of messages to a list of dictionaries in the format expected by the Gemini API.

    This optimized version pre-allocates the result list and
    reduces function call overhead.
    r   r   r/   textr2   r$   r&   r%   >   r/   r0   zUnsupported role: zUnsupported content item type: zUnsupported message type: )r   r   r9   r   r5   ContentPart	from_textFilerc   rw   r:   r   r   r   to_genairU   )r   r   r   r>   content_partscontent_items         r   convert_to_genai_messagesr   E  s    #57F 3Kgs#MM :://W/=> /MM'",MM'"&W$$$'''v(*v&77 #5gfo5F!GHH'),c2!EMM$V_$zz339K3LM GI.5 "$+I$6 L!,4%,,UZZ-A-A|-A-TU#L5%2EF%,,\-B-B-DE(=d<>P=QR  !EMM$V_+ 9$w-IJJg3Kj Mr   c           
        ddl m} d|j                  |j                  d   j                  j
                  |j                  d   j                  j                        gdd|j                  |j                  |j                  d   j                  j
                  dd| i	      
      gdddgdg}| d   j                  |       | S )z
    Handle reask for Gemini tools mode when validation fails.

    Kwargs modifications:
    - Adds: "contents" (tool response messages indicating validation errors)
    r   )generativelanguager0   )r   argsr2   functionerrorzValidation Error(s) found:
r   response)function_responser/   z:Recall the function arguments correctly and fix the errorsr   )
	google.air   FunctionCallr3   function_callr   r   r   FunctionResponseextend)r   r  	exceptionglm
reask_msgss        r   reask_gemini_toolsr    s     4   !*88==!*88== ! 	
 &)&:&:%^^A.<<AA")-I)+U!V '; '  
	
 RS	
+J4 :j)Mr   c                V    | d   j                  dd|j                   d| gd       | S )z
    Handle reask for Gemini JSON mode when validation fails.

    Kwargs modifications:
    - Adds: "contents" (user message requesting JSON correction)
    r   r/   zMCorrect the following JSON response, based on the errors given below:

JSON:
z

Exceptions:
r2   )r5   r   )r   r  r  s      r   reask_gemini_jsonr    sF     :"--(9)F	
 Mr   c                    ddl m} | j                         } |j                  d   j                   |||      g}| d   j                  |       | S )z
    Handle reask for Vertex AI tools mode when validation fails.

    Kwargs modifications:
    - Adds: "contents" (tool response messages indicating validation errors)
    r_   )!vertexai_function_response_parserr   r   )vertexai.clientr  r   
candidatesr&   r  )r   r  r  r  r
  s        r   reask_vertexai_toolsr    sR     D[[]FA&&)(I>J :j)Mr   c                    ddl m} | j                         } |j                  d   j                   |dd| d|j
                   d      g}| d   j                  |       | S )	z
    Handle reask for Vertex AI JSON mode when validation fails.

    Kwargs modifications:
    - Adds: "contents" (user message requesting JSON correction)
    r_   )vertexai_message_parserr   r/   zValidation Errors found:
zO
Recall the function correctly, fix the errors found in the following attempt:
r$   r&   r   )r  r  r   r  r&   r   r  )r   r  r  r  r
  s        r   reask_vertexai_jsonr    su     :[[]F 	A&&0 <GGO}}oW	
J :j)Mr   c                4   ddl m} | j                         } | j                  d      }t	        |t
              r|j                         | d<   n|g | d<   nt        |      | d<   d}d}d}|t        |dd      nd}t	        |t
              rJ|D ]E  }	t        |	dd      }
|
||
}t        |
dd      xs g }|D ]  }t        |dd      }||
} n |E n d	| d
}|Y|| d   j                  |       | d   j                   |j                  d|j                  j                  |      g             | S |j                  j                  |j                  d|i      }| d   j                  |       | d   j                   |j                  d|g             | S )z
    Handle reask for Google GenAI tools mode when validation fails.

    Kwargs modifications:
    - Adds: "contents" (model response preserved for thought_signature,
                        tool response with validation errors)
    r   r   r   Nr  r&   r3   r  Validation Error found:
z.
Recall the function correctly, fix the errorsr/   r   r2   r   r   tool)r   r   r   r+   r9   r:   r   r5   r   r   r   from_function_responser   )r   r  r  r   existing_contentsmodel_contentfunction_call_contentr  r  	candidater&   r3   r   	error_msgfunction_response_parts                  r   reask_genai_toolsr!    s    #[[]F

:.#T*.335z		"z!"34zM M:B:N<6TXJ*d## 	IiD9G$ 'GWd39rE  'ot D ,,3)	 (!	& $I; /8 	8 
 $:%%m4z!!EMMzz+++;<	
 "ZZ>>9% ? 
 :34
:6*@)AB Mr   c           
         ddl m} | j                         } |rt        |d      r|j                  nd}| d   j                   |j                  |j                  j                  d| d|       g	             | S )
z
    Handle reask for Google GenAI structured outputs mode when validation fails.

    Kwargs modifications:
    - Adds: "contents" (user message describing validation errors)
    r   r   r   z]You must generate a response to the user's request that is consistent with the response modelr   r  zI
Recall the function correctly, fix the errors in the following attempt:
r   )r3   )	r   r   r   r   r   r5   ModelContentr   r   )r   r  r  r   genai_responses        r   reask_genai_structured_outputsr%  O  s     #[[]F &1 	l  :

$$4YK  @K  LZ  K[  \ % 	
 Mr   c                    ddl m} | j                  dg       }t        |      | d<   ddlm}  || d   |      | d<   d| vr#t        |      }|r |j                  |      | d	<   | j                  dd
       | S )z
    Convert OpenAI-style messages to GenAI contents.

    Kwargs modifications:
    - Removes: "messages"
    - Adds: "contents" (GenAI-style messages)
    - Adds: "config" (system instruction) when system not provided
    r   r   r   r   r
    extract_genai_multimodal_contentr%   )system_instructionr   N)	r   r   r+   r   processing.multimodalr(  r   GenerateContentConfigrv   )r   autodetect_imagesr   r   r(  system_messages         r   handle_genai_message_conversionr.  q  s     #~~j"-H 7x@Jz J=: 1Jz
 z!5h?#>5#>#>#1$Jx 
 NN:t$r   c                j   d|v rt        d      | t        |      }d|fS t        dt        j                  t        |       dd       d      }|d	   d
   d   dk7  r|d	   j                  d
d|d       n|d	   d
   dxx   d| z  cc<   |j                  di       ddiz  |d<   t        |      }| |fS )a  
    Handle Gemini JSON mode.

    When response_model is None:
        - Updates kwargs for Gemini compatibility (converts messages format)
        - No JSON schema or response format is configured

    When response_model is provided:
        - Adds/modifies system message with JSON schema instructions
        - Sets response_mime_type to "application/json"
        - Updates kwargs for Gemini compatibility

    Kwargs modifications:
    - Modifies: "messages" (adds/modifies system message with JSON schema) - only when response_model provided
    - Adds/Modifies: "generation_config" (sets response_mime_type to "application/json") - only when response_model provided
    - All modifications from update_gemini_kwargs (converts messages to Gemini format)
    r0   dGemini `model` must be set while patching the client, not passed as a parameter to the create methodNz
        As a genius expert, your task is to understand the content and provide
        the parsed objects in json that match the following json_schema:


        r_   F)indentensure_asciizU

        Make sure to return an instance of the JSON, not the schema itself
        r   r   r$   r%   r  r&   r(   r   response_mime_typeapplication/json)r   r   r   jsondumpsr   r;   r+   )r   r   r>   s      r   handle_gemini_jsonr7    s   ( * r
 	
 )*5
Z	 
%n5ae	TU V				G *a (H4:%%a(w)OP:q!),$wi0@@,&0nn5H"&M0Q 'J"# &j1J:%%r   c                    d|v rt        d      | t        |      }d|fS | j                  g|d<   ddt        |       gdi|d<   t        |      }| |fS )	at  
    Handle Gemini tools mode.

    Kwargs modifications:
    - When response_model is None: Only applies update_gemini_kwargs transformations
    - When response_model is provided:
      - Adds: "tools" (list with gemini schema)
      - Adds: "tool_config" (function calling config with mode and allowed functions)
      - All modifications from update_gemini_kwargs
    r0   r0  Ntoolsfunction_calling_configANYmodeallowed_function_namestool_config)r   r   gemini_schemar"   )r   r   s     r   handle_gemini_toolsrA    s     * r
 	
 )*5
Z)778Jw!'6~'F&G$
!J} &j1J:%%r   c                   ddl m} | t        ||      }d|fS |j                  dd      rt	        | t
              s	t        |    } |j                  d      }d}d}t        |t              r#|j                  d      }|j                  d      }n2|0t        |d      r|j                  }t        |d      r|j                  }d|vr|||d<   |j                  d	      r|j                  d	      }n"|j                  d
      rt        |d
         }nd}t        |d
         |d<   ddlm}  ||d   |      |d<   t#        t%        |              d| d}	|||	d<   t'        ||	      }
 |j(                  di |
|d<   |j                  dd       |j                  d
d       |j                  dd       |j                  dd       |j                  dd       | |fS )a  
    Handle Google GenAI structured outputs mode.

    Kwargs modifications:
    - When response_model is None: Applies handle_genai_message_conversion
    - When response_model is provided:
      - Removes: "messages", "response_model", "generation_config", "safety_settings"
      - Adds: "contents" (GenAI-style messages)
      - Adds: "config" (GenerateContentConfig with system_instruction, response_mime_type, response_schema)
      - Handles multimodal content extraction
    r   r   NstreamFr   r   r   r%   r   r   r
   r'  r4  )r3  response_schemar)  r   r   r   rG   )r   r   r.  r+   
issubclassr   r   r9   rc   r   r   r   rv   r   r   r*  r(  rz   r   r   r+  )r   r   r,  r   r   r   user_cached_contentr-  r(  r   r   s              r   handle_genai_structured_outputsrG    s     #4ZARS
Z ~~h&z.+/V 0
 ..*K+t$*/@A)oo.>?		 ; 12#.#>#> ; 01"-"<"< 
*/C/O(<
$%~~h#1	
	#5j6LM6z*7MNJz J=: 1Jz
 ""3N"CD 1)K ",:()+JD6566K9JKJxNN#T*NN:t$NN&-NN$d+NN$d+:%%r   c                   ddl m} | t        ||      }d|fS |j                  dd      rt	        | t
              s	t        |    } |j                  d      }d}d}t        |t              r#|j                  d      }|j                  d      }n2|0t        |d      r|j                  }t        |d      r|j                  }d|vr|||d<   t        t        |             } |j                  t        |       t!        | d	d      |
      }|j                  d      r|j#                  d      }	n"|j                  d      rt%        |d         }	nd}	i }
|c|	|
d<    |j&                  |g      g|
d<    |j(                   |j*                  |j,                  j.                  t        |       g            |
d<   t1        |d         |d<   ddlm}  ||d   |      |d<   t7        ||
      } |j8                  di ||d<   |j#                  dd       |j#                  dd       |j#                  dd       |j#                  dd       |j#                  dd       | |fS )a  
    Handle Google GenAI tools mode.

    Kwargs modifications:
    - When response_model is None: Applies handle_genai_message_conversion
    - When response_model is provided:
      - Removes: "messages", "response_model", "generation_config", "safety_settings"
      - Adds: "contents" (GenAI-style messages)
      - Adds: "config" (GenerateContentConfig with tools and tool_config)
      - Handles multimodal content extraction
    r   r   NrC  Fr   r   r   __doc__)r   rN   
parametersr%   r   r)  )function_declarationsr9  r<  )r:  r?  r   r
   r'  r   r   r   rG   )r   r   r.  r+   rE  r   r   r9   rc   r   r   r   r   r   FunctionDeclarationr"   r   rv   r   Tool
ToolConfigFunctionCallingConfigFunctionCallingConfigModer;  r   r*  r(  r   r+  )r   r   r,  r   r   r   rF  ry   function_definitionr-  r   r(  r   s                r   handle_genai_toolsrR  H  s}     #4ZARS
Z ~~h&z.+/V 0
 ..*K+t$*/@A)oo.>?		 ; 12#.#>#> ; 01"-"<"< 
*/C/O(<
$% !2>!BCF3%33^,NIt< ~~h#1	
	#5j6LM"$K
 ",:() *

BUAV WXG%5U%5%5$?E$?$?4488(7(G'H%&
M" 7z*7MNJz J=: 1Jz ,JD6566K9JKJxNN#T*NN:t$NN&-NN$d+NN$d+:%%r   c                    ddl m} ddlm} ddlm} |j                  dd      rt        d      t         ||             } |||      \  }}}||d	<   ||d
<   ||d<    ||       |fS )z
    Handle Vertex AI parallel tools mode.

    Kwargs modifications:
    - Adds: "contents", "tools", "tool_config" via vertexai_process_response
    - Validates: stream=False
    r   )get_argsr_   vertexai_process_response)VertexAIParallelModelrC  FzDstream=True is not supported when using VERTEXAI_PARALLEL_TOOLS moder   r9  r?  )typehint)	typingrT  r  rV  instructor.dsl.parallelrW  r+   r   r:   )	r   r   rT  rV  rW  model_typesr   r9  r?  s	            r   handle_vertexai_parallel_toolsr\    s}      ;=~~h& R
 	

 x/0K#<Z#U He[%JzJw +J} .9:EEr   c                \    ddl m} 	 | d |fS  |||       \  }}}||d<   ||d<   ||d<   | |fS )Nr_   rU  r   r9  r?  )r  rV  )r   r   rV  r   r9  r?  s         r   handle_vertexai_toolsr^    s[     < Z#<Z#X He[%JzJw +J}:%%r   c                P    ddl m} 	 | d |fS  |||       \  }}||d<   ||d<   | |fS )Nr   )vertexai_process_json_responser   r   )$instructor.providers.vertexai.clientr`  )r   r   r`  r   r   s        r   handle_vertexai_jsonrb    sW     T Z"@N#H &Jz&7J"#:%%r   )reaskr  )r   r   rs   r   )r   r   rs   r   )r<   z list[ChatCompletionMessageParam]rs   list[dict[str, Any]])rH   r   rs   r   )rH   r   rs   r   )rH   r   rs   zgenai_types.Schema)r   r   r   r   rs   r   )r   r   rs   r   )r   rd  rs   r   )r   z6list[Union[str, dict[str, Any], list[dict[str, Any]]]]rs   z	list[Any])r   r   r  r   r  	Exception)F)r   r   r,  r   rs   r   )r   type[Any] | Noner   r   rs   'tuple[type[Any] | None, dict[str, Any]])r   rf  r   r   r,  r   rs   rg  )r   z	type[Any]r   r   rs   ztuple[Any, dict[str, Any]])?rI  
__future__r   r5  r   textwrapr   rY  r   r   r   openai.types.chatr   pydanticr	   dsl.partialr   r   core.exceptionsr   r=  r   r*  r   r   r   
utils.corer   r   r   r   r"   rE   rI   rz   genai_typesr   r   r   r   r   r  r  r  r  r!  r%  r.  r7  rA  rG  rR  r\  r^  rb  GEMINI_TOOLSGEMINI_JSONGENAI_TOOLSGENAI_STRUCTURED_OUTPUTSVERTEXAI_TOOLSVERTEXAI_JSONVERTEXAI_PARALLEL_TOOLSGOOGLE_HANDLERSrG   r   r   <module>rx     sW   #  	  , , 8  / 1  6 6 -"<*8 @6@@F,SVl 1:@@@)7@@FIX "  FBDBBL((( (V . , >JJJ JZ F ;@$$37$$N3&$3&2@3&,3&l &$ &2@ &, &L $T&$T&T& T& -	T&t $a&$a&a& a& -	a&HFF+9FF<&$&2@&,&4&$&2@&,&: 	#' 	"& 	"& 	!!/3$ 	%) 	$( 	  %2#3r   