o
    iA                     @  s   d dl mZ d dl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 dd	lmZmZmZmZmZmZ d
dlmZmZ eddG dd dee ZG dd dee ZdS )    )annotations)	AwaitableCallableSequence)	dataclassreplace)Anyoverload)GenerateJsonSchema   )
AgentDepsT
RunContext)	UserError)DocstringFormatGenerateToolJsonSchemaToolToolFuncEither
ToolParamsToolPrepareFunc   )AbstractToolsetToolsetToolT)kw_onlyc                   @  s"   e Zd ZU dZded< ded< dS )FunctionToolsetToolzWA tool definition for a function toolset tool that keeps track of the function to call.zBCallable[[dict[str, Any], RunContext[AgentDepsT]], Awaitable[Any]]	call_funcboolis_asyncN)__name__
__module____qualname____doc____annotations__ r"   r"   c/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/toolsets/function.pyr      s   
 r   c                   @  s  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< g fdddedddddd	dEddZedFddZe	dGd"d#Z
e	dddddddddddd$dHd.d#Z
	dIdddddddddddd$dJd1d#Z
												dKdLd4d5ZdMd8d9ZdNd=d>ZdOdCdDZdS )PFunctionToolsetzA toolset that lets Python functions be used as tools.

    See [toolset docs](../toolsets.md#function-toolset) for more information.
    zdict[str, Tool[Any]]toolsintmax_retries
str | None_idr   docstring_formatr   require_parameter_descriptionstype[GenerateJsonSchema]schema_generatorr   autoFN)	r'   r*   r+   r-   strict
sequentialrequires_approvalmetadataid<Sequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]]r/   bool | Noner0   r1   r2   dict[str, Any] | Noner3   c       	         C  sj   || _ |
| _|| _|| _|| _|| _|| _|| _|	| _i | _	|D ]}t
|tr-| | q | | q dS )aq  Build a new function toolset.

        Args:
            tools: The tools to add to the toolset.
            max_retries: The maximum number of retries for each tool during a run.
                Applies to all tools, unless overridden when adding a tool.
            docstring_format: Format of tool docstring, see [`DocstringFormat`][pydantic_ai.tools.DocstringFormat].
                Defaults to `'auto'`, such that the format is inferred from the structure of the docstring.
                Applies to all tools, unless overridden when adding a tool.
            require_parameter_descriptions: If True, raise an error if a parameter description is missing. Defaults to False.
                Applies to all tools, unless overridden when adding a tool.
            schema_generator: The JSON schema generator class to use for this tool. Defaults to `GenerateToolJsonSchema`.
                Applies to all tools, unless overridden when adding a tool.
            strict: Whether to enforce JSON schema compliance (only affects OpenAI).
                See [`ToolDefinition`][pydantic_ai.tools.ToolDefinition] for more info.
            sequential: Whether the function requires a sequential/serial execution environment. Defaults to False.
                Applies to all tools, unless overridden when adding a tool.
            requires_approval: Whether this tool requires human-in-the-loop approval. Defaults to False.
                See the [tools documentation](../deferred-tools.md#human-in-the-loop-tool-approval) for more info.
                Applies to all tools, unless overridden when adding a tool.
            metadata: Optional metadata for the tool. This is not sent to the model but can be used for filtering and tool behavior customization.
                Applies to all tools, unless overridden when adding a tool, which will be merged with the toolset's metadata.
            id: An optional unique ID for the toolset. A toolset needs to have an ID in order to be used in a durable execution environment like Temporal,
                in which case the ID will be used to identify the toolset's activities within the workflow.
        N)r'   r)   r*   r+   r-   r/   r0   r1   r2   r%   
