a
    ”˜ëj~Ä  ã                	   @  s  d Z ddlmZ ddlZddlZddlZddlZddl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mZmZmZmZmZmZ ddlmZmZmZmZmZmZmZm Z  ddl!mZ" dd	l!mZ# dd
l!m Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?m@Z@mAZAmBZBmCZCmDZDmEZE e�ršddlFZFddlGmHZH dZIdZJG dd„ deKƒZLdddœdd„ZMddd œd!d"„ZNd#d$œd%d&d'dd(d)œd*d+„ZOd,d-œd&d(dd.d/œd0d1„ZPd(d(d2d3œd4d5„ZQd,d,d6œd&ddd.d7œd8d9„ZRdˆd;d<dd=œd>d?„ZSd@d&ddAœdBdC„ZTG dDdE„ dEƒZUdd,d,d#dFœd<d&dGdddd%dHœdIdJ„ZVG dKdL„ dLeWƒZXee@eYeZef f Z[G dMdN„ dNe4eeZeYe/f ef ƒZ\d;ddOœdPdQ„Z]dRdSd<dTœdUdV„Z^dLdWd<dTœdXdY„Z_dZd[d;d\d]œd^d_„Z`d;d;d`d<d<dadbœdcdd„Zad;ddeœdfdg„Zbd;ddeœdhdi„Zcd;d<djœdkdl„Zdd&dmdnœdodp„Zed&d`dnœdqdr„ZfG dsdt„ dtƒZgG dudv„ dvegƒZhd‰dwdxddyœdzd{„Zid#d|œd}dd~dœd€d�„ZjdŠd#d|œdwd‚ddwdƒœd„d…„ZkG d†d‡„ d‡ee	ƒZldS )‹z/Base classes and utilities for LangChain tools.é    )ÚannotationsN)ÚABCÚabstractmethod)Ú	signature)ÚTYPE_CHECKINGÚ	AnnotatedÚAnyÚCallableÚLiteralÚOptionalÚTypeVarÚUnionÚcastÚget_argsÚ
get_originÚget_type_hints)Ú	BaseModelÚ
ConfigDictÚFieldÚPydanticDeprecationWarningÚSkipValidationÚValidationErrorÚmodel_validatorÚvalidate_arguments)r   )r   )r   )Úoverride)Ú
deprecated)ÚAsyncCallbackManagerÚBaseCallbackManagerÚCallbackManagerÚ	Callbacks)ÚToolCallÚToolMessageÚToolOutputMixin)ÚRunnableConfigÚRunnableSerializableÚensure_configÚpatch_configÚrun_in_executor)Úset_config_context)Úcoro_with_context)Ú_parse_google_docstringÚ_py_38_safe_origin)ÚTypeBaseModelÚ_create_subset_modelÚ
get_fieldsÚis_basemodel_subclassÚis_pydantic_v1_subclassÚis_pydantic_v2_subclass)ÚSequence)Úrun_managerÚ	callbacks)ÚtextZ	image_urlÚimageÚjsonZsearch_resultZcustom_tool_call_outputÚdocumentÚfilec                   @  s   e Zd ZdZdS )ÚSchemaAnnotationErrorzGRaised when args_schema is missing or has an incorrect type annotation.N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r@   r@   úX/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/tools/base.pyr:   Y   s   r:   z	type[Any]Úbool)ÚtypÚreturnc                 C  s   t | ƒtju S )z£Check if a type is an Annotated type.

    Args:
        typ: The type to check.

    Returns:
        True if the type is an Annotated type, False otherwise.
    )r   Útypingr   )rC   r@   r@   rA   Ú_is_annotated_type]   s    	rF   Útypez
str | None)Úarg_typerD   c                 C  s8   t | ƒr4t| ƒ}|dd… D ]}t|tƒr|  S qdS )zºExtract description from an Annotated type.

    Args:
        arg_type: The type to extract description from.

    Returns:
        The description string if found, None otherwise.
    é   N)rF   r   Ú
isinstanceÚstr)rH   Zannotated_argsÚ
annotationr@   r@   rA   Ú_get_annotation_descriptioni   s    	

rM   T)Úinclude_injectedútype[BaseModel]r	   zSequence[str]Údict)Úinferred_modelÚfuncÚfilter_argsrN   rD   c                  s4   |   ¡ d ‰t|ƒj}‡ ‡‡fdd„t| ¡ ƒD ƒS )a’  Get filtered arguments from a function's signature.

    Args:
        inferred_model: The Pydantic model inferred from the function.
        func: The function to extract arguments from.
        filter_args: Arguments to exclude from the result.
        include_injected: Whether to include injected arguments.

    Returns:
        Dictionary of filtered arguments with their schema definitions.
    Ú
propertiesc                   sF   i | ]>\}\}}|ˆ vr|d ks*|j dvrˆs8t|jƒs|ˆ| “qS )r   >   ÚselfÚcls)ÚnameÚ_is_injected_arg_typerL   )Ú.0ÚiÚkÚparam©rS   rN   Úschemar@   rA   Ú
<dictcomp>Ž   s
   
üz&_get_filtered_args.<locals>.<dictcomp>)Úmodel_json_schemar   Ú
parametersÚ	enumerateÚitems)rQ   rR   rS   rN   Z
valid_keysr@   r]   rA   Ú_get_filtered_argsz   s
    

