
    {hʷ                       d dl 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
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m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$m%Z%m&Z& d dl'm(Z(m)Z)m*Z* d dl+m,Z,m-Z- d dl.m/Z/ d dl0m1Z1m2Z2 d dl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:  ejv                  d      Z< ede      Z= ed      Z> ed      Z? ed      Z@ddde/j                  d	 	 	 	 	 	 	 	 	 	 	 	 	 dDdZBddde/j                  d	 	 	 	 	 	 	 	 	 	 	 dEdZCdFdZD	 	 	 	 	 	 dGdZE	 	 	 	 	 	 dHdZF	 	 	 	 	 	 dGd ZG	 	 	 	 	 	 dGd!ZH	 	 	 	 	 	 dGd"ZI	 	 	 	 	 	 dGd#ZJ	 	 	 	 	 	 dGd$ZK	 	 	 	 	 	 dGd%ZL	 	 	 	 	 	 dGd&ZM	 	 	 	 	 	 dGd'ZN	 	 	 	 	 	 	 	 dId(ZO	 	 	 	 	 	 dGd)ZP	 	 	 	 	 	 dGd*ZQ	 	 	 	 	 	 dGd+ZRdJd,ZS	 	 	 	 	 	 dGd-ZT	 	 	 	 	 	 dGd.ZU	 	 	 	 	 	 dGd/ZV	 	 	 	 	 	 dGd0ZW	 	 	 	 	 	 dGd1ZX	 	 	 	 	 	 dGd2ZY	 	 	 	 	 	 dKd3ZZ	 	 	 	 	 	 dGd4Z[	 	 	 	 	 	 dGd5Z\	 	 	 	 dLd6Z]	 	 	 	 	 	 dGd7Z^	 	 	 	 	 	 dGd8Z_	 	 	 	 	 	 dGd9Z`	 	 	 	 	 	 dGd:Za	 	 	 	 	 	 dGd;Zb	 	 	 	 	 	 dGd<Zc	 	 	 	 	 	 dGd=Zd	 	 	 	 	 	 dGd>Ze	 	 	 	 	 	 dGd?ZfdFd@ZDdMdAZg	 	 	 	 	 	 dGdBZhe/j                  f	 	 	 	 	 	 	 dNdCZiy)O    )annotationsN)Iterable)dedent)AnyTypeVarget_args
get_originpydantic_function_tool)ChatCompletion)	BaseModelcreate_model)	ParamSpec)IterableBaseIterableModel)	ParallelBaseParallelModelAnthropicParallelBaseAnthropicParallelModelVertexAIParallelBaseVertexAIParallelModelget_types_arrayhandle_parallel_modelhandle_anthropic_parallel_model)PartialBasePartial)AdapterBaseModelAdapteris_simple_type)OpenAISchemaopenai_schema)Mode)convert_messages extract_genai_multimodal_content)combine_system_messagesconvert_to_genai_messagesextract_genai_system_messageextract_system_messagesmap_to_gemini_function_schemamerge_consecutive_messagesupdate_genai_kwargs
instructorT_Model)boundT_RetvalT_ParamSpecTF)streamvalidation_contextstrictmodec               N  K   t         j                  d|         || S t        j                  |      r5t	        |t
        t        f      r|r|j                  | |       d{   }|S |j                  | |||      }t        |t
              r/t         j                  d       |j                  D cg c]  }| c}S t        |t              rt         j                  d       |S t        |t              r!t         j                  d       |j                  S | |_        |S 7 c c}w w)aZ  
    Asynchronously processes the response from the OpenAI API.

    Args:
        response (ChatCompletion): The raw response from the OpenAI API.
        response_model (type[T_Model | OpenAISchema | BaseModel] | None): The expected model type for the response.
        stream (bool): Whether the response is streamed.
        validation_context (dict[str, Any] | None): Additional context for validation.
        strict (bool | None): Whether to apply strict validation.
        mode (Mode): The processing mode to use.

    Returns:
        T_Model | ChatCompletion: The processed response, either as the specified model type or the raw ChatCompletion.

    This function handles various response types, including streaming responses and different model bases.
    It applies the appropriate processing based on the response_model and mode provided.
    Instructor Raw Response: Nr5   r3   r4   r5   !Returning takes from IterableBase!Returning model from ParallelBase Returning model from AdapterBase)loggerdebuginspectisclass
issubclassr   r   from_streaming_response_asyncfrom_response
isinstancetasksr   r   content_raw_responseresponseresponse_modelr2   r3   r4   r5   modeltasks           \/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/instructor/process_response.pyprocess_response_asyncrN   7   s    6 LL
#H:.  	'~k'BC$BB C 
 
 ((-	 ) E %&8:!&---.,/8:%%79}}"EL9
" .s&   A D%"D#AD%1	D :A%D% D%)rJ   r3   r4   r5   c               \   t         j                  d|         |t         j                  d       | S t        j                  |      r-t	        |t
        t        f      r|r|j                  | |      }|S |j                  | |||      }t        |t
              r/t         j                  d       |j                  D cg c]  }| c}S t        |t              rt         j                  d       |S t        |t              r!t         j                  d       |j                  S | |_        |S c c}w )a1  
    Process the response from the API call and convert it to the specified response model.

    Args:
        response (T_Model): The raw response from the API call.
        response_model (type[OpenAISchema | BaseModel] | None): The model to convert the response to.
        stream (bool): Whether the response is a streaming response.
        validation_context (dict[str, Any] | None): Additional context for validation.
        strict (bool | None): Whether to use strict validation.
        mode (Mode): The mode used for processing the response.

    Returns:
        The processed response, which could be:
        - The raw response if no response_model is specified
        - An instance of the response_model
        - A list of tasks if the model is an IterableBase
        - The content of the model if it's an AdapterBase

    This function handles various types of responses and models, including streaming
    responses, iterable models, parallel models, and adapter models. It also attaches
    the raw response to the processed model when applicable.
    r7   z+No response model, returning response as isr8   r9   r:   r;   r<   )r=   r>   r?   r@   rA   r   r   from_streaming_responserC   rD   rE   r   r   rF   rG   rH   s           rM   process_responserQ   |   s   > LL
#H:. BC 	'~k'BC66 7 
 ((-	 ) E %&8:!&---.,/8:%%79}}"EL .s   <	D)c                b    t        | t              xr t        | t              xr t	        | d      S N__annotations__rD   typerA   dicthasattrclss    rM   is_typed_dictr[      0    3 	,sD!	,C*+    c                    |j                  dd      rddlm}  |d      t        |       |d<   d|d<   t	        | 	      |fS )
Nr2   Fr   ConfigurationErrorz;stream=True is not supported when using PARALLEL_TOOLS modetoolsautotool_choicetypehint)getinstructor.exceptionsr`   r   r   )rJ   
new_kwargsr`   s      rM   handle_parallel_toolsri      sP     ~~h&< I
 	
 0?Jw &J}.1:==r]   c                `   |j                  dd      rddlm}  |d      t        |       |d<   ddi|d	<   t	        |j                  d
