
    Áj5n                       d dl mZ d dlZd dl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mZmZ d dlmZmZ d dlmZmZ d dlZddlmZmZmZmZ dd	lm Z m!Z! dd
l"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZD erddlEmFZFmGZG  edee-e	   e/e	   e1e2f         ZH ed      ZI ej                  eK      ZL G d ded      ZM G d deeHe>f         ZN G d  d!eNe.e>f   eeIe>f   e      ZO G d" d#eOe?e>   e>f         ZP G d$ d%eOe;e>   e>f         ZQ G d& d'eNe0e>f   eeIe>f   e      ZR G d( d)eRe?e>   e>f         ZS G d* d+eRe<e>   e>f         ZTy),    )annotationsN)ABCabstractmethod)TYPE_CHECKINGAnyListUnionGenericTypeVarCallableIterableIterator	CoroutineAsyncIterator)contextmanagerasynccontextmanager)	TypedDictoverride   )BodyQueryHeadersNotGiven)consume_sync_iteratorconsume_async_iterator)BetaMessageBetaMessageParam)merge_headers   )tool_registrytool_error_contentavailable_tool_names)	ToolErrorBetaFunctionToolBetaRunnableToolBetaAsyncFunctionToolBetaAsyncRunnableToolBetaBuiltinFunctionToolBetaAsyncBuiltinFunctionTool   )helper_headerstainless_helper_header)DEFAULT_THRESHOLDDEFAULT_SUMMARY_PROMPTCompactionControl)BetaMessageStreamBetaAsyncMessageStream)ResponseFormatTParsedBetaMessageParsedBetaContentBlock)ParseMessageCreateParamsBase)BetaToolResultBlockParam)	AnthropicAsyncAnthropicAnyFunctionToolT)boundRunnerItemTc                  6    e Zd ZU ded<   ded<   ded<   ded<   y	)
RequestOptionszHeaders | Noneextra_headerszQuery | Noneextra_queryzBody | None
extra_bodyz'float | httpx.Timeout | None | NotGiventimeoutN)__name__
__module____qualname____annotations__     G/tmp/pip-target-k_scjv0h/lib/python/anthropic/lib/tools/_beta_runner.pyr=   r=   <   s    !!44rG   r=   F)totalc                  Z    e Zd Zddd	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 d	dZd
dZddZddZy)BaseToolRunnerNmax_iterationscompaction_controlc               x   t        |      | _        i |d|d   D cg c]  }| c}i| _        t        | j                  j	                         |j                  d            }|r't        ||j                  d      xs i       }i |d|i}|| _        d| _        d | _	        || _
        d| _        || _        y c c}w )Nmessages)toolsrP   r>   Fr   )r    _tools_by_name_paramsr,   valuesgetr   _options_messages_modified_cached_tool_call_response_max_iterations_iteration_count_compaction_control)	selfparamsoptionsrQ   rM   rN   messager+   merged_headerss	            rH   __init__zBaseToolRunner.__init__D   s     ,E2G
G
z0BCWCG
 0%%,,.ZZ
+
 *='++o:V:\Z\]NBB/>BG"'CG'- !#5  Ds   	B7c                L    t        |      r || j                        }|| _        y)a  
        Update the parameters for the next API call. This invalidates any cached tool responses.

        Args:
            params (ParsedMessageCreateParamsBase[ResponseFormatT] | Callable): Either new parameters or a function to mutate existing parameters
        N)callablerS   )r\   r]   s     rH   set_messages_paramsz"BaseToolRunner.set_messages_params`   s!     FDLL)FrG   c                    |D cg c]-  }t        |t              r|j                  |j                  dn|/ c}d| _        | j                  fd       d| _        yc c}w )zAdd one or more messages to the conversation history.

        This invalidates the cached tool response, i.e. if tools were already called, then they will
        be called again on the next loop iteration.
        rolecontentTc                "    i | dg | d   iS )NrP   rF   )r]   message_paramss    rH   <lambda>z0BaseToolRunner.append_messages.<locals>.<lambda>z   s&    0n60n:GmPZI[Gm^lGm0n rG   N)