þrd   F©Úerror_on_invalid_docstringztuple[str, dict])Úfunctionr   rf   rD   c                C  s   t  | ¡}t|t|ƒ|d�S )aÁ  Parse function and argument descriptions from a docstring.

    Assumes the function docstring follows Google Python style guide.

    Args:
        function: The function to parse the docstring from.
        annotations: Type annotations for the function parameters.
        error_on_invalid_docstring: Whether to raise an error on invalid docstring.

    Returns:
        A tuple containing the function description and argument descriptions.
    re   )ÚinspectÚgetdocr*   Úlist)rg   r   rf   Ú	docstringr@   r@   rA   Ú _parse_python_function_docstring—   s    
ýrl   ÚNone)Úarg_descriptionsr   rD   c                 C  s*   | D ] }||vrd|› d�}t |ƒ‚qdS )a-  Validate that docstring arguments match function annotations.

    Args:
        arg_descriptions: Arguments described in the docstring.
        annotations: Type annotations from the function signature.

    Raises:
        ValueError: If a docstring argument is not found in function signature.
    zArg z. in docstring not found in function signature.N)Ú
ValueError)rn   r   Zdocstring_argÚmsgr@   r@   rA   Ú,_validate_docstring_args_against_annotations®   s    rq   ©Úparse_docstringrf   )Úfnrs   rf   rD   c          	      C  s~   t j| dd�}|r&t| ||d�\}}nt | ¡p2d}i }|rFt||ƒ | ¡ D ]&\}}||v r`qNt|ƒ }rN|||< qN||fS )a�  Infer argument descriptions from function docstring and annotations.

    Args:
        fn: The function to infer descriptions from.
        parse_docstring: Whether to parse the docstring for descriptions.
        error_on_invalid_docstring: Whether to raise error on invalid docstring.

    Returns:
        A tuple containing the function description and argument descriptions.
    T)Úinclude_extrasre   Ú )rE   r   rl   rh   ri   rq   rc   rM   )	rt   rs   rf   r   Údescriptionrn   ÚargrH   Údescr@   r@   rA   Ú_infer_arg_descriptionsÀ   s    ÿ

rz   Úv2r   rK   )rL   Úpydantic_versionrD   c                 C  s6   |dkrt nt}zt| |ƒW S  ty0   Y dS 0 dS )a  Check if a type annotation is a Pydantic model.

    Args:
        annotation: The type annotation to check.
        pydantic_version: The Pydantic version to check against ("v1" or "v2").

    Returns:
        True if the annotation is a Pydantic model, False otherwise.
    Úv1FN)ÚBaseModelV1r   Ú
issubclassÚ	TypeError)rL   r|   Zbase_model_classr@   r@   rA   Ú_is_pydantic_annotationâ   s
    
r�   zinspect.Signature)r   rR   rD   c                 C  sV   t dd„ | j ¡ D ƒƒ}t dd„ | j ¡ D ƒƒ}|rL|rLd|› d�}t|ƒ‚|oT| S )a_  Check if all Pydantic annotations in a function are from V1.

    Args:
        signature: The function signature to check.
        func: The function being checked.

    Returns:
        True if all Pydantic annotations are from V1, False otherwise.

    Raises:
        NotImplementedError: If the function contains mixed V1 and V2 annotations.
    c                 s  s   | ]}t |jd d�V  qdS )r}   ©r|   N©r�   rL   ©rY   Z	parameterr@   r@   rA   Ú	<genexpr>  s   ÿz8_function_annotations_are_pydantic_v1.<locals>.<genexpr>c                 s  s   | ]}t |jd d�V  qdS )r{   r‚   Nrƒ   r„   r@   r@   rA   r…     s   ÿz	Function zv contains a mix of Pydantic v1 and v2 annotations. Only one version of Pydantic annotations per function is supported.)Úanyra   ÚvaluesÚNotImplementedError)r   rR   Zany_v1_annotationsZany_v2_annotationsrp   r@   r@   rA   Ú%_function_annotations_are_pydantic_v1ó   s    þþ
ÿr‰   c                   @  s*   e Zd ZU dZdZded< dZded< dS )	Ú_SchemaConfigzEConfiguration for Pydantic models generated from function signatures.ZforbidrK   ÚextraTrB   Úarbitrary_types_allowedN)r<   r=   r>   r?   r‹   Ú__annotations__rŒ   r@   r@   r@   rA   rŠ     s   
rŠ   )rS   rs   rf   rN   zOptional[Sequence[str]])Ú
model_namerR   rS   rs   rf   rN   rD   c                C  s´  t  |¡}t||ƒr"t|td�}nBt ¡ �* tjdtd� t	|td�}W d  ƒ n1 sZ0    Y  t
|jotd|jv ƒ}d}	d}
|j ¡ D ]&}|j|jkr d}	qŠ|j|jkrŠd}
qŠ|j}|rÂ|}nlt|j ¡ ƒ}|rø|d d	v rø|rø|d gttƒ¢}nttƒ}|D ](}|�st|j| jƒ�r| |¡ �qt|||d
�\}}g }t|ƒD ]P}|	�sd|dk�rd�qL|
�sx|dk�rx�qL|dk�r†�qL||v�rL| |¡ �qLt| |t|ƒ||d�S )aˆ  Create a pydantic schema from a function's signature.

    Args:
        model_name: Name to assign to the generated pydantic schema.
        func: Function to generate the schema from.
        filter_args: Optional list of arguments to exclude from the schema.
            Defaults to FILTERED_ARGS.
        parse_docstring: Whether to parse the function's docstring for descriptions
            for each argument. 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.
        include_injected: Whether to include injected arguments in the schema.
            Defaults to True, since we want to include them in the schema
            when *validating* tool inputs.

    Returns:
        A pydantic model with the same arguments as the function.
    )ÚconfigÚignore)ÚcategoryNÚ.FTr   >   rU   rV   rr   ÚargsÚkwargsZv__duplicate_kwargs)ZdescriptionsÚfn_description)rh   r   r‰   Úvalidate_arguments_v1rŠ   ÚwarningsÚcatch_warningsÚsimplefilterr   r   rB   r>   ra   r‡   ÚkindÚVAR_POSITIONALÚVAR_KEYWORDÚmodelrj   ÚkeysÚFILTERED_ARGSrX   rL   Úappendrz   r.   r-   )rŽ   rR   rS   rs   rf   rN   ÚsigZ	validatedZin_classZhas_argsZ
has_kwargsr\   rQ   Zfilter_args_Zexisting_paramsZexisting_paramrw   rn   Zvalid_propertiesÚfieldr@   r@   rA   Úcreate_schema_from_function  s`    


