
    4Rjlk                       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) ddl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z; ddl<m=Z=m>Z>m?Z? ddl@mAZA ddlBmCZC erddlDmEZEmFZF  edee,e	   e.e	   e0e1f         ZG ed      ZH ej                  eJ      ZK G d ded      ZL G d deeGe=f         ZM G d  d!eMe-e=f   eeHe=f   e      ZN G d" d#eNe>e=   e=f         ZO G d$ d%eNe:e=   e=f         ZP G d& d'eMe/e=f   eeHe=f   e      ZQ G d( d)eQe>e=   e=f         ZR G d* d+eQe;e=   e=f         ZSy),    )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)	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__     h/var/www/html/meridian/meridian-ai/venv/lib/python3.12/site-packages/anthropic/lib/tools/_beta_runner.pyr<   r<   <   s    !!44rF   r<   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               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)toolsrO   r=   Fr   )r    _tools_by_name_paramsr+   valuesgetr   _options_messages_modified_cached_tool_call_response_max_iterations_iteration_count_compaction_control)	selfparamsoptionsrP   rL   rM   messager*   merged_headerss	            rG   __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)callablerR   )r[   r\   s     rG   set_messages_paramsz"BaseToolRunner.set_messages_params`   s!     FDLL)FrF   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 )NrO   rE   )r\   message_paramss    rG   <lambda>z0BaseToolRunner.append_messages.<locals>.<lambda>z   s&    0n60n:GmPZI[Gm^lGm0n rF   N)
isinstancer   rf   rg   rV   rc   rW   )r[   rO   r^   ri   s      @rG   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)rX   rY   r[   s    rG   _should_stopzBaseToolRunner._should_stop}   s'    +0E0EI]I]0]rF   )r\   -ParseMessageCreateParamsBase[ResponseFormatT]r]   r<   rP   zIterable[AnyFunctionToolT]rL   
int | NonerM   CompactionControl | NonereturnNone)r\   zParseMessageCreateParamsBase[ResponseFormatT] | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]rs   rt   )rO   z5BetaMessageParam | ParsedBetaMessage[ResponseFormatT]rs   rt   rs   bool)rA   rB   rC   r`   rc   rl   ro   rE   rF   rG   rJ   rJ   C   so     &*7;6 >6  	6
 *6 #6 56 
68s 
	/rF   rJ   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 )BaseSyncToolRunnerNrK   c                   t         |   |||||       || _        |-|j                  d      rt	        j
                  dt        d       | j                         | _        d | _	        y N)r\   r]   rP   rL   rM   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`   _clientrT   warningswarnDeprecationWarning__run__	_iterator_last_messager[   r\   r]   rP   clientrL   rM   	__class__s          rG   r`   zBaseSyncToolRunner.__init__   sy     	)1 	 	
 ).@.D.DY.OMM} #   	rF   c                6    | j                   j                         S N)r   __next__rn   s    rG   r   zBaseSyncToolRunner.__next__   s    ~~&&((rF   c              #  6   K   | j                   D ]  }|  y wr   r   r[   items     rG   __iter__zBaseSyncToolRunner.__iter__   s     NN 	DJ	s   c              #     K   t               wr   NotImplementedErrorrn   s    rG   _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.modelrO   rf   	assistantrg   typetool_useusersummary_promptre   
