a
    ”˜ëj¾?  ã                   @   sŽ  d Z ddl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mZ ddlmZ ddlmZ ddlmZmZ ddlmZ dd	lmZ e	dd
dddd
ddœee eee eed eeeeeef gef dœdd„ƒZe	dd
dddd
ddœeeee eee eed eeedœ
dd„ƒZe	dd
dddd
ddœeee eee eed eeedœ	dd„ƒZe	dd
dddd
ddœeee eee eed eeeeeef gef dœ	dd„ƒZd#dd
dddd
ddœeeeef  ee eee eee eed eeeeeeeef gef f dœdd„Zeedœdd„Zd$eeeeeef  ee dœdd„Zd%ddddœeeee  ee ee eeeef  ed œd!d"„Z dS )&z)Convert functions and runnables to tools.é    N)ÚAnyÚCallableÚLiteralÚOptionalÚUnionÚget_type_hintsÚoverload)Ú	BaseModelÚFieldÚcreate_model)Ú	Callbacks)ÚRunnable)Ú
ArgsSchemaÚBaseTool)ÚTool)ÚStructuredToolFTÚcontent©ÚdescriptionÚreturn_directÚargs_schemaÚinfer_schemaÚresponse_formatÚparse_docstringÚerror_on_invalid_docstring)r   Zcontent_and_artifact)r   r   r   r   r   r   r   Úreturnc                 C   s   d S ©N© r   r   r   ú[/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/tools/convert.pyÚtool   s    
r   )
Úname_or_callableÚrunnabler   r   r   r   r   r   r   r   c          	      C   s   d S r   r   )	r    r!   r   r   r   r   r   r   r   r   r   r   r      s    )	r    r   r   r   r   r   r   r   r   c                C   s   d S r   r   ©r    r   r   r   r   r   r   r   r   r   r   r   +   s    c                C   s   d S r   r   r"   r   r   r   r   9   s    )r    r!   Úargsr   r   r   r   r   r   r   r   c                   sô   t ttttf gtf dœ‡‡‡‡‡‡‡fdd„‰ t|	ƒdkrJd}
t|
ƒ‚|dur„| sbd}
t|
ƒ‚t| t ƒsxd}
t|
ƒ‚ˆ | ƒ|ƒS | durÔt| ƒr¬t	| d	ƒr¬ˆ | j
ƒ| ƒS t| t ƒr¾ˆ | ƒS d
t| ƒ› �}
t|
ƒ‚tttf tdœ‡ fdd„}|S )a…  Make tools out of functions, can be used with or without arguments.

    Args:
        name_or_callable: Optional name of the tool or the callable to be
            converted to a tool. Must be provided as a positional argument.
        runnable: Optional runnable to convert to a tool. Must be provided as a
            positional argument.
        description: Optional description for the tool.
            Precedence for the tool description value is as follows:

            - ``description`` argument
                (used even if docstring and/or ``args_schema`` are provided)
            - tool function docstring
                (used even if ``args_schema`` is provided)
            - ``args_schema`` description
                (used only if `description` / docstring are not provided)
        *args: Extra positional arguments. Must be empty.
        return_direct: Whether to return directly from the tool rather
            than continuing the agent loop. Defaults to False.
        args_schema: optional argument schema for user to specify.
            Defaults to None.
        infer_schema: Whether to infer the schema of the arguments from
            the function's signature. This also makes the resultant tool
            accept a dictionary input to its `run()` function.
            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 True.

    Raises:
        ValueError: If too many positional arguments are provided.
        ValueError: If a runnable is provided without a string name.
        ValueError: If the first argument is not a string or callable with
            a ``__name__`` attribute.
        ValueError: If the function does not have a docstring and description
            is not provided and ``infer_schema`` is False.
        ValueError: If ``parse_docstring`` is True and the function has an invalid
            Google-style docstring and ``error_on_invalid_docstring`` is True.
        ValueError: If a Runnable is provided that does not have an object schema.

    Returns:
        The tool.

    Requires:
        - Function must be of type (str) -> str
        - Function must have a docstring

    Examples:
        .. code-block:: python

            @tool
            def search_api(query: str) -> str:
                # Searches the API for the query.
                return


            @tool("search", return_direct=True)
            def search_api(query: str) -> str:
                # Searches the API for the query.
                return


            @tool(response_format="content_and_artifact")
            def search_api(query: str) -> tuple[str, dict]:
                return "partial json of results", {"full": "object of results"}

    .. versionadded:: 0.2.14

        Parse Google-style docstrings:

        .. code-block:: python

            @tool(parse_docstring=True)
            def foo(bar: str, baz: int) -> str:
                """The foo.

                Args:
                    bar: The bar.
                    baz: The baz.
                """
                return bar

            foo.args_schema.model_json_schema()

        .. code-block:: python

            {
                "title": "foo",
                "description": "The foo.",
                "type": "object",
                "properties": {
                    "bar": {
                        "title": "Bar",
                        "description": "The bar.",
                        "type": "string",
                    },
                    "baz": {
                        "title": "Baz",
                        "description": "The baz.",
                        "type": "integer",
                    },
                },
                "required": ["bar", "baz"],
            }

        Note that parsing by default will raise ``ValueError`` if the docstring
        is considered invalid. A docstring is considered invalid if it contains
        arguments not in the function signature, or is unable to be parsed into
        a summary and "Args:" blocks. Examples below:

        .. code-block:: python

            # No args section
            def invalid_docstring_1(bar: str, baz: int) -> str:
                """The foo."""
                return bar

            # Improper whitespace between summary and args section
            def invalid_docstring_2(bar: str, baz: int) -> str:
                """The foo.
                Args:
                    bar: The bar.
                    baz: The baz.
                """
                return bar

            # Documented args absent from function signature
            def invalid_docstring_3(bar: str, baz: int) -> str:
                """The foo.

                Args:
                    banana: The bar.
                    monkey: The baz.
                """
                return bar

    )Ú	tool_namer   c              	      s.   t ttf tdœ‡‡‡‡‡‡‡‡ fdd„}|S )zöCreate a decorator that takes a callable and returns a tool.

        Args:
            tool_name: The name that will be assigned to the tool.

        Returns:
            A function that takes a callable or Runnable and returns a tool.
        )Údec_funcr   c                    s  ˆ}t | tƒr†| ‰ ˆ j ¡  d¡dkr2d}t|ƒ‚dtt ttdœ‡ fdd„}dtt ttdœ‡ fdd„}|}|}ˆ j}ˆp‚t	ˆ ƒ}n$t
 | ¡rž| }d }ˆ}nd }| }ˆ}ˆs¶ˆd urÔtj||ˆ|ˆ|ˆˆˆˆd	�
S | jd u rêd
}t|ƒ‚tˆ|ˆ› d�ˆ|ˆd�S )NÚtypeÚobjectz$Runnable must have an object schema.©Ú	callbacksÚkwargsr   c                 ›   s   ˆ   |d| i¡I d H S ©Nr)   ©Úainvoke©r)   r*   ©r!   r   r   Úainvoke_wrapperý   s    zRtool.<locals>._create_tool_factory.<locals>._tool_factory.<locals>.ainvoke_wrapperc                    s   ˆ   |d| i¡S r+   ©Úinvoker.   r/   r   r   Úinvoke_wrapper  s    zQtool.<locals>._create_tool_factory.<locals>._tool_factory.<locals>.invoke_wrapper)Únamer   r   r   r   r   r   r   zUFunction must have a docstring if description not provided and infer_schema is False.z tool)r4   Úfuncr   r   Ú	coroutiner   )N)N)Ú
isinstancer   Úinput_schemaÚmodel_json_schemaÚgetÚ
ValueErrorr   r   r   ÚreprÚinspectÚiscoroutinefunctionr   Úfrom_functionÚ__doc__r   )r%   Ztool_descriptionÚmsgr0   r3   r6   r5   Úschema)r   r   r   r   r   r   r   r$   r/   r   Ú_tool_factoryô   sh    
 ÿþ ÿþ