*
ÿý


ûr£   c                   @  s   e Zd ZdZdS )ÚToolExceptiona  Exception thrown when a tool execution error occurs.

    This exception allows tools to signal errors without stopping the agent.
    The error is handled according to the tool's handle_tool_error setting,
    and the result is returned as an observation to the agent.
    Nr;   r@   r@   r@   rA   r¤   €  s   r¤   c                      sz  e Zd ZU dZdddœ‡ fdd„Zded< 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�Z
ded< eddddd�ed
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%< d&Zd'ed(< dddœ‡ fd)d*„Zedd+�Zedd,œd-d.„ƒZed/d,œd0d1„ƒZed2d,œd3d4„ƒZedbd5d6d7œ‡ fd8d9„ƒZedcd:d5ddd;œd<d=„ƒZeddd:d5ddd;œd>d?„ƒZd@dAdBdCœdDdE„ZedFdG�ed/ddHœdIdJ„ƒƒZ e!ddddKœdLdM„ƒZ"ddddKœdNdO„Z#d@dAdPdCœdQdR„Z$ded
d
d
d
d
d
dTœdBdUdAdAddd dAdVd5dAdddWœdXdY„Z%dfd
d
d
d
d
d
dTœd@dUdAdAddd dAdVd5dAdddWœdZd[„Z&ed\d]dd^�dgdddd_œd`da„ƒZ'‡  Z(S )hÚBaseToolzÓBase class for all LangChain tools.

    This abstract class defines the interface that all LangChain tools must implement.
    Tools are components that can be called by agents to perform specific actions.
    r   rm   )r”   rD   c                   s\   t ƒ jf i |¤Ž | j dd¡}|durX|tkrXd}| j}d|› d|› d|› �}t|ƒ‚dS )a  Validate the tool class definition during subclass creation.

        Args:
            **kwargs: Additional keyword arguments passed to the parent class.

        Raises:
            SchemaAnnotationError: If args_schema has incorrect type annotation.
        Úargs_schemaNzZ
class ChildTool(BaseTool):
    ...
    args_schema: Type[BaseModel] = SchemaClass
    ...zTool definition for z‰ must include valid type annotations for argument 'args_schema' to behave as expected.
Expected annotation of 'Type[BaseModel]' but got 'z'.
Expected class looks like:
)ÚsuperÚ__init_subclass__r�   Úgetr   r<   r:   )rV   r”   Zargs_schema_typeZtypehint_mandaterW   rp   ©Ú	__class__r@   rA   r¨   “  s    	ýûÿzBaseTool.__init_subclass__rK   rW   rw   NzThe tool schema.)Údefaultrw   z1Annotated[Optional[ArgsSchema], SkipValidation()]r¦   FrB   Úreturn_directÚverboseT)r¬   Úexcluder   r4   Úcallback_managerz0.1.7z1.0)rW   ZsinceÚremovalÚalternativez)Callback manager to add to the run trace.)r¬   r¯   rw   zOptional[BaseCallbackManager]zOptional[list[str]]ÚtagszOptional[dict[str, Any]]Úmetadataz:Optional[Union[bool, str, Callable[[ToolException], str]]]Úhandle_tool_errorzVOptional[Union[bool, str, Callable[[Union[ValidationError, ValidationErrorV1]], str]]]Úhandle_validation_errorÚcontentz*Literal['content', 'content_and_artifact']Úresponse_formatc                   s\   d|v rF|d durFt |d ƒsFt|d tƒsFd|d › d�}t|ƒ‚tƒ jf i |¤Ž dS )z�Initialize the tool.

        Raises:
            TypeError: If ``args_schema`` is not a subclass of pydantic ``BaseModel`` or
                dict.
        r¦   NzQargs_schema must be a subclass of pydantic BaseModel or a JSON schema dict. Got: r’   )r/   rJ   rP   r€   r§   Ú__init__)rU   r”   rp   rª   r@   rA   r¹   û  s    ÿ
þ
ýüÿÿzBaseTool.__init__)rŒ   ©rD   c                 C  s   dd„ | j D ƒ}t|ƒdkS )z�Check if the tool accepts only a single input argument.

        Returns:
            True if the tool has only one input argument, False otherwise.
        c                 S  s   h | ]}|d kr|’qS )r”   r@   )rY   r[   r@   r@   rA   Ú	<setcomp>  ó    z+BaseTool.is_single_input.<locals>.<setcomp>rI   )r“   Úlen)rU   rž   r@   r@   rA   Úis_single_input  s    zBaseTool.is_single_inputrP   c                 C  sJ   t | jtƒr| j}n.| jr2t| jtƒr2| j ¡ }n|  ¡ }| ¡ }|d S )zƒGet the tool's input arguments schema.

        Returns:
            Dictionary containing the tool's argument properties.
        rT   )rJ   r¦   rP   r   r~   r^   Úget_input_schemar`   )rU   Zjson_schemaZinput_schemar@   r@   rA   r“     s    zBaseTool.argsÚ
