
    Áj\                       U 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 d dlmZmZmZmZ d dlmZ d dlmZmZmZ d dlZd dlZd dlZd dlmZ d	d
l m!Z! d	dl"m#Z# d	dl!m$Z$ d	dl%m&Z& d	dl'm(Z(m)Z)m*Z* d	dl+m,Z, d	dl-m.Z. d	dl/m0Z1  ejd                  e3      Z4e	e5ee1   f   Z6de7d<    G d de8      Z9ede6f   Z: ede:      Z;edeeee6f   f   Z< ede<      Z= G d de      Z> G d de      Z? G d de
e,         Z@ G d  d!e@e;         ZA G d" d#e@e=         ZBd0d$ZCd0d%ZDd1d&ZEed2d'       ZFedddddddddd(		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d3d)       ZFedddddddddd(		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d4d*       ZF	 d5dddddddddd(		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d6d+ZFed7d,       ZGedddddddddd(		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d8d-       ZGedddddddddd(		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d9d.       ZG	 d5dddddddddd(		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d:d/ZGe	eAe   e>f   ZHe	eBe   e?f   ZIy);    )annotationsN)ABCabstractmethod)	AnyUnionGenericTypeVarCallableIterable	Coroutinecastoverload)isawaitableisasyncgenfunctioniscoroutinefunctionisgeneratorfunction)	Awaitable)Literal	TypeAliasoverride)	BaseModel   )_compat)is_dict)cached_property)TypeAdapter)BetaToolParamBetaToolUnionParamBetaCacheControlEphemeralParam)	CallableT)InputSchema)Contentr   BetaFunctionToolResultTypec                  0     e Zd ZU dZded<   d fdZ xZS )	ToolErrora  Error that can be raised from a tool to return structured content with ``is_error: True``.

    When the tool runner catches this error, it will use the :attr:`content`
    property as the tool result instead of ``repr(exc)``.

    Example::

        raise ToolError(
            [
                {"type": "text", "text": "Error details here"},
                {"type": "image", "source": {"type": "base64", "data": "...", "media_type": "image/png"}},
            ]
        )
    r#   contentc                :   t        |t              r|}nqg }|D ]U  }|j                  d      }||j                  t        |             1|j                  d|j                  dd       d       W |rdj	                  |      nd}t
        |   |       || _        y )Ntext[typeunknown] z
