
    Iig                       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&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= erddl>m?Z?m@Z@  edee'e	   e)e	   e+e,f         ZA ed      ZB ej                  eD      ZE G d ded      ZF G d deeAe7f         ZG G d deGe(e7f   eeBe7f   e      ZH G d  d!eHe8e7   e7f         ZI G d" d#eHe4e7   e7f         ZJ G d$ d%eGe*e7f   eeBe7f   e      ZK G d& d'eKe8e7   e7f         ZL G d( d)eKe5e7   e7f         ZMy)*    )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   )	ToolErrorBetaFunctionToolBetaRunnableToolBetaAsyncFunctionToolBetaAsyncRunnableToolBetaBuiltinFunctionToolBetaAsyncBuiltinFunctionTool   )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/volume1/homes/robertsu/coba/app/.venv/lib/python3.12/site-packages/anthropic/lib/tools/_beta_runner.pyr8   r8   :   s    !!44rB   r8   F)totalc                  R    e Zd Zddd	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 ddZd	dZd
dZy)BaseToolRunnerNmax_iterationscompaction_controlc                  |D ci c]  }|j                   | c}| _        i |d|d   D cg c]  }| c}i| _        t        | j                  j	                         |j                  d            }|r!i ||j                  d      xs i }	i |d|	i}|| _        d| _        d | _        || _	        d| _
        || _        y c c}w c c}w )Nmessages)toolsrK   r9   Fr   )name_tools_by_name_paramsr'   valuesget_options_messages_modified_cached_tool_call_response_max_iterations_iteration_count_compaction_control)
selfparamsoptionsrL   rH   rI   toolmessagehelper_headermerged_headerss
             rC   __init__zBaseToolRunner.__init__B   s     <AA54tyy$5AG
G
z0BC0BW0BCG
 0%%,,.ZZ
+
 VV'++o2N2TRTVNBB/>BG"'CG'- !#5 # B Ds
   C	C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)callablerO   )rX   rY   s     rC   set_messages_paramsz"BaseToolRunner.set_messages_params^   s!     FDLL)FrB   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 )NrK   rA   )rY   message_paramss    rC   <lambda>z0BaseToolRunner.append_messages.<locals>.<lambda>x   s$    0n60n:GmPZI[Gm^lGm0nrB   N)
isinstancer   re   rf   rS   rb   rT   )rX   rK   r\   rh   s      @rC   append_messageszBaseToolRunner.append_messagesm   sg     $2
# CMWVaBbW\\goo>hoo#2
 #'  !no*.'2
s   2Ac                P    | j                   | j                  | j                   k\  ryy)NTF)rU   rV   rX   s    rC   _should_stopzBaseToolRunner._should_stop{   s'    +0E0EI]I]0]rB   )rY   -ParseMessageCreateParamsBase[ResponseFormatT]rZ   r8   rL   zIterable[AnyFunctionToolT]rH   
int | NonerI   CompactionControl | NonereturnNone)rY   zParseMessageCreateParamsBase[ResponseFormatT] | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]rr   rs   )rK   z5BetaMessageParam | ParsedBetaMessage[ResponseFormatT]rr   rs   rr   bool)r=   r>   r?   r_   rb   rk   rn   rA   rB   rC   rF   rF   A   so     &*7;6 >6  	6
 *6 #6 56 
68s 
	/rB   rF   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 )BaseSyncToolRunnerNrG   c                   t         |   |||||       || _        |-|j                  d      rt	        j
                  dt        d       | j                         | _        d | _	        y N)rY   rZ   rL   rH   rI   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
superr_   _clientrQ   warningswarnDeprecationWarning__run__	_iterator_last_messagerX   rY   rZ   rL   clientrH   rI   	__class__s          rC   r_   zBaseSyncToolRunner.__init__   sy     	)1 	 	
 ).@.D.DY.OMM} #   	rB   c                6    | j                   j                         S N)r   __next__rm   s    rC   r   zBaseSyncToolRunner.__next__   s    ~~&&((rB   c              #  6   K   | j                   D ]  }|  y wr   r   rX   items     rC   __iter__zBaseSyncToolRunner.__iter__   s     NNDJ #s   c              #     K   t               wr   NotImplementedErrorrm   s    rC   _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   ddi      }	t        j                  d|	j                  j                          t        |	j,                        d   