ArgsSchemac                 C  st   t | jtƒr,| jr&i | j¥d| ji¥S | jS |  ¡ }g }t|ƒ ¡ D ]\}}t|ƒsD| |¡ qDt	| j
||| jd�S )z§Get the schema for tool calls, excluding injected arguments.

        Returns:
            The schema that should be used for tool calls from language models.
        rw   )r•   )rJ   r¦   rP   rw   r¿   Úget_all_basemodel_annotationsrc   rX   r    r-   rW   )rU   Zfull_schemaÚfieldsrW   Útype_r@   r@   rA   Útool_call_schema-  s     ÿþÿzBaseTool.tool_call_schemaúOptional[RunnableConfig]rO   )r�   rD   c                   s6   | j dur(t| j tƒr"tƒ  |¡S | j S t| j| jƒS )z¡The tool's input schema.

        Args:
            config: The configuration for the tool.

        Returns:
            The input schema for the tool.
        N)r¦   rJ   rP   r§   r¿   r£   rW   Ú_run)rU   r�   rª   r@   rA   r¿   H  s
    
zBaseTool.get_input_schemaúUnion[str, dict, ToolCall])Úinputr�   r”   rD   c                 K  s(   t ||fi |¤Ž\}}| j|fi |¤ŽS ©N)Ú_prep_run_argsÚrun©rU   rÈ   r�   r”   Ú
tool_inputr@   r@   rA   ÚinvokeZ  s    zBaseTool.invokec                 Ë  s.   t ||fi |¤Ž\}}| j|fi |¤ŽI d H S rÉ   )rÊ   ÚarunrÌ   r@   r@   rA   Úainvoked  s    zBaseTool.ainvokeúUnion[str, dict]úOptional[str]zUnion[str, dict[str, Any]])rÍ   Útool_call_idrD   c           	        s–  | j }tˆtƒrŒ|durˆt|tƒr.d}t|ƒ‚ttt|ƒ ¡ ƒƒ}t	|t
ƒr\| |ˆi¡ n,t	|tƒrv| |ˆi¡ nd|› �}t|ƒ‚ˆS |du�r’t|tƒr¤ˆS t	|t
ƒ�rt|ƒ ¡ D ]0\}}t|td�r¼|du räd}t|ƒ‚|ˆ|< q¼| ˆ¡‰ ˆ  ¡ }nxt	|tƒ�rft|ƒ ¡ D ]6\}}t|td��r|du �rFd}t|ƒ‚|ˆ|< �q| ˆ¡‰ ˆ  ¡ }nd| j › �}t|ƒ‚‡ ‡fdd„| ¡ D ƒS ˆS )a$  Parse and validate tool input using the args schema.

        Args:
            tool_input: The raw input to the tool.
            tool_call_id: The ID of the tool call, if available.

        Returns:
            The parsed and validated input.

        Raises:
            ValueError: If string input is provided with JSON schema ``args_schema``.
            ValueError: If InjectedToolCallId is required but ``tool_call_id`` is not
                provided.
            TypeError: If args_schema is not a Pydantic ``BaseModel`` or dict.
        NzQString tool inputs are not allowed when using tools with JSON schema args_schema.z.args_schema must be a Pydantic BaseModel, got ©Úinjected_typezÁWhen tool includes an InjectedToolCallId argument, tool must always be invoked with a full model ToolCall of the form: {'args': {...}, 'name': '...', 'type': 'tool_call', 'tool_call_id': '...'}c                   s$   i | ]\}}|ˆv r|t ˆ |ƒ“qS r@   )Úgetattr©rY   r[   Úv©ÚresultrÍ   r@   rA   r_   º  s   z)BaseTool._parse_input.<locals>.<dictcomp>)r¦   rJ   rK   rP   ro   ÚnextÚiterr.   rž   r   r   Zmodel_validater~   Z	parse_objr€   rÁ   rc   rX   ÚInjectedToolCallIdZ
model_dumprˆ   )	rU   rÍ   rÓ   Z
input_argsrp   Úkey_r[   rØ   Zresult_dictr@   rÙ   rA   Ú_parse_inputp  sZ    

ÿ




ÿ



ÿ


ÿÿzBaseTool._parse_inputÚbefore)Úmode)r‡   rD   c                 C  s2   |  d¡dur.tjdtdd� | dd¡|d< |S )z®Raise deprecation warning if callback_manager is used.

        Args:
            values: The values to validate.

        Returns:
            The validated values.
        r°   Nz=callback_manager is deprecated. Please use callbacks instead.é   )Ú