Tool error)
isinstancestrgetappendjoinsuper__init__r&   )selfr&   messagepartsblockr(   	__class__s         J/tmp/pip-target-k_scjv0h/lib/python/anthropic/lib/tools/_beta_functions.pyr4   zToolError.__init__0   s    gs#G!E  Fyy(#LLT+LL1UYYvy%A$B!!DEF */chhuoLG!    )r&   r#   returnNone)__name__
__module____qualname____doc____annotations__r4   __classcell__r9   s   @r:   r%   r%      s     (' r;   r%   .	FunctionT)boundAsyncFunctionTc                  B    e Zd Zedd       Zedd       Zedd       Zy)BetaBuiltinFunctionToolc                     y N r5   s    r:   to_dictzBetaBuiltinFunctionTool.to_dictH       -0r;   c                     y rK   rL   r5   inputs     r:   callzBetaBuiltinFunctionTool.callK   s    ADr;   c                >    | j                         }d|v r|d   S |d   S Nmcp_server_namenamerN   r5   raws     r:   rW   zBetaBuiltinFunctionTool.nameN   +    lln#())6{r;   Nr<   r   rR   objectr<   r#   r<   r/   r>   r?   r@   r   rN   rS   propertyrW   rL   r;   r:   rI   rI   G   s0    0 0D D r;   rI   c                  B    e Zd Zedd       Zedd       Zedd       Zy)BetaAsyncBuiltinFunctionToolc                     y rK   rL   rM   s    r:   rN   z$BetaAsyncBuiltinFunctionTool.to_dictW   rO   r;   c                   K   y wrK   rL   rQ   s     r:   rS   z!BetaAsyncBuiltinFunctionTool.callZ   s	     GJs   c                >    | j                         }d|v r|d   S |d   S rU   rX   rY   s     r:   rW   z!BetaAsyncBuiltinFunctionTool.name]   r[   r;   Nr\   r]   r_   r`   rL   r;   r:   rc   rc   V   s0    0 0J J r;   rc   c            
          e Zd ZU ded<   	 ded<   	 ded<   ded<   dZd	ed
<   	 dZded<   	 dddddddddd		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       ZddZ	e
dd       ZddZddZe
dd       Zy)BaseFunctionToolr    funcr/   rW   descriptionr!   input_schemaNz+Callable[[], None | Awaitable[None]] | Noneclosezobject | None_context_manager	rW   rj   rk   defer_loadingcache_controlallowed_callerseager_input_streaminginput_examplesstrictc       	           t         j                  rt        d      || _        t	        j
                  |      | _        |xs |j                  | _        || _	        || _
        || _        || _        |	| _        |
| _        |xs | j                         | _        |.t#        |t$              r|j'                         | _        y || _        y | j+                         | _        y )N2Tool functions are only supported with Pydantic v2)r   PYDANTIC_V1RuntimeErrorri   pydanticvalidate_call_func_with_validater>   rW   _defer_loading_cache_control_allowed_callers_eager_input_streaming_input_examples_strict_get_description_from_docstringrj   r.   r*   model_json_schemark   _create_schema_from_function)r5   ri   rW   rj   rk   ro   rp   rq   rr   rs   rt   s              r:   r4   zBaseFunctionTool.__init__   s    " STT	#+#9#9$#? )DMM	++ /&;#-&P$*N*N*P#,-1=1O1O1Q!$0! $ A A CDr;   c                    | j                   S rK   ri   rM   s    r:   __call__zBaseFunctionTool.__call__   s    yyr;   c                   | j                   | j                  | j                  d}| j                  | j                  |d<   | j                  | j                  |d<   | j
                  | j
                  |d<   | j                  | j                  |d<   | j                  | j                  |d<   | j                  | j                  |d<   |S )N)rW   rj   rk   ro   rp   rq   rr   rs   rt   )	rW   rj   rk   r|   r}   r~   r   r   r   )r5   defns     r:   rN   zBaseFunctionTool.to_dict   s    II++ --

 *$($7$7D!*$($7$7D!  ,&*&;&;D"#&&2,0,G,GD()+%)%9%9D!"<<#!\\DNr;   c                \    t        j                  | j                  j                  xs d      S )N )docstring_parserparseri   rA   rM   s    r:   _parsed_docstringz"BaseFunctionTool._parsed_docstring   s"    %%dii&7&7&=2>>r;   c                    | j                   j                  rJ| j                   j                  }| j                   j                  r|d| j                   j                   z  }|S y)z*Extract description from parsed docstring.z

r   )r   short_descriptionlong_description)r5   rj   s     r:   r   z0BaseFunctionTool._get_description_from_docstring   sX    !!3300BBK%%66d&<&<&M&M%NOOr;   c                    ddl m} ddlm}m} ddlm}  G d d|      } || j                  | j                        }| j                  j                  |      S )	z:Create JSON schema from function signature using pydantic.r   )
CoreSchema)JsonSchemaValueGenerateJsonSchema)ArgumentsParameterc                  J     e Zd Zd fdZddZe	 	 	 	 	 	 d fd       Z xZS )OBaseFunctionTool._create_schema_from_function.<locals>.CustomGenerateJsonSchemac               >    t         |           || _        || _        y rK   )r3   r4   _funcr   )r5   ri   parsed_docstringr9   s      r:   r4   zXBaseFunctionTool._create_schema_from_function.<locals>.CustomGenerateJsonSchema.__init__   s     "!
)9&r;   c                    | S rK   rL   )r5   _args_kwdss      r:   r   zXBaseFunctionTool._create_schema_from_function.<locals>.CustomGenerateJsonSchema.__call__   s    r;   c                ^   t         |   ||      }|j                  d      dk7  r|S |j                  d      }|rt        |      s|S | j                  j
                  D ]L  }|j                  |j                        }|rt        |      s,|j                  s9d|vs>|j                  |d<   N |S )Nr*   r^   
