
    g3fiBB                        d Z ddlZddlmZ ddl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ddedz  dededz  deded   dededeeef   dz  deeez  gef   fd       Ze	ddddddddddedededz  dededz  deded   dededeeef   dz  defd       Ze	ddddddddddededz  dededz  deded   dededeeef   dz  defd       Ze	ddddddddddededz  dededz  deded   dededeeef   dz  deeez  gef   fd       Z	 	 d'ddddddddddeez  dz  dedz  dededz  dededz  deded   dededeeef   dz  deeeez  gef   z  fd Zdedefd!Z	 d(ded"ed#eeef   dz  dee   fd$Z	 d(dddd%dedee   dz  d"edz  dedz  d#eeef   dz  defd&Z y))z)Convert functions and runnables to tools.    N)Callable)AnyLiteralcast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extrasr   r   r   r   r   )r   content_and_artifactr   r   r   returnc                      y N r   s           Z/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/tools/convert.pytoolr"      s     14    name_or_callablerunnablec                     y r   r    )
r$   r%   r   r   r   r   r   r   r   r   s
             r!   r"   r"      s     r#   c                     y r   r    	r$   r   r   r   r   r   r   r   r   s	            r!   r"   r"   .   s     r#   c                     y r   r    r(   s	            r!   r"   r"   =   s     14r#   argsc          	        	 dt         dt        t        t        z  gt        f   f	fdt	        |
      dk7  rd}t        |      |:| sd}t        |      t        | t               sd}t        |        |       |      S | `t        |       r$t        | d      r  | j                        |       S t        | t               r |       S d	t        |        }t        |      d
t        t        z  dt        ffd}|S )a  Convert Python functions and `Runnables` to LangChain tools.

    Can be used as a decorator with or without arguments to create tools from functions.

    Functions can have any signature - the tool will automatically infer input schemas
    unless disabled.

    !!! note "Requirements"
        - Functions must have type hints for proper schema inference
        - When `infer_schema=False`, functions must be `(str) -> str` and have
            docstrings
        - When using with `Runnable`, a string name must be provided

    Args:
        name_or_callable: Optional name of the tool or the `Callable` to be
            converted to a tool. Overrides the function's name.

            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:

            - This `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` and 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.
        args_schema: Optional argument schema for user to specify.
        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.
        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`.
        parse_docstring: If `infer_schema` and `parse_docstring`, will attempt to
            parse parameter descriptions from Google Style function docstrings.
        error_on_invalid_docstring: If `parse_docstring` is provided, configure
            whether to raise `ValueError` on invalid Google Style docstrings.
        extras: Optional provider-specific extra fields for the tool.

            Used to pass configuration that doesn't fit into standard tool fields.
            Chat models should process known extras when constructing model payloads.

            !!! example

                For example, Anthropic-specific fields like `cache_control`,
                `defer_loading`, or `input_examples`.

    Raises:
        ValueError: If too many positional arguments are provided (e.g. violating the
            `*args` constraint).
        ValueError: If a `Runnable` is provided without a string name. When using `tool`
            with a `Runnable`, a `str` name must be provided as the `name_or_callable`.
        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.

    Examples:
        ```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"}
        ```

        Parse Google-style docstrings:

        ```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()
        ```

        ```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:

        ```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           
      L     dt         t        z  dt        f	 f	d}|S )zCreate 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                 <  	 
}t        | t              r| j                  j                         j	                  d      dk7  rd}t        |      	 ddt        d z  dt        dt        ffd}	 ddt        d z  dt        dt        ffd}|}|}j                  }
xs t              }n"t        j                  |       r| }d }	}nd }| }	}s	 t        j                  ||||	      S | j                  d
}t        |      t        | d|      S )Ntypeobjectz$Runnable must have an object schema.	callbackskwargsr   c                 H   K   j                  |d| i       d {   S 7 wNr2   ainvoker2   r3   r%   s     r!   ainvoke_wrapperzRtool.<locals>._create_tool_factory.<locals>._tool_factory.<locals>.ainvoke_wrapper  s'      "*!1!1&;	:R!SSSSs   " "c                 ,    j                  |d| i      S r5   invoker8   s     r!   invoke_wrapperzQtool.<locals>._create_tool_factory.<locals>._tool_factory.<locals>.invoke_wrapper  s     $??6K3KLLr#   )	namer   r   r   r   r   r   r   r   zUFunction must have a docstring if description not provided and infer_schema is False.z tool)r>   funcr   r   	coroutiner   r   r   )
isinstancer   input_schemamodel_json_schemaget
ValueErrorr   r   reprinspectiscoroutinefunctionr   from_function__doc__r   )r.   tool_descriptionmsgr9   r=   r@   r?   schemar%   r   r   r   r   r   r   r   r   r,   s           @r!   _tool_factoryz9tool.<locals>._create_tool_factory.<locals>._tool_factory	  s{   *(H-#((::<@@HHT@C$S/) 37T(4/TBETT 37M(4/MBEMM
 ,	%,4,A,A#.#@$x. ,,X6$	$ 	${6%33" 0"/ &!-$3$3/I!  'J  !o%(k/+# / r#   )r   r   r   )
r,   rN   r   r   r   r   r   r   r   r   s
   ` r!   _create_tool_factoryz"tool.<locals>._create_tool_factory   s)    >	Hx$7 >	H >	 >	@ r#   r   z3Too many arguments for tool decorator. A decorator z*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 r?   c                 |    t        | t              r| j                         n| j                  } |      } ||       S )z:Partial function that takes a callable and returns a tool.)rA   r   get_namerP   )r?   name_tool_factoryrO   s      r!   _partialztool.<locals>._partialz  s2    #-dH#=4==+E2D!!r#   )strr   r   r   lenrE   rA   callablehasattrrP   r0   )r$   r%   r   r   r   r   r   r   r   r   r*   rL   rU   rO   s     ````````   @r!   r"   r"   L   s4   bLL	8h&'1	2L L\ 4yA~
 Do  >CS/!*C0>CS/!5#$45h??#$%'2BJ*O
 C'(8(A(ABCSTT&, ((899''+,<'=&>@ 	 o"x(* "x " Or#   c                 B    | j                   j                         }d| dS )z1Generate a placeholder description of a runnable.zTakes .)rB   rC   )r%   rB   s     r!   _get_description_from_runnabler\     s%    ((::<LL>##r#   r>   	arg_typesc           	      
   |	 t        | j                        }|j                         D ci c]  \  }}||t	        d      f }}}t        dt        |fi |      S # t        $ r}d| }t        |      |d}~ww xY wc c}}w )zInfer args_schema for tool.NzTool 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. .ztype[BaseModel])r   	InputType	TypeErroritemsr
   r   r   )r%   r>   r]   erL   keykey_typefieldss           r!   '_get_schema_from_runnable_and_arg_typesrf     s     	(&x'9'9:I @I?PQmc8cHeCj))QFQ!<#?#?@@  	(99:= 
 C.a'	( Rs   A A?	A<&A77A<)r>   r   r]   c                <    |r j                  |       |xs t               }|xs  j                         } j                  j	                         }|j                  d      dk(  r#t        | j                   j                  |      S ddt        dz  dt        dt        f fd	}ddt        dz  dt        dt        f fd
}|2|j                  d      dk(  r|j                  d      r j                  }nt         ||      }t        j                  |||||      S )aC  Convert a Runnable into a BaseTool.

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

    Returns:
        The tool.
    )
input_typer0   string)r>   r?   r@   r   Nr2   r3   r   c                 J   K   j                  |d| i       d {   S 7 wNr2   )configr6   r8   s     r!   r9   z1convert_runnable_to_tool.<locals>.ainvoke_wrapper  s(     %%fk95M%NNNNs   #!#c                 .    j                  |d| i      S rk   r;   r8   s     r!   r=   z0convert_runnable_to_tool.<locals>.invoke_wrapper  s    v{I.FGGr#   r1   
properties)r]   )r>   r?   r@   r   r   r   )
with_typesr\   rR   rB   rC   rD   r   r<   r7   r   r   rf   r   rI   )r%   r   r>   r   r]   rM   r9   r=   s   `       r!   convert_runnable_to_toolrp     s2   ( &&+&>I!?!IK&8$$&D""446Fzz&X%&&#	
 	
OT)9 OC OTW OH)d"2 HS HS H 	JJv(*JJ|$++=di
 ''! r#   )NNr   )!rJ   rG   collections.abcr   typingr   r   r   r   r   pydanticr	   r
   r   langchain_core.callbacksr   langchain_core.runnablesr   langchain_core.tools.baser   r   langchain_core.tools.simpler   langchain_core.tools.structuredr   rV   booldictr"   r\   r0   rf   rp   r    r#   r!   <module>r{      s   /  $ ? ? 3 3 . - : , : 
 #%)BK!'+$(
4t
4 
4 d"	
4
 
4 >?
4 
4 !%
4 cNT!
4 x("#X-.
4 

4 

 #%)BK!'+$( t	
  d"  >?  !% cNT!  
 
 #%)BK!'+$( t 	
 d"  >?  !% cNT!  
 
 #%)BK!'+$(44 t4 	4
 d"4 4 >?4 4 !%4 cNT!4 x("#X-.4 
4 /3 $t #%)BK!'+$(tHnt+tot t t	t
 t d"t t >?t t !%t cNT!t (X-.899tn	$X $# $ )-AA
A CI%A 
)_	A, +/9 "(,99i4'9 *	9
 t9 CI%9 9r#   