o
    ^۷i^                     @  sn  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rddl>m?Z?m@Z@ edee'e	 e)e	 e+e,f dZAedZBeCeDZEG dd deddZFG dd deeAe7f ZGG dd deGe(e7f eeBe7f eZHG d d! d!eHe8e7 e7f ZIG d"d# d#eHe4e7 e7f ZJG d$d% d%eGe*e7f eeBe7f eZKG d&d' d'eKe8e7 e7f ZLG d(d) d)eKe5e7 e7f ZMdS )*    )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                   @  s.   e Zd ZU ded< ded< ded< ded< d	S )
RequestOptionszHeaders | Noneextra_headerszQuery | Noneextra_queryzBody | None
extra_bodyz'float | httpx.Timeout | None | NotGiventimeoutN)__name__
__module____qualname____annotations__ r?   r?   V/home/ubuntu/vllm_env/lib/python3.10/site-packages/anthropic/lib/tools/_beta_runner.pyr6   :   s
   
 r6   F)totalc                   @  s<   e Zd ZddddddZdddZdddZdddZdS )BaseToolRunnerNmax_iterationscompaction_controlparams-ParseMessageCreateParamsBase[ResponseFormatT]optionsr6   toolsIterable[AnyFunctionToolT]rD   
int | NonerE   CompactionControl | NonereturnNonec                C  s   dd |D | _ i |ddd |d D i| _t| j  |dd}|r9i ||dp/i }i |d|i}|| _d| _d | _|| _d	| _	|| _
d S )
Nc                 S  s   i | ]}|j |qS r?   )name).0toolr?   r?   r@   
<dictcomp>K   s    z+BaseToolRunner.__init__.<locals>.<dictcomp>messagesc                 S  s   g | ]}|qS r?   r?   rP   messager?   r?   r@   
<listcomp>N   s    z+BaseToolRunner.__init__.<locals>.<listcomp>)rI   rS   r7   Fr   )_tools_by_name_paramsr&   valuesget_options_messages_modified_cached_tool_call_response_max_iterations_iteration_count_compaction_control)selfrF   rH   rI   rD   rE   helper_headermerged_headersr?   r?   r@   __init__B   s&   	
zBaseToolRunner.__init__ParseMessageCreateParamsBase[ResponseFormatT] | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]]c                 C  s   t |r	|| j}|| _dS )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)callablerX   )ra   rF   r?   r?   r@   set_messages_params^   s   

z"BaseToolRunner.set_messages_paramsrS   5BetaMessageParam | ParsedBetaMessage[ResponseFormatT]c                   s2   dd |D  d_  fdd d_dS )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.
        c                 S  s(   g | ]}t |tr|j|jd n|qS )rolecontent)
isinstancer   rj   rk   rT   r?   r?   r@   rV   s   s    z2BaseToolRunner.append_messages.<locals>.<listcomp>Tc                   s   i | dg j d  iS )NrS   )rX   rF   message_paramsra   r?   r@   <lambda>x   s    z0BaseToolRunner.append_messages.<locals>.<lambda>N)r\   rg   r]   )ra   rS   r?   rn   r@   append_messagesm   s   
zBaseToolRunner.append_messagesboolc                 C  s   | j d ur| j| j krdS dS )NTF)r^   r_   ra   r?   r?   r@   _should_stop{   s   zBaseToolRunner._should_stop)rF   rG   rH   r6   rI   rJ   rD   rK   rE   rL   rM   rN   )rF   re   rM   rN   )rS   rh   rM   rN   rM   rr   )r;   r<   r=   rd   rg   rq   rt   r?   r?   r?   r@   rB   A   s    

