
    6iM                       d Z ddlmZ ddl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 dd
lmZ ddlmZmZ ddlmZ d!dZd"dZd#dZ	 d$	 	 	 	 	 	 	 d%dZ	 d$	 	 	 	 	 	 	 d%dZ	 d$	 	 	 	 	 	 	 d%dZ	 d$	 	 	 	 	 	 	 d%dZ	 	 	 	 	 	 d&dZ	 	 	 	 	 	 d'dZ	 	 	 	 	 	 d'dZ 	 	 	 	 	 	 d'dZ!	 	 	 	 	 	 d'dZ"	 	 	 	 	 	 d'dZ#	 	 	 	 	 	 d'dZ$	 	 	 	 	 	 	 	 d(dZ%	 	 	 	 	 	 d&dZ&ejN                  ee!dejP                  ee dejR                  eedejT                  ed dejV                  ed dejX                  ed  dejZ                  ee$dej\                  eedej^                  ee"dej`                  ee#dejb                  ee&diZ2y))zOpenAI-specific utilities.

This module contains utilities specific to the OpenAI provider,
including reask functions, response handlers, and message formatting.
    )annotationsN)dedent)Anycastpydantic_function_tool   )ParallelModelhandle_parallel_model)ConfigurationError)Mode)dump_messagemerge_consecutive_messagesgenerate_openai_schemac                (    | du xs t        | d       S )zCheck if response is a Stream object rather than a ChatCompletion.

    Stream objects don't have 'choices' attribute and can't be used
    for detailed reask messages that reference the response content.
    Nchoices)hasattr)responses    l/root/.openclaw/workspace/visionaryfx/venv/lib/python3.12/site-packages/instructor/providers/openai/utils.py_is_stream_responser      s     t?78Y#???    c                    g }| D ]F  }t        |dd      }|dv r|j                  |       &|)t        |d      s6|j                  |       H |S )z7Return response output items that represent tool calls.typeN>   	tool_callfunction_call	arguments)getattrappendr   )output_items
tool_callsitem	item_types       r   _filter_responses_tool_callsr$      sc    J $D&$/	66d#{!;d#$ r   c                    t        | dd      }t        | dd      xs t        | dd      xs t        | dd      }g }|r|j                  d|        |r|j                  d|        |syd	d
j                  |       dS )z4Format tool call name/id details for reask messages.nameNidcall_idtool_call_idzname=zid= z (tool call z, ))r   r   join)r   	tool_nametool_iddetailss       r   #_format_responses_tool_call_detailsr0   ,   s    	640I	4& 	49i.	49nd3 
 Gyk*+WI'$))G,-Q//r   c           	        | j                         } t        |      r| d   j                  dd| dd       | S t        |j                  d   j
                        g}|j                  d   j
                  j                  D ]:  }|j                  d|j                  |j                  j                  d| dd       < | d   j                  |       | S )	z
    Handle reask for OpenAI tools mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (tool response messages indicating validation errors)
    messagesuserValidation Error found:
.
Recall the function correctly, fix the errorsrolecontentr   tool)r7   r)   r&   r8   )copyr   r   r   r   messager!   r'   functionr&   extend)kwargsr   	exceptionfailed_attempts
reask_msgsr   s         r   reask_toolsrB   >   s     [[]F 8$z!!/	{ ;D D	
 x//2::;<J%%a(00;; 

	 )!**///	{:ij		


 :j)Mr   c           	     >   | j                         } |t        |d      s| d   j                  dd| dd       | S g }t        |j                        D ]3  }t        |      }|j                  dd| d|j                   | d       5 | d   j                  |       | S )z
    Handle reask for OpenAI responses tools mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (user messages with validation errors)
    outputr2   r3   r4   r5   r6   z4
Recall the function correctly, fix the errors with )r:   r   r   r$   rD   r0   r   r=   )r>   r   r?   r@   reask_messagesr   r/   s          r   reask_responses_toolsrF   j   s     [[]F wx:z!!/	{ ;D D	
 N1(//B 
	5i@/	{ ;J **+G96		

 :n-Mr   c                   | j                         } t        |      r| d   j                  dd| d       | S t        |j                  d   j
                        g}|j                  dd| d       | d   j                  |       | S )z
    Handle reask for OpenAI JSON modes when validation fails.

    Kwargs modifications:
    - Adds: "messages" (user message requesting JSON correction)
    r2   r3   z@Correct your JSON ONLY RESPONSE, based on the following errors:
r6   r   r:   r   r   r   r   r;   r=   r>   r   r?   r@   rA   s        r   reask_md_jsonrJ      s     [[]F 8$z!!^_h^ij	
 x//2::;<JZ[dZef	
 :j)Mr   c                   | j                         } t        |      r| d   j                  dd| d       | S t        |j                  d   j
                        g}|j                  dd| d       | d   j                  |       | S )z
    Handle reask for OpenAI default mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (user message requesting function correction)
    r2   r3   z@Recall the function correctly, fix the errors, exceptions found