stacklevelr4   )r©   r—   ÚwarnÚDeprecationWarningÚpop)rV   r‡   r@   r@   rA   Úraise_deprecation¿  s    ýzBaseTool.raise_deprecation)r“   r”   rD   c                 O  s   dS )zÏUse the tool.

        Add run_manager: Optional[CallbackManagerForToolRun] = None
        to child implementations to enable tracing.

        Returns:
            The result of the tool execution.
        Nr@   ©rU   r“   r”   r@   r@   rA   rÆ   Ó  s    zBaseTool._runc                 Ï  sL   |  d¡r,t| jƒj  d¡r,|d  ¡ |d< td| jg|¢R i |¤ŽI dH S )zãUse the tool asynchronously.

        Add run_manager: Optional[AsyncCallbackManagerForToolRun] = None
        to child implementations to enable tracing.

        Returns:
            The result of the tool execution.
        r3   N)r©   r   rÆ   ra   Zget_syncr'   rè   r@   r@   rA   Ú_arunÞ  s
    	ÿzBaseTool._arunztuple[tuple, dict]c                 C  s‚   | j dur2t| j tƒr2t| j ƒr2t| j ƒs2di fS |  ||¡}t|tƒrR|fi fS t|tƒrhd| ¡ fS dt|ƒ› �}t	|ƒ‚dS )aa  Convert tool input to positional and keyword arguments.

        Args:
            tool_input: The input to the tool.
            tool_call_id: The ID of the tool call, if available.

        Returns:
            A tuple of (positional_args, keyword_args) for the tool.

        Raises:
            TypeError: If the tool input type is invalid.
        Nr@   zInvalid tool input type: )
r¦   rJ   rG   r/   r.   rß   rK   rP   Úcopyr€   )rU   rÍ   rÓ   rp   r@   r@   rA   Ú_to_args_and_kwargsí  s     ÿ
þýü


zBaseTool._to_args_and_kwargsÚgreen)r³   r´   Úrun_nameÚrun_idr�   rÓ   zOptional[bool]zOptional[uuid.UUID])rÍ   r®   Ústart_colorÚcolorr4   r³   r´   rí   rî   r�   rÓ   r”   rD   c             
   K  sl  t  || j| jpt|ƒ|| j|| j¡}|j| j| j	dœt
|tƒrD|nt|ƒf|||	t
|tƒr`|nddœ|¤Ž}d}d}d}d}zît|
| ¡ d�}t|ƒ�r}|  ||¡\}}t| jƒj d¡rÈ|d|iO }t| jƒ }râ|||
iO }|j| jg|¢R i |¤Ž}W d  ƒ n1 �s0    Y  | jdk�rft
|tƒ�rBt|ƒdk�r\d	t|ƒ› d
�}t|ƒ}n|\}}n|}W nº ttf�y¶ } z,| j�s�|}nt|| jd�}d}W Y d}~nzd}~0  t �yú } z,| j!�sÔ|}nt"|| j!d�}d}W Y d}~n6d}~0  t#t$f�y& } z|}W Y d}~n
d}~0 0 |�r<| %|¡ |‚t&|||| j|ƒ}|j'|f|| jdœ|¤Ž |S )a&  Run the tool.

        Args:
            tool_input: The input to the tool.
            verbose: Whether to log the tool's progress. Defaults to None.
            start_color: The color to use when starting the tool. Defaults to 'green'.
            color: The color to use when ending the tool. Defaults to 'green'.
            callbacks: Callbacks to be called during tool execution. Defaults to None.
            tags: Optional list of tags associated with the tool. Defaults to None.
            metadata: Optional metadata associated with the tool. Defaults to None.
            run_name: The name of the run. Defaults to None.
            run_id: The id of the run. Defaults to None.
            config: The configuration for the tool. Defaults to None.
            tool_call_id: The id of the tool call. Defaults to None.
            kwargs: Keyword arguments to be passed to tool callbacks (event handler)

        Returns:
            The output of the tool.

        Raises:
            ToolException: If an error occurs during tool execution.
        ©rW   rw   N©rð   rW   rî   ÚinputsÚsuccess©r4   r3   Úcontent_and_artifacté   ú•Since response_format='content_and_artifact' a two-tuple of the message content and raw tool output is expected. Instead generated response of type: r’   ©ÚflagÚerror©rð   rW   )(r   Ú	configurer4   r®   rB   r³   r´   Úon_tool_startrW   rw   rJ   rK   rP   r&   Ú	get_childr(   rë   r   rÆ   ra   r©   Ú_get_runnable_config_paramrË   r¸   Útupler½   rG   ro   r   ÚValidationErrorV1r¶   Ú_handle_validation_errorr¤   rµ   Ú_handle_tool_errorÚ	ExceptionÚKeyboardInterruptÚon_tool_errorÚ_format_outputÚon_tool_end)rU   rÍ   r®   rï   rð   r4   r³   r´   rí   rî   r�   rÓ   r”   r°   r3   r·   ÚartifactÚstatusÚerror_to_raiseÚchild_configÚcontextÚ	tool_argsÚtool_kwargsÚconfig_paramÚresponserp   ÚeÚoutputr@   r@   rA   rË     s|    &ù
þöõ
ÿ:ýÿ


zBaseTool.runc             
   Ë  s�  t  || j| jpt|ƒ|| j|| j¡}|j| j| j	dœt
|tƒrD|nt|ƒf|||	t
|tƒr`|nddœ|¤ŽI dH }d}d}d}d}�z|  ||¡\}}t|
| ¡ d�}t|ƒ�v}| jjtju rÆ| jn| j}t|ƒj d¡rä||d< t|ƒ }rø|
||< | j|i |¤Ž}t||ƒI dH }W d  ƒ n1 �s.0    Y  | jdk�r‚t
|tƒ�r^t|ƒdk�rxd	t|ƒ› d
�}t|ƒ}n|\}}n|}W n¶ t�yÎ } z,| j �s¨|}nt!|| j d�}d}W Y d}~nzd}~0  t"�y } z,| j#�sì|}nt$|| j#d�}d}W Y d}~n6d}~0  t%t&f�y> } z|}W Y d}~n
d}~0 0 |�rZ| '|¡I dH  |‚t(|||| j|ƒ}|j)|f|| jdœ|¤ŽI dH  |S )a%  Run the tool asynchronously.

        Args:
            tool_input: The input to the tool.
            verbose: Whether to log the tool's progress. Defaults to None.
            start_color: The color to use when starting the tool. Defaults to 'green'.
            color: The color to use when ending the tool. Defaults to 'green'.
            callbacks: Callbacks to be called during tool execution. Defaults to None.
            tags: Optional list of tags associated with the tool. Defaults to None.
            metadata: Optional metadata associated with the tool. Defaults to None.
            run_name: The name of the run. Defaults to None.
            run_id: The id of the run. Defaults to None.
            config: The configuration for the tool. Defaults to None.
            tool_call_id: The id of the tool call. Defaults to None.
            kwargs: Keyword arguments to be passed to tool callbacks

        Returns:
            The output of the tool.

        Raises:
            ToolException: If an error occurs during tool execution.
        rñ   Nrò   rô   rõ   r3   rö   r÷   rø   r’   rù   rû   rü   )*r   rý   r4   r®   rB   r³   r´   rþ   rW   rw   rJ   rK   rP   rë   r&   rÿ   r(   r«   ré   r¥   rÆ   r   ra   r©   r   r)   r¸   r  r½   rG   ro   r   r¶   r  r¤   rµ   r  r  r  r  r  r	  )rU   rÍ   r®   rï   rð   r4   r³   r´   rí   rî   r�   rÓ   r”   r°   r3   r·   r
  r  r  r  r  r  r  Zfunc_to_checkr  Úcoror  rp   r  r  r@   r@   rA   rÏ   „  s~    &ù	þöõ