rB   c                      s   e Zd Zdddd. fddZd/ddZd0ddZeed0ddZd1ddZ	d0ddZ
d2d!d"Zd3d$d%Zd3d&d'Zd4d)d*Zd5d,d-Z  ZS )6BaseSyncToolRunnerNrC   rF   rG   rH   r6   rI   Iterable[BetaRunnableTool]clientr1   rD   rK   rE   rL   rM   rN   c                  0   t  j|||||d || _|  | _d | _d S N)rF   rH   rI   rD   rE   superrd   _client__run__	_iterator_last_messagera   rF   rH   rI   rx   rD   rE   	__class__r?   r@   rd      s   

zBaseSyncToolRunner.__init__r5   c                 C  s
   | j  S N)r   __next__rs   r?   r?   r@   r      s   
zBaseSyncToolRunner.__next__Iterator[RunnerItemT]c                 c  s    | j D ]}|V  qd S r   r   ra   itemr?   r?   r@   __iter__   s   
zBaseSyncToolRunner.__iter__c                 c  s    t  r   NotImplementedErrorrs   r?   r?   r@   _handle_request      z"BaseSyncToolRunner._handle_requestrr   c           	        sv  | j du s
| j d sdS |  }d}|dur,|jj|jjpd |jjp$d }||jj }| j dt}||k r9dS t	
d| d| d | j d	| jd	 }t| jd
 }|d d dkrvdd |d d D }|rr||d d< n|  g |td| j dtd}| jjjj||| jd ddid}t	
d|jj  t|jd   jdkrtd|  fdd dS )
        Check token usage and compact messages if threshold exceeded.
        Returns True if compaction was performed, False otherwise.
        NenabledFr   context_token_thresholdToken usage  has exceeded the threshold of . Performing compaction.modelrS   rj   	assistantc                 S  (   g | ]}t |tr|d dkr|qS typetool_userl   dictrZ   rP   blockr?   r?   r@   rV          z9BaseSyncToolRunner._check_and_compact.<locals>.<listcomp>rk   usersummary_promptri   
max_tokensX-Stainless-Helper
compactionr   rS   r   r7   &Compaction complete. New token usage: text1Compaction response content is not of type 'text'c                   "   i | ddd j dgdgiS NrS   r   r   )r   r   ri   r   rm   first_contentr?   r@   rp          z7BaseSyncToolRunner._check_and_compact.<locals>.<lambda>Tr`   _get_last_messageusageinput_tokenscache_creation_input_tokenscache_read_input_tokensoutput_tokensrZ   r'   loginforX   listpopr   r(   r}   betarS   createrk   r   
ValueErrorrg   	ra   rU   tokens_usedtotal_input_tokens	thresholdr   rS   non_tool_blocksresponser?   r   r@   _check_and_compact   s^   





z%BaseSyncToolRunner._check_and_compactc                 c  s    |   sU|  }|V  |  }|d usJ W d    n1 s!w   Y  |  jd7  _|  sI|  }|d u r@td d S | jsI| 	|| d| _d | _
|   rd S d S Nr   z;Tool call was not requested, exiting from tool runner loop.Frt   r   r   r_   r   generate_tool_call_responser   debugr\   rq   r]   ra   r   rU   r   r?   r?   r@   r~      s$   

zBaseSyncToolRunner.__run__"ParsedBetaMessage[ResponseFormatT]c                 C  s    t |  |  }|dusJ |S z
        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.
        N)r   r   ra   last_messager?   r?   r@   
until_done  s   zBaseSyncToolRunner.until_doneBetaMessageParam | Nonec                 C  s,   | j durtd | j S |  }|| _ |S a  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.
        Nz$Returning cached tool call response.r]   r   r   _generate_tool_call_responsera   r   r?   r?   r@   r     s   

