Skip to content

The agent engineering platform.

docs(core): improve tools module docstrings (#33755)

Mason Daugherty90aefc607f72
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index 588d71efdc..4c06483761 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -391,6 +391,7 @@ class BaseTool(RunnableSerializable[str | dict | ToolCall, Any]):
"""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.
"""
@@ -401,7 +402,7 @@ class BaseTool(RunnableSerializable[str | dict | ToolCall, Any]):
**kwargs: Additional keyword arguments passed to the parent class.
Raises:
- SchemaAnnotationError: If args_schema has incorrect type annotation.
+ SchemaAnnotationError: If `args_schema` has incorrect type annotation.
"""
super().__init_subclass__(**kwargs)
@@ -442,15 +443,15 @@ class ChildTool(BaseTool):
Args schema should be either:
- - A subclass of pydantic.BaseModel.
- - A subclass of pydantic.v1.BaseModel if accessing v1 namespace in pydantic 2
- - a JSON schema dict
+ - A subclass of `pydantic.BaseModel`.
+ - A subclass of `pydantic.v1.BaseModel` if accessing v1 namespace in pydantic 2
+ - A JSON schema dict
"""
return_direct: bool = False
"""Whether to return the tool's output directly.
- Setting this to True means
- that after the tool is called, the AgentExecutor will stop looping.
+ Setting this to `True` means that after the tool is called, the `AgentExecutor` will
+ stop looping.
"""
verbose: bool = False
"""Whether to log the tool's progress."""
@@ -460,31 +461,37 @@ class ChildTool(BaseTool):
tags: list[str] | None = None
"""Optional list of tags associated with the tool.
+
These tags will be associated with each call to this tool,
and passed as arguments to the handlers defined in `callbacks`.
- You can use these to eg identify a specific instance of a tool with its use case.
+
+ You can use these to, e.g., identify a specific instance of a tool with its use
+ case.
"""
metadata: dict[str, Any] | None = None
"""Optional metadata associated with the tool.
+
This metadata will be associated with each call to this tool,
and passed as arguments to the handlers defined in `callbacks`.
- You can use these to eg identify a specific instance of a tool with its use case.
+
+ You can use these to, e.g., identify a specific instance of a tool with its use
+ case.
"""
handle_tool_error: bool | str | Callable[[ToolException], str] | None = False
- """Handle the content of the ToolException thrown."""
+ """Handle the content of the `ToolException` thrown."""
handle_validation_error: (
bool | str | Callable[[ValidationError | ValidationErrorV1], str] | None
) = False
- """Handle the content of the ValidationError thrown."""
+ """Handle the content of the `ValidationError` thrown."""
response_format: Literal["content", "content_and_artifact"] = "content"
"""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`.
+ 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`.
"""
def __init__(self, **kwargs: Any) -> None:
@@ -492,7 +499,7 @@ class ChildTool(BaseTool):
Raises:
TypeError: If `args_schema` is not a subclass of pydantic `BaseModel` or
- dict.
+ `dict`.
"""
if (
"args_schema" in kwargs
@@ -526,7 +533,7 @@ class ChildTool(BaseTool):
"""Get the tool's input arguments schema.
Returns:
- Dictionary containing the tool's argument properties.
+ `dict` containing the tool's argument properties.
"""
if isinstance(self.args_schema, dict):
json_schema = self.args_schema
@@ -616,9 +623,9 @@ class ChildTool(BaseTool):
Raises:
ValueError: If `string` input is provided with JSON schema `args_schema`.
- ValueError: If InjectedToolCallId is required but `tool_call_id` is not
+ ValueError: If `InjectedToolCallId` is required but `tool_call_id` is not
provided.
- TypeError: If args_schema is not a Pydantic `BaseModel` or dict.
+ TypeError: If `args_schema` is not a Pydantic `BaseModel` or dict.
"""
input_args = self.args_schema
if isinstance(tool_input, str):
@@ -710,8 +717,8 @@ class ChildTool(BaseTool):
def _filter_injected_args(self, tool_input: dict) -> dict:
"""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.
+ 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.
@@ -746,7 +753,7 @@ class ChildTool(BaseTool):
tool_call_id: The ID of the tool call, if available.
Returns:
- A tuple of (positional_args, keyword_args) for the tool.
+ A tuple of `(positional_args, keyword_args)` for the tool.
Raises:
TypeError: If the tool input type is invalid.
@@ -1048,7 +1055,7 @@ def _handle_validation_error(
Args:
e: The validation error that occurred.
- flag: How to handle the error (bool, string, or callable).
+ flag: How to handle the error (`bool`, `str`, or `Callable`).
Returns:
The error message to return.
@@ -1080,7 +1087,7 @@ def _handle_tool_error(
Args:
e: The tool exception that occurred.
- flag: How to handle the error (bool, string, or callable).
+ flag: How to handle the error (`bool`, `str`, or `Callable`).
Returns:
The error message to return.
@@ -1111,12 +1118,12 @@ def _prep_run_args(
"""Prepare arguments for tool execution.
Args:
- value: The input value (string, dict, or ToolCall).
+ value: The input value (`str`, `dict`, or `ToolCall`).
config: The runnable configuration.
**kwargs: Additional keyword arguments.
Returns:
- A tuple of (tool_input, run_kwargs).
+ A tuple of `(tool_input, run_kwargs)`.
"""
config = ensure_config(config)
if _is_tool_call(value):
@@ -1147,7 +1154,7 @@ def _format_output(
name: str,
status: str,
) -> ToolOutputMixin | Any:
- """Format tool output as a ToolMessage if appropriate.
+ """Format tool output as a `ToolMessage` if appropriate.
Args:
content: The main content of the tool output.
@@ -1157,7 +1164,7 @@ def _format_output(
status: The execution status.
Returns:
- The formatted output, either as a ToolMessage or the original content.
+ The formatted output, either as a `ToolMessage` or the original content.
"""
if isinstance(content, ToolOutputMixin) or tool_call_id is None:
return content
@@ -1228,7 +1235,7 @@ def _get_type_hints(func: Callable) -> dict[str, type] | None:
func: The function to get type hints from.
Returns:
- Dictionary of type hints, or None if extraction fails.
+ `dict` of type hints, or `None` if extraction fails.
"""
if isinstance(func, functools.partial):
func = func.func
@@ -1239,13 +1246,13 @@ def _get_type_hints(func: Callable) -> dict[str, type] | None:
def _get_runnable_config_param(func: Callable) -> str | None:
- """Find the parameter name for RunnableConfig in a function.
+ """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.
+ The parameter name for `RunnableConfig`, or `None` if not found.
"""
type_hints = _get_type_hints(func)
if not type_hints:
@@ -1269,9 +1276,11 @@ class _DirectlyInjectedToolArg:
Injected via direct type annotation, rather than annotated metadata.
- For example, ToolRuntime is a directly injected argument.
+ For example, `ToolRuntime` is a directly injected argument.
+
Note the direct annotation rather than the verbose alternative:
- Annotated[ToolRuntime, InjectedRuntime]
+ `Annotated[ToolRuntime, InjectedRuntime]`
+
```python
from langchain_core.tools import tool, ToolRuntime
@@ -1314,11 +1323,11 @@ class InjectedToolCallId(InjectedToolArg):
def _is_directly_injected_arg_type(type_: Any) -> bool:
"""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.
+ 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.
+ Ex: `ToolRuntime` or `ToolRuntime[ContextT, StateT]` would both return `True`.
"""
return (
isinstance(type_, type) and issubclass(type_, _DirectlyInjectedToolArg)
@@ -1360,14 +1369,14 @@ def _is_injected_arg_type(
def get_all_basemodel_annotations(
cls: TypeBaseModel | Any, *, default_to_bound: bool = True
) -> dict[str, type | TypeVar]:
- """Get all annotations from a Pydantic BaseModel and its parents.
+ """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.
+ 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.
+ `dict` of field names to their type annotations.
"""
# cls has no subscript: cls = FooBar
if isinstance(cls, type):
@@ -1433,15 +1442,15 @@ def _replace_type_vars(
*,
default_to_bound: bool = True,
) -> type | TypeVar:
- """Replace TypeVars in a type annotation with concrete types.
+ """Replace `TypeVar`s 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.
+ generic_map: Mapping of `TypeVar`s to concrete types.
+ default_to_bound: Whether to use `TypeVar` bounds as defaults.
Returns:
- The type with TypeVars replaced.
+ The type with `TypeVar`s replaced.
"""
generic_map = generic_map or {}
if isinstance(type_, TypeVar):
diff --git a/libs/core/langchain_core/tools/convert.py b/libs/core/langchain_core/tools/convert.py
index ee51e30840..1dabed5e00 100644
--- a/libs/core/langchain_core/tools/convert.py
+++ b/libs/core/langchain_core/tools/convert.py
@@ -81,60 +81,72 @@ def tool(
parse_docstring: bool = False,
error_on_invalid_docstring: bool = True,
) -> BaseTool | Callable[[Callable | Runnable], BaseTool]:
- """Make tools out of Python functions, can be used with or without arguments.
+ """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. Must be provided as a positional argument.
- runnable: Optional runnable to convert to a tool. Must be provided as a
- positional argument.
+ 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:
- - `description` argument
+ - 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` / docstring are not provided)
+ (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.
+ 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.
+ 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`.
+ 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
+ error_on_invalid_docstring: If `parse_docstring` is provided, configure
whether to raise `ValueError` on invalid Google Style docstrings.
Raises:
- ValueError: If too many positional arguments are provided.
- ValueError: If a runnable is provided without a string name.
+ 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.
+ ValueError: If a `Runnable` is provided that does not have an object schema.
Returns:
The tool.
- Requires:
- - Function must be of type `(str) -> str`
- - Function must have a docstring
-
Examples:
```python
@tool