ÿ0ýÿ

 zBaseTool.arunz0.1.47rÎ   )r²   r±   )rÍ   r4   rD   c                 C  s   | j ||d�S )zÒMake tool callable (deprecated).

        Args:
            tool_input: The input to the tool.
            callbacks: Callbacks to use during execution.

        Returns:
            The tool's output.
        rõ   )rË   )rU   rÍ   r4   r@   r@   rA   Ú__call__ö  s    zBaseTool.__call__)N)N)N)Nrì   rì   N)Nrì   rì   N)N))r<   r=   r>   r?   r¨   r�   r   r¦   r­   r®   r4   r   r°   r³   r´   rµ   r¶   r¸   r¹   r   Zmodel_configÚpropertyr¾   r“   rÄ   r   r¿   rÎ   rÐ   rß   r   Úclassmethodrç   r   rÆ   ré   rë   rË   rÏ   r  Ú__classcell__r@   r@   rª   rA   r¥   Œ  sž   
!ÿÿýý	ÿ
þ
ÿ	 ÿ ý	 ýO
*    úó*s    úó*rr¥   )ÚxrD   c                 C  s   t | tƒo|  d¡dkS )z¥Check if the input is a tool call dictionary.

    Args:
        x: The input to check.

    Returns:
        True if the input is a tool call, False otherwise.
    rG   Z	tool_call)rJ   rP   r©   )r  r@   r@   rA   Ú_is_tool_call  s    	r  z)Union[ValidationError, ValidationErrorV1]zUUnion[Literal[True], str, Callable[[Union[ValidationError, ValidationErrorV1]], str]])r  rú   rD   c                C  sH   t |tƒrd}n4t |tƒr |}n$t|ƒr2|| ƒ}nd|› �}t|ƒ‚|S )a,  Handle validation errors based on the configured flag.

    Args:
        e: The validation error that occurred.
        flag: How to handle the error (bool, string, or callable).

    Returns:
        The error message to return.

    Raises:
        ValueError: If the flag type is unexpected.
    zTool input validation errorz\Got unexpected type of `handle_validation_error`. Expected bool, str or callable. Received: )rJ   rB   rK   Úcallablero   ©r  rú   r·   rp   r@   r@   rA   r    s    


ÿÿr  zCOptional[Union[Literal[True], str, Callable[[ToolException], str]]]c                C  sX   t |tƒr | jr| jd nd}n4t |tƒr0|}n$t|ƒrB|| ƒ}nd|› �}t|ƒ‚|S )a.  Handle tool execution errors based on the configured flag.

    Args:
        e: The tool exception that occurred.
        flag: How to handle the error (bool, string, or callable).

    Returns:
        The error message to return.

    Raises:
        ValueError: If the flag type is unexpected.
    r   zTool execution errorzVGot unexpected type of `handle_tool_error`. Expected bool, str or callable. Received: )rJ   rB   r“   rK   r  ro   r  r@   r@   rA   r  2  s    