r6   r   rH   rI   s        r   reask_defaultrL      s     [[]F 8$z!!WXaWbc	
 x//2::;<JST]S^_	
 :j)Mr   c                    |j                  dd      rt        d      t        |       |d<   d|d<   t        t        t
           t        |             |fS )a  
    Handle OpenAI parallel tools mode for concurrent function calls.

    This mode enables making multiple independent function calls in a single request,
    useful for batch processing or when you need to extract multiple structured outputs
    simultaneously. The response_model should be a list/iterable type or use the
    ParallelModel wrapper.

    Example usage:
        # Define models for parallel extraction
        class PersonInfo(BaseModel):
            name: str
            age: int

        class EventInfo(BaseModel):
            date: str
            location: str

        # Use with PARALLEL_TOOLS mode
        result = client.chat.completions.create(
            model="gpt-4",
            response_model=[PersonInfo, EventInfo],
            mode=instructor.Mode.PARALLEL_TOOLS,
            messages=[{"role": "user", "content": "Extract person and event info..."}]
        )

    Kwargs modifications:
    - Adds: "tools" (multiple function schemas from parallel model)
    - Adds: "tool_choice" ("auto" to allow model to choose which tools to call)
    - Validates: stream=False (streaming not supported in parallel mode)
    streamFz;stream=True is not supported when using PARALLEL_TOOLS modetoolsautotool_choice)typehint)getr   r   r   r   r   r
   response_model
new_kwargss     r   handle_parallel_toolsrW      sY    D ~~h& I
 	
 0?Jw &J}S	=.ABJNNr   c                    t        j                          | d|fS t        |       g|d<   dt        |       d   i|d<   | |fS )a  
    Handle OpenAI functions mode (deprecated).

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Adds: "functions" (list with function schema)
      - Adds: "function_call" (forced function call)
    N	functionsr&   r   )r   warn_mode_functions_deprecationr   rT   s     r   handle_functionsr[     s\     	((*Z5nEFJ{&~6v>#J :%%r   c                h    | d|fS t        |       }d|d   d<   |g|d<   dd|d   d   id|d<   | |fS )	a  
    Handle OpenAI strict tools mode.

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Adds: "tools" (list with strict function schema)
      - Adds: "tool_choice" (forced function call)
    NTr<   strictrO   r&   r   r<   rQ   r   )rU   rV   response_model_schemas      r   handle_tools_strictr`   '  sl     Z2>B26*%h/01Jw2:>vFG!J} :%%r   c                f    | d|fS dt        |       dg|d<   ddt        |       d   id|d<   | |fS )z
    Handle OpenAI tools mode.

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Adds: "tools" (list with function schema)
      - Adds: "tool_choice" (forced function call)
    Nr<   r^   rO   r&   rQ   r   rT   s     r   handle_toolsrb   @  sd     Z .~>	
Jw 3NCFKL!J} :%%r   c                F   |j                  d      |j                  d      |d<   | d|fS 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t	        |       d   d|d<   | |fS )aF  
    Handle OpenAI responses tools mode.

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Adds: "tools" (list with function schema)
      - Adds: "tool_choice" (forced function call)
      - Adds: "max_output_tokens" (converted from max_tokens)
    
max_tokensNmax_output_tokensr<   r]   r&   
parametersr   r&   rf   descriptionCorrectly extracted `5` with all the required parameters with correct typesrO   r   r&   rQ   )rS   popr   __name__r   rU   rV   schematool_definitions       r   handle_responses_toolsrq   \  s    ~~l#/*4..*F
&' Z#N3Fz8$ z"6*Z(6O z**)/
);M)J& $N$;$;#< =9 : 	& :&v. ,\:	
Jw &~6v>!J}
 :%%r   c                x   |j                  d      |j                  d      |d<   | d|fS 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t	        |       d   d|d<   | |fS |d   j                  |       | |fS )aY  
    Handle OpenAI responses tools with inbuilt tools mode.

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Adds: "tools" (list with function schema)
      - Adds: "tool_choice" (forced function call)
      - Adds: "max_output_tokens" (converted from max_tokens)
    rd   Nre   r<   r]   r&   rf   rg   rh   ri   rj   rO   rk   rQ   )rS   rl   r   rm   r   r   rn   s       r   )handle_responses_tools_with_inbuilt_toolsrs     s"    ~~l#/*4..*F
&' Z#N3Fz8$ z"6*Z(6O z**)/
);M)J& $N$;$;#< =9 : 	&
 >>'"./
7*>:6B%

=! :%% 	7""?3:%%r   c                   |j                  dg       D cg c]  }|d   	 }}d|v rt        d      | d|fS t        dt        j                  | j                         dd	       d
      }|d   j                  d|d       | |fS c c}w )a  
    Handle OpenAI o1 JSON mode.

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Modifies: "messages" (appends user message with JSON schema)
      - Validates: No system messages allowed for O1 models
    r2   r7   systemz3System messages are not supported For the O1 modelsNz
        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
        r3   r6   )rS   
ValueErrorr   jsondumpsmodel_json_schemar   )rU   rV   r;   roless       r   handle_json_o1r     s     -7NN:r,JKWV_KEK5NOOZ	 
N446qu	UV W				G z!!	
 :%%1 Ls   Bc                   | d|fS 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<   |t        j                  k7  r|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      | |fS )a  
    Handle OpenAI JSON modes (JSON, MD_JSON, JSON_SCHEMA).

    Kwargs modifications:
    - When response_model is None: No modifications
    - When response_model is provided:
      - Mode.JSON_SCHEMA: Adds "response_format" with json_schema
      - Mode.JSON: Adds "response_format" with type="json_object", modifies system message
      - Mode.MD_JSON: Appends user message for markdown JSON response
    Nz
        As a genius expert, your task is to understand the content and provide
        the parsed objects in json that match the following json_schema:


        rv   Frw   rz   r   json_objectresponse_formatjson_schema)r&   ro   r   r   r2   r3   zPReturn the correct JSON response within a ```json codeblock. not the JSON_SCHEMAr6   r   r7   ru   r8   z

textz>Invalid message format, must be a string or a list of messages)r   r|   r}   r~   r   JSONJSON_SCHEMArm   MD_JSONr   r   insert
isinstancestrlistr{   )rU   rV   moder;   s       r   handle_json_modesr     s    Z	 
N446qu	UV W				G tyy)/(?
$%	!!	!!&//(::<)

$% 
	:%%m	
 "<Jz<R!S
:tj!!$V,8z"))$&  :%% 
:.q1)<cBz"1%i0d7)4DD0 :%% 
:.q1)<dCz"1%i03F;gY?OO; :%%	 P  :%%r   c                `    | j                         }d|d<   d| j                  |ddd|d<   | |fS )z
    Handle OpenRouter structured outputs mode.

    Kwargs modifications:
    - Adds: "response_format" (json_schema with strict mode enabled)
    FadditionalPropertiesr   T)r&   ro   r]   r   r   )r~   rm   )rU   rV   ro   s      r   $handle_openrouter_structured_outputsr   .  sN     --/F%*F!""++