g             }|rt        |j                  d      |      |d<   |j                  d
g       D cg c]  }|d   dk7  s| c}|d
<   t        |       |fS c c}w )Nr2   Fr   r_   zEstream=True is not supported when using ANTHROPIC_PARALLEL_TOOLS modera   rV   rb   rc   messagessystemrolerd   )rf   rg   r`   r   r(   r%   r   )rJ   rh   r`   system_messagesms        rM   handle_anthropic_parallel_toolsrp      s     ~~h&< S
 	
 :.IJw!' 0J}-jnnZ.LMO6NN8$o 

8
 >>*b1QvY(5JJz ">:JFF	s   B+B+c                z    t        j                          | j                  g|d<   d| j                  d   i|d<   | |fS )N	functionsnamefunction_call)r"   warn_mode_functions_deprecationr!   rJ   rh   s     rM   handle_functionsrw      sH     	((*-;;<J{#)>+G+G+O"PJ:%%r]   c                \    t        |       }d|d   d<   |g|d<   dd|d   d   id|d<   | |fS )NTfunctionr4   ra   rs   rV   ry   rc   r
   )rJ   rh   response_model_schemas      rM   handle_tools_strictr|     s[     3>B26*%h/01Jw2:>vFG!J} :%%r]   c                ^    d| j                   dg|d<   dd| j                   d   id|d<   | |fS )Nry   rz   ra   rs   rc   r!   rv   s     rM   handle_toolsr     sR    
 &44	
Jw ^99&AB!J} :%%r]   c                <   t        |       }|d   d= d|d   d   |d   d   d}d|d   v r|d   d   |d<   nd| j                   d|d<   d|d   d   |d   d   dg|d	<   d| j                  d   d
|d<   |j                  d      |j	                  d      |d<   | |fS Nry   r4   rs   
parameters)rV   rs   r   descriptionzCorrectly extracted `z5` with all the required parameters with correct typesra   rV   rs   rc   
max_tokensmax_output_tokens)r   __name__r!   rf   poprJ   rh   schematool_definitions       rM   handle_responses_toolsr     s    $N3Fz8$ z"6*Z(6O z**)/
);M)J& $N$;$;#< =9 : 	& :&v. ,\:	
Jw ,,V4!J} ~~l#/*4..*F
&':%%r]   c                h   t        |       }|d   d= d|d   d   |d   d   d}d|d   v r|d   d   |d<   nd| j                   d|d<   |j                  d	      s|g|d	<   d| j                  d   d
|d<   n|d	   j	                  |       |j                  d      |j                  d      |d<   | |fS r   )r   r   rf   r!   appendr   r   s       rM   )handle_responses_tools_with_inbuilt_toolsr   E  s    $N3Fz8$ z"6*Z(6O z**)/
);M)J& $N$;$;#< =9 : 	&
 >>'"./