propertiesrj   )r3   kw_arguments_schemar0   r   r   paramsarg_namerj   )r5   	argumentsvar_kwargs_schemaschemar   paramprop_schemar9   s          r:   r   zcBaseFunctionTool._create_schema_from_function.<locals>.CustomGenerateJsonSchema.kw_arguments_schema   s     4Y@QR::f%1!M#ZZ5
!)<!M "33:: GE",.."@K&gk.B ((]+-M5:5F5FM2G r;   )ri   zCallable[..., Any]r   r   r<   r=   )r   r   r   r   r<   z'CustomGenerateJsonSchema')r   z'list[ArgumentsParameter]'r   zCoreSchema | Noner<   r   )r>   r?   r@   r4   r   r   r   rC   rD   s   @r:   CustomGenerateJsonSchemar      s=    :
 5 $5 !	 r;   r   )ri   r   )schema_generator)pydantic_corer   pydantic.json_schemar   r   pydantic_core.core_schemar   ri   r   _adapterjson_schema)r5   r   r   r   r   r   r   s          r:   r   z-BaseFunctionTool._create_schema_from_function   sN     	-L@ 	'9  	D 4UYUkUkl}}((:J(KKr;   c                ,    t        | j                        S rK   )r   r{   rM   s    r:   r   zBaseFunctionTool._adapter  s    43344r;   )ri   r    rW   
str | Nonerj   r   rk   $InputSchema | type[BaseModel] | Nonero   bool | Nonerp   %BetaCacheControlEphemeralParam | Nonerq   olist[Literal['direct', 'code_execution_20250825', 'code_execution_20260120', 'code_execution_20260521']] | Nonerr   r   rs   "Iterable[dict[str, object]] | Nonert   r   r<   r=   )r<   r    )r<   r   )r<   zdocstring_parser.Docstringr_   )r<   r!   )r<   zTypeAdapter[Any])r>   r?   r@   rB   rl   rm   r4   ra   r   rN   r   r   r   r   r   rL   r;   r:   rh   rh   e   s*   
O,
I;9=E6=$ '+m*  "&=A%)?C -1=A"&D&D 	&D
  &D ;&D #&D =&D&D  +&D ;&D &D  
!&DP  ( ? ?*LX 5 5r;   rh   c                      e Zd ZddZy)BetaFunctionToolc                D   t        | j                        rt        d      t        |      s!t	        dt        |      j                         	  | j                  di t        t        |      S # t        j                  $ r}t        d| j                         |d }~ww xY w)NzJCannot call a coroutine function synchronously. Use `@async_tool` instead. Input must be a dictionary, got Invalid arguments for function rL   r   ri   rx   r   	TypeErrorr*   r>   r{   r   r   ry   ValidationError
ValueErrorrW   r5   rR   es      r:   rS   zBetaFunctionTool.call
  s    tyy)kllu~>tE{?S?S>TUVV	S+4++?d3.>??'' 	S>tyykJKQRR	Ss   A. .BBBNr]   r>   r?   r@   rS   rL   r;   r:   r   r   	      