j.                  dk7  rt1        d      | j3                  
fd       yc c}w )
        Check token usage and compact messages if threshold exceeded.
        Returns True if compaction was performed, False otherwise.
        rz   Fr   context_token_thresholdToken usage  has exceeded the threshold of . Performing compaction.modelrK   re   	assistantrf   typetool_useusersummary_promptrd   
max_tokensX-Stainless-Helper
compactionr   rK   r   r9   &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 NrK   r   r   )r   r   rd   r   rY   first_contents    rC   ri   z7BaseSyncToolRunner._check_and_compact.<locals>.<lambda>   =      & )/(5(:(:$
rB   TrW   _get_last_messageusageinput_tokenscache_creation_input_tokenscache_read_input_tokensoutput_tokensrQ   r(   loginforO   listrj   dictpopr   r)   r   betarK   createrf   r   
ValueErrorrb   rX   r\   tokens_usedtotal_input_tokens	thresholdr   rK   blocknon_tool_blocksresponser   s             @rC   _check_and_compactz%BaseSyncToolRunner._check_and_compact   sa   
 ##+43K3KI3V((***==<<AC==88=A? 
 -w}}/J/JJK,,001JL]^	" 	<},KI;Vnop((,,Wdll76KLZ01B<;.
 &b\)44EeT*uyy/@J/N 4   *9Y'

00445EG]^
 <<$$--44||L1/>	 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                         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   z;Tool call was not requested, exiting from tool runner loop.Frn   r   r   _get_last_assistant_messager   idrO   rV   r   generate_tool_call_responser   debugrS   rk   rT   rX   r   r\   last_assistant_messager   s        rC   r   zBaseSyncToolRunner.__run__  s    ##%%%'4
002*** *.)I)I)K&)5:P:Z:Z:f0F0P0P0S0SDLL- ( !!Q&! **,;;=#II[\..(((;&+D#.2D+1 ##%''s$   !DAD=BDDDD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   rX   last_messages     rC   
until_donezBaseSyncToolRunner.until_done  s,    
 	d#--/'''rB   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.rT   r   r   _generate_tool_call_responserX   r   s     rC   r   z.BaseSyncToolRunner.generate_tool_call_response)  sD     **6II<=222446*2'rB   c           
        | j                         }|sy |D cg c]  }|j                  dk(  s| }}|sy g }|D ]  }| j                  j                  |j                        }|}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        $ r5}|j                  d|j                  |j                  d