7"008%

=!
 	7""?3~~l#/*4..*F
&':%%r]   c                :    d| j                   dg|d<   d|d<   | |fS )Nry   rz   ra   anyrc   r~   rv   s     rM   handle_mistral_toolsr   h  s8    
 &44	
Jw !&J}:%%r]   c                t    ddl m}  ||       |d<   |j                  dd        |j                  dd        | |fS )Nr   )#response_format_from_pydantic_modelresponse_formatra   rJ   )mistralai.extrar   r   )rJ   rh   r   s      rM   !handle_mistral_structured_outputsr   u  s@     D$G$WJ !NN7D!NN#T*:%%r]   c                
   |j                  dg       D cg c]  }|d   	 }}d|v rt        d      t        dt        j                  | j                         dd       d	      }|d   j                  d
|d       | |fS c c}w )Nrk   rm   rl   z3System messages are not supported For the O1 modelsz
        Understand the content and provide
        the parsed objects in json that match the following json_schema:


           Findentensure_asciiU

        Make sure to return an instance of the JSON, not the schema itself
        userrm   rF   )rf   
ValueErrorr   jsondumpsmodel_json_schemar   )rJ   rh   messageroless       rM   handle_json_o1r     s     -7NN:r,JKWV_KEK5NOO	 
N446qu	UV W				G z!!	
 :%%+ Ls   B c                   t        dt        j                  | j                         dd       d      }|t        j
                  k(  rddi|d<   nr|t        j                  k(  r$d	| j                  | j                         d
d|d<   n;|t        j                  k(  r(|d   j                  ddd       t        |d         |d<   |d   d   d   dk7  r|d   j                  dd|d       | |fS t        |d   d   d   t              r|d   d   dxx   d| z  cc<   | |fS t        |d   d   d   t              r |d   d   d   d   dxx   d| z  cc<   | |fS t        d      )N
        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   Fr   r   rV   json_objectr   json_schema)rs   r   rV   r   rk   r   zPReturn the correct JSON response within a ```json codeblock. not the JSON_SCHEMAr   r   rm   rl   rF   

textz>Invalid message format, must be a string or a list of messages)r   r   r   r   r"   JSONJSON_SCHEMAr   MD_JSONr   r*   insertrD   strlistr   )rJ   rh   r5   r   s       rM   handle_json_modesr     s    	 
N446qu	UV W				G tyy)/(?
$%	!!	!!&//(::<)

$% 
	:%%m	
 "<Jz<R!S
:*a (H4:%% "	
  :%% 
Jz*1-i8#	>:q!),$wi0@@, :%% 
Jz*1-i8$	?:q!),Q/7T';KK7 :%%	 L
 	
r]   c                *   | j                   }|g|d<   d| j                  d|d<   t        |j                  dg             }|rt	        |j                  d      |      |d<   |j                  dg       D cg c]  }|d   dk7  s| c}|d<   | |fS c c}w )Nra   toolr   rc   rk   rl   rm   )anthropic_schemar   r(   rf   r%   )rJ   rh   tool_descriptionsrn   ro   s        rM   handle_anthropic_toolsr     s     '77,-Jw''!J}
 .jnnZ.LMO6NN8$o 

8
 >>*b1QvY(5JJz :%%	s   4BBc                    t        | |      \  } }ddi|d<   t        d      }t        |j                  d      d|dg      |d<   | |fS )NrV   rb   rc   zC
        Return only the tool call and no additional text.
        rl   r   rV   r   )r   r   r%   rf   )rJ   rh   implict_forced_tool_messages      rM    handle_anthropic_reasoning_toolsr     sn    
 "8
!SNJ "( 0J} #)	#
 3x "=	>?Jx :%%r]   c                   t        |j                  dg             }|rt        |j                  d      |      |d<   |j                  dg       D cg c]  }|d   dk7  s| c}|d<   t        dt	        j
                  | j                         dd       d      }t        |j                  d      d	|d
g      |d<   | |fS c c}w )Nrk   rl   rm   r   r   Fr   r   r   r   )r(   rf   r%   r   r   r   r   )rJ   rh   rn   ro   json_schema_messages        rM   handle_anthropic_jsonr      s     .jnnZ.LMO6NN8$o 

8
 >>*b1QvY(5JJz !	 
N446qu	UV W				 3x "5	67Jx
 :%%)s   CCc                    | j                  dg       }g }|d d D ]  }|j                  |d   |d   d        |d   d   | d<   || d<   d| v rd	| vr| j                  d      | d	<   | j                  d
d        d | fS )Nrk   rm   rF   rm   r   r   chat_history
model_namerK   r4   )r   r   )rh   rk   r   r   s       rM   handle_cohere_modesr   !  s    ~~j"-HLCR= 
"9-	

 %RL3Jy!-J~z!gZ&?(nn\:
7NN8T"r]   c                p    d|vrd|d<   d| j                   dg|d<   dd| j                   d   id|d<   | |fS )Nr2   Fry   rz   ra   rs   rc   r~   rv   s     rM   handle_fireworks_toolsr   3  sf     z!$
8 &44	
Jw ^99&AB!J} :%%r]   c                H    d|vrd|d<   d| j                         d|d<   | |fS )Nr2   Fr   rV   r   r   r   rv   s     rM   handle_fireworks_jsonr   E  sA     z!$
8  224%J ! :%%r]   c                ^   d|v rddl m}  |d      ddlm} t	        dt        j                  | j                         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<    ||      }| |fS )NrK   r   r_   dGemini `model` must be set while patching the client, not passed as a parameter to the create method   update_gemini_kwargsr   r   Fr   r   rk   rm   rl   r   rF   r   generation_configresponse_mime_typeapplication/json)
rg   r`   utilsr   r   r   r   r   r   rf   )rJ   rh   r`   r   r   s        rM   handle_gemini_jsonr   R  s     *< r
 	
 ,	 
N446qu	UV W				G *a (H4:%%a(w)OP:q!),$wi0@@,&0nn5H"&M0Q 'J"# &j1J:%%r]   c                    d|v rddl m}  |d      ddlm} | j                  g|d<   dd	| j
                  gd
i|d<    ||      }| |fS )NrK   r   r_   r   r   r   ra   function_calling_configANYr5   allowed_function_namestool_config)rg   r`   r   r   gemini_schemar   )rJ   rh   r`   r   s       rM   handle_gemini_toolsr   v  sq     *< r
 	
 ,)778Jw!'5'>'>&?$
!J} &j1J:%%r]   c                (   ddl m} |j                  dd      rt        | t              s	t
        |    } |j                  d      r|j                  d      }n"|j                  d      rt        |d         }nd }t        |d         |d<   t        | j                                |d| d	}t        ||      } |j                  di ||d
<   |j                  dd        |j                  dd        |j                  dd        |j                  dd        | |fS )Nr   typesr2   Frl   rk   contentsr   )system_instructionr   response_schemaconfigrJ   r   safety_settings )google.genair   rf   rA   r   r   r   r'   r&   r)   r   r+   GenerateContentConfig)rJ   rh   r   system_messagebase_configr   s         rM   handle_genai_structured_outputsr     s    # ~~h&z.+/V 0~~h#1	
	#5j6LM6z*7MNJz "."B"B"DE -0)K ,JD6566K9JKJxNN#T*NN:t$NN&-NN$d+:%%r]   c                   ddl m} |j                  dd      rt        | t              s	t
        |    } t        | j                               }|j                  | j                  | j                  |      }|j                  d      r|j                  d      }n"|j                  d      rt        |d         }nd }||j                  |g      g|j                  |j                  d	| j                  g
            d}t!        ||      } |j"                  di ||d<   t%        |d         |d<   |j                  dd        |j                  dd        |j                  dd        |j                  dd        | |fS )Nr   r   r2   F)rs   r   r   rl   rk   )function_declarationsr   r   )r   )r   ra   r   r   r   rJ   r   r   r   )r   r   rf   rA   r   r   r)   r   FunctionDeclarationr   __doc__r   r'   Tool
ToolConfigFunctionCallingConfigr+   r   r&   )rJ   rh   r   r   function_definitionr   r   r   s           rM   handle_genai_toolsr     s~    # ~~h&z.+/V 0*>+K+K+MNF33$$"** 4  ~~h#1	
	#5j6LM -**4G3H*IJ''$)$?$?N4K4K3L %@ % ( 
K ,JD6566K9JKJx6z*7MNJzNN#T*NN:t$NN&-NN$d+:%%r]   c                    |j                  dd      rddlm}  |d      ddlm} t        t        |             } |||      \  }}}||d<   ||d<   ||d	<   t        | 
      |fS )Nr2   Fr   r_   zDstream=True is not supported when using VERTEXAI_PARALLEL_TOOLS modevertexai_process_responser   ra   r   rd   )rf   rg   r`   instructor.client_vertexair   r   r   r   )rJ   rh   r`   r   model_typesr   ra   r   s           rM   handle_vertexai_parallel_toolsr     s}     ~~h&< R
 	
 E ~67K#<Z#U He[%JzJw +J} .9:EEr]   c                N    ddl m}  |||       \  }}}||d<   ||d<   ||d<   | |fS )Nr   r   r   ra   r   )r   r   )rJ   rh   r   r   ra   r   s         rM   handle_vertexai_toolsr     sD     E#<Z#X He[%JzJw +J}:%%r]   c                B    ddl m}  |||       \  }}||d<   ||d<   | |fS )Nr   )vertexai_process_json_responser   r   )r   r   )rJ   rh   r   r   r   s        rM   handle_vertexai_jsonr     s?     J"@N#H &Jz&7J"#:%%r]   c                   d| v rit        | d   t              rV| j                  d      }|rCt        |d   t              r0d|d   v r)|d   d   }d| vrg | d<   | d   j	                  dd|d       d| v rd| vr| j                  d      | d<   i }d| v r| j                  d      |d<   d	| v r| j                  d	      |d
<   nd
| v r| j                  d
      |d
<   d| v r| j                  d      |d<   nd| v r| j                  d      |d<   d| v r>| j                  d      }t        |t
              r|g|d<   nGt        |t              r7||d<   n1d| v r| j                  d      |d<   nd| v r| j                  d      |d<   |r1d| v r(| d   }|j                         D ]  \  }}||vs|||<    n|| d<   d| v r>t        | d   t              r*| j                  d      }g }	g }
|D ]  }t        |t              s|
j                  |       &|j                         }|j                  d      }|j                  d      }|dk(  r<t        |t
              r|	j                  d|i       t        dt        |       d      d|v rVt        |t
              r	d|ig|d<   n=t        |t              r"|r t        |d   t              rd|d   v r||d<   nt        d      |
j                  |        |	r|	| d<   |
| d<   | S )zMinimal processing to support `converse` parameters for the Bedrock client

    See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse.html
    rl   r   r   rk   r   rK   modelIdtemperaturer   	maxTokenstop_ptopPstopstopSequencesstop_sequencesinferenceConfigrm   rF   z\System message content must be a string for Bedrock processing by this handler. Found type: .zENon-text prompts are not currently supported in the Bedrock provider.)rD   r   r   rW   r   r   itemsr   copyrf   r   rV   NotImplementedError)call_kwargssystem_contentsystem_textinference_config_paramsstop_valexisting_inference_configkeyvalueoriginal_input_messagesbedrock_system_list$bedrock_user_assistant_messages_listmsg_dictcurrent_message_for_apirm   rF   s                  rM   )_prepare_bedrock_converse_kwargs_internalr    s    ;:k(.CT#J$2>!,d3.++ )+F3K,*,J'
#**H=
 +);">!,!9I ! #1<1O. {"/:|/L,		#/:{/K, +*5//'*B'	;	*5//&*A' ??6*h$8@z#O4$'7?#O4	[	(3>??CS3T0;&3>???3S0
 + )44E(F%5;;= ;
U775:-c2; .EK)* [ ZJ0G%N"-//*"=46EG,/ +	UHh-
 5;;HE '/mmo#*..v6D-11G xgs+'../@A$''+G}oQ8 
  77!'3/?Ew>O=P/	:"7D1#&wqz48"gaj0 >E/	: 2c  5;;<STW+	UZ $7K!
 #GJr]   c                ,   t        |      }t        dt        j                  | j	                         dd       d      }|j                  dd       }|sd|ig|d<   | |fS t        |t              st        d      |j                  d|i       ||d<   | |fS )	Nr   r   Fr   z

        Make sure to return an instance of the JSON, not the schema itself
        and don't include any other text in the response apart from the json
        rl   r   zsystem must be a list of SystemMessage, refer to:
                https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-runtime/client/converse.html
                )
r  r   r   r   r   r   rD   r   r   r   )rJ   rh   json_messager   s       rM   handle_bedrock_jsonr    s     ;:FJ	 
N446qu	UV W			
L  ^^Hd3N!' 67
8 :%% .$/ 
 	v|45-
8:%%r]   c                     t        |      }| |fS N)r  rv   s     rM   handle_bedrock_toolsr"    s     ;:FJ:%%r]   c                R    d| j                         d|d<   t        |      \  }}| |fS )Nr   r   r   )r   r   )rJ   rh   _s      rM   handle_cohere_json_schemar%    s;      224%J ! (
3MAz:%%r]   c                    |j                  dd      rt        d      d| j                  dg|d<   dd| j                  d   id|d<   | |fS )	Nr2   Fz1Stream is not supported for Cerebras Tool Callingry   rz   ra   rs   rc   )rf   r   r!   rv   s     rM   handle_cerebras_toolsr'    sn     ~~h&LMM &44	
Jw ^99&AB!J} :%%r]   c                j    d| j                          d| j                   d}d|dg|d   z   |d<   | |fS )Nz
You are a helpful assistant that excels at following instructions.Your task is to understand the content and provide the parsed objects in json that match the following json_schema:


Here is the relevant JSON schema to adhere to

<schema>
zK
</schema>

Your response should consist only of a valid JSON object that `0.model_validate_json()` can successfully parse.
rl   r   rk   r   r   )rJ   rh   instructions      rM   handle_cerebras_jsonr,    sl     !!# $ %@ AO@W@W?X Y
K (0KHIJM Jz :%%r]   c           	         t        |      \  }}d| j                   d| j                          d| j                   d| j                   d	}d|dg|d   z   |d<   | |fS )	NzExtract a valid z= object based on the chat history and the json schema below.
z=
The JSON schema was obtained by running:
```python
schema = zG.model_json_schema()
```

The output must be a valid JSON object that `r)  r   r   r   )r   r   r   )rJ   rh   r$  r+  s       rM   handle_cohere_toolsr.    s     (
3MAz(() *!!# $ %
 
!
!	" #. /=.E.E-F G	K K0">""#J~ :%%r]   c                :    d| j                   dg|d<   d|d<   | |fS )Nry   rz   ra   rb   rc   r~   rv   s     rM   handle_writer_toolsr0    s8    
 &44	
Jw !'J}:%%r]   c                :    dd| j                         id|d<   | |fS Nr   r   r   r   r   rv   s     rM   handle_writer_jsonr3    2      ."B"B"DE%J !
 :%%r]   c                :    dd| j                         id|d<   | |fS r2  r   rv   s     rM   handle_perplexity_jsonr6  %  r4  r]   c                b    t        | t              xr t        | t              xr t	        | d      S rS   rU   rY   s    rM   r[   r[   0  r\   r]   c                h   | yt        |       r	t        |    } t        |       rDt        | j                  fi | j
                  j                         D ci c]
  \  }}||df c}}} t        |       t        u rt        |       d   }t        |      } t        | t              st        |       } | S c c}}w )a  
    Prepares the response model for use in the API call.

    This function performs several transformations on the input response_model:
    1. If the response_model is None, it returns None.
    2. If it's a simple type, it wraps it in a ModelAdapter.
    3. If it's a TypedDict, it converts it to a Pydantic BaseModel.
    4. If it's an Iterable, it wraps the element type in an IterableModel.
    5. If it's not already a subclass of OpenAISchema, it applies the openai_schema decorator.

    Args:
        response_model (type[T] | None): The input response model to be prepared.

    Returns:
        type[T] | None: The prepared response model, or None if the input was None.
    N.r   )r   r   r[   r   r   rT   r  r	   r   r   r   rA   r    r!   )rJ   kviterable_element_classs       rM   prepare_response_modelr<  8  s    " n%%n5^$$0##%