ÿÿr  rÇ   rÅ   ztuple[Union[str, dict], dict])Úvaluer�   r”   rD   c                 K  s‚   t |ƒ}t| ƒr2td| ƒd }td| ƒd  ¡ }nd}td| ƒ}|tf | d¡| d¡| d¡| d	¡| d
d¡||dœ|¤ŽfS )a  Prepare arguments for tool execution.

    Args:
        value: The input value (string, dict, or ToolCall).
        config: The runnable configuration.
        **kwargs: Additional keyword arguments.

    Returns:
        A tuple of (tool_input, run_kwargs).
    r    Úidr“   NrÑ   r4   r³   r´   rí   rî   )r4   r³   r´   rí   rî   r�   rÓ   )r%   r  r   rê   rP   r©   ræ   )r  r�   r”   rÓ   rÍ   r@   r@   rA   rÊ   R  s&    

ùøþrÊ   rÒ   zUnion[ToolOutputMixin, Any])r·   r
  rÓ   rW   r  rD   c                 C  s8   t | tƒs|du r| S t| ƒs&t| ƒ} t| ||||d�S )a‚  Format tool output as a ToolMessage if appropriate.

    Args:
        content: The main content of the tool output.
        artifact: Any artifact data from the tool.
        tool_call_id: The ID of the tool call.
        name: The name of the tool.
        status: The execution status.

    Returns:
        The formatted output, either as a ToolMessage or the original content.
    N)r
  rÓ   rW   r  )rJ   r"   Ú_is_message_content_typeÚ
_stringifyr!   )r·   r
  rÓ   rW   r  r@   r@   rA   r  w  s    ûr  )ÚobjrD   c                 C  s&   t | tƒp$t | tƒo$tdd„ | D ƒƒS )zûCheck if object is valid message content format.

    Validates content for OpenAI or Anthropic format tool messages.

    Args:
        obj: The object to check.

    Returns:
        True if the object is valid message content, False otherwise.
    c                 s  s   | ]}t |ƒV  qd S rÉ   )Ú_is_message_content_block)rY   r  r@   r@   rA   r…   £  r¼   z+_is_message_content_type.<locals>.<genexpr>)rJ   rK   rj   Úall©r"  r@   r@   rA   r   —  s    
ÿr   c                 C  s,   t | tƒrdS t | tƒr(|  dd¡tv S dS )zõCheck if object is a valid message content block.

    Validates content blocks for OpenAI or Anthropic format.

    Args:
        obj: The object to check.

    Returns:
        True if the object is a valid content block, False otherwise.
    TrG   NF)rJ   rK   rP   r©   ÚTOOL_MESSAGE_BLOCK_TYPESr%  r@   r@   rA   r#  §  s
    

r#  )r·   rD   c                 C  s0   zt j| dd�W S  ty*   t| ƒ Y S 0 dS )z©Convert content to string, preferring JSON format.

    Args:
        content: The content to stringify.

    Returns:
        String representation of the content.
    F)Úensure_asciiN)r7   Údumpsr  rK   )r·   r@   r@   rA   r!  ¹  s    	r!  zOptional[dict[str, type]])rR   rD   c                 C  s6   t | tjƒr| j} z
t| ƒW S  ty0   Y dS 0 dS )zËGet type hints from a function, handling partial functions.

    Args:
        func: The function to get type hints from.

    Returns:
        Dictionary of type hints, or None if extraction fails.
    N)rJ   Ú	functoolsÚpartialrR   r   r  )rR   r@   r@   rA   Ú_get_type_hintsÈ  s    	
r+  c                 C  s6   t | ƒ}|sdS | ¡ D ]\}}|tu r|  S qdS )zÁFind the parameter name for RunnableConfig in a function.

    Args:
        func: The function to check.

    Returns:
        The parameter name for RunnableConfig, or None if not found.
    N)r+  rc   r#   )rR   Z
type_hintsrW   rÃ   r@   r@   rA   r   Ù  s    	
r   c                   @  s   e Zd ZdZdS )ÚInjectedToolArgzÙAnnotation for tool arguments that are injected at runtime.

    Tool arguments annotated with this class are not included in the tool
    schema sent to language models and are instead injected during execution.
    Nr;   r@   r@   r@   rA   r,  ë  s   r,  c                   @  s   e Zd ZdZdS )rÝ   a¥  Annotation for injecting the tool call ID.

    This annotation is used to mark a tool parameter that should receive
    the tool call ID at runtime.

    .. code-block:: python

        from typing_extensions import Annotated
        from langchain_core.messages import ToolMessage
        from langchain_core.tools import tool, InjectedToolCallId

        @tool
        def foo(
            x: int, tool_call_id: Annotated[str, InjectedToolCallId]
        ) -> ToolMessage:
            """Return x."""
            return ToolMessage(
                str(x),
                artifact=x,
                name="foo",
                tool_call_id=tool_call_id
            )

    Nr;   r@   r@   r@   rA   rÝ   ó  s   rÝ   zUnion[type, TypeVar]zOptional[type[InjectedToolArg]])rÃ   rÕ   rD   c                   s*   ˆ pt ‰ t‡ fdd„t| ƒdd… D ƒƒS )a  Check if a type annotation indicates an injected argument.

    Args:
        type_: The type annotation to check.
        injected_type: The specific injected type to check for.

    Returns:
        True if the type is an injected argument, False otherwise.
    c                 3  s,   | ]$}t |ˆ ƒp"t |tƒo"t|ˆ ƒV  qd S rÉ   )rJ   rG   r   ©rY   rx   rÔ   r@   rA   r…     s   þ
