
    g3fi                    D   U 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 ddlmZmZmZmZmZmZmZmZm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! 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* ddl+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z=m>Z>m?Z?m@Z@mAZAmBZB er
ddlCZCddlmDZD dZEdZF G d deG      ZHdHdZIdIdZJdd	 	 	 	 	 	 	 	 	 dJdZKdd 	 	 	 	 	 	 	 dKd!ZL	 	 	 	 	 	 dLd"ZMddd#	 	 	 	 	 	 	 dMd$ZNdNdOd%ZO	 	 	 	 	 	 dPd&ZP G d' d(      ZQddddd)	 	 	 	 	 	 	 	 	 	 	 	 	 dQd*ZR G d+ d,eS      ZTe=eUeVef   z  ZW eX       ZYd-eZd.<    G d/ d0e1eVeUz  e,z  ef         Z[dRd1Z\	 	 	 	 	 	 dSd2Z]	 	 	 	 	 	 dTd3Z^	 	 	 	 	 	 	 	 dUd4Z_	 	 	 	 	 	 	 	 	 	 	 	 dVd5Z`dWd6ZadWd7ZbdXd8ZcdYd9ZddZd:Ze G d; d<      Zf G d= d>      Zg G d? d@ef      Zhd[dAZi	 d\	 	 	 	 	 d]dBZjddC	 	 	 	 	 d^dDZk	 d\ddC	 	 	 	 	 	 	 d_dEZl G dF dGee	      Zmy)`z/Base classes and utilities for LangChain tools.    )annotationsN)ABCabstractmethod)Callable)	signature)	TYPE_CHECKING	AnnotatedAnyLiteralTypeVarcastget_args
get_originget_type_hints)	BaseModel
ConfigDictFieldPydanticDeprecationWarningSkipValidationValidationErrorvalidate_arguments)	FieldInfo)r   )r   )r   )override)AsyncCallbackManager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)text	image_urlimagejsonsearch_resultcustom_tool_call_outputdocumentfilec                      e Zd ZdZy)SchemaAnnotationErrorzGRaised when args_schema is missing or has an incorrect type annotation.N__name__
__module____qualname____doc__     W/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/tools/base.pyr;   r;   V   s    QrB   r;   c                X    t        |       t        j                  t        j                  hv S )zCheck 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	   typing_extensions)typs    rC   _is_annotated_typerH   Z   s%     c?v//1B1L1LMMMrB   c                    t        |       rTt        |       }|dd D ]A  }t        |t              r|c S t        |t              s(|j
                  s5|j
                  c S  y)a  Extract description from an Annotated type.

    Checks for string annotations and `FieldInfo` objects with descriptions.

    Args:
        arg_type: The type to extract description from.

    Returns:
        The description string if found, None otherwise.
       N)rH   r   
isinstancestrr   description)arg_typeannotated_args
annotations      rC   _get_annotation_descriptionrQ   f   s_     (#!(+(, 	.J*c*!!*i0Z5K5K!---		.
 rB   T)include_injectedc               &   | j                         d   }t        |      j                  }t        |j	                               D ci c]<  \  }\  }}||vr0|dkD  s|j
                  dvr|st        |j                        s|||   > c}}}S c c}}}w )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.
    
propertiesr   >   clsself)model_json_schemar   
parameters	enumerateitemsname_is_injected_arg_typerP   )	inferred_modelfuncfilter_argsrR   schema
valid_keysikparams	            rC   _get_filtered_argsre   {   s    $ --/=F4++J 'z'7'7'9: Az5KUejj7%:5;K;K%L	 	
6!9  s   ABFerror_on_invalid_docstringc               Z    t        j                  |       }t        |t        |      |      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.
    rf   )inspectgetdocr'   list)functionr   rg   	docstrings       rC    _parse_python_function_docstringrn      s-     x(I"[#= rB   c                <    | D ]  }||vsd| d}t        |       y)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)arg_descriptionsr   docstring_argmsgs       rC   ,_validate_docstring_args_against_annotationsrt      s4     * "+'UVCS/!"rB   parse_docstringrg   c                  t        j                  | d      }|rt        | ||      \  }}nt        j                  |       xs d}i }|rt        ||        |j                         D ]  \  }}||v rt        |      x}s|||<    ||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_extrasrf    )rE   r   rn   ri   rj   rt   rZ   rQ   )	fnrv   rg   r   rM   rq   argrN   descs	            rC   _infer_arg_descriptionsr}      s      ''4@K(H8R)