'5'E'E'K'K'MNtq!q1c({N%

 .!X-!).!9!!<&'=>nl3&~6 Os   B.c                `    | j                         }d|d<   d| j                  |ddd|d<   | |fS )NFadditionalPropertiesr   T)rs   r   r4   r   r   r*  )rJ   rh   r   s      rM   $handle_openrouter_structured_outputsr?  _  sN     --/F%*F!""++
%J ! :%%r]   c                
   |j                         }|j                  dd      }| q|t        j                  t        j                  hv rt        |      S d|v r;t        |d   ||      }|t        j                  t        j                  hv r6|D cg c]  }|d   dk7  s| c}|d<   d|vrt        |      }|r||d<   d|fS |t        j                  t        j                  hv rddd	lm}m}	  ||      |d
<   t        |d
   |      |d
<   d|vr% |	|      }|rddlm}
 |
j%                  |      |d<   |j                  dd       d|fS |t        j&                  t        j(                  hv r%|j+                  d      r|j                  d      |d<   ||d<   d|fS |t        j,                  hv rt/        | |      S |t        j0                  hv rt3        | |      S |t        j4                  hv rt7        | |      S t9        |       } i t        j:                  t<        t        j>                  t@        t        jB                  tD        t        jF                  tH        t        jJ                  tL        t        jN                  tP        t        jR                  d t        jT                  d t        jV                  d t        j                  tX        t        jZ                  t\        t        j                  t^        t        j                  t`        t        j                  tb        t        jd                  tf        t        jh                  tj        t        j                  tl        t        j                  tn        t        jp                  tr        t        jt                  tv        t        jx                  tz        t        j|                  t~        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j                  t        t        j&                  t        t        j(                  t        i}||v r ||   | |      \  } }nt        d|       d|v rt        |d   ||      |d<   |t        j                  t        j                  hv rt        |d
   |      |d
<   t        j                  d|j                  d| d||j                  | t        | d      r| j                  n
t        |       |d       | |fS c c}w )a   
    Handles the response model based on the specified mode and prepares the kwargs for the API call.

    Args:
        response_model (type[T] | None): The response model to be used for parsing the API response.
        mode (Mode): The mode to use for handling the response model. Defaults to Mode.TOOLS.
        **kwargs: Additional keyword arguments to be passed to the API call.

    Returns:
        tuple[type[T] | None, dict[str, Any]]: A tuple containing the processed response model and the updated kwargs.

    This function prepares the response model and modifies the kwargs based on the specified mode.
    It handles various modes like TOOLS, JSON, FUNCTIONS, etc., and applies the appropriate
    transformations to the response model and kwargs.
    autodetect_imagesFNrk   )rA  rm   rl   r   )r&   r'   r   r   )r   r   r   r   c                8    t        | |t        j                        S r!  )r   r"   r   rmnks     rM   <lambda>z'handle_response_model.<locals>.<lambda>  s    "3BDII"F r]   c                8    t        | |t        j                        S r!  )r   r"   r   rC  s     rM   rF  z'handle_response_model.<locals>.<lambda>  s    %6r2t||%L r]   c                8    t        | |t        j                        S r!  )r   r"   r   rC  s     rM   rF  z'handle_response_model.<locals>.<lambda>  s    ):2r4CSCS)T r]   zInvalid patch mode: zInstructor Request: mode.value=z, response_model=z, new_kwargs=r   )r5   rJ   rh   )extra)Yr  r   r"   COHERE_JSON_SCHEMACOHERE_TOOLSr   r#   ANTHROPIC_JSONANTHROPIC_TOOLSr(   GENAI_TOOLSGENAI_STRUCTURED_OUTPUTSinstructor.utilsr&   r'   r$   r   r   r   RESPONSES_TOOLS"RESPONSES_TOOLS_WITH_INBUILT_TOOLSrf   PARALLEL_TOOLSri   VERTEXAI_PARALLEL_TOOLSr   ANTHROPIC_PARALLEL_TOOLSrp   r<  	FUNCTIONSrw   TOOLS_STRICTr|   TOOLSr   MISTRAL_TOOLSr   MISTRAL_STRUCTURED_OUTPUTSr   JSON_O1r   r   r   r   r   ANTHROPIC_REASONING_TOOLSr   r   r%  r.  GEMINI_JSONr   GEMINI_TOOLSr   r   r   VERTEXAI_TOOLSr   VERTEXAI_JSONr   CEREBRAS_JSONr,  CEREBRAS_TOOLSr'  FIREWORKS_JSONr   FIREWORKS_TOOLSr   WRITER_TOOLSr0  WRITER_JSONr3  BEDROCK_JSONr  BEDROCK_TOOLSr"  PERPLEXITY_JSONr6  OPENROUTER_STRUCTURED_OUTPUTSr?  r   r   r   r=   r>   r  rX   r   r   )rJ   r5   kwargsrh   rA  rk   ro   r   r&   r'   r   mode_handlerss               rM   handle_response_modelrm  o  s0   & J"':EBD++T->->??&z22#':&"3H
 ++T-A-ABB5=)W6hAV!)W
:&:-%<X%FN%/=
8,L ZI $**D,I,IJJ *C8)L
:& *Jz*,=*
:&
 :-%A(%KN%6/4/J/J/= 0K 0
8,
 z40 Z ((;;  !nn\26@nn\6RJ23)1
:&Z##$$$^Z@@	$../	/-njII	$//0	0.~zJJ+N;N!(!.! 	

L! 	0	!
 	'')J! 	n! 			F! 	L! 	T! 	4! 	&&(H! 	2! 	!:! 	.! 	,!  	.!!" 	,#!$ 	%%'F200224.,.04**,P4//1ZA!MF }%8]4%8%T"
/v677Z!1z"/"

:   $"?"?@@!Az"$5"

: LL
*tzzm+=n->nNJJ "-'.*2U ''($
   :%%k *Xs   UU)rI   r   rJ   z/type[T_Model | OpenAISchema | BaseModel] | Noner2   boolr3   dict[str, Any] | Noner4   zbool | Noner5   r"   returnzT_Model | ChatCompletion)rI   r-   rJ   z%type[OpenAISchema | BaseModel] | Noner2   rn  r3   ro  r5   r"   rp  z5T_Model | list[T_Model] | VertexAIParallelBase | None)rp  rn  )rJ   type[T]rh   dict[str, Any]rp  tuple[type[T], dict[str, Any]])rJ   type[Iterable[T]]rh   rr  rp  z,tuple[AnthropicParallelBase, dict[str, Any]])rJ   rq  rh   rr  r5   r"   rp  rs  )rh   rr  rp  ztuple[None, dict[str, Any]])rJ   rt  rh   rr  rp  z+tuple[VertexAIParallelBase, dict[str, Any]])r  rr  rp  rr  )rJ   type[T] | Nonerp  ru  )rJ   ru  r5   r"   rk  r   rp  z<tuple[type[T] | VertexAIParallelBase | None, dict[str, Any]])j
__future__r   r?   r   loggingcollections.abcr   textwrapr   typingr   r   r   r	   openair   openai.types.chatr   pydanticr   r   typing_extensionsr   instructor.dsl.iterabler   r   instructor.dsl.parallelr   r   r   r   r   r   r   r   r   instructor.dsl.partialr   r   instructor.dsl.simple_typer   r   r   instructor.function_callsr    r!   instructor.moder"   instructor.multimodalr#   r$   rP  r%   r&   r'   r(   r)   r*   r+   	getLoggerr=   r-   r/   r0   r1   rX  rN   rQ   r[   ri   rp   rw   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r"  r%  r'  r,  r.  r0  r3  r6  r<  r?  rm  r   r]   rM   <module>r     s   "    $  5 5 ) , , ' ?
 
 
 8 
 B   T   
		<	(
)9
-:&CL 04BB DB 	B
 .B B B BP =A04II :I 	I
 .I I ;IX>>)7>#>G%G3AG1G6&&)7&#&
&
&)7
&#
&&&)7&#& #&#&)7#&##&L & &)7 &# &F
&
&)7
&#
&&&)7&#&&&)7&#&62&2&)72&?C2&#2&j&&)7&#&0&&)7&#&0&&)7&#&B$&&)7&#&$
&
&)7
&#
&!&!&)7!&#!&H&&)7&#&0#&#&)7#&##&L,&,&)7,&#,&^F%F3AF0F,
&
&)7
&#
&&&)7&#&HHHV&&)7&#&>&&)7&#&	&	&)7	&#	&&&)7&#&$&&)7&#&*&&)7&#&*
&
&)7
&#
&&&)7&#&&&)7&#&$N&&)7&#&" 26Y&"Y&*.Y&GJY&AY&r]   