Sr;   r   c                      e Zd ZddZy)BetaAsyncFunctionToolc                `  K   t        | j                        st        d      t        |      s!t	        dt        |      j                         	  | j                  di t        t        |       d {   S 7 # t        j                  $ r}t        d| j                         |d }~ww xY ww)NzGCannot call a synchronous function asynchronously. Use `@tool` instead.r   r   rL   r   r   s      r:   rS   zBetaAsyncFunctionTool.call  s     "499-hiiu~>tE{?S?S>TUVV	S111EDe4DEEEE'' 	S>tyykJKQRR	Ss<   AB.#A: 3A84A: 7B.8A: :B+B&&B++B.Nr]   r   rL   r;   r:   r   r     r   r;   r   c                >    t        | dd      }|duxr t        |      S )u  True when ``fn`` is a function produced by :func:`contextlib.contextmanager`.

    ``contextmanager`` wraps the generator function with ``functools.wraps``, so
    the original generator function is reachable as ``__wrapped__`` — the same
    signal :mod:`inspect` itself uses. We never call ``fn`` to find out, so a
    plain tool function is never accidentally invoked during detection.
    __wrapped__N)getattrr   fnwrappeds     r:   _is_sync_cm_factoryr   %  s(     b-.G$?#6w#??r;   c                >    t        | dd      }|duxr t        |      S )zRTrue when ``fn`` is a function produced by :func:`contextlib.asynccontextmanager`.r   N)r   r   r   s     r:   _is_async_cm_factoryr   1  s&    b-.G$>#5g#>>r;   c           	       K   t        | dd      xs t        | dd      }|	  |       }t        |      r
| d{    t        | dd      }|7	 t        |dd      }| |ddd       d{    y|j                  ddd       yy7 K# t        $ r,}t        j	                  dt        | dd      |       Y d}~yd}~ww xY w7 T# t        $ r,}t        j	                  d	t        | dd      |       Y d}~yd}~ww xY ww)
u  Run a runnable tool's optional cleanup.

    Drives the legacy ``aclose`` / ``close`` attribute (awaited if it returns an
    awaitable) and, when the tool was defined as a context manager via
    :func:`beta_tool` / :func:`beta_async_tool`, its ``__exit__`` /
    ``__aexit__``. Both run when both are present — the context-manager support
    is purely additive to ``close``. Exceptions are logged, never raised, so one
    tool's bad cleanup can't abort another tool's.
    acloseNrl   z"tool.close failed tool=%s error=%srW   ?rm   	__aexit__z4tool context-manager cleanup failed tool=%s error=%s)r   r   	Exceptionlogwarning__exit__)toolcloserresultr   cmaexits         r:   aclose_runnable_toolr   7  s     T8T*JgdGT.JF	]XF6" 
)4	0B	~	oBT2E D$---D$-   	]KK<gdFTW>XZ[\\	] .  	oKKNPWX\^dfiPjlmnn	os   C9B BB C9C *B?+C /C90C C9B 	B<"B72C97B<<C9?C 	C6
"C1,C91C66C9c                     y rK   rL   r   s    r:   	beta_toolr   V  s    ?Br;   rn   c       	             y rK   rL   
ri   rW   rj   rk   ro   rp   rq   rr   rs   rt   s
             r:   r   r   Z  s      #&r;   c        	             y rK   rL   rn   s	            r:   r   r   m  s     :=r;   c       	   
     ~   	 t         j                  rt        d      d	f	d}
|  |
|       S |
S )aF  Create a FunctionTool from a function with automatic schema inference.

    Can be used as a decorator with or without parentheses:

    @function_tool
    def my_func(x: int) -> str: ...

    @function_tool()
    def my_func(x: int) -> str: ...

    @function_tool(name="custom_name")
    def my_func(x: int) -> str: ...
    rv   c                r  	 t        |       rt        d      t        |       rR t        t        |              }|j                         }	 t        t        t        |      
	
      }||_        |S t        | 
	
      S # t        $ r#  |j                  t        j                            w xY w)Nzi@beta_tool was applied to an @asynccontextmanager; use @beta_async_tool for an async context-manager toolrn   )r   r   r   r   r   	__enter__r   rE   BaseExceptionr   sysexc_inform   )r   r   innerr   rq   rp   ro   rj   rr   rs   rk   rW   rt   s       r:   _makezbeta_tool.<locals>._make  s    #I  r"
 c2BLLNE'E* +!-"/"/$3*?#1!" %'D!K#%''+"7)
 	
 !  S\\^,	s   	#B
 
,B6)r   rE   r<   BetaFunctionTool[FunctionT]r   rw   rx   ri   rW   rj   rk   ro   rp   rq   rr   rs   rt   r   s    ````````` r:   r   r     s=    : OPP,
 ,
\ T{Lr;   c                     y rK   rL   r   s    r:   beta_async_toolr     s    TWr;   c       	             y rK   rL   r   s
             r:   r   r     s      -0r;   c        	             y rK   rL   rn   s	            r:   r   r     s	     ILr;   c       	   
     ~   	 t         j                  rt        d      d	f	d}
