
    g-                    d   U d dl mZ d dlZd dl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mZ d dlmZ d dlmZ d dlmZmZmZmZ d	d
lmZmZmZmZ d	dlm Z m!Z! e
rd	dl"m#Z# dZ$ edd      Z%	 ej                   G d dee%                Z& edd      Z'	 eee&e%   ge(f   ee&e%   gee(   f   eg e(f   eg ee(   f   f   Z)	 eee&e%   e'f   ef   Z*	 ee'ef   Z+	 ee*e%e'f   e+e'   f   Z,	 dZ-de.d<   	  ed      Z/ ed       G d dee%                Z0e1e(ef   Z2de.d<   	 e G d d             Z3y)    )annotationsN)	Awaitable)	dataclassfield)TYPE_CHECKINGAnyCallableGenericUnioncast)ValidationError)SchemaValidator)Concatenate	ParamSpec	TypeAliasTypeVar   )	_pydantic_utilsmessagesmodels)
ModelRetryUnexpectedModelBehavior)Usage)	AgentDeps
RunContextSystemPromptFuncToolFuncContextToolFuncPlainToolFuncEither
ToolParamsToolPrepareFuncToolObjectJsonSchemaToolDefinitionr   )defaultc                      e Zd ZU dZded<   	 ded<   	 ded<   	 ded	<   	  ee
      Zded<   	 dZded<   	 dZ	ded<   	 dZ
ded<   	 dej                  f	 	 	 	 	 ddZy)r   z#Information about the current call.r   depszmodels.Modelmodelr   usagestrprompt)default_factoryzlist[_messages.ModelMessage]r   N
str | None	tool_namer   intretryrun_stepc                n    i }|||d<   |t         j                  ur||d<   t        j                  | fi |S )Nr1   r/   )r   UNSETdataclassesreplace)selfr1   r/   kwargss       F/var/www/openai/venv/lib/python3.12/site-packages/pydantic_ai/tools.pyreplace_withzRunContext.replace_with:   sD     #F7OFLL("+F;""42622    )r1   
int | Noner/   zstr | None | _utils.UnsetreturnRunContext[AgentDeps])__name__
__module____qualname____doc____annotations__r   listr   r/   r1   r2   r   r4   r:    r;   r9   r   r   %   s    -
O%%L,K5-24-HH*H8 Iz (E3N#Hc& #'v||	3	33L	3		3r;   r   r!   .zSCallable[[RunContext[AgentDeps], ToolDefinition], Awaitable[ToolDefinition | None]]r   r"   AFinitc                     e Zd ZU dZded<   ded<   ded<   ded	<   ded
<   ded<    ed      Zded<    ed      Zded<    ed      Zded<    ed      Z	ded<    edd      Z
ded<    ed      Zded<    edd      Zded<   dddddd	 	 	 	 	 	 	 	 	 	 	 d%d Zd&d!Z	 	 	 	 	 	 d'd"Z	 	 	 	 	 	 	 	 d(d#Z	 	 	 	 	 	 d)d$Zy)*r#   zA tool function for an agent.ToolFuncEither[AgentDeps]functionbool	takes_ctxr<   max_retriesr+   namedescription!ToolPrepareFunc[AgentDeps] | NoneprepareFrG   	_is_asyncr.   _single_arg_namez	list[str]_positional_fields_var_positional_field)rH   reprr   
_validatorr$   _parameters_json_schemar   )r&   rH   r0   current_retryN)rM   rN   rO   rP   rR   c                  |t        j                  |      }t        j                  ||      }|| _        || _        || _        |xs |j
                  | _        |xs |d   | _        || _        t        j                  | j                        | _        |d   | _        |d   | _        |d   | _        |d   | _        |d   | _        y)a0  Create a new tool instance.

        Example usage:

        ```python {lint="not-imports"}
        from pydantic_ai import Agent, RunContext, Tool

        async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
            return f'{ctx.deps} {x} {y}'

        agent = Agent('test', tools=[Tool(my_tool)])
        ```

        or with a custom prepare method:

        ```python {lint="not-imports"}
        from typing import Union

        from pydantic_ai import Agent, RunContext, Tool
        from pydantic_ai.tools import ToolDefinition

        async def my_tool(ctx: RunContext[int], x: int, y: int) -> str:
            return f'{ctx.deps} {x} {y}'

        async def prep_my_tool(
            ctx: RunContext[int], tool_def: ToolDefinition
        ) -> Union[ToolDefinition, None]:
            # only register the tool if `deps == 42`
            if ctx.deps == 42:
                return tool_def

        agent = Agent('test', tools=[Tool(my_tool, prepare=prep_my_tool)])
        ```


        Args:
            function: The Python function to call as the tool.
            takes_ctx: Whether the function takes a [`RunContext`][pydantic_ai.tools.RunContext] first argument,
                this is inferred if unset.
            max_retries: Maximum number of retries allowed for this tool, set to the agent default if `None`.
            name: Name of the tool, inferred from the function if `None`.
            description: Description of the tool, inferred from the function if `None`.
            prepare: custom method to prepare the tool definition for each step, return `None` to omit this
                tool from a given step. This is useful if you want to customise a tool at call time,
                or omit it completely from a step. See [`ToolPrepareFunc`][pydantic_ai.tools.ToolPrepareFunc].
        NrP   single_arg_namepositional_fieldsvar_positional_field	validatorjson_schema)r   rM   function_schemarK   rN   r?   rO   rP   rR   inspectiscoroutinefunctionrS   rT   rU   rV   rX   rY   )r7   rK   rM   rN   rO   rP   rR   fs           r9   __init__zTool.__init__   s    p !++H5I%%h	: "&-H--	&:!M*: 44T]]C !"3 4"#$7"8%&'=%>"K.'('7$r;   c                   K   t        | j                  | j                  | j                        }| j                  | j	                  ||       d{   S |S 7 w)a  Get the tool definition.

        By default, this method creates a tool definition, then either returns it, or calls `self.prepare`
        if it's set.

        Returns:
            return a `ToolDefinition` or `None` if the tools should not be registered for this run.
        )rO   rP   parameters_json_schemaN)r%   rO   rP   rY   rR   )r7   ctxtool_defs      r9   prepare_tool_defzTool.prepare_tool_def   sU      "((#'#?#?

 <<#c8444O 5s   AAAAc                x  K   	 t        |j                  t        j                        r0| j                  j                  |j                  j                        }n/| j                  j                  |j                  j                        }| j                  |||      \  }}	 | j                  r@t        t        t        gt         t"           f   | j$                        } ||i | d{   }nIt        t        t        gt"        f   | j$                        }t'        j(                  |g|i | d{   }d| _        t        j.                  |j0                  ||j2                        S # t        $ r}| j                  ||      cY d}~S d}~ww xY w7 7 a# t*        $ r}| j                  ||      cY d}~S d}~ww xY ww)z%Run the tool function asynchronously.Nr   r/   contenttool_call_id)