%% nnR(.B45E{S***, )X"".x8848$(S!	)
 (((rB   c                \    |dk(  rt         nt        }	 t        | |      S # t        $ r Y yw xY w)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.
    v1F)BaseModelV1r   
issubclass	TypeError)rP   pydantic_versionbase_model_classs      rC   _is_pydantic_annotationr      s8     '7$&>{I*&677 s    	++c                    t        d | j                  j                         D              }t        d | j                  j                         D              }|r|rd| d}t        |      |xr | S )aa  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              3  J   K   | ]  }t        |j                  d         yw)r   r   Nr   rP   .0	parameters     rC   	<genexpr>z8_function_annotations_are_pydantic_v1.<locals>.<genexpr>  (       	 	 4 4tLL   !#c              3  J   K   | ]  }t        |j                  d         yw)v2r   Nr   r   s     rC   r   z8_function_annotations_are_pydantic_v1.<locals>.<genexpr>  r   r   z	Function zv contains a mix of Pydantic v1 and v2 annotations. Only one version of Pydantic annotations per function is supported.)anyrX   valuesNotImplementedError)r   r^   any_v1_annotationsany_v2_annotationsrs   s        rC   %_function_annotations_are_pydantic_v1r      s      "--446   "--446  0v R R 	 "#&&8&8"88rB   c                  0    e Zd ZU dZdZded<   	 dZded<   y)	_SchemaConfigzEConfiguration for Pydantic models generated from function signatures.forbidrL   extraTboolarbitrary_types_allowedN)r=   r>   r?   r@   r   __annotations__r   rA   rB   rC   r   r     s     OE35$(T(8rB   r   )r_   rv   rg   rR   c               (   t        j                  |      }t        ||      rt        |t              }nIt        j                         5  t        j                  dt               t        |t              }ddd       t        |j                  xr d|j                  v       }d}	d}
|j                  j                         D ]:  }|j                  |j                  k(  rd}	|j                  |j                   k(  s9d}
< j"                  }|r|}nt%        |j                  j'                               }|r|d   d	v r|r|d   gt%        t(              }nt%        t(              }|D ]9  }|rt+        |j                  |   j,                        s)|j/                  |       ; t1        |||
      \  }}g }t3        |      D ].  }|	s|dk(  r|
s|dk(  r|dk(  r||vs|j/                  |       0 t5        | |t%        |      ||      S # 1 sw Y   xY w)aZ  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.
        error_on_invalid_docstring: if `parse_docstring` is provided, configure
            whether to raise `ValueError` on invalid Google Style docstrings.
        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   ru   argskwargsv__duplicate_kwargs)descriptionsfn_description)ri   r   r   validate_arguments_v1r   warningscatch_warningssimplefilterr   r   r   r?   rX   r   kindVAR_POSITIONALVAR_KEYWORDmodelrk   keysFILTERED_ARGSr\   rP   appendr}   r+   r*   )
model_namer^   r_   rv   rg   rR   sig	validatedin_classhas_args
has_kwargsrd   r]   filter_args_existing_paramsexisting_paramrM   rq   valid_propertiesfields                       rC   create_schema_from_functionr     s   6 

D
!C,S$7)$}E	 $$& 	G !!(5OP*4FI	G D%%B#1B1B*BCHHJ&&( ::---HZZ5,,,J	 __N" &*#..*=*=*?%@q1_D+A.Em1DEL.L- 	4N#(=~.99) ##N3		4 %<'#=%!K! N+ 
+EVOex/))$##E*
+  %" s	G 	Gs   -HHc                      e Zd ZdZy)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<   rA   rB   rC   r   r     s    rB   r   frozenset[str]
_EMPTY_SETc                      e Zd ZU dZd0 fdZded<   	 de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<   	 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<   	 d0 fdZ ed       Zed1d!       Zed2d"       Zed3d#       Zej2                  d4d$       Zed5d6 fd%       Ze	 d5	 	 	 	 	 	 	 d7d&       Ze	 d5	 	 	 	 	 	 	 d7d'       Z	 	 	 	 	 	 d8d(Ze d9d)       Z!d9d*Z"d:d+Z#	 	 	 	 	 	 d;d,Z$	 	 	 	 d<ddddddd-	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d=d.Z%	 	 	 	 d<ddddddd-	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d>d/Z& xZ'S )?BaseToolzBase 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.
    c                    t        |   di | | j                  j                  dd      }|.|t        k(  r$d}| j
                  }d| d| d| }t        |      yy)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:
rA   )super__init_subclass__r   getr   r=   r;   )rU   r   args_schema_typetypehint_mandater[   rs   	__class__s         rC   r   zBaseTool.__init_subclass__  s     	!+F+..22=$G',<	,I 
 <<D&tf - .. //#$&  (,,% -J'rB   rL   r[   rM   NzThe tool schema.)defaultrM   z.Annotated[ArgsSchema | None, SkipValidation()]r   Fr   return_directverboseT)r   excluder   r1   list[str] | Nonetagsdict[str, Any] | Nonemetadataz2bool | str | Callable[[ToolException], str] | Nonehandle_tool_errorzHbool | str | Callable[[ValidationError | ValidationErrorV1], str] | Nonehandle_validation_errorcontentz*Literal['content', 'content_and_artifact']response_formatextrasc                    d|v r:|d   5t        |d         s't        |d   t              sd|d    d}t        |      t	        |   di | y)zInitialize 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   rA   )r,   rK   dictr   r   __init__)rV   r   rs   r   s      rC   r   zBaseTool.__init__  sm     V#}%1)&*?@vm4d;,,2=,A+B!E  C. "6"rB   )r   c                f    | j                   D ch c]
  }|dk7  s	| }}t        |      dk(  S c c}w )zCheck if the tool accepts only a single input argument.

        Returns:
            `True` if the tool has only one input argument, `False` otherwise.
        r   rJ   )r   len)rV   rc   r   s      rC   is_single_inputzBaseTool.is_single_input#  s4      996aX664yA~ 7s   
..c                N   t        | j                  t              r| j                  }np| j                  r5t        | j                  t              r| j                  j                         }n/| j                  }t        |t              r|}n|j                         }t        d|d         S )zGet the tool's input arguments schema.

        Returns:
            `dict` containing the tool's argument properties.
        r   rT   )	rK   r   r   r   r   r`   tool_call_schemarW   r   )rV   json_schemainput_schemas      rC   r   zBaseTool.args-  s     d&&-**K*T-=-={"K**113K00L,-**<<>FK566rB   c                   t        | j                  t              r4| j                  ri | j                  d| j                  iS | j                  S | j	                         }g }t        |      j                         D ]"  \  }}t        |      r|j                  |       $ t        | j                  ||| j                        S )zGet the schema for tool calls, excluding injected arguments.

        Returns:
            The schema that should be used for tool calls from language models.
        rM   )r   )rK   r   r   rM   get_input_schemaget_all_basemodel_annotationsrZ   r\   r   r*   r[   )rV   full_schemafieldsr[   type_s        rC   r   zBaseTool.tool_call_schema@  s     d&&-&&!4#3#3 
 ###++-8EKKM 	$KD%(/d#	$ $II{F4;K;K
 	
rB   c                    t         S N)r   rV   s    rC   _injected_args_keyszBaseTool._injected_args_keysY  s
     rB   c                    | j                   5t        | j                   t              rt        |   |      S | j                   S t        | j                  | j                        S )zThe tool's input schema.

        Args:
            config: The configuration for the tool.

        Returns:
            The input schema for the tool.
        )r   rK   r   r   r   r   r[   _run)rV   r   r   s     rC   r   zBaseTool.get_input_schema`  sR     '$**D1w/77###*499dii@@rB   c                H    t        ||fi |\  }} | j                  |fi |S r   )_prep_run_argsrunrV   inputr   r   
tool_inputs        rC   invokezBaseTool.invokep  s0     ,E6DVD
Ftxx
-f--rB   c                d   K   t        ||fi |\  }} | j                  |fi | d {   S 7 wr   )r   arunr   s        rC   ainvokezBaseTool.ainvokez  s:      ,E6DVD
FTYYz4V4444s   '0.0c                (   | j                   }t        |t              r|t        |t              rd}t	        |      t        t        t        |      j                                     }t        |t              r|j                  ||i       |S t        |t              r|j                  ||i       |S d| }t        |      |S |t        |t              r|S t        |t              rit        |      j!                         D ]+  \  }}t#        |t$              s|d}t	        |      |||<   - |j                  |      }|j'                         }	nt        |t              rit        |      j!                         D ]+  \  }}t#        |t$              s|d}t	        |      |||<   - |j                  |      }|j                         }	nd| j                    }t)        |      t        |      }
i }|	D ]b  }||v rt+        ||      ||<   ||
v s|dvs!|
|   }t-        |d      r|j/                          nt+        |dd       }|sTt+        ||      ||<   d | j0                  D ])  }||v r	||   ||<   |d	k(  s|d}t	        |      |||<   + |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.
        zQString tool inputs are not allowed when using tools with JSON schema args_schema.z.args_schema must be a Pydantic BaseModel, got )injected_typezWhen 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': '...'})r   r   is_requiredrequiredTtool_call_id)r   rK   rL   r   rp   nextiterr+   r   r   r   model_validater   	parse_objr   r   rZ   r\   InjectedToolCallId