isinstancer   add_tooladd_function)selfr%   r'   r*   r+   r-   r/   r0   r1   r2   r3   toolr"   r"   r#   __init__+   s   '
zFunctionToolset.__init__returnc                 C  s   | j S N)r)   )r:   r"   r"   r#   r3   c   s   zFunctionToolset.idfunc&ToolFuncEither[AgentDepsT, ToolParams]c                C     d S r>   r"   )r:   r?   r"   r"   r#   r;   g   s   zFunctionToolset.tool)namedescriptionretriespreparer*   r+   r-   r/   r0   r1   r2   rB   rC   rD   
int | NonerE   "ToolPrepareFunc[AgentDepsT] | NoneDocstringFormat | Nonetype[GenerateJsonSchema] | NoneZCallable[[ToolFuncEither[AgentDepsT, ToolParams]], ToolFuncEither[AgentDepsT, ToolParams]]c               C  rA   r>   r"   )r:   rB   rC   rD   rE   r*   r+   r-   r/   r0   r1   r2   r"   r"   r#   r;   j   s   -ToolFuncEither[AgentDepsT, ToolParams] | Noner   c                 s8   d 	
fdd}|du r|S ||S )a  Decorator to register a tool function which takes [`RunContext`][pydantic_ai.tools.RunContext] as its first argument.

        Can decorate a sync or async functions.

        The docstring is inspected to extract both the tool description and description of each parameter,
        [learn more](../tools.md#function-tools-and-schema).

        We can't add overloads for every possible signature of tool, since the return type is a recursive union
        so the signature of functions decorated with `@toolset.tool` is obscured.

        Example:
        ```python
        from pydantic_ai import Agent, FunctionToolset, RunContext

        toolset = FunctionToolset()

        @toolset.tool
        def foobar(ctx: RunContext[int], x: int) -> int:
            return ctx.deps + x

        @toolset.tool(retries=2)
        async def spam(ctx: RunContext[str], y: float) -> float:
            return ctx.deps + y

        agent = Agent('test', toolsets=[toolset], deps_type=int)
        result = agent.run_sync('foobar', deps=1)
        print(result.output)
        #> {"foobar":1,"spam":1.0}
        ```

        Args:
            func: The tool function to register.
            name: The name of the tool, defaults to the function name.
            description: The description of the tool,defaults to the function docstring.
            retries: The number of retries to allow for this tool, defaults to the agent's default retries,
                which defaults to 1.
            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].
            docstring_format: The format of the docstring, see [`DocstringFormat`][pydantic_ai.tools.DocstringFormat].
                If `None`, the default value is determined by the toolset.
            require_parameter_descriptions: If True, raise an error if a parameter description is missing.
                If `None`, the default value is determined by the toolset.
            schema_generator: The JSON schema generator class to use for this tool.
                If `None`, the default value is determined by the toolset.
            strict: Whether to enforce JSON schema compliance (only affects OpenAI).
                See [`ToolDefinition`][pydantic_ai.tools.ToolDefinition] for more info.
                If `None`, the default value is determined by the toolset.
            sequential: Whether the function requires a sequential/serial execution environment. Defaults to False.
                If `None`, the default value is determined by the toolset.
            requires_approval: Whether this tool requires human-in-the-loop approval. Defaults to False.
                See the [tools documentation](../deferred-tools.md#human-in-the-loop-tool-approval) for more info.
                If `None`, the default value is determined by the toolset.
            metadata: Optional metadata for the tool. This is not sent to the model but can be used for filtering and tool behavior customization.
                If `None`, the default value is determined by the toolset. If provided, it will be merged with the toolset's metadata.
        func_r@   r=   c                   s(   	j | d  
d | S )N)r?   	takes_ctxrB   rC   rD   rE   r*   r+   r-   r/   r0   r1   r2   )r9   )rL   rC   r*   r2   rB   rE   r+   r1   rD   r-   r:   r0   r/   r"   r#   tool_decorator   s    z,FunctionToolset.tool.<locals>.tool_decoratorN)rL   r@   r=   r@   r"   )r:   r?   rB   rC   rD   rE   r*   r+   r-   r/   r0   r1   r2   rO   r"   rN   r#   r;   |   s   $JrM   Nonec                 C  s   |du r| j }|du r| j}|	du r| j}	|
du r| j}
|du r#| j}|du r*| j}tt |||||||||	|
|||d}| | dS )ax
  Add a function as a tool to the toolset.

        Can take a sync or async function.

        The docstring is inspected to extract both the tool description and description of each parameter,
        [learn more](../tools.md#function-tools-and-schema).

        Args:
            func: The tool function to register.
            takes_ctx: Whether the function takes a [`RunContext`][pydantic_ai.tools.RunContext] as its first argument. If `None`, this is inferred from the function signature.
            name: The name of the tool, defaults to the function name.
            description: The description of the tool, defaults to the function docstring.
            retries: The number of retries to allow for this tool, defaults to the agent's default retries,
                which defaults to 1.
            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].
            docstring_format: The format of the docstring, see [`DocstringFormat`][pydantic_ai.tools.DocstringFormat].
                If `None`, the default value is determined by the toolset.
            require_parameter_descriptions: If True, raise an error if a parameter description is missing.
                If `None`, the default value is determined by the toolset.
            schema_generator: The JSON schema generator class to use for this tool.
                If `None`, the default value is determined by the toolset.
            strict: Whether to enforce JSON schema compliance (only affects OpenAI).
                See [`ToolDefinition`][pydantic_ai.tools.ToolDefinition] for more info.
                If `None`, the default value is determined by the toolset.
            sequential: Whether the function requires a sequential/serial execution environment. Defaults to False.
                If `None`, the default value is determined by the toolset.
            requires_approval: Whether this tool requires human-in-the-loop approval. Defaults to False.
                See the [tools documentation](../deferred-tools.md#human-in-the-loop-tool-approval) for more info.
                If `None`, the default value is determined by the toolset.
            metadata: Optional metadata for the tool. This is not sent to the model but can be used for filtering and tool behavior customization.
                If `None`, the default value is determined by the toolset. If provided, it will be merged with the toolset's metadata.
        N)rM   rB   rC   r'   rE   r*   r+   r-   r/   r0   r1   r2   )	r*   r+   r-   r/   r0   r1   r   r   r8   )r:   r?   rM   rB   rC   rD   rE   r*   r+   r-   r/   r0   r1   r2   r;   r"   r"   r#   r9      s8   2zFunctionToolset.add_functionr;   Tool[AgentDepsT]c                 C  sZ   |j | jv rtd|j |jdu r| j|_| jdur%| j|jp"i B |_|| j|j < dS )zUAdd a tool to the toolset.

        Args:
            tool: The tool to add.
        z(Tool name conflicts with existing tool: N)rB   r%   r   r'   r2   )r:   r;   r"   r"   r#   r8   -  s   