%J ! :%%r   )reaskr   c                8    t        | |t        j                        S N)r   r   r   rmnks     r   <lambda>r   T  s    #4RTYY#G r   c                8    t        | |t        j                        S r   )r   r   r   r   s     r   r   r   X  s    #4RT\\#J r   c                8    t        | |t        j                        S r   )r   r   r   r   s     r   r   r   \  s    #4RT=M=M#N r   )r   r   returnbool)r    	list[Any]r   r   )r   r   r   r   r   )r>   dict[str, Any]r   r   r?   	Exceptionr@   zlist[Any] | None)rU   z	type[Any]rV   r   r   z tuple[type[Any], dict[str, Any]])rU   type[Any] | NonerV   r   r   'tuple[type[Any] | None, dict[str, Any]])rU   r   rV   r   r   r   r   r   )3__doc__
__future__r   r|   textwrapr   typingr   r   openair   dsl.parallelr
   r   core.exceptionsr   r   r   
utils.corer   r   processing.schemar   r   r$   r0   rB   rF   rJ   rL   rW   r[   r`   rb   rq   rs   r   r   r   TOOLSTOOLS_STRICT	FUNCTIONSr   r   r   JSON_O1PARALLEL_TOOLSRESPONSES_TOOLS"RESPONSES_TOOLS_WITH_INBUILT_TOOLSOPENROUTER_STRUCTURED_OUTPUTSOPENAI_HANDLERS r   r   <module>r      s   #    ) @ 1  B 7@
0, )-	))) ) &	)` )-	*** * &	*b )-	!!! ! &	!P )-	%%% % &	%R(O(O+9(O%(OV&$&2@&,&0&$&2@&,&2&$&2@&,&83&$3&2@3&,3&l/&$/&2@/&,/&d$&$$&2@$&,$&N@&$@&2@@&HL@&,@&F&&+9&%&0 	JJ  	' 	NN$ 	IIG 	LLJ 	N 	LL" 	) 	&* 	++&=. 	&&8)S-r   