model_dumpr   getattrhasattrr   r   )rV   r   r   
input_argsrs   key_rc   vresultresult_dict
field_infovalidated_inputfihas_defaults                 rC   _parse_inputzBaseTool._parse_input  s   $ %%
j#&%j$/D  %S/)DJ!7!<!<!>?@j)4--tZ.@A   
K8(($
);<  K:,WC#C.(!*d+!!*i09*EKKM 5DAq,Q>PQ'/!9   #-S/1(4
15 $22:>$//1J49*EKKM 5DAq,Q>PQ'/!9   #-S/1(4
15 $--j9$kkm ETEUEUDVW  *#..
 $J/J O  @
?)0);OA&*_2D)D $AB #2}5 NN,,!(Z!>>  
 #-4VQ-?*!@$ -- 6
?)3AOA&.(#+5  )o-)5OA&6 #"rB   c                     y)zUse the tool.

        Add `run_manager: CallbackManagerForToolRun | None = None` to child
        implementations to enable tracing.

        Returns:
            The result of the tool execution.
        NrA   rV   r   r   s      rC   r   zBaseTool._run      rB   c                   K   |j                  d      rDt        | j                        j                  j                  d      r|d   j	                         |d<   t        d| j                  g|i | d{   S 7 w)zUse the tool asynchronously.

        Add `run_manager: AsyncCallbackManagerForToolRun | None = None` to child
        implementations to enable tracing.

        Returns:
            The result of the tool execution.
        r0   N)r   r   r   rX   get_syncr$   r  s      rC   _arunzBaseTool._arun
  sn      ::m$499)=)H)H)L)L*
 %+=$9$B$B$DF=!$T499FtFvFFFFs   A3A<5A:6A<c                   t        t           t              }|j                  | j                         | j
                  M	 t        | j
                        } |j                         D ]"  \  }}t        |      s|j                  |       $ 	 |j                         D ci c]  \  }}||vs|| c}}S # t        $ r Y 4w xY wc c}}w )a  Filter out injected tool arguments from the input dictionary.

        Injected arguments are those annotated with `InjectedToolArg` or its
        subclasses, or arguments in `FILTERED_ARGS` like `run_manager` and callbacks.

        Args:
            tool_input: The tool input dictionary to filter.

        Returns:
            A filtered dictionary with injected arguments removed.
        )setrL   r   updater   r   r   rZ   r\   add	Exception)rV   r   filtered_keysr   
field_name
field_typerc   r
  s           rC   _filter_injected_argszBaseTool._filter_injected_args  s     C/ 	T556 ';D<L<LM.?k.?.?.A 6*J
,Z8%))*56 ",!1!1!3NAq7M1NN  
 Os#   7B4 7B4 C+C4	C ?C c                n   | j                   Ht        | j                   t              r.t        | j                         rt	        | j                         sdi fS | j                  ||      }t        |t              r|fi fS t        |t              rd|j                         fS dt        |       }t        |      )ac  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.
        rA   zInvalid tool input type: )
r   rK   typer,   r+   r  rL   r   copyr   )rV   r   r   rs   s       rC   _to_args_and_kwargszBaseTool._to_args_and_kwargs9  s      (4++T2%d&6&67t//0 r6M&&z<@
 j#&="$$j$' z((()$z*:);<nrB   )r   r   run_namerun_idr   r   c          	        t        j                  || j                  | j                  xs t	        |      || j
                  || j                        }t        |t              r| j                  |      nd}t        |t              r|nt        ||n|      } |j                  | j                  | j                  d|f|||	||d|}d}d}d}d}	 t        |
