Skip to content

The agent engineering platform.

fix(core): preserve `Field(description=...)` in `@tool` decorator (#34354)

rari4041cc4dc7cc9ee
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index d9ca7b0afa..fc7cc012fd 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -32,6 +32,7 @@ from pydantic import (
ValidationError,
validate_arguments,
)
+from pydantic.fields import FieldInfo
from pydantic.v1 import BaseModel as BaseModelV1
from pydantic.v1 import ValidationError as ValidationErrorV1
from pydantic.v1 import validate_arguments as validate_arguments_v1
@@ -101,6 +102,8 @@ def _is_annotated_type(typ: type[Any]) -> bool:
def _get_annotation_description(arg_type: type) -> str | None:
"""Extract description from an Annotated type.
+ Checks for string annotations and `FieldInfo` objects with descriptions.
+
Args:
arg_type: The type to extract description from.
@@ -112,6 +115,8 @@ def _get_annotation_description(arg_type: type) -> str | None:
for annotation in annotated_args[1:]:
if isinstance(annotation, str):
return annotation
+ if isinstance(annotation, FieldInfo) and annotation.description:
+ return annotation.description
return None
diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.py
index ec6b18869f..99c42e83b0 100644
--- a/libs/core/tests/unit_tests/test_tools.py
+++ b/libs/core/tests/unit_tests/test_tools.py
@@ -1408,6 +1408,39 @@ def test_tool_annotated_descriptions() -> None:
}
+def test_tool_field_description_preserved() -> None:
+ """Test that `Field(description=...)` is preserved in `@tool` decorator."""
+
+ @tool
+ def my_tool(
+ topic: Annotated[str, Field(description="The research topic")],
+ depth: Annotated[int, Field(description="Search depth level")] = 3,
+ ) -> str:
+ """A tool for research."""
+ return f"{topic} at depth {depth}"
+
+ args_schema = _schema(my_tool.args_schema)
+ assert args_schema == {
+ "title": "my_tool",
+ "type": "object",
+ "description": "A tool for research.",
+ "properties": {
+ "topic": {
+ "title": "Topic",
+ "type": "string",
+ "description": "The research topic",
+ },
+ "depth": {
+ "title": "Depth",
+ "type": "integer",
+ "description": "Search depth level",
+ "default": 3,
+ },
+ },
+ "required": ["topic"],
+ }
+
+
def test_tool_call_input_tool_message_output() -> None:
tool_call = {
"name": "structured_api",