d       Y d }~'d }~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_idrf   is_errorr   r   rf   #Error occurred while calling tool: exc_infor   rd   #_get_last_assistant_message_contentr   rN   rQ   rM   r   r   r   keysUserWarningappendr   callinputr   rf   	Exceptionr   	exceptionrepr	rX   rf   r   tool_use_blocksresultsr   r[   resultexcs	            rC   r   z/BaseSyncToolRunner._generate_tool_call_response7  s   ::<.5RgUz9Q5gR24'H&&**8==9D|X]]O ,((,T-@-@-E-E-G(H'I Jmn     -'/{{%28==/#M$(	 8>>2hkk^def/ (X 733e S<   -'/{{#&;;$(	   	 CDII;OZ]^ -'/{{#'9$(	 	s/   D#D#":D((	G1*E!!G-AG  Gc                d    t        | j                        r| j                         S | j                  S r   ra   r   rm   s    rC   r   z$BaseSyncToolRunner._get_last_messagep  s+    D&&'%%''!!!rB   c                b    | j                         }||j                  dk7  s|j                  sy |S Nr   r   re   rf   r   s     rC   r   z.BaseSyncToolRunner._get_last_assistant_messageu  s4    --/<#4#4#C<K_K_rB   c                @    | j                         }|y |j                  S r   r   rf   rX   r   s     rC   r   z6BaseSyncToolRunner._get_last_assistant_message_content|  s&    !%!A!A!C!)%---rB   )rY   ro   rZ   r8   rL   zIterable[BetaRunnableTool]r   r2   rH   rp   rI   rq   rr   rs   rr   r6   )rr   zIterator[RunnerItemT]rt   rr   z"ParsedBetaMessage[ResponseFormatT]rr   zBetaMessageParam | Nonerr   z)ParsedBetaMessage[ResponseFormatT] | Nonerr   z4list[ParsedBetaContentBlock[ResponseFormatT]] | None)r=   r>   r?   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r   s   @rC   rw   rw      s     &*7; >  	
 *  # 5 
B)   Rh3674r"
.rB   rw   c                  (    e Zd Zeedd              Zy)BetaToolRunnerc              #     K    | j                   j                  j                  j                  di | j                  | j
                  }|| _        | y wNrA   r   r   rK   parserO   rR   r   rX   r\   s     rC   r   zBetaToolRunner._handle_request  sG      3$,,##,,22ST\\ST]]S$s   AAN)rr   z,Iterator[ParsedBetaMessage[ResponseFormatT]]r=   r>   r?   r   r   r   rA   rB   rC   r	  r	    s      rB   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   rK   streamrO   rR   get_final_messager   rX   r  s     rC   r   z'BetaStreamingToolRunner._handle_request  sZ      /T\\''..OOOSY!'!9!9DL POOs   AA4	A(	A4(A1-A4N)rr   z,Iterator[BetaMessageStream[ResponseFormatT]]r  rA   rB   rC   r  r    s      rB   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 )BaseAsyncToolRunnerNrG   c                   t         |   |||||       || _        |-|j                  d      rt	        j
                  dt        d       | j                         | _        d | _	        y ry   r}   r   s          rC   r_   zBaseAsyncToolRunner.__init__  sy     	)1 	 	
 ).@.D.DY.OMM} # 
 	 	rB   c                R   K   | j                   j                          d {   S 7 wr   )r   	__anext__rm   s    rC   r  zBaseAsyncToolRunner.__anext__  s     ^^--////s   '%'c               H   K   | j                   2 3 d {   }| 7 
6 y wr   r   r   s     rC   	__aiter__zBaseAsyncToolRunner.__aiter__  s!     .. 	$J	.s   "  " "c                  K   t               wr   r   rm   s    rC   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   ddi       d{   }	t        j                  d|	j                  j                          t        |	j,                        d   

j.                  dk7  rt1        d      | j3                  
fd       y7 <c c}w 7 w)r   Nrz   Fr   r   r   r   r   r   rK   r   re   r   rf   r   r   r   r   rd   r   r   r   r   r   r   r   c                8    i | dddj                   dgdgiS r   r   r   s    rC   ri   z8BaseAsyncToolRunner._check_and_compact.<locals>.<lambda>  r   rB   Tr   r   s             @rC   r   z&BaseAsyncToolRunner._check_and_compact  sw    
 ##+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4EeT*uyy/@J/N 4   *9Y'

