a
    ”˜ëj÷$  ã                   @  sì   d Z ddlmZ ddlZddlmZ ddl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 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  ddl!m"Z" e	rÈddl#m$Z$ G dd„ deƒZ%dddœdd„Z&dS )zStructured tool.é    )ÚannotationsN)Ú	Awaitable)Ú	signature)ÚTYPE_CHECKINGÚ	AnnotatedÚAnyÚCallableÚLiteralÚOptionalÚUnion)ÚFieldÚSkipValidation)Úoverride)ÚAsyncCallbackManagerForToolRunÚCallbackManagerForToolRun)ÚRunnableConfigÚrun_in_executor)ÚFILTERED_ARGSÚ
ArgsSchemaÚBaseToolÚ_get_runnable_config_paramÚcreate_schema_from_function)Úis_basemodel_subclass)ÚToolCallc                      sÜ   e Zd ZU dZdZded< eddd�Zded	< d
Zded< d
Z	ded< e
d*dddddœ‡ fdd„ƒZd
dœddddddœdd„Zd
dœddddddœ‡ fdd„Zed+d ddd!œd"dd#d#d$d%d$d&d$d$dd d'œd(d)„ƒZ‡  ZS ),ÚStructuredToolz.Tool that can operate on any number of inputs.Ú ÚstrÚdescription.zThe tool schema.)r   z'Annotated[ArgsSchema, SkipValidation()]Úargs_schemaNzOptional[Callable[..., Any]]Úfuncz'Optional[Callable[..., Awaitable[Any]]]Ú	coroutinezUnion[str, dict, ToolCall]zOptional[RunnableConfig]r   )ÚinputÚconfigÚkwargsÚreturnc                 ‹  s@   | j s$t|| j||fi |¤ŽI d H S tƒ j||fi |¤ŽI d H S ©N)r    r   ZinvokeÚsuperÚainvoke)Úselfr!   r"   r#   ©Ú	__class__© ú^/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/tools/structured.pyr'   7   s    zStructuredTool.ainvoke)Úrun_managerr   z#Optional[CallbackManagerForToolRun])Úargsr"   r-   r#   r$   c                O  s^   | j rN|r(t| j ƒj d¡r(| ¡ |d< t| j ƒ }r>|||< | j |i |¤ŽS d}t|ƒ‚dS )aP  Use the tool.

        Args:
            *args: Positional arguments to pass to the tool
            config: Configuration for the run
            run_manager: Optional callback manager to use for the run
            **kwargs: Keyword arguments to pass to the tool

        Returns:
            The result of the tool execution
        Ú	callbacksz0StructuredTool does not support sync invocation.N)r   r   Ú
parametersÚgetÚ	get_childr   ÚNotImplementedError)r(   r"   r-   r.   r#   Úconfig_paramÚmsgr+   r+   r,   Ú_runF   s    zStructuredTool._runz(Optional[AsyncCallbackManagerForToolRun]c                �  sr   | j rT|r(t| j ƒj d¡r(| ¡ |d< t| j ƒ }r>|||< | j |i |¤ŽI dH S tƒ j|||dœ|¤ŽI dH S )a_  Use the tool asynchronously.

        Args:
            *args: Positional arguments to pass to the tool
            config: Configuration for the run
            run_manager: Optional callback manager to use for the run
            **kwargs: Keyword arguments to pass to the tool

        Returns:
            The result of the tool execution
        r/   N)r"   r-   )r    r   r0   r1   r2   r   r&   Ú_arun)r(   r"   r-   r.   r#   r4   r)   r+   r,   r7   a   s    ÿÿzStructuredTool._arunFTÚcontent)Úresponse_formatÚparse_docstringÚerror_on_invalid_docstringzOptional[Callable]zOptional[str]ÚboolzOptional[ArgsSchema]z*Literal['content', 'content_and_artifact'])r   r    Únamer   Úreturn_directr   Úinfer_schemar9   r:   r;   r#   r$   c             
   K  s*  |dur|}n|dur|}nd}t |ƒ‚|p0|j}|du rT|rTt|||	|