|j                               }t!        |      5 }| j#                  ||      \  }}t%        | j&                        j(                  j+                  d      r|d|iz  }t-        | j&                        x}r|||
iz  } |j.                  | j&                  g|i |}ddd       | j0                  dk(  r2dt3               d	}t        |t4              st7        |      }n		 |\  }}n}|r|jK                  |       |tM        |||| j                  |      } |jN                  |f|| j                  d| |S # 1 sw Y   xY w# t6        $ r t7        |      }Y rw xY w# t8        t:        f$ r2}| j<                  s|}nt?        || j<                  
      }d}Y d}~d}~wt@        $ r2}| jB                  s|}ntE        || jB                  
      }d}Y d}~d}~wtF        tH        f$ r}|}Y d}~d}~ww xY w)an  Run the tool.

        Args:
            tool_input: The input to the tool.
            verbose: Whether to log the tool's progress.
            start_color: The color to use when starting the tool.
            color: The color to use when ending the tool.
            callbacks: Callbacks to be called during tool execution.
            tags: Optional list of tags associated with the tool.
            metadata: Optional metadata associated with the tool.
            run_name: The name of the run.
            run_id: The id of the run.
            config: The configuration for the tool.
            tool_call_id: The id of the tool call.
            **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.
        Nr[   rM   colorr[   r&  inputsr   successr1   r0   content_and_artifactSince response_format='content_and_artifact' a two-tuple of the message content and raw tool output is expected. Instead, generated response is of type: r   flagerrorr*  r[   )(r   	configurer1   r   r   r   r   rK   r   r   rL   on_tool_startr[   rM   r#   	get_childr%   r$  r   r   rX   r   _get_runnable_config_paramr   r   r"  tuplerp   r   ValidationErrorV1r   _handle_validation_errorr   r   _handle_tool_errorr  KeyboardInterrupton_tool_error_format_outputon_tool_end)rV   r   r   start_colorr*  r1   r   r   r%  r&  r   r   r   callback_managerfiltered_tool_inputtool_input_strr0   r   artifactstatuserror_to_raisechild_configcontext	tool_argstool_kwargsconfig_paramresponsers   eoutputs                                 rC   r   zBaseTool.run`  s   L +44NNLL)DMIIMM
 *d+ &&z2 	 *c* ':'F#J 	 5&44YYt/?/?@	
 &%	
 	
 ?C(	'+:O:O:QRL#L1 MW)-)A)A*&	; TYY'2266}EM;#??K#=dii#HH<HL&#99K&7;;tyyL9LLM ##'==I H~&a)  "(E2%/_N9,4) #  %%n5  <FSNe$))NvN[M M* & 9)3C9  !23 	!//!"214;W;WX  	!))!",QT5K5KL ,- 	N	sn   &H? 5B	H>AH? H% H? H"H? %H<9H? ;H<<H? ?K(I;;K(J44KKKc          	     D  K   t        j                  || j                  | j                  xs t	        |      || j
                  || j                        }t        |t              r| j                  |      nd}t        |t              r|nt        ||n|      } |j                  | j                  | j                  d|f|||	||d| d{   }d}d}d}d}	 | j                  ||      \  }}t        |
|j!                               }t#        |      5 }| j$                  j&                  t(        j&                  u r| j*                  n| j&                  }t-        |      j.                  j1                  d      r||d<   t3        |      x}r|
||<    | j&                  |i |}t5        ||       d{   }ddd       | j6                  dk(  r2dt9               d	}t        |t:              st=        |      }n		 |\  }}n}|r|jO                  |       d{    |tQ        |||| j                  |      } |jR                  |f|| j                  d| d{    |S 7 7 # 1 sw Y   xY w# t<        $ r t=        |      }Y w xY w# t>        $ r2}| j@                  s|}ntC        || j@                  
      }d}Y d}~d}~wtD        $ r2}| jF                  s|}ntI        || jF                  
      }d}Y d}~d}~wtJ        tL        f$ r}|}Y d}~d}~ww xY w7 7 ŭw)am  Run the tool asynchronously.

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

        Returns:
            The output of the tool.

        Raises:
            ToolException: If an error occurs during tool execution.
        Nr(  r)  r,  r-  r0   r.  r/  r   r0  r2  r3  )*r   r4  r1   r   r   r   r   rK   r   r   rL   r5  r[   rM   r$  r#   r6  r%   r   r  r   r   r   rX   r   r7  r&   r   r"  r8  rp   r   r   r:  r   r   r;  r  r<  r=  r>  r?  ) rV   r   r   r@  r*  r1   r   r   r%  r&  r   r   r   rA  rB  rC  r0   r   rD  rE  rF  rI  rJ  rG  rH  func_to_checkrK  cororL  rs   rM  rN  s                                    rC   r   zBaseTool.arun  s?    L 099NNLL)DMIIMM
 *d+ &&z2 	 *c* ':'F#J 	 ;,::YYt/?/?@	
 &%	
 	
 	
 ?C+	%)%=%=j,%W"I{'+:O:O:QRL#L1 