z.BaseSyncToolRunner.generate_tool_call_responsec                 C  sR  |   }|sd S dd |D }|sd S g }|D ]}| j|j}|d u rJtjd|j dt| j  dtdd |	d|j
d	|j d
dd qz||j}|	d|j
|d W q tyz } z|	d|j
|jdd W Y d }~qd }~w ty } ztjd|j |d |	d|j
t|dd W Y d }~qd }~ww d|dS )Nc                 S     g | ]	}|j d kr|qS r   r   r   r?   r?   r@   rV   .      zCBaseSyncToolRunner._generate_tool_call_response.<locals>.<listcomp>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   
stackleveltool_resultError: Tool '' not foundTr   tool_use_idrk   is_errorr   r   rk   #Error occurred while calling tool: exc_infor   ri   #_get_last_assistant_message_contentrW   rZ   rO   warningswarnr   keysUserWarningappendidcallinputr   rk   	Exceptionr   	exceptionreprra   rk   tool_use_blocksresultsr   rQ   resultexcr?   r?   r@   r   )  sb   

z/BaseSyncToolRunner._generate_tool_call_response)ParsedBetaMessage[ResponseFormatT] | Nonec                 C  s   t | jr	|  S | jS r   rf   r   rs   r?   r?   r@   r   b  s   
z$BaseSyncToolRunner._get_last_message4list[ParsedBetaContentBlock[ResponseFormatT]] | Nonec                 C  s*   |   }|d u s|jdks|jsd S |jS Nr   r   rj   rk   r   r?   r?   r@   r   g  s   z6BaseSyncToolRunner._get_last_assistant_message_content)rF   rG   rH   r6   rI   rw   rx   r1   rD   rK   rE   rL   rM   rN   rM   r5   )rM   r   ru   rM   r   rM   r   rM   r   rM   r   )r;   r<   r=   rd   r   r   r   r   r   r   r~   r   r   r   r   r   __classcell__r?   r?   r   r@   rv      s     



T




9rv   c                   @     e Zd ZeedddZdS )BetaToolRunnerrM   ,Iterator[ParsedBetaMessage[ResponseFormatT]]c                 c  s0    | j jjjdi | j| j}|| _|V  d S Nr?   r}   r   rS   parserX   r[   r   ra   rU   r?   r?   r@   r   p  s   
zBetaToolRunner._handle_requestN)rM   r  r;   r<   r=   r   r   r   r?   r?   r?   r@   r  o      r  c                   @  r  )BetaStreamingToolRunnerrM   ,Iterator[BetaMessageStream[ResponseFormatT]]c                 c  sT    | j jjjdi | j| j}|j| _|V  W d    d S 1 s#w   Y  d S r  r}   r   rS   streamrX   r[   get_final_messager   ra   r  r?   r?   r@   r   y  s
    "z'BetaStreamingToolRunner._handle_requestN)rM   r  r
  r?   r?   r?   r@   r  x  r  r  c                      s   e Zd Zdddd. fddZd/ddZd0ddZeed0ddZd1ddZ	d0ddZ
d2d!d"Zd3d$d%Zd4d'd(Zd5d*d+Zd3d,d-Z  ZS )6BaseAsyncToolRunnerNrC   rF   rG   rH   r6   rI   Iterable[BetaAsyncRunnableTool]rx   r2   rD   rK   rE   rL   rM   rN   c                  ry   rz   r{   r   r   r?   r@   rd     s   

zBaseAsyncToolRunner.__init__r5   c                   s   | j  I d H S r   )r   	__anext__rs   r?   r?   r@   r    s   zBaseAsyncToolRunner.__anext__AsyncIterator[RunnerItemT]c                 C s"   | j 2 z	3 d H W }|V  q6 d S r   r   r   r?   r?   r@   	__aiter__  s   zBaseAsyncToolRunner.__aiter__c                 C s   t  r   r   rs   r?   r?   r@   r     r   z#BaseAsyncToolRunner._handle_requestrr   c           	        s  | j du s| j d sdS |  I dH }d}|dur0|jj|jjp"d |jjp(d }||jj }| j dt}||k r=dS t	
d| d| d | j d	| jd	 }t| jd
 }|d d dkrzdd |d d D }|rv||d d< n|  g | jd
 td| j dtd}| jjjj||| jd ddidI dH }t	
