o
    iO                     @  sL  U d dl mZ d dlmZmZmZ d dlmZ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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 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*m+Z+ dZ,edddZ-	 ee%e$ ge.f ee%e$ gee. f B eg e.f B eg ee. f B Z/de0d< 	 eee%e$ e-f ef Z1de0d< 	 ee-ef Z2de0d< 	 e1e$e-f e2e- B Z3de0d< 	 ee%e$ dged f Z4de0d< 	 ee%e$ e5d ged f Z6de0d< 	 ed Z7de0d< 	 e	ddG d d! d!Z8e	ddG d"d# d#Z9e	G d$d% d%Z:dCd*d+Z;ee9e:B ed,f Z<de0d-< 	 eee+ed.f ee'ed/f B ee)ed0f B ee;f Z=de0d1< 	 e<e=B Z>	 e	ddG d2d3 d3Z?ed4Z@G d5d6 d6eZAed7eBdd8ZC	 e	d9d:G d;d< d<eeC ZDeEe.ef ZFde0d=< 	 ed> ZGde0d?< 	 e	d9dd@G dAd dZHdBS )D    )annotations)	AwaitableCallableSequence)KW_ONLY	dataclassfield)	AnnotatedAnyConcatenateGenericLiteral	TypeAliascast)DiscriminatorTag)GenerateJsonSchemaJsonSchemaValue)SchemaValidatorcore_schema)	ParamSpecSelfTypeVar   )_function_schema_utils)
AgentDepsT
RunContext)
ModelRetry)RetryPromptPartToolCallPart
ToolReturn)r   DocstringFormatr   SystemPromptFuncToolFuncContextToolFuncPlainToolFuncEither
ToolParamsToolPrepareFuncToolsPrepareFuncToolObjectJsonSchemaToolDefinitionDeferredToolRequestsDeferredToolResultsToolApproved
ToolDeniedr'   .defaultr   r#   r$   r%   r&   r,   ToolDefinition | Noner(   zlist[ToolDefinition] | Noner)   )googlenumpysphinxautor"   T)kw_onlyc                   @  s8   e Zd ZU dZeedZded< 	 eedZded< dS )r-   a  Tool calls that require approval or external execution.

    This can be used as an agent's `output_type` and will be used as the output of the agent run if the model called any deferred tools.

    Results can be passed to the next agent run using a [`DeferredToolResults`][pydantic_ai.tools.DeferredToolResults] object with the same tool call IDs.

    See [deferred tools docs](../deferred-tools.md#deferred-tools) for more information.
    default_factoryzlist[ToolCallPart]calls	approvalsN)	__name__
__module____qualname____doc__r   listr;   __annotations__r<    rC   rC   W/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/tools.pyr-      s   
 	r-   c                   @  s,   e Zd ZU dZdZded< 	 dZded< dS )r/   z[Indicates that a tool call has been approved and that the tool function should be executed.Ndict[str, Any] | Noneoverride_argsztool-approvedzLiteral['tool-approved']kind)r=   r>   r?   r@   rF   rB   rG   rC   rC   rC   rD   r/      s
   
 r/   c                   @  s4   e Zd ZU dZdZded< 	 ded< dZded	< d
S )r0   zeIndicates that a tool call has been denied and that a denial message should be returned to the model.zThe tool call was denied.strmessager   _ztool-deniedzLiteral['tool-denied']rG   N)r=   r>   r?   r@   rI   rB   rG   rC   rC   rC   rD   r0      s   
 r0   xr
   return