isinstanceargs	_messagesArgsJsonrX   validate_json	args_jsonvalidate_python	args_dictr   	_on_error
_call_argsrS   r   r	   r   r   r+   rK   r   run_in_executorr   rZ   ToolReturnPartr/   rn   )	r7   messagerun_contextrv   erp   r8   rK   response_contents	            r9   runzTool.run   sn    	.',,	(:(:; OO99',,:P:PQ	 OO;;GLL<R<RS	 y';Gf	.~~#	#)> ?O)14)B6)B#B # 4dmmD)/)?)?)Z4)ZSY)Z#Z  ''''$ --
 	
  	.>>!W--	. $C $[ 	.>>!W--	.s   F:BE& F:AF $F%A	F .F/F 33F:&	F/F FF:FF:F F 	F7F2,F7-F:2F77F:c                   | j                   r| j                   |i}t        j                  || j                  |j                        }| j
                  r|gng }| j                  D ]"  }|j                  |j                  |             $ | j                  r*|j                  |j                  | j                               ||fS )N)r1   r/   )rT   r5   r6   rZ   r/   rM   rU   appendpoprV   extend)r7   rv   r{   r|   rh   rp   positional_fields          r9   rx   zTool._call_args  s       ..	:I!!+T5G5GSZSdSdeuB $ 7 7KK	&678 !8%%KK	d&@&@ABYr;   c                ^   | xj                   dz  c_         | j                  | j                   | j                  kD  rt        d| j                         |t        |t              r|j                  d      }n|j                  }t        j                  |j                  ||j                        S )Nr   z#Tool exceeded max retries count of F)include_urlrl   )rZ   rN   r   ro   r   errorsr{   rq   RetryPromptPartr/   rn   )r7   exccall_messagerm   s       r9   rw   zTool._on_error#  s     	a#t'9'9D<L<L'L),OPTP`P`Oa*bcill#/***7++,,&00)66 r;   )rK   rJ   rM   zbool | NonerN   r<   rO   r.   rP   r.   rR   rQ   )rh   r>   r=   zToolDefinition | None)r{   _messages.ToolCallPartr|   r>   r=   z_messages.ModelRequestPart)rv   zdict[str, Any]r{   r   r|   r>   r=   z tuple[list[Any], dict[str, Any]])r   zValidationError | ModelRetryr   r   r=   z_messages.RetryPromptPart)r?   r@   rA   rB   rC   r   rS   rT   rU   rV   rX   rY   rZ   re   rj   r   rx   rw   rE   r;   r9   r#   r#      s[   '''O
I..'It'#(e#4j4$)u$5	5(-5(9:9"'U"?J?0550A-Aqu5M35 "&"&"&59G8+G8 	G8
  G8 G8  G8 3G8R&
-
<Q
	#
<! ( +	
 
*$/?U	"r;   r#   r$   c                  D    e Zd ZU dZded<   	 ded<   	 ded<   	 dZded	<   y)
r%   zdDefinition of a tool passed to a model.

    This is used for both function tools result tools.
    r+   rO   rP   r$   rg   Nr.   outer_typed_dict_key)r?   r@   rA   rB   rC   r   rE   r;   r9   r%   r%   >  s3    
 I&,,4'+*+r;   r%   )4
__future__r   _annotationsr5   rb   collections.abcr   r   r   typingr   r   r	   r
   r   r   pydanticr   pydantic_corer   typing_extensionsr   r   r   r    r   r   r   rq   r   
exceptionsr   r   resultr   __all__r   r   r!   r+   r   r   r   r    r"   rC   rF   r#   dictr$   r%   rE   r;   r9   <module>r      s   2   % ( E E $ ) H H > > ; K.	 + 3# 3 3@ |S1
 $j#$c)*j#$in45RWR3 " 
 ;z)'<j'HI3NO S) y*'<=}Z?XXY s r6 CL l79 l l^ #38n ) ,   r;   