zFunctionToolset.add_toolctxRunContext[AgentDepsT]"dict[str, ToolsetTool[AgentDepsT]]c           	   	     s   i }| j  D ]W\}}|jd ur|jn| j}t|||j|d|d}||I d H }|s/q|j}||v rM||krEtd|d|dtd|dt	| |||j
j|j
j|j
jd||< q|S )	Nr   )	tool_nameretryr'   zRenaming tool z to z conflicts with existing tool.z2Tool name conflicts with previously renamed tool: .)toolsettool_defr'   args_validatorr   r   )r%   itemsr'   r   rD   getprepare_tool_defrB   r   r   function_schema	validatorcallr   )	r:   rR   r%   original_namer;   r'   run_contextrY   new_namer"   r"   r#   	get_tools;  s6   zFunctionToolset.get_toolsstr	tool_argsdict[str, Any]ToolsetTool[AgentDepsT]c                   s"   t |tsJ |||I d H S r>   )r7   r   r   )r:   rB   rf   rR   r;   r"   r"   r#   	call_toolZ  s   zFunctionToolset.call_tool)r%   r4   r'   r&   r*   r   r+   r   r-   r,   r/   r5   r0   r   r1   r   r2   r6   r3   r(   )r=   r(   )r?   r@   r=   r@   )rB   r(   rC   r(   rD   rF   rE   rG   r*   rH   r+   r5   r-   rI   r/   r5   r0   r5   r1   r5   r2   r6   r=   rJ   r>   )r?   rK   rB   r(   rC   r(   rD   rF   rE   rG   r*   rH   r+   r5   r-   rI   r/   r5   r0   r5   r1   r5   r2   r6   r=   r   )NNNNNNNNNNNN)r?   r@   rM   r5   rB   r(   rC   r(   rD   rF   rE   rG   r*   rH   r+   r5   r-   rI   r/   r5   r0   r5   r1   r5   r2   r6   r=   rP   )r;   rQ   r=   rP   )rR   rS   r=   rT   )
rB   re   rf   rg   rR   rS   r;   rh   r=   r   )r   r   r   r    r!   r   r<   propertyr3   r	   r;   r9   r8   rd   ri   r"   r"   r"   r#   r$      s   
 8d
P
r$   N)
__future__r   collections.abcr   r   r   dataclassesr   r   typingr   r	   pydantic.json_schemar
   _run_contextr   r   
exceptionsr   r%   r   r   r   r   r   r   abstractr   r   r   r$   r"   r"   r"   r#   <module>   s     