str | Nonec                 C  sj   t | trd| v rtt| d S d| v rtt| d S d S t| dr(tt| jS t| dr3tt| jS d S )NrG   	part_kind)
isinstancedictr   rH   hasattrrG   rN   )rK   rC   rC   rD   (_deferred_tool_call_result_discriminator   s   


rR   rG   DeferredToolApprovalResultztool-returnzmodel-retryzretry-promptDeferredToolCallResultc                   @  s8   e Zd ZU dZeedZded< 	 eedZded< dS )r.   a[  Results for deferred tool calls from a previous run that required approval or external execution.

    The tool call IDs need to match those from the [`DeferredToolRequests`][pydantic_ai.output.DeferredToolRequests] output object from the previous run.

    See [deferred tools docs](../deferred-tools.md#deferred-tools) for more information.
    r9   z'dict[str, DeferredToolCallResult | Any]r;   z,dict[str, bool | DeferredToolApprovalResult]r<   N)	r=   r>   r?   r@   r   rP   r;   rB   r<   rC   rC   rC   rD   r.      s   
 r.   Ac                      s,   e Zd Zd fddZd fd	d
Z  ZS )GenerateToolJsonSchemaschemacore_schema.TypedDictSchemarL   r   c                   s   t  |}d|vr?|dp|di d}|dkr7|dd }|d ur1| |p,d|d< |S d|d< |S |dkr?d	|d< |S )
NadditionalPropertiesextra_behaviorconfigextra_fields_behaviorallowextras_schemaTforbidF)supertyped_dict_schemagetgenerate_inner)selfrW   json_schemaextrar^   	__class__rC   rD   ra      s   z(GenerateToolJsonSchema.typed_dict_schemanamed_required_fieldsSequence[tuple[str, bool, Any]]c                   s6   t  |}|di D ]}|d | dd  q|S )N
propertiestitle)r`   _named_required_fields_schemarb   pop)rd   ri   sprg   rC   rD   rm      s   z4GenerateToolJsonSchema._named_required_fields_schema)rW   rX   rL   r   )ri   rj   rL   r   )r=   r>   r?   ra   rm   __classcell__rC   rC   rg   rD   rV      s    rV   ToolAgentDepsT)r2   contravariantF)initc                   @  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< ded< ded< ded< ded< ded< ded< ded< 	 dddddddeddddddd0d d!Ze		d1d2d'd(Ze	d)d* Z
d3d.d/ZdS )4r*   zA tool function for an agent.ToolFuncEither[ToolAgentDepsT]functionbool	takes_ctx
int | Nonemax_retriesrH   namerM   description&ToolPrepareFunc[ToolAgentDepsT] | Nonepreparer"   docstring_formatrequire_parameter_descriptionsbool | Nonestrict
sequentialrequires_approvalrE   metadataz_function_schema.FunctionSchemafunction_schemaNr7   F)rx   rz   r{   r|   r~   r   r   schema_generatorr   r   r   r   r   r   type[GenerateJsonSchema]&_function_schema.FunctionSchema | Nonec                C  sx   || _ |ptj||	|||d| _| jj| _|| _|p|j| _|p#| jj| _|| _|| _	|| _
|
| _|| _|| _|| _dS )a  Create a new tool instance.

        Example usage:

        ```python {noqa="I001"}
        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 {noqa="I001"}

        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
        ) -> 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].
            docstring_format: The format of the docstring, see [`DocstringFormat`][pydantic_ai.tools.DocstringFormat].
                Defaults to `'auto'`, such that the format is inferred from the structure of the docstring.
            require_parameter_descriptions: If True, raise an error if a parameter description is missing. Defaults to False.
            schema_generator: The JSON schema generator class to use. Defaults to `GenerateToolJsonSchema`.
            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.
            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.
            metadata: Optional metadata for the tool. This is not sent to the model but can be used for filtering and tool behavior customization.
            function_schema: The function schema to use for the tool. If not provided, it will be generated.
        )rx   r   r   N)rv   r   r   rx   rz   r=   r{   r|   r~   r   r   r   r   r   r   )rd   rv   rx   rz   r{   r|   r~   r   r   r   r   r   r   r   r   rC   rC   rD   __init__  s&   J

zTool.__init__Callable[..., Any]re   r   rL   r   c              	   C  s:   t j||tt d||t|d}| ||||||dS )aw  Creates a Pydantic tool from a function and a JSON schema.

        Args:
            function: The function to call.
                This will be called with keywords only, and no validation of
                the arguments will be performed.
            name: The unique name of the tool that clearly communicates its purpose
            description: Used to tell the model how/when/why to use the tool.
                You can provide few-shot examples as a part of the description.
            json_schema: The schema for the function arguments
            takes_ctx: An optional boolean parameter indicating whether the function
                accepts the context object as an argument.
            sequential: Whether the function requires a sequential/serial execution environment. Defaults to False.

        Returns:
            A Pydantic tool that calls the function
        )rW   )rv   r|   	validatorre   rx   is_async)rx   r{   r|   r   r   )r   FunctionSchemar   r   
any_schemar   is_async_callable)clsrv   r{   r|   re   rx   r   r   rC   rC   rD   from_schemal  s    	zTool.from_schemac              	   C  s2   t | j| j| jj| j| j| j| jrddS ddS )N
unapprovedrv   )r{   r|   parameters_json_schemar   r   r   rG   )	r,   r{   r|   r   re   r   r   r   r   rd   rC   rC   rD   tool_def  s   zTool.tool_defctxRunContext[ToolAgentDepsT]r3   c                   s(   | j }| jdur| ||I dH S |S )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.
        N)r   r~   )rd   r   base_tool_defrC   rC   rD   prepare_tool_def  s
   	
zTool.prepare_tool_def)rv   ru   rx   r   rz   ry   r{   rM   r|   rM   r~   r}   r   r"   r   rw   r   r   r   r   r   rw   r   rw   r   rE   r   r   )FF)rv   r   r{   rH   r|   rM   re   r   rx   rw   r   rw   rL   r   )r   r   rL   r3   )r=   r>   r?   r@   rB   rV   r   classmethodr   propertyr   r   rC   rC   rC   rD   r*      sJ   
 
^,
r*   r+   )rv   outputexternalr   ToolKind)reprr8   c                   @  s   e Zd ZU dZded< 	 edd dZded< 	 d	Zd
ed< 	 d	Zd
ed< 	 d	Z	ded< 	 dZ
ded< 	 eddZded< 	 d	Zded< 	 edddZejZd	S )r,   zhDefinition of a tool passed to a model.

    This is used for both function tools and output tools.
    rH   r{   c                   C  s
   di dS )Nobject)typerk   rC   rC   rC   rC   rD   <lambda>  s   
 zToolDefinition.<lambda>r9   r+   r   NrM   r|   outer_typed_dict_keyr   r   Frw   r   rv   r1   r   rG   rE   r   rL   c                 C  s
   | j dv S )zWhether calls to this tool will be deferred.

        See the [tools documentation](../deferred-tools.md#deferred-tools) for more info.
        )r   r   )rG   r   rC   rC   rD   defer  s   
zToolDefinition.defer)rL   rw   )r=   r>   r?   r@   rB   r   r   r|   r   r   r   rG   r   r   r   r   dataclasses_no_defaults_repr__repr__rC   rC   rC   rD   r,     s*   
 

N)rK   r
   rL   rM   )I
__future__r   _annotationscollections.abcr   r   r   dataclassesr   r   r   typingr	   r
   r   r   r   r   r   pydanticr   r   pydantic.json_schemar   r   pydantic_corer   r   typing_extensionsr   r   r    r   r   _run_contextr   r   
exceptionsr   messagesr   r    r!   __all__r'   rH   r#   rB   r$   r%   r&   r(   rA   r)   r"   r-   r/   r0   rR   rS   rT   DeferredToolResultr.   rU   rV   r   rr   r*   rP   r+   r   r,   rC   rC   rC   rD   <module>   s    $

  		
 ?