BW!%!5!5!GDIITZZ  ]+66::=I1<K.#=m#LL<L06K-!tzz9<<!24!AA
B ##'==I H~&a)  "(E2%/_N9,4) #  ++N;;;  <FS%k%%fTE		TVTTTC	
6 B
B 
B. & 9)3C9  	!//!"214;W;WX  	!))!",QT5K5KL ,- 	N	 < 	Us   C	L IL ;J
 BI$/I"0I$4AJ
 7I0 <J
 ?L LAL LL "I$$I-)J
 0JJ
 JJ
 
	L(K ;L  L(K94L 9LLL LL L )r   r
   returnNone)rR  r   )rR  r   )rR  
ArgsSchema)rR  r   r   )r   RunnableConfig | NonerR  type[BaseModel])r   str | dict | ToolCallr   rU  r   r
   rR  r
   )r   
str | dictr   
str | NonerR  str | dict[str, Any])r   r
   r   r
   rR  r
   )r   r   rR  r   )r   rX  r   rY  rR  ztuple[tuple, dict])Ngreenr[  N)r   rZ  r   bool | Noner@  rY  r*  rY  r1   r   r   r   r   r   r%  rY  r&  uuid.UUID | Noner   rU  r   rY  r   r
   rR  r
   )r   rX  r   r\  r@  rY  r*  rY  r1   r   r   r   r   r   r%  rY  r&  r]  r   rU  r   rY  r   r
   rR  r
   )(r=   r>   r?   r@   r   r   r   r   r   r   r1   r   r   r   r   r   r   r   r   model_configpropertyr   r   r   	functoolscached_propertyr   r   r   r   r   r  r   r   r  r   r$  r   r   __classcell__)r   s   @rC   r   r     s   -B IL
 CH"4CK?   M4
 GT- t<Iy<7!D
! '+H#* MRIQ; 	 P >BKO?K %)F!("#(  $L   7 7$ 
 
0   A A  )-.$. &. 	.
 
. .  )-5$5 &5 	5
 
5 5w$w4>w	wr  GO@%$%4>%	%T  $")##~ "&*.##'(,#'~(~ ~  	~
 ~ ~ ~ (~ ~ !~ &~ !~ ~ 
~F  $")##A "&*.##'(,#'AA A  	A
 A A A (A A !A &A !A A 
ArB   r   c                N    t        | t              xr | j                  d      dk(  S )zCheck 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.
    r"  	tool_call)rK   r   r   )xs    rC   _is_tool_callrf  d  s#     a?155=K#??rB   c                   t        |t              rd}|S t        |t              r|}|S t        |      r
 ||       }|S d| }t	        |      )a/  Handle validation errors based on the configured flag.

    Args:
        e: The validation error that occurred.
        flag: How to handle the error (`bool`, `str`, 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: )rK   r   rL   callablerp   rM  r1  r   rs   s       rC   r:  r:  p  sk    " $/ N 
D#	 N 
$q' N	**.1 	 orB   c                   t        |t              r!| j                  r| j                  d   }|S d}|S t        |t              r|}|S t	        |      r
 ||       }|S d| }t        |      )a1  Handle tool execution errors based on the configured flag.

    Args:
        e: The tool exception that occurred.
        flag: How to handle the error (`bool`, `str`, 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: )rK   r   r   rL   rh  rp   ri  s       rC   r;  r;    s    " $ vv!&&) N ,B N 
D#	 N 
$q' N	&&*V- 	 orB   c                f   t        |      }t        |       r-t        d|       d   }t        d|       d   j                         }nd}t        d|       }|t	        d|j                  d      |j                  d      |j                  d      |j                  d	      |j                  d
d      ||d|fS )a  Prepare arguments for tool execution.

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

    Returns:
        A tuple of `(tool_input, run_kwargs)`.
    r   idr   NrX  r1   r   r   r%  r&  )r1   r   r   r%  r&  r   r   rA   )r"   rf  r   r#  r   r   pop)valuer   r   r   r   s        rC   r   r     s     6"FU#'
E#:4#@!%j%!8!@!E!E!G
,.
 		
jj-F#ZZ
+ZZ
+::h-%		
 		
 rB   c                v    t        | t              s|| S t        |       st        |       } t	        | ||||      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.
    )rD  r   r[   rE  )rK   r   _is_message_content_type
