
    6i{@              
      ~   d 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
 ddlmZ  G d d	e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
j.                  eede
j0                  eede
j2                  eede
j4                  eediZy)zAnthropic-specific utilities.

This module contains utilities specific to the Anthropic provider,
including reask functions, response handlers, and message formatting.
    )annotations)dedent)Any	TypedDictUnion   )Mode)generate_anthropic_schemac                  ,    e Zd ZU ded<   ded<   ded<   y)SystemMessagestrtypetextzdict[str, str]cache_controlN)__name__
__module____qualname____annotations__     o/root/.openclaw/workspace/visionaryfx/venv/lib/python3.12/site-packages/instructor/providers/anthropic/utils.pyr   r      s    
I
I!!r   r   F)totalc                   | |S t        | t        t        f      rt        |t        t        f      s#t        dt	        |        dt	        |             t        | t              rt        |t              r|  d| S t        | t              r.t        |t              rt        |       }|j                  |       |S t        | t              r1t        |t              r!t        d|       g}|j                  |       |S t        | t              r;t        |t              r+t        d|      }t        |       }|j                  |       |S | S )a)  
    Combine existing and new system messages.

    This optimized version uses a more direct approach with fewer branches.

    Args:
        existing_system: Existing system message(s) or None
        new_system: New system message(s) to add

    Returns:
        Combined system message(s)
    z.System messages must be strings or lists, got z and z

r   r   r   )
isinstancer   list
ValueErrorr   extendr   append)existing_system
new_systemresultnew_messages       r   combine_system_messagesr$      s0   "  oT{3:S$K< <T/=R<SSXY]^hYiXjk
 	

 /3'Jz3,G ""$zl33	OT	*z*d/K o&j!	OS	)jT.J  V/BCj!	OT	*z*c/J $jAo&k" r   c                >   | sg S t        d | D              }|dk(  rg S dd}g }| D ]t  }|j                  d      dk(  s|j                  d      }|s,t        |t              r"|D ]  }|s|j	                   ||              ^|j	                   ||             v |S )a  
    Extract system messages from a list of messages.

    This optimized version pre-allocates the result list and
    reduces function call overhead.

    Args:
        messages: List of messages to extract system messages from

    Returns:
        List of system messages
    c              3  J   K   | ]  }|j                  d       dk(  sd  yw)rolesystem   N)get).0ms     r   	<genexpr>z*extract_system_messages.<locals>.<genexpr>b   s     HQaeeFmx.GqHs   ##r   contentc                    t        | t              rt        d|       S t        | t              rt        di | S t	        dt        |              )Nr   r   zUnsupported content type: r   )r   r   r   dictr   r   )r.   s    r   convert_messagez0extract_system_messages.<locals>.convert_messagei   sH    gs# f7;;& +7++9$w-IJJr   r'   r(   )r.   r   returnr   )sumr*   r   r   r   )messagessystem_countr1   r"   messager.   items          r   extract_system_messagesr8   P   s     	 H(HHL q	K #%F 8;;v(*kk),G  '4(# =Dod&;<=
 og67!8$ Mr   c                   | j                         } ddlm} t        ||      s| d   j	                  dd| dd       | S g }d}|j
                  D ]=  }|j	                  |j                                |j                  d	k(  s2|j                  }? d
|dg}||j	                  dd|d| dddgd       n|j	                  dd| dd       | d   j                  |       | S )z
    Handle reask for Anthropic tools mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (tool result messages indicating validation errors)
    r   Messager4   userzValidation Error found:
.
Recall the function correctly, fix the errorsr'   r.   Ntool_use	assistanttool_resultT)r   tool_use_idr.   is_errorz,Validation Error due to no tool invocation:
)
copyanthropic.typesr;   r   r   r.   
model_dumpr   idr   )kwargsresponse	exceptionr;   assistant_contentrB   r.   
reask_msgss           r   reask_anthropic_toolsrM      s3    [[]F' h(z!!/	{ ;D D	
 K## %  !3!3!56<<:%!**K%
 '3DEFJ !.'2%>ykIx#y$(	
	
 	J9+  VE  F	
 :j)Mr   c                F   | j                         } ddlm} t        ||      s| d   j	                  dd| dd       | S |j
                  D cg c]  }|j                  dk(  s| }}|sd	}n|d
   j                  }dd| d| d}| d   j	                  |       | S c c}w )z
    Handle reask for Anthropic JSON mode when validation fails.

    Kwargs modifications:
    - Adds: "messages" (user message requesting JSON correction)
    r   r:   r4   r<   zValidation Errors found:
r=   r>   r   z!No text content found in responsezO
Recall the function correctly, fix the errors found in the following attempt:
)rD   rE   r;   r   r   r.   r   r   )rH   rI   rJ   r;   ctext_blockstext_content	reask_msgs           r   reask_anthropic_jsonrT      s     [[]F' h(z!!0 <D D	
  '..C!&&F2B1CKC: #2++ 1)  =N  O[  N\  _I :i(M Ds   B#Bc                    | j                  dg       }|D cg c]  }|d   dk7  s| c}| d<   d| vrt        |      }|r|| d<   | S c c}w )z
    Handle message conversion for Anthropic modes when response_model is None.

    Kwargs modifications:
    - Modifies: "messages" (removes system messages)
    - Adds/Modifies: "system" (if system messages found in messages)
    r4   r'   r(   )r*   r8   )
new_kwargsr4   r,   system_messagess       r   #handle_anthropic_message_conversionrX      sa     ~~j"-H *2KAQvY(5JaKJzz!1(;#2Jx  Ls
   AAc                J   | t        |      }d|fS t        |       }|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 )	a  
    Handle Anthropic tools mode.

    When response_model is None:
        - Extracts system messages from the messages list and moves them to the 'system' parameter
        - Filters out system messages from the messages list
        - No tools are configured
        - Allows for unstructured responses from Claude

    When response_model is provided:
        - Generates Anthropic tool schema from the response model
        - Sets up forced tool use with the specific tool name
        - Extracts and combines system messages
        - Filters system messages from the messages list

    Kwargs modifications:
    - Modifies: "messages" (removes system messages)
    - Adds/Modifies: "system" (combines existing with extracted system messages)
    - Adds: "tools" (list with tool schema) - only when response_model provided
    - Adds: "tool_choice" (forced tool use) - only when response_model provided
    Ntoolstool)r   nametool_choicer4   r(   r'   )rX   r
   r   r8   r*   r$   )response_modelrV   tool_descriptionsrW   r,   s        r   handle_anthropic_toolsr`     s    0 8D
Z1.A,-Jw''!J}
 .jnnZ.LMO6NN8$o 

8
 >>*b1QvY(5JJz :%%	s   B B c                    t        | |      \  } }| d|fS ddi|d<   t        d      }t        |j                  d      d|dg      |d<   | |fS )	av  
    Handle Anthropic reasoning tools mode.

    This mode is similar to regular tools mode but with reasoning enabled:
    - Uses "auto" tool choice instead of forced tool use
    - Adds a system message encouraging tool use only when relevant
    - Allows Claude to reason about whether to use tools

    When response_model is None:
        - Performs the same message conversion as handle_anthropic_tools
        - No tools are configured

    When response_model is provided:
        - Sets up tools as in regular tools mode
        - Changes tool_choice to "auto" to allow reasoning
        - Adds system message to guide tool usage

    Kwargs modifications:
    - All modifications from handle_anthropic_tools, plus:
    - Modifies: "tool_choice" (changes to {"type": "auto"}) - only when response_model provided
    - Modifies: "system" (adds implicit forced tool message)
    Nr   autor]   zC
        Return only the tool call and no additional text.
        r(   r   r   )r`   r   r$   r*   )r^   rV   implict_forced_tool_messages      r    handle_anthropic_reasoning_toolsrd   :  s    6 "8