|  |
|       S |
S )aU  Create an AsyncFunctionTool from a function with automatic schema inference.

    Can be used as a decorator with or without parentheses:

    @async_tool
    async def my_func(x: int) -> str: ...

    @async_tool()
    async def my_func(x: int) -> str: ...

    @async_tool(name="custom_name")
    async def my_func(x: int) -> str: ...
    rv   c                  	 t        |       rt        d      t        |       rt        d       t        t        |              d ddt        j                         g dfddfd}xs t        | dd      |_        nt        | d	d       |_	        t        t        t        |      
	

      }j                  |       |S t        | 
	

      S )Nza@beta_async_tool was applied to a @contextmanager; use @beta_tool for a sync context-manager toolzan @asynccontextmanager tool needs an explicit input_schema= (its parameters can't be inferred until the context manager is entered)F)	validatedenteredc                 &  K   d   sd4 d {    d   s?j                          d {   } t        j                  |       d<   dd<   d   _        d d d       d {    d   S d   S 7 b7 G7 # 1 d {  7  sw Y   d   S xY ww)Nr   r   Tr   )
__aenter__ry   rz   rm   )r   r   
enter_lockstatetool_boxs    r:   _enteredz0beta_async_tool.<locals>._make.<locals>._entered1  s     Y') > >$Y/*,--/$9E191G1G1NE+./3E), <>HQK8> > [))u[))>$9> > > > [))sT   BA2BA8A4+A8B#A6$B4A86B8B>B?BBc                 n   K            d {   }t        t         |di |  d {         S 7 "7 
w)NrL   )r   r#   )kwargsr   r   s     r:   _lazyz-beta_async_tool.<locals>._make.<locals>._lazy=  s3     "**,	6i>Q&>Q8QRR -8Qs   5153
	55r>   r   rA   rn   )r<   r   )r   r   r<   r#   )r   r   r   r   r   anyioLockr   r>   rA   r   rG   r1   )r   r   r   r   r   r   r   r   rq   rp   ro   rj   rr   rs   rk   rW   rt   s      @@@@@r:   r   zbeta_async_tool.<locals>._make  s   r"s   # #^  c2B265$IEJDFH
* 
*S "DWRV%DEN+6+BKPRT]_cHdEM(^U+')++ /&;-D OOD!K$#%''+"7)
 	
r;   )r   rG   r<   %BetaAsyncFunctionTool[AsyncFunctionT]r   r   s    ````````` r:   r   r     s?    : OPP@
 @
D T{Lr;   )r   r^   r<   bool)r   r^   r<   r=   )ri   rE   r<   r   )ri   rE   rW   r   rj   r   rk   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   r<   r   )rW   r   rj   r   rk   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   r<   z2Callable[[FunctionT], BetaFunctionTool[FunctionT]]rK   )ri   zFunctionT | NonerW   r   rj   r   rk   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   r<   zPBetaFunctionTool[FunctionT] | Callable[[FunctionT], BetaFunctionTool[FunctionT]])ri   rG   r<   r  )ri   rG   rW   r   rj   r   rk   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   r<   r  )rW   r   rj   r   rk   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   r<   zACallable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]])ri   zAsyncFunctionT | NonerW   r   rj   r   rk   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   r<   ziBetaAsyncFunctionTool[AsyncFunctionT] | Callable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]])J
__future__r   r   loggingabcr   r   typingr   r   r   r	   r
   r   r   r   r   inspectr   r   r   r   collections.abcr   typing_extensionsr   r   r   r   ry   r   r   r   r   _utilsr   r   _modelsr   
types.betar   r   r   _utils._utilsr    types.tool_paramr!   'types.beta.beta_tool_result_block_paramr"   BetaContent	getLoggerr>   r   r/   r#   rB   r   r%   FunctionrE   AsyncFunctionrG   rI   rc   rh   r   r   r   r   r   r   r   BetaRunnableToolBetaAsyncRunnableToolrL   r;   r:   <module>r     sL   " 
  # ^ ^ ^ ] ] % : :       & " [ [ & + Mg!(-c8K3H.H(I I I	 D C334Kx0	iS2L(LMMN)?c 3 a5wy) a5HS'	2 SS,^< S	@?o> 
 B 
 B 
 "9=!%;? )-9=&
& & 	&
 7& & 9&& '& 7& & !& 
&$ 
 "9=!%;? )-9==
= = 7	=
 = 9== '= 7= = 8= 
=$ "Q "9=!%;? )-9=Q
Q Q 	Q
 7Q Q 9QQ 'Q 7Q Q VQh 
 W 
 W 
 "9=!%;? )-9=0
0 0 	0
 70 0 900 '0 70 0 +0 
0$ 
 "9=!%;? )-9=L
L L 7	L
 L 9LL 'L 7L L GL 
L$ #'e "9=!%;? )-9=e
e e 	e
 7e e 9ee 'e 7e e oeP )#.0GGH 3C8:VVW r;   