_stringifyr   )r   rD  r   r[   rE  s        rC   r>  r>    sF    & '?+|/C#G,W%! rB   c                n    t        | t              xs$ t        | t              xr t        d | D              S )zCheck 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              3  2   K   | ]  }t        |        y wr   )_is_message_content_block)r   rM  s     rC   r   z+_is_message_content_type.<locals>.<genexpr>  s     %Pq&?&B%Ps   )rK   rL   rk   allobjs    rC   rp  rp    s2     c3 3P#%PC%P"PrB   c                v    t        | t              ryt        | t              r| j                  dd      t        v S y)zCheck 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.
    Tr"  NF)rK   rL   r   r   TOOL_MESSAGE_BLOCK_TYPESrv  s    rC   rt  rt    s5     #s#twwvt$(@@@rB   c                f    	 t        j                  | d      S # t        $ r t        |       cY S w xY w)zConvert content to string, preferring JSON format.

    Args:
        content: The content to stringify.

    Returns:
        String representation of the content.
    F)ensure_ascii)r5   dumpsr  rL   )r   s    rC   rq  rq    s1    zz'66 7|s    00c                    t        | t        j                        r| j                  } 	 t	        |       S # t
        $ r Y yw xY w)zGet type hints from a function, handling partial functions.

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

    Returns:
        `dict` of type hints, or `None` if extraction fails.
    N)rK   r`  partialr^   r   r  )r^   s    rC   _get_type_hintsr  &  s?     $	))*yyd## s   
3 	??c                h    t        |       }|sy|j                         D ]  \  }}|t        u s|c S  y)zFind 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  rZ   r    )r^   
type_hintsr[   r   s       rC   r7  r7  7  sB     !&J!'') eN"K rB   c                      e Zd ZdZy)InjectedToolArgzAnnotation 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<   rA   rB   rC   r  r  I  s    rB   r  c                      e Zd ZdZy)_DirectlyInjectedToolArga  Annotation for tool arguments that are injected at runtime.

    Injected via direct type annotation, rather than annotated metadata.

    For example, `ToolRuntime` is a directly injected argument.

    Note the direct annotation rather than the verbose alternative:
    `Annotated[ToolRuntime, InjectedRuntime]`

    ```python
    from langchain_core.tools import tool, ToolRuntime


    @tool
    def foo(x: int, runtime: ToolRuntime) -> str:
        # use runtime.state, runtime.context, runtime.store, etc.
        ...
    ```
    Nr<   rA   rB   rC   r  r  Q  s    rB   r  c                      e Zd ZdZy)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.

    ```python
    from typing 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<   rA   rB   rC   r  r  g  s    rB   r  c                    t        | t              xr t        | t              xs3 t	        |       x}duxr" t        |t              xr t        |t              S )aw  Check if a type annotation indicates a directly injected argument.

    This is currently only used for `ToolRuntime`.
    Checks if either the annotation itself is a subclass of `_DirectlyInjectedToolArg`
    or the origin of the annotation is a subclass of `_DirectlyInjectedToolArg`.

    Ex: `ToolRuntime` or `ToolRuntime[ContextT, StateT]` would both return `True`.
    N)rK   r"  r   r  r   )r   origins     rC   _is_directly_injected_arg_typer    sX     	5$OJu6N$O e$	$T1 	9vt$	9v78rB   c                l    t        |       ryt        t        f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.
    NTc              3  v   K   | ]0  }t        |      xs t        |t              xr t        |       2 y wr   )rK   r"  r   )r   r{   r   s     rC   r   z(_is_injected_arg_type.<locals>.<genexpr>  sD        	3& 	FsD!Djm&D	Fs   69rJ   )r  r  r   r   )r   r   s    `rC   r\   r\     sF      *%0'   E?12&  rB   default_to_boundc          	        t        | t              rt        |       }|j                         D ci c]  \  }}|j                  s|j                  |! }}}i }t        j                  |       j                  j                         D ]1  \  }}|r	||vr||vr|j                  ||      }|j                  ||<   3 t        | dd      }	nt        t        |       d      }| f}	t        | t              rt        |       s|	D ]  }
t        |
t              r)t        |
      r |j                  t        |
d             <t        |
      }|sJt        |dd      }t!        t#        |t%        |
      d            }t        |di       D ]  }t'        ||   ||      ||<      |j                         D ci c]  \  }}|t'        ||       c}}S c c}}w c c}}w )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:
        `dict` of field names to their type annotations.
    __orig_bases__rA   Fr  __parameters__)strictr   )rK   r"  r+   rZ   aliasri   r   rX   r   rP   r  r   r   r.   r-   r  r   zipr   _replace_type_vars)rU   r  r   r[   r   	alias_mapr   rd   r  