d|jj  t|jd   jdkrtd|  fdd dS )r   Nr   Fr   r   r   r   r   r   rS   r   rj   r   c                 S  r   r   r   r   r?   r?   r@   rV     r   z:BaseAsyncToolRunner._check_and_compact.<locals>.<listcomp>rk   r   r   ri   r   r   r   r   r   r   r   c                   r   r   r   rm   r   r?   r@   rp     r   z8BaseAsyncToolRunner._check_and_compact.<locals>.<lambda>Tr   r   r?   r   r@   r     s`   





z&BaseAsyncToolRunner._check_and_compactc              	   C s   |   sh|  4 I d H }|V  |  I d H }|d usJ W d   I d H  n1 I d H s.w   Y  |  jd7  _|  I d H s\|  I d H }|d u rStd d S | js\| 	|| d| _d | _
|   rd S d S r   r   r   r?   r?   r@   r~     s$   (
zBaseAsyncToolRunner.__run__r   c                   s.   t | I dH  |  I dH }|dusJ |S r   )r   r   r   r?   r?   r@   r     s
   zBaseAsyncToolRunner.until_doner   c                   s4   | j durtd | j S |  I dH }|| _ |S r   r   r   r?   r?   r@   r     s   

z/BaseAsyncToolRunner.generate_tool_call_responser   c                   s    t | jr|  I d H S | jS r   r   rs   r?   r?   r@   r   .  s   
z%BaseAsyncToolRunner._get_last_messager   c                   s2   |   I d H }|d u s|jdks|jsd S |jS r   r   r   r?   r?   r@   r   3  s
   z7BaseAsyncToolRunner._get_last_assistant_message_contentc                   s`  |   I d H }|sd S dd |D }|sd S g }|D ]}| j|j}|d u rNtjd|j dt| j  dtdd |	d|j
d	|j d
dd qz||jI d H }|	d|j
|d W q ty } z|	d|j
|jdd W Y d }~qd }~w ty } ztjd|j |d |	d|j
t|dd W Y d }~qd }~ww d|dS )Nc                 S  r   r   r   r   r?   r?   r@   rV   ?  r   zDBaseAsyncToolRunner._generate_tool_call_response.<locals>.<listcomp>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   ri   r   r   r?   r?   r@   r   :  sd   

z0BaseAsyncToolRunner._generate_tool_call_response)rF   rG   rH   r6   rI   r  rx   r2   rD   rK   rE   rL   rM   rN   r   )rM   r  ru   r   r   r   r  )r;   r<   r=   rd   r  r  r   r   r   r   r~   r   r   r   r   r   r  r?   r?   r   r@   r    s     




T




r  c                   @  r  )BetaAsyncToolRunnerrM   1AsyncIterator[ParsedBetaMessage[ResponseFormatT]]c                 C s6   | j jjjdi | j| jI d H }|| _|V  d S r  r  r	  r?   r?   r@   r   u  s   $
z#BetaAsyncToolRunner._handle_requestN)rM   r  r;   r<   r=   r   r   r   r?   r?   r?   r@   r  t  r  r  c                   @  r  )BetaAsyncStreamingToolRunnerrM   6AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]c              	   C sh   | j jjjdi | j| j4 I d H }|j| _|V  W d   I d H  d S 1 I d H s-w   Y  d S r  r  r  r?   r?   r@   r   ~  s
   (.z,BetaAsyncStreamingToolRunner._handle_requestN)rM   r  r  r?   r?   r?   r@   r  }  r  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_paramsr/   'types.beta.beta_tool_result_block_paramr0   r}   r1   r2   r3   r5   	getLoggerr;   r   r6   rB   rv   r  r  r  r  r  r?   r?   r?   r@   <module>   sP    4$	
$@ o	
	 t 	