max_tokens
compactionr   rO   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 NrO   r   r   )r   r   re   r   r\   first_contents    rG   rj   z7BaseSyncToolRunner._check_and_compact.<locals>.<lambda>   ?      & )/(5(:(:$
 rF   TrZ   _get_last_messageusageinput_tokenscache_creation_input_tokenscache_read_input_tokensoutput_tokensrT   r,   loginforR   listrk   dictpopr   r-   r   betarO   creater*   rg   r   
ValueErrorrc   r[   r^   tokens_usedtotal_input_tokens	thresholdr   rO   blocknon_tool_blocksresponser   s             @rG   _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ro   r   r   _get_last_assistant_messager   idrR   rY   stop_reasonr   debugr   generate_tool_call_responserV   rl   rW   r[   r   r^   last_assistant_messager   s        rG   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     rG   
until_donezBaseSyncToolRunner.until_done(  s,    
 	d#--/'''rF   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.rW   r   r   _generate_tool_call_responser[   r   s     rG   r   z.BaseSyncToolRunner.generate_tool_call_response2  sD     **6II<=222446*2'rF   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        $ r4}|j                  d|j                  t        |      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_idrg   is_errorr   r   rg   #Error occurred while calling tool: exc_infor   re   #_get_last_assistant_message_contentr   rQ   rT   namer   r   r   keysUserWarningappendr   callinputr"   r!   	Exceptionr   	exception	r[   rg   r   tool_use_blocksresultsr   toolresultexcs	            rG   r   z/BaseSyncToolRunner._generate_tool_call_response@  s   ::<.5RUz9Q5R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<   -'/{{#5c#:$(	   	 CDII;OZ]^ -'/{{#5c#:$(	 	s/   D#D#":D((	G1)E  G,AF??Gc                d    t        | j                        r| j                         S | j                  S r   rb   r   rn   s    rG   r   z$BaseSyncToolRunner._get_last_messagey  s+    D&&'%%''!!!rF   c                b    | j                         }||j                  dk7  s|j                  sy |S Nr   r   rf   rg   r   s     rG   r   z.BaseSyncToolRunner._get_last_assistant_message~  s4    --/<#4#4#C<K_K_rF   c                @    | j                         }|y |j                  S r   r   rg   r[   r   s     rG   r   z6BaseSyncToolRunner._get_last_assistant_message_content  s&    !%!A!A!C!)%---rF   )r\   rp   r]   r<   rP   zIterable[BetaRunnableTool]r   r6   rL   rq   rM   rr   rs   rt   rs   r:   )rs   zIterator[RunnerItemT]ru   rs   z"ParsedBetaMessage[ResponseFormatT]rs   zBetaMessageParam | Noners   z)ParsedBetaMessage[ResponseFormatT] | Noners   z4list[ParsedBetaContentBlock[ResponseFormatT]] | None)rA   rB   rC   r`   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r   s   @rG   rx   rx      s     &*7; >  	
 *  # 5 
B)   Rh 3D74r"
.rF   rx   c                  (    e Zd Zeedd              Zy)BetaToolRunnerc              #     K    | j                   j                  j                  j                  di | j                  | j
                  }|| _        | y wNrE   r   r   rO   parserR   rU   r   r[   r^   s     rG   r   zBetaToolRunner._handle_request  sG      3$,,##,,22ST\\ST]]S$s   AAN)rs   z,Iterator[ParsedBetaMessage[ResponseFormatT]]rA   rB   rC   r   r   r   rE   rF   rG   r  r    s      rF   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   rO   streamrR   rU   get_final_messager   r[   r  s     rG   r   z'BetaStreamingToolRunner._handle_request  sb      /T\\''..OOO 	SY!'!9!9DL	 	 	s   AA4	A(	A4(A1-A4N)rs   z,Iterator[BetaMessageStream[ResponseFormatT]]r  rE   rF   rG   r  r    s      rF   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 )BaseAsyncToolRunnerNrK   c                   t         |   |||||       || _        |-|j                  d      rt	        j
                  dt        d       | j                         | _        d | _	        y rz   r~   r   s          rG   r`   zBaseAsyncToolRunner.__init__  sy     	)1 	 	
 ).@.D.DY.OMM} # 
 	 	rF   c                R   K   | j                   j                          d {   S 7 wr   )r   	__anext__rn   s    rG   r  zBaseAsyncToolRunner.__anext__  s     ^^--////s   '%'c               H   K   | j                   2 3 d {   }| 7 
6 y wr   r   r   s     rG   	__aiter__zBaseAsyncToolRunner.__aiter__  s&     .. 	 	$J	.s   "  " "c                  K   t               wr   r   rn   s    rG   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   rO   r   rf   r   rg   r   r   r   r   re   r   r   r   r   r   r   c                8    i | dddj                   dgdgiS r   r   r   s    rG   rj   z8BaseAsyncToolRunner._check_and_compact.<locals>.<lambda>  r   rF   Tr   r   s             @rG   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        rG   r   zBaseAsyncToolRunner.__run__&  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     rG   r   zBaseAsyncToolRunner.until_doneH  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     rG   r   z/BaseAsyncToolRunner.generate_tool_call_responseR  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   rn   s    rG   r   z%BaseAsyncToolRunner._get_last_messagea  s7     D&&'++---!!! .s   )><>c                ~   K   | j                          d {   }||j                  dk7  s|j                  sy |S 7 $wr   r   r   s     rG   r   z/BaseAsyncToolRunner._get_last_assistant_messagef  s@     !3355<#4#4#C<K_K_	 6s   =;%=c                \   K   | j                          d {   }|y |j                  S 7 wr   r  r  s     rG   r   z7BaseAsyncToolRunner._get_last_assistant_message_contentm  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        $ r4}|j                  d|j                  t        |      d
d       Y d }~3d }~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   re   r   r   s	            rG   r   z0BaseAsyncToolRunner._generate_tool_call_responset  s    @@BB.5RUz9Q5R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  -'/{{#5c#:$(	   	 CDII;OZ]^ -'/{{#5c#:$(	 	st   GD5GD8D8B0G,D?
D=#D?.G8G=D??	G)E71G7GAGGGG)r\   rp   r]   r<   rP   zIterable[BetaAsyncRunnableTool]r   r7   rL   rq   rM   rr   rs   rt   r  )rs   zAsyncIterator[RunnerItemT]ru   r  r  r  r  )rA   rB   rC   r`   r  r   r   r   r   r   r   r   r   r   r   r   r   r	  r
  s   @rG   r  r    s     &*7;! >!  	!
 /! ! #! 5! 
!F0   Rh 3D"
.74rF   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     rG   r   z#BetaAsyncToolRunner._handle_request  sP      9))2288Y4<<Y4==YY$ Zs   A
A AA N)rs   z1AsyncIterator[ParsedBetaMessage[ResponseFormatT]]rA   rB   rC   r   r   r   rE   rF   rG   r,  r,    s      rF   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     rG   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)rs   z6AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]r.  rE   rF   rG   r0  r0    s      rF   r0  )T
__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!   _beta_functionsr"   r#   r$   r%   r&   r'   r(   _stainless_helpersr*   r+   _beta_compaction_controlr,   r-   r.   streaming._beta_messagesr/   r0   types.beta.parsed_beta_messager1   r2   r3    types.beta.message_create_paramsr4   'types.beta.beta_tool_result_block_paramr5   r   r6   r7   r8   r:   	getLoggerrA   r   r<   rJ   rx   r  r  r  r,  r0  rE   rF   rG   <module>rF     s   "   #    ; 1  4 4 C 7 ) =   H b b P h h L O4 
4S9;RTpp  m$g!5Ye 5=W->? =@G.(8/(IJGT_apTpLqsv G.T'(9/(JO([\ 01B?1SUd1de L4(/9:GKQ`D`<acfL4^-.?.PRa.ab #67Mo7^`o7o#p rF   