z(_is_injected_arg_type.<locals>.<genexpr>rI   N)r,  r†   r   )rÃ   rÕ   r@   rÔ   rA   rX     s    ýrX   ©Údefault_to_boundzUnion[TypeBaseModel, Any]zdict[str, Union[type, TypeVar]])rV   r/  rD   c                  sB  t | tƒr|t| ƒ}dd„ | ¡ D ƒ}i }t | ¡j ¡ D ]4\}}|rV||vrV||vrVq8| ||¡}|j||< q8t	| ddƒ}nt
t| ƒdd�}| f}t | tƒr¦t| ƒ�s,|D ]€}	t |	tƒrÔt|	ƒrÔ| t
|	dd�¡ qªt|	ƒ}
|
sâqªt	|
ddƒ}tt|t|	ƒƒƒ}t	|
di ƒD ]}t|| |ˆ d�||< �qqª‡ fd	d„| ¡ D ƒS )
a  Get all annotations from a Pydantic BaseModel and its parents.

    Args:
        cls: The Pydantic BaseModel class.
        default_to_bound: Whether to default to the bound of a TypeVar if it exists.

    Returns:
        A dictionary of field names to their type annotations.
    c                 S  s   i | ]\}}|j r|j |“qS r@   )Úalias)rY   rW   r¢   r@   r@   rA   r_   1  r¼   z1get_all_basemodel_annotations.<locals>.<dictcomp>Ú__orig_bases__r@   Fr.  Ú__parameters__r�   c                   s   i | ]\}}|t |ˆ d �“qS )r.  ©Ú_replace_type_varsr×   r.  r@   rA   r_   b  s   ÿ)rJ   rG   r.   rc   rh   r   ra   r©   rL   rÖ   rÁ   r   r1   r0   ÚupdaterP   Úzipr   r4  )rV   r/  rÂ   Z	alias_mapr   rW   r\   Ú
field_nameZ
orig_basesÚparentZparent_originZgeneric_type_varsÚgeneric_mapr¢   r@   r.  rA   rÁ   "  sB    
ÿ
ÿ
ÿ
þrÁ   zOptional[dict[TypeVar, type]])rÃ   r9  r/  rD   c                  s~   ˆpi ‰t | tƒr>| ˆv r"ˆ|  S ˆ r:| jdur6| jS tS | S t| ƒ }rzt| ƒ }rzt‡ ‡fdd„|D ƒƒ}t|ƒ| S | S )a1  Replace TypeVars in a type annotation with concrete types.

    Args:
        type_: The type annotation to process.
        generic_map: Mapping of TypeVars to concrete types.
        default_to_bound: Whether to use TypeVar bounds as defaults.

    Returns:
        The type with TypeVars replaced.
    Nc                 3  s   | ]}t |ˆˆ d �V  qdS )r.  Nr3  r-  ©r/  r9  r@   rA   r…   €  s   ÿz%_replace_type_vars.<locals>.<genexpr>)rJ   r   Ú	__bound__r   r   r   r  r+   )rÃ   r9  r/  Úoriginr“   Únew_argsr@   r:  rA   r4  h  s    
þr4  c                   @  s"   e Zd ZdZeddœdd„ƒZdS )ÚBaseToolkitzÄBase class for toolkits containing related tools.

    A toolkit is a collection of related tools that can be used together
    to accomplish a specific task or work with a particular system.
    zlist[BaseTool]rº   c                 C  s   dS )zmGet all tools in the toolkit.

        Returns:
            List of tools contained in this toolkit.
        Nr@   )rU   r@   r@   rA   Ú	get_tools�  s    zBaseToolkit.get_toolsN)r<   r=   r>   r?   r   r?  r@   r@   r@   rA   r>  ˆ  s   r>  )r{   )N)N)mr?   Ú
__future__r   r)  rh   r7   rE   r—   Úabcr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   Zpydanticr   r   r   r   r   r   r   r   Zpydantic.v1r~   r  r–   Ztyping_extensionsr   Zlangchain_core._apir   Zlangchain_core.callbacksr   r   r   r   Zlangchain_core.messages.toolr    r!   r"   Zlangchain_core.runnablesr#   r$   r%   r&   r'   Zlangchain_core.runnables.configr(   Zlangchain_core.runnables.utilsr)   Z%langchain_core.utils.function_callingr*   r+   Zlangchain_core.utils.pydanticr,   r-   r.   r/   r0   r1   ÚuuidÚcollections.abcr2   rŸ   r&  r€   r:   rF   rM   rd   rl   rq   rz   r�   r‰   rŠ   r£   r  r¤   rP   rK   rÀ   r¥   r  r  r  rÊ   r  r   r#  r!  r+  r   r,  rÝ   rX   rÁ   r4  r>  r@   r@   r@   rA   Ú<module>   s”   8(
 	ûÿü" ùd	"    |" %  ÿÿH þü 