t|ƒd�}|}|du rn|	sn|jpld}|du rÖ|rÖt|tƒr®t|ƒr®|j}|r¤d|v r¤d}qÖ|sÖd}n(t|tƒrÄ| 	d¡}nd|› �}t
|ƒ‚|du rêd}t |ƒ‚|du �rt |¡ ¡ }| ¡ › }| f |||||||d	œ|¤ŽS )
ay  Create tool from a given function.

        A classmethod that helps to create a tool from a function.

        Args:
            func: The function from which to create a tool.
            coroutine: The async function from which to create a tool.
            name: The name of the tool. Defaults to the function name.
            description: The description of the tool.
                Defaults to the function docstring.
            return_direct: Whether to return the result directly or as a callback.
                Defaults to False.
            args_schema: The schema of the tool's input arguments. Defaults to None.
            infer_schema: Whether to infer the schema from the function's signature.
                Defaults to True.
            response_format: The tool response format. If "content" then the output of
                the tool is interpreted as the contents of a ToolMessage. If
                "content_and_artifact" then the output is expected to be a two-tuple
                corresponding to the (content, artifact) of a ToolMessage.
                Defaults to "content".
            parse_docstring: if ``infer_schema`` and ``parse_docstring``, will attempt
                to parse parameter descriptions from Google Style function docstrings.
                Defaults to False.
            error_on_invalid_docstring: if ``parse_docstring`` is provided, configure
                whether to raise ValueError on invalid Google Style docstrings.
                Defaults to False.
            kwargs: Additional arguments to pass to the tool

        Returns:
            The tool.

        Raises:
            ValueError: If the function is not provided.
            ValueError: If the function does not have a docstring and description
                is not provided.
            TypeError: If the ``args_schema`` is not a ``BaseModel`` or dict.

        Examples:

            .. code-block:: python

                def add(a: int, b: int) -> int:
                    """Add two numbers"""
                    return a + b
                tool = StructuredTool.from_function(add)
                tool.run(1, 2) # 3

        Nz*Function and/or coroutine must be provided)r:   r;   Úfilter_argsz)A base class for creating Pydantic modelsr   r   z5Invalid args_schema: expected BaseModel or dict, got z;Function must have a docstring if description not provided.)r=   r   r    r   r   r>   r9   )Ú
ValueErrorÚ__name__r   Ú_filter_schema_argsÚ__doc__Ú
isinstanceÚtyper   Údictr1   Ú	TypeErrorÚtextwrapÚdedentÚstrip)Úclsr   r    r=   r   r>   r   r?   r9   r:   r;   r#   Zsource_functionr5   Zdescription_r+   r+   r,   Úfrom_function€   sh    @
û
ÿþ
ÿÿ

ùøzStructuredTool.from_function)N)NNNNFNT)rB   Ú
__module__Ú__qualname__rD   r   Ú__annotations__r   r   r   r    r   r'   r6   r7   ÚclassmethodrM   Ú__classcell__r+   r+   r)   r,   r   '   s6   
ÿ ýüü       ø
ôr   r   z	list[str])r   r$   c                 C  s"   t tƒ}t| ƒ }r| |¡ |S r%   )Úlistr   r   Úappend)r   r@   r4   r+   r+   r,   rC   ü   s    
rC   )'rD   Ú
__future__r   rI   Úcollections.abcr   Úinspectr   Útypingr   r   r   r   r	   r
   r   Zpydanticr   r   Ztyping_extensionsr   Zlangchain_core.callbacksr   r   Zlangchain_core.runnablesr   r   Zlangchain_core.tools.baser   r   r   r   r   Zlangchain_core.utils.pydanticr   Zlangchain_core.messagesr   r   rC   r+   r+   r+   r,   Ú<module>   s    $
 V