orig_basesparentparent_origingeneric_type_varsgeneric_maprc   r
  s                   rC   r   r     s    #tC:@,,.X;4EKKU[[$&X	X13",,S1<<BBD 	7KD% $f,Y1F"tT2J&+&6&6K
#	7 $C)92>
 4sOe
 V
 sD!&=c&B ! 	F&$',CF,K"""1&5Q &v.M ! (/}>NPR'Ss#4hv6FuUVK 0A2F %7&FV&E"+	8 &K%%'Aq 	
a2BCC c Ybs   GG0Gc                  xs i t        | t              r+| v r|    S r| j                  | j                  S t        S | S t	        |       x}r:t        |       x}r-t        fd|D              }t        dt        |      |         S | S )a9  Replace `TypeVar`s in a type annotation with concrete types.

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

    Returns:
        The type with `TypeVar`s replaced.
    c              3  :   K   | ]  }t        |         yw)r  N)r  )r   r{   r  r  s     rC   r   z%_replace_type_vars.<locals>.<genexpr>  s&      
 sKBRSS
s   r"  )	rK   r   	__bound__r
   r   r   r8  r   r(   )r   r  r  r  r   new_argss    ``   rC   r  r    s      #K%!Ku%%&+oo&A5??JsJU###(5/*A$*A 

 
 F.v6x@AALrB   c                  "    e Zd ZdZedd       Zy)BaseToolkitzBase 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.
    c                     y)zmGet all tools in the toolkit.

        Returns:
            List of tools contained in this toolkit.
        NrA   r   s    rC   	get_toolszBaseToolkit.get_tools  r  rB   N)rR  zlist[BaseTool])r=   r>   r?   r@   r   r  rA   rB   rC   r  r    s      rB   r  )rG   z	type[Any]rR  r   )rN   r"  rR  rY  )
r]   rV  r^   r   r_   zSequence[str]rR   r   rR  r   )rl   r   r   r   rg   r   rR  tuple[str, dict])rq   r   r   r   rR  rS  )rz   r   rv   r   rg   r   rR  r  )r   )rP   r
   r   rL   rR  r   )r   zinspect.Signaturer^   r   rR  r   )r   rL   r^   r   r_   zSequence[str] | Nonerv   r   rg   r   rR   r   rR  rV  )re  r
   rR  r   )rM  z#ValidationError | ValidationErrorV1r1  zJLiteral[True] | str | Callable[[ValidationError | ValidationErrorV1], str]rR  rL   )rM  r   r1  z;Literal[True] | str | Callable[[ToolException], str] | NonerR  rL   )rn  rW  r   rU  r   r
   rR  ztuple[str | dict, dict])r   r
   rD  r
   r   rY  r[   rL   rE  rL   rR  zToolOutputMixin | Any)rw  r
   rR  r   )r   r
   rR  rL   )r^   r   rR  zdict[str, type] | None)r^   r   rR  rY  )r   r
   rR  r   r   )r   type | TypeVarr   ztype[InjectedToolArg] | NonerR  r   )rU   zTypeBaseModel | Anyr  r   rR  zdict[str, type | TypeVar])r   r  r  zdict[TypeVar, type] | Noner  r   rR  r  )nr@   
__future__r   r`  ri   r5   rE   r   abcr   r   collections.abcr   r   r   r	   r
   r   r   r   r   r   r   rF   pydanticr   r   r   r   r   r   r   pydantic.fieldsr   pydantic.v1r   r9  r   r   langchain_core.callbacksr   r   r   langchain_core.messages.toolr   r   r   langchain_core.runnablesr    r!   r"   r#   r$   langchain_core.runnables.configr%   langchain_core.runnables.utilsr&   %langchain_core.utils.function_callingr'   r(   langchain_core.utils.pydanticr)   r*   r+   r,   r-   r.   uuidr/   r   ry  r   r;   rH   rQ   re   rn   rt   r}   r   r   r   r   r  r   r   rL   rT  	frozensetr   r   r   rf  r:  r;  r   r>  rp  rt  rq  r  r7  r  r  r  r  r\   r   r  r  rA   rB   rC   <module>r     s   5 "      # $ 
 
 
    & 0 < C & 
 P O  ? <  (,	 RI R	N4 "#
 	
  
< RW%)JN."")-"	"* "',	)) ) !%	)
 )D"9 9(09	9@9 9 )-!',!``
` &	`
 ` !%` ` `FI  T#s(^+
&[
N (S#C$J$93$>? Sl	@* U 		@ F 		@" "!" " 	"J  	
  @ $"$  , 6& JN*F	: ;?C	C37CCP /3 "	+ 	
 @)S rB   