isinstancer   rg   rh   rW   rd   rX   )r\   rP   r_   rj   s      @rH   append_messageszBaseToolRunner.append_messageso   sb     $2
 CMWVaBbW\\goo>hoo2
 #'  !no*.'2
s   2Ac                P    | j                   | j                  | j                   k\  ryy)NTF)rY   rZ   r\   s    rH   _should_stopzBaseToolRunner._should_stop}   s'    +0E0EI]I]0]rG   c                H    t        | j                  d   | j                        S )am  The tool names currently available, after applying any
        mid-conversation ``tool_removal`` / ``tool_addition`` blocks.

        Removal is only a hint to the model, which can still emit a ``tool_use``
        for a withdrawn tool; a name absent from this set routes that call down
        the same unknown-tool path as a tool that was never declared.
        rP   )r"   rS   rR   ro   s    rH   _available_tool_namesz$BaseToolRunner._available_tool_names   s      $DLL$<d>Q>QRRrG   )r]   -ParseMessageCreateParamsBase[ResponseFormatT]r^   r=   rQ   zIterable[AnyFunctionToolT]rM   
int | NonerN   CompactionControl | NonereturnNone)r]   zParseMessageCreateParamsBase[ResponseFormatT] | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]rv   rw   )rP   z5BetaMessageParam | ParsedBetaMessage[ResponseFormatT]rv   rw   rv   bool)rv   zset[str])rB   rC   rD   ra   rd   rm   rp   rr   rF   rG   rH   rK   rK   C   su     &*7;6 >6  	6
 *6 #6 56 
68s 
	/