!SNJZ "( 0J} #)	#
 3x "=	>?Jx :%%r   c                   ddl }t        |j                  dg             }|rt        |j                  d      |      |d<   |j                  dg       D cg c]  }|d   dk7  s| c}|d<   | d|fS t	        d|j                  | j                         dd	       d
      }t        |j                  d      d|dg      |d<   | |fS c c}w )ac  
    Handle Anthropic JSON mode.

    This mode instructs Claude to return JSON responses:
    - System messages are extracted and combined
    - A JSON schema message is added to guide the response format

    When response_model is None:
        - Extracts and moves system messages to the 'system' parameter
        - Filters system messages from the messages list
        - No JSON schema is added

    When response_model is provided:
        - Performs system message handling as above
        - Adds a system message with the JSON schema
        - Instructs Claude to return an instance matching the schema

    Kwargs modifications:
    - Modifies: "messages" (removes system messages)
    - Adds/Modifies: "system" (combines existing with extracted system messages)
    - Modifies: "system" (adds JSON schema message) - only when response_model provided
    r   Nr4   r(   r'   z
        As a genius expert, your task is to understand the content and provide
        the parsed objects in json that match the following json_schema:


           F)indentensure_asciizU

        Make sure to return an instance of the JSON, not the schema itself
        r   r   )jsonr8   r*   r$   r   dumpsmodel_json_schema)r^   rV   ri   rW   r,   json_schema_messages         r   handle_anthropic_jsonrm   l  s    2 -jnnZ.LMO6NN8$o 

8
 >>*b1QvY(5JJz Z 	 
N446qu	UV W				 3x "5	67Jx
 :%%1s   C"Cc                d   ddl m}m} ddlm} |j                  dd      r |d       ||       |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<    ||       |fS c c}w )ay  
    Handle Anthropic parallel tools mode.

    Kwargs modifications:
    - Adds: "tools" (multiple function schemas from parallel model)
    - Adds: "tool_choice" ("auto" to allow model to choose which tools to call)
    - Modifies: "system" (moves system messages into system parameter)
    - Removes: "system" messages from "messages" list
    - Validates: stream=False
    r   )AnthropicParallelModelhandle_anthropic_parallel_model)ConfigurationErrorstreamFzEstream=True is not supported when using ANTHROPIC_PARALLEL_TOOLS moderZ   r   rb   r]   r4   r(   r'   )typehint)dsl.parallelro   rp   core.exceptionsrq   r*   r8   r$   )r^   rV   ro   rp   rq   rW   r,   s          r   handle_anthropic_parallel_toolsrv     s     6~~h& S
 	
 :.IJw!' 0J}-jnnZ.LMO6NN8$o 

8
 >>*b1QvY(5JJz ">:JFF	s   
B-B-)reaskrI   N)r    z%Union[str, list[SystemMessage], None]r!   Union[str, list[SystemMessage]]r2   rx   )r4   zlist[dict[str, Any]]r2   zlist[SystemMessage])rH   dict[str, Any]rI   r   rJ   	Exception)rV   ry   r2   ry   )r^   ztype[Any] | NonerV   ry   r2   z'tuple[type[Any] | None, dict[str, Any]])r^   z	type[Any]rV   ry   r2   ztuple[Any, dict[str, Any]])__doc__
__future__r   textwrapr   typingr   r   r   moder	   processing.schemar
   r   r$   r8   rM   rT   rX   r`   rd   rm   rv   ANTHROPIC_TOOLSANTHROPIC_JSONANTHROPIC_REASONING_TOOLSANTHROPIC_PARALLEL_TOOLSANTHROPIC_HANDLERSr   r   r   <module>r      su   #  ( (  :"IU "6:6/6 %6r6r::: :z*** *Z*/&$/&2@/&,/&d/&$/&2@/&,/&d:&$:&2@:&,:&z&G&G+9&G&GV 	&* 	%) 	""&4% 	!!&3$ r   