ö
ÿúz9tool.<locals>._create_tool_factory.<locals>._tool_factory)r   r   r   r   )r$   rC   )r   r   r   r   r   r   r   )r$   r   Ú_create_tool_factoryè   s    *>z"tool.<locals>._create_tool_factoryr   z3Too many arguments for tool decorator. A decorator Nz*Runnable without name for tool constructorz*Name must be a string for tool constructorÚ__name__zZThe first argument must be a string or a callable with a __name__ for tool decorator. Got )r5   r   c                    s(   t | tƒr|  ¡ n| j}ˆ |ƒ}|| ƒS )z:Partial function that takes a callable and returns a tool.)r7   r   Úget_namerE   )r5   Zname_Ztool_factory)rD   r   r   Ú_partialc  s    ztool.<locals>._partial)Ústrr   r   r   r   Úlenr;   r7   ÚcallableÚhasattrrE   r&   )r    r!   r   r   r   r   r   r   r   r#   rA   rG   r   )rD   r   r   r   r   r   r   r   r   r   G   s6     #þL

ÿÿ)r!   r   c                 C   s   | j  ¡ }d|› d�S )z1Generate a placeholder description of a runnable.zTakes Ú.)r8   r9   )r!   r8   r   r   r   Ú_get_description_from_runnablel  s    
rM   )r!   r4   Ú	arg_typesr   c              
   C   sr   |du rPzt | jƒ}W n8 tyN } z d|› �}t|ƒ|‚W Y d}~n
d}~0 0 dd„ | ¡ D ƒ}t|fi |¤ŽS )zInfer args_schema for tool.Nz¢Tool input must be str or dict. If dict, dict arguments must be typed. Either annotate types (e.g., with TypedDict) or pass arg_types into `.as_tool` to specify. c                 S   s   i | ]\}}||t d ƒf“qS ).)r
   )Ú.0ÚkeyZkey_typer   r   r   Ú
<dictcomp>‚  ó    z;_get_schema_from_runnable_and_arg_types.<locals>.<dictcomp>)r   Z	InputTypeÚ	TypeErrorÚitemsr   )r!   r4   rN   ÚerA   Úfieldsr   r   r   Ú'_get_schema_from_runnable_and_arg_typesr  s    þÿ rW   )r4   r   rN   )r!   r   r4   r   rN   r   c                   sÖ   |rˆ j |d�‰ |ptˆ ƒ}|p&ˆ  ¡ }ˆ j ¡ }| d¡dkrTt|ˆ jˆ j|d�S dt	t
 ttdœ‡ fdd„}dt	t
 ttdœ‡ fd	d
„}|du r´| d¡dkr´| d¡r´ˆ j}ntˆ ||d�}tj|||||d�S )a‹  Convert a Runnable into a BaseTool.

    Args:
        runnable: The runnable to convert.
        args_schema: The schema for the tool's input arguments. Defaults to None.
        name: The name of the tool. Defaults to None.
        description: The description of the tool. Defaults to None.
        arg_types: The types of the arguments. Defaults to None.

    Returns:
        The tool.
    )Z
input_typer&   Ústring)r4   r5   r6   r   Nr(   c                 ›   s   ˆ j |d| id�I d H S ©Nr)   )Úconfigr,   r.   r/   r   r   r0   ¨  s    z1convert_runnable_to_tool.<locals>.ainvoke_wrapperc                    s   ˆ j |d| id�S rY   r1   r.   r/   r   r   r3   ­  s    z0convert_runnable_to_tool.<locals>.invoke_wrapperr'   Z
properties)rN   )r4   r5   r6   r   r   )N)N)Z
with_typesrM   rF   r8   r9   r:   r   r2   r-   r   r   r   rW   r   r?   )r!   r   r4   r   rN   rB   r0   r3   r   r/   r   Úconvert_runnable_to_tool†  sF    
ü ÿþÿþýÿûr[   )NN)N)N)!r@   r=   Útypingr   r   r   r   r   r   r   Zpydanticr	   r
   r   Zlangchain_core.callbacksr   Zlangchain_core.runnablesr   Zlangchain_core.tools.baser   r   Zlangchain_core.tools.simpler   Zlangchain_core.tools.structuredr   rH   Úboolr   rM   Údictr&   rW   r[   r   r   r   r   Ú<module>   s  $ø÷öõ÷ö÷ö  þöÿÿõ  '	 ýü þú
ù