SrG   rK   c                       e Zd Zddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZddZee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 xZS )BaseSyncToolRunnerNrL   c                   t         |   |||||       || _        |-|j                  d      rt	        j
                  dt        d       | j                         | _        d | _	        y N)r]   r^   rQ   rM   rN   enableda!  The 'compaction_control' parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits=[{'type': 'compact_20260112'}]` in your the params passed to `tool_runner()`. See https://platform.claude.com/docs/en/build-with-claude/compactionr   
stacklevel
superra   _clientrU   warningswarnDeprecationWarning__run__	_iterator_last_messager\   r]   r^   rQ   clientrM   rN   	__class__s          rH   ra   zBaseSyncToolRunner.__init__   sy     	)1 	 	
 ).@.D.DY.OMM} #   	rG   c                6    | j                   j                         S N)r   __next__ro   s    rH   r   zBaseSyncToolRunner.__next__   s    ~~&&((rG   c              #  6   K   | j                   D ]  }|  y wr   r   r\   items     rH   __iter__zBaseSyncToolRunner.__iter__   s     NN 	DJ	s   c              #     K   t               wr   NotImplementedErrorro   s    rH   _handle_requestz"BaseSyncToolRunner._handle_request         "##   c                  
 | j                   | j                   d   sy| j                         }d}|e|j                  j                  |j                  j                  xs dz   |j                  j
                  xs dz   }||j                  j                  z   }| j                   j                  dt              }||k  ryt        j                  d| d| d       | j                   j                  d| j                  d         }t        | j                  d	         }|d
   d   dk(  rT|d
   d   D cg c](  }t        |t              r|j                  d      dk7  r|* }}|r	||d
   d<   n|j                          g |t!        d| j                   j                  dt"                    }| j$                  j&                  j(                  j+                  ||| j                  d   t-        d            }	t        j                  d|	j                  j                          t        |	j.                        d   

j0                  dk7  rt3        d      | j5                  
fd       yc c}w )
        Check token usage and compact messages if threshold exceeded.
        Returns True if compaction was performed, False otherwise.
        r~   Fr   context_token_thresholdToken usage  has exceeded the threshold of . Performing compaction.modelrP   rg   	assistantrh   typetool_useusersummary_promptrf   
max_tokens
compactionr   rP   r   r>   &Compaction complete. New token usage: text1Compaction response content is not of type 'text'c                8    i | dddj                   dgdgiS NrP   r   r   )r   r   rf   r   r]   first_contents    rH   rk   z7BaseSyncToolRunner._check_and_compact.<locals>.<lambda>   ?      & )/(5(:(:$
 rG   Tr[   _get_last_messageusageinput_tokenscache_creation_input_tokenscache_read_input_tokensoutput_tokensrU   r-   loginforS   listrl   dictpopr   r.   r   betarP   creater+   rh   r   
ValueErrorrd   r\   r_   tokens_usedtotal_input_tokens	thresholdr   rP   blocknon_tool_blocksresponser   s             @rH   _check_and_compactz%BaseSyncToolRunner._check_and_compact   s^   
 ##+43K3KI3V((***==<<AC==88=A? 
 -w}}/J/JJK,,001JL]^	" 	<},KI;Vnop((,,Wdll76KLZ01B<;.
 &b\)4eT*uyy/@J/N O  *9Y'

00445EG]^
 <<$$--44||L1'5	 5 
 	9(..:V:V9WXYX--.q1'PQQ  	
  cs   /-I$c              #    K   | j                         s#| j                         5 }| | j                         }|J | j                         }|/|j                  #|j                  j
                  | j                  d<   d d d        | xj                  dz  c_        j                  dk(  rt        j                  d       y | j                         sF| j                         }|t        j                  d       y | j                  s| j                  ||       d| _        d | _        | j                         s"y y # 1 sw Y   xY wwN	containerr   refusalz9Turn ended with a refusal, exiting from tool runner loop.z;Tool call was not requested, exiting from tool runner loop.Frp   r   r   _get_last_assistant_messager   idrS   rZ   stop_reasonr   debugr   generate_tool_call_responserW   rm   rX   r\   r   r_   last_assistant_messager   s        rH   r   zBaseSyncToolRunner.__run__  s3    ##%%%' T4
002*** *.)I)I)K&)5:P:Z:Z:f0F0P0P0S0SDLL-T !!Q&!
 ""i/		UV **,;;=#II[\..(((;&+D#.2D+? ##%%T Ts$   "EAD8>B6E6E8E=Ec                D    t        |        | j                         }|J |S )
        Consumes the tool runner stream and returns the last message if it has not been consumed yet.
        If it has, it simply returns the last message.
        )r   r   r\   last_messages     rH   
until_donezBaseSyncToolRunner.until_done2  s,    
 	d#--/'''rG   c                    | j                   !t        j                  d       | j                   S | j                         }|| _         |S )  Generate a MessageParam by calling tool functions with any tool use blocks from the last message.

        Note the tool call response is cached, repeated calls to this method will return the same response.

        None can be returned if no tool call was applicable.
        $Returning cached tool call response.rX   r   r   _generate_tool_call_responser\   r   s     rH   r   z.BaseSyncToolRunner.generate_tool_call_response<  sD     **6II<=222446*2'rG   c           
        | j                         }|sy |D cg c]  }|j                  dk(  s| }}|sy g }| j                         }|D ]  }|j                  |v r%| j                  j                  |j                        nd }|}t        j                  d|j                   dt        | j                  j                                dt        d       |j                  d|j                  d|j                   d	d
d       	 |j                  |j                        }|j                  d|j                  |d        d|dS c c}w # t        $ r4}	|j                  d|j                  t!        |	      d
d       Y d }	~	6d }	~	wt"        $ rX}	t$        j'                  d|j                   |	       |j                  d|j                  t!        |	      d
d       Y d }	~	d }	~	ww xY w)Nr   Tool '-' not found in tool runner. Available tools: z. If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. Otherwise, pass the tool using `beta_tool(func)` or a `@beta_tool` decorated function.r   r   tool_resultError: Tool '' not foundTr   tool_use_idrh   is_errorr   r   rh   #Error occurred while calling tool: exc_infor   rf   #_get_last_assistant_message_contentr   rr   namerR   rU   r   r   r   keysUserWarningappendr   callinputr#   r!   	Exceptionr   	exception
r\   rh   r   tool_use_blocksresults	availabler   toolresultexcs
             rH   r   z/BaseSyncToolRunner._generate_tool_call_responseJ  s   ::<.5RUz9Q5RR24..0	' *	H=E]]i=W4&&**8==9]aD|X]]O ,((,T-@-@-E-E-G(H'I Jmn     -'/{{%28==/#M$(	 8>>2hkk^def/*	X 733g S>   -'/{{#5c#:$(	   	 CDII;OZ]^ -'/{{#5c#:$(	 	s/   EE:E	G$)F  G$AGG$c                d    t        | j                        r| j                         S | j                  S r   rc   r   ro   s    rH   r   z$BaseSyncToolRunner._get_last_message  s+    D&&'%%''!!!rG   c                b    | j                         }||j                  dk7  s|j                  sy |S Nr   r   rg   rh   r   s     rH   r   z.BaseSyncToolRunner._get_last_assistant_message  s4    --/<#4#4#C<K_K_rG   c                @    | j                         }|y |j                  S r   r   rh   r\   r   s     rH   r   z6BaseSyncToolRunner._get_last_assistant_message_content  s&    !%!A!A!C!)%---rG   )r]   rs   r^   r=   rQ   zIterable[BetaRunnableTool]r   r7   rM   rt   rN   ru   rv   rw   rv   r;   )rv   zIterator[RunnerItemT]rx   rv   z"ParsedBetaMessage[ResponseFormatT]rv   zBetaMessageParam | Nonerv   z)ParsedBetaMessage[ResponseFormatT] | Nonerv   z4list[ParsedBetaContentBlock[ResponseFormatT]] | None)rB   rC   rD   ra   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r   s   @rH   r{   r{      s     &*7; >  	
 *  # 5 
B)   Rh 3D84t"
.rG   r{   c                  (    e Zd Zeedd              Zy)BetaToolRunnerc              #     K    | j                   j                  j                  j                  di | j                  | j
                  }|| _        | y wNrF   r   r   rP   parserS   rV   r   r\   r_   s     rH   r   zBetaToolRunner._handle_request  sG      3$,,##,,22ST\\ST]]S$s   AAN)rv   z,Iterator[ParsedBetaMessage[ResponseFormatT]]rB   rC   rD   r   r   r   rF   rG   rH   r  r    s      rG   r  c                  (    e Zd Zeedd              Zy)BetaStreamingToolRunnerc              #     K    | j                   j                  j                  j                  di | j                  | j
                  5 }|j                  | _        | d d d        y # 1 sw Y   y xY wwr  r   r   rP   streamrS   rV   get_final_messager   r\   r  s     rH   r   z'BetaStreamingToolRunner._handle_request  sb      /T\\''..OOO 	SY!'!9!9DL	 	 	s   AA4	A(	A4(A1-A4N)rv   z,Iterator[BetaMessageStream[ResponseFormatT]]r  rF   rG   rH   r  r    s      rG   r  c                       e Zd Zddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZddZee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 xZS )BaseAsyncToolRunnerNrL   c                   t         |   |||||       || _        |-|j                  d      rt	        j
                  dt        d       | j                         | _        d | _	        y r}   r   r   s          rH   ra   zBaseAsyncToolRunner.__init__  sy     	)1 	 	
 ).@.D.DY.OMM} # 
 	 	rG   c                R   K   | j                   j                          d {   S 7 wr   )r   	__anext__ro   s    rH   r"  zBaseAsyncToolRunner.__anext__  s     ^^--////s   '%'c               H   K   | j                   2 3 d {   }| 7 
6 y wr   r   r   s     rH   	__aiter__zBaseAsyncToolRunner.__aiter__  s&     .. 	 	$J	.s   "  " "c                  K   t               wr   r   ro   s    rH   r   z#BaseAsyncToolRunner._handle_request  r   r   c                  
K   | j                   | j                   d   sy| j                          d{   }d}|e|j                  j                  |j                  j                  xs dz   |j                  j
                  xs dz   }||j                  j                  z   }| j                   j                  dt              }||k  ryt        j                  d| d| d       | j                   j                  d	| j                  d	         }t        | j                  d
         }|d   d   dk(  rT|d   d   D cg c](  }t        |t              r|j                  d      dk7  r|* }}|r	||d   d<   n|j                          g |t!        d| j                   j                  dt"                    }| j$                  j&                  j(                  j+                  ||| j                  d   t-        d             d{   }	t        j                  d|	j                  j                          t        |	j.                        d   

j0                  dk7  rt3        d      | j5                  
fd       y7 Cc c}w 7 w)r   Nr~   Fr   r   r   r   r   r   rP   r   rg   r   rh   r   r   r   r   rf   r   r   r   r   r   r   c                8    i | dddj                   dgdgiS r   r   r   s    rH   rk   z8BaseAsyncToolRunner._check_and_compact.<locals>.<lambda>   r   rG   Tr   r   s             @rH   r   z&BaseAsyncToolRunner._check_and_compact  st    
 ##+43K3KI3V..00**==<<AC==88=A? 
 -w}}/J/JJK,,001JL]^	" 	<},KI;Vnop((,,Wdll76KLZ01B<;.
 &b\)4eT*uyy/@J/N O  *9Y'

00445EG]^
 **33::||L1'5	 ; 
 
 	9(..:V:V9WXYX--.q1'PQQ  	
  U 12&
s0   0J I6DJ 9-I9&BJ >I>?A8J 9J c                 K   | j                         sT| j                         4 d {   }| | j                          d {   }|J | j                          d {   }|/|j                  #|j                  j
                  | j                  d<   d d d       d {    | xj                  dz  c_        j                  dk(  rt        j                  d       y | j                          d {   sN| j                          d {   }|t        j                  d       y | j                  s| j                  ||       d| _        d | _        | j                         sSy y 7 A7 '7 7 # 1 d {  7  sw Y   xY w7 7 ~wr   r   r   s        rH   r   zBaseAsyncToolRunner.__run__1  sw    ##%++- T T
 $ 6 6 88*** 04/O/O/Q)Q&)5:P:Z:Z:f0F0P0P0S0SDLL-T T !!Q&!
 ""i/		UV 00222!%!A!A!CC#II[\..(((;&+D#.2D+? ##%%T8 *RT T T T( 3Cs   &FE)FE4E,E4!E/"5E4F"E2#AF4F	5FFAF'F,E4/E42F4F:E=;FFFc                t   K   t        |        d{    | j                          d{   }|J |S 7 "7 w)r   N)r   r   r   s     rH   r   zBaseAsyncToolRunner.until_doneS  sB     
 %T***!3355''' 	+5s   848688c                   K   | j                   !t        j                  d       | j                   S | j                          d{   }|| _         |S 7 w)r   Nr   r   r   s     rH   r   z/BaseAsyncToolRunner.generate_tool_call_response]  sP      **6II<=222::<<*2' =s   AAAAc                   K   t        | j                        r| j                          d {   S | j                  S 7 wr   r  ro   s    rH   r   z%BaseAsyncToolRunner._get_last_messagel  s7     D&&'++---!!! .s   )><>c                ~   K   | j                          d {   }||j                  dk7  s|j                  sy |S 7 $wr  r  r   s     rH   r   z/BaseAsyncToolRunner._get_last_assistant_messageq  s@     !3355<#4#4#C<K_K_	 6s   =;%=c                \   K   | j                          d {   }|y |j                  S 7 wr   r  r  s     rH   r   z7BaseAsyncToolRunner._get_last_assistant_message_contentx  s3     '+'G'G'I!I!)%---	 "Js   ,*,c           
        K   | j                          d {   }|sy |D cg c]  }|j                  dk(  s| }}|sy g }| j                         }|D ]  }|j                  |v r%| j                  j                  |j                        nd }|}t        j                  d|j                   dt        | j                  j                                dt        d       |j                  d|j                  d|j                   d	d
d       	 |j                  |j                         d {   }|j                  d|j                  |d        d|dS 7 ?c c}w 7 2# t        $ r4}	|j                  d|j                  t!        |	      d
d       Y d }	~	Cd }	~	wt"        $ rX}	t$        j'                  d|j                   |	       |j                  d|j                  t!        |	      d
d       Y d }	~	d }	~	ww xY ww)Nr   r   r   z. If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. Otherwise, pass the tool using `beta_async_tool(func)` or a `@beta_async_tool` decorated function.r   r   r   r   r   Tr   r   r   r   r   rf   r   r   s
             rH   r   z0BaseAsyncToolRunner._generate_tool_call_response  s    @@BB.5RUz9Q5RR24..0	' *	H=E]]i=W4&&**8==9]aD|X]]O ,((,T-@-@-E-E-G(H'I Jyz     -'/{{%28==/#M$(	 #yy88hkk^def/*	X 733o C S: 9  -'/{{#5c#:$(	   	 CDII;OZ]^ -'/{{#5c#:$(	 	st   G>EG>EECG>E*E+#EG>G>E	G;()FG>G;#AG60G>6G;;G>)r]   rs   r^   r=   rQ   zIterable[BetaAsyncRunnableTool]r   r8   rM   rt   rN   ru   rv   rw   r  )rv   zAsyncIterator[RunnerItemT]rx   r	  r
  r  r  )rB   rC   rD   ra   r"  r$  r   r   r   r   r   r   r   r   r   r   r   r  r  s   @rH   r  r    s     &*7;! >!  	!
 /! ! #! 5! 
!F0   Rh 3D"
.84rG   r  c                  (    e Zd Zeedd              Zy)BetaAsyncToolRunnerc                  K    | j                   j                  j                  j                  di | j                  | j
                   d {   }|| _        | y 7 wr  r  r  s     rH   r   z#BetaAsyncToolRunner._handle_request  sP      9))2288Y4<<Y4==YY$ Zs   A
A AA N)rv   z1AsyncIterator[ParsedBetaMessage[ResponseFormatT]]rB   rC   rD   r   r   r   rF   rG   rH   r0  r0    s      rG   r0  c                  (    e Zd Zeedd              Zy)BetaAsyncStreamingToolRunnerc               (  K    | j                   j                  j                  j                  di | j                  | j
                  4 d {   }|j                  | _        | d d d       d {    y 7 +7 # 1 d {  7  sw Y   y xY wwr  r  r  s     rH   r   z,BetaAsyncStreamingToolRunner._handle_request  s}      54<<$$--44Ut||Ut}}U 	 	Y_!'!9!9DL	 	 	 	 	 	 	sH   ABA9BA=(B3A;4B;B=BBBBN)rv   z6AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]r2  rF   rG   rH   r4  r4    s      rG   r4  )U
__future__r   loggingr   abcr   r   typingr   r   r   r	   r
   r   r   r   r   r   r   
contextlibr   r   typing_extensionsr   r   httpx_typesr   r   r   r   _utilsr   r   
types.betar   r   _base_clientr   _tool_dispatchr    r!   r"   _beta_functionsr#   r$   r%   r&   r'   r(   r)   _stainless_helpersr+   r,   _beta_compaction_controlr-   r.   r/   streaming._beta_messagesr0   r1   types.beta.parsed_beta_messager2   r3   r4    types.beta.message_create_paramsr5   'types.beta.beta_tool_result_block_paramr6   r   r7   r8   r9   r;   	getLoggerrB   r   r=   rK   r{   r  r  r  r0  r4  rF   rG   rH   <module>rJ     s   "   #    ; 1  4 4 C 7 ) S S   H b b P h h L O4 
4S9;RTpp  m$g!5Ye 5GSW->? GSTH.(8/(IJGT_apTpLqsv H.V'(9/(JO([\ 01B?1SUd1de M4(/9:GKQ`D`<acfM4`-.?.PRa.ab #67Mo7^`o7o#p rG   