LangChain Tools API


@tool Decorator

ParameterTypeDefault ValueDescription
args_schemaBaseModel or NoneNoneParameter validation model. If not provided, it is automatically generated from the function signature.
return_directboolFalseWhether to return directly (skip model rethinking)
namestr or NoneFunction nameTool name
descriptionstr or NoneFunction docstringTool description

BaseTool Key Attributes and Methods

Attribute/MethodDescription
nameTool name (string)
descriptionTool description (string)
args_schemaParameter Pydantic model
return_directWhether to return directly (bool)
invoke(input)Call the tool; input is the parameter dictionary
ainvoke(input)Asynchronously call the tool

Dependency Injection Markers

MarkerPurposeUsage
InjectedStateInject Agent stateAnnotated[dict, InjectedState]
InjectedStoreInject cross-session storeAnnotated[BaseStore, InjectedStore()]
InjectedToolCallIdInject tool call IDAnnotated[str, InjectedToolCallId]
InjectedToolArgGeneric injection markerAnnotated[T, InjectedToolArg]

Common Usage Examples

Examples

from langchain.tools import tool, InjectedState, InjectedStore, ToolException
from typing import Annotated
from langgraph.store.base import BaseStore

# Basic tool
@tool
def my_tool(param: str) -> str:
    """Tool description"""
    return f"Result: {param}"

# With parameter validation
from pydantic import BaseModel, Field

class MyInput(BaseModel):
    param: str = Field(description="Parameter description", min_length=1)

@tool(args_schema=MyInput)
def validated_tool(param: str) -> str:
    return param

# Direct return
@tool(return_direct=True)
def query_tool(query: str) -> str:
    return f"Result: {query}"

# Inject state
@tool
def stateful_tool(
    param: str,
    state: Annotated[dict, InjectedState],
) -> str:
    return f"Message count: {len(state.get('messages', []))}"

# Inject Store
@tool
def store_tool(
    key: str,
    store: Annotated[BaseStore, InjectedStore()],
) -> str:
    item = store.get(("ns",), key)
    return str(item.value if item else "None")

# Exception handling
@tool
def safe_tool(param: int) -> str:
    if param < 0:
        raise ToolException(f"Parameter must be a positive number: {param}")
    return f"OK: {param}"
Other Extensions