00445EG]^
 **33::||L1/>	 ; 
 
 	9(..:V:V9WXYX--.q1'PQQ  	
  U 12&
s0   0I9I/DI99-I2&BI97I78A8I92I9c                 K   | j                         s/| j                         4 d {   }| | j                          d {   }|J | j                          d {   }|/|j                  #|j                  j
                  | j                  d<   d d d       d {    | xj                  dz  c_        | j                          d {   sN| j                          d {   }|t        j                  d       y | j                  s| j                  |       d| _        d | _        | j                         s.y y 7 7 7 7 # 1 d {  7  sw Y   xY w7 7 }wr   r   r   s        rC   r   zBaseAsyncToolRunner.__run__  s=    ##%++--
 $ 6 6 88*** 04/O/O/Q)Q&)5:P:Z:Z:f0F0P0P0S0SDLL- .- !!Q&! 00222!%!A!A!CC#II[\..(((;&+D#.2D+1 ##%%-8 *R .--- 3Cs   &E'EE'EEE!E
"5EE'"E#,E'E#E''E%(AE'E'E
EE'E EE E'%E'c                t   K   t        |        d{    | j                          d{   }|J |S 7 "7 w)r   N)r   r   r   s     rC   r   zBaseAsyncToolRunner.until_done8  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     rC   r   z/BaseAsyncToolRunner.generate_tool_call_responseB  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   rm   s    rC   r   z%BaseAsyncToolRunner._get_last_messageQ  s7     D&&'++---!!! .s   )><>c                ~   K   | j                          d {   }||j                  dk7  s|j                  sy |S 7 $wr   r   r   s     rC   r   z/BaseAsyncToolRunner._get_last_assistant_messageV  s@     !3355<#4#4#C<K_K_	 6s   =;%=c                \   K   | j                          d {   }|y |j                  S 7 wr   r   r   s     rC   r   z7BaseAsyncToolRunner._get_last_assistant_message_content]  s3     '+'G'G'I!I!)%---	 "Js   ,*,c           
       K   | j                          d {   }|sy |D cg c]  }|j                  dk(  s| }}|sy g }|D ]  }| j                  j                  |j                        }|}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        $ r5}|j                  d|j                  |j                  d
d       Y d }~4d }~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   rd   r   r   s	            rC   r   z0BaseAsyncToolRunner._generate_tool_call_responsed  s    @@BB.5RgUz9Q5gR24'H&&**8==9D|X]]O ,((,T-@-@-E-E-G(H'I Jyz     -'/{{%28==/#M$(	 #yy88hkk^def/ (X 733m C S8 9  -'/{{#&;;$(	   	 CDII;OZ]^ -'/{{#'9$(	 	st   GD5GD8D8B0G,D?
D=#D?.G8G=D??	G*E82G8GAGGGG)rY   ro   rZ   r8   rL   zIterable[BetaAsyncRunnableTool]r   r3   rH   rp   rI   rq   rr   rs   r  )rr   zAsyncIterator[RunnerItemT]rt   r  r  r  r  )r=   r>   r?   r_   r  r  r   r   r   r   r   r   r   r   r   r   r   r  r  s   @rC   r  r    s     &*7;! >!  	!
 /! ! #! 5! 
!F0   Rh36"
.74rB   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     rC   r   z#BetaAsyncToolRunner._handle_request  sP      9))2288Y4<<Y4==YY$ Zs   A
A AA N)rr   z1AsyncIterator[ParsedBetaMessage[ResponseFormatT]]r=   r>   r?   r   r   r   rA   rB   rC   r)  r)    s      rB   r)  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     rC   r   z,BetaAsyncStreamingToolRunner._handle_request  sk      54<<$$--44Ut||Ut}}UUY_!'!9!9DL VUUUUUUsH   ABA9BA=(B3A;4B;B=BBBBN)rr   z6AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]r+  rA   rB   rC   r-  r-    s      rB   r-  )N
__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   _beta_functionsr   r    r!   r"   r#   r$   r%   _stainless_helpersr'   _beta_compaction_controlr(   r)   r*   streaming._beta_messagesr+   r,   types.beta.parsed_beta_messager-   r.   r/    types.beta.message_create_paramsr0   'types.beta.beta_tool_result_block_paramr1   r   r2   r3   r4   r6   	getLoggerr=   r   r8   rF   rw   r	  r  r  r)  r-  rA   rB   rC   <module>rA     s   "   #    ; 1  4 4 C 7   9 b b P h h L O4 
4S9;RTpp  m$g!5Ye 5=W->? =@@.(8/(IJGT_apTpLqsv @.F'(9/(JO([\ 01B?1SUd1de E4(/9:GKQ`D`<acfE4P-.?.PRa.ab #67Mo7^`o7o#p rB   