AI AgentsLangChain
How do you define tools with the @tool decorator?
Question 291 of 324 · Updated
On this page
- Direct answer
- 1. From a Python function to a LangChain tool
- 2. Define a minimal tool with @tool
- 3. Inspect the tool object before registering it
- 4. Direct invocation: test a tool without a model
- 5. Give tools a stable name and accurate metadata
- 6. Register the tool with a LangChain agent
- Decorating versus binding versus executing
- 7. Return values and validation boundaries
- 8. Locally tested Python implementation: decorator, inferred schema and direct invocation
- 9. Testing an actual LangChain tool in production
- Direct tool tests
- Agent integration tests
- Outcome tests
- 10. Production practices and common mistakes
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
In LangChain, import tool from langchain.tools and apply the @tool decorator to a Python function with a clear docstring and typed parameters. The decorator converts the function into a LangChain tool object with a callable implementation, a name, a description and an input schema. You can inspect that contract, invoke the tool directly with structured arguments, and register it with an agent through create_agent(tools=[...]). The model proposes a tool call; the application runtime validates and executes the corresponding tool.
The decorator does not by itself authorize a request, validate every business constraint, make an external operation idempotent, or prove that a model will choose the correct tool.
The earlier first-agent lesson (#281) introduced a small decorated multiplication function. AI Agents #81, #85–87 and #102 cover general tools, argument passing, schemas, descriptions and output validation. This lesson extends that foundation with LangChain's decorator-to-tool-object workflow: registration, automatic input-schema inference, direct invocation, model integration and testing. The next lessons separately examine tool-selection metadata, explicit Pydantic schemas and runtime dependency injection.
1. From a Python function to a LangChain tool#
A normal function has executable logic and a Python signature. A model cannot directly call an arbitrary Python function in your process. It receives a description of available tools, then generates structured requests that a trusted application runtime can interpret and dispatch.
A LangChain tool wraps a callable with information suitable for that workflow.
| Component | Purpose | Example |
|---|---|---|
| Callable | Implements the actual operation | Calculate a fictional delivery estimate |
| Name | Stable identifier used for dispatch | estimate_delivery |
| Description | Explains the operation to the model | Estimate delivery cost; does not create a shipment |
| Input schema | Describes expected arguments | postcode: string, parcels: integer |
| Validation | Rejects unsupported inputs | Parcel count must be between 1 and 10 |
| Output | Returns the resulting observation | Currency and cost in integer cents |
The decorator is evaluated when Python defines the function. For ordinary decorated functions with inferred schemas, the result is commonly a structured tool object rather than the original plain function. Defining it does not immediately make it available to every model or agent. The host must explicitly bind or register the tool in an appropriate runtime.
The diagram shows the conceptual construction path. Exact internal classes, schema representation and provider conversion depend on the installed LangChain and integration versions.
2. Define a minimal tool with @tool#
For example, consider a read-only delivery estimate used in an online store. The calculation uses fictional pricing and does not reserve inventory, charge money or create a shipment.
PYTHONfrom langchain.tools import tool @tool def estimate_delivery(postcode: str, parcels: int = 1) -> dict: """Estimate fictional delivery cost in cents; no shipment is created.""" if len(postcode) != 5 or not postcode.isascii() or not postcode.isdigit(): raise ValueError("invalid postcode") if not 1 <= parcels <= 10: raise ValueError("parcel count out of range") return {"currency": "USD", "cost_cents": 400 + 150 * parcels}
Here postcode is deliberately a string because a postal code can begin with zero. This example accepts only five ASCII digits as a fictional service constraint; it is not a universal postal-code validator. The parcels parameter is optional because the function provides a default of one parcel. The return value uses integer cents rather than a floating-point currency amount.
The default tool name ordinarily comes from the function name. The docstring supplies the default description. Type annotations and defaults allow the decorator to construct an inferred input schema under supported versions.
The explicit validation inside the function illustrates the distinction between type correctness and domain correctness. An integer value of zero satisfies an integer schema but violates the fictional pricing rule.
SDK verification note: LangChain, langchain_core and LangGraph are not installed in the local execution environment. All LangChain-specific snippets are illustrative and unexecuted; validate exact signatures, inferred schemas and supported behavior in the installed release. The independent standard-library demonstration in section 8 was executed locally and its 11 checks passed.
3. Inspect the tool object before registering it#
Inspecting a tool's public contract helps detect unintended parameters, missing descriptions or incorrect types before a model ever receives the tool definition.
PYTHONprint(estimate_delivery.name) print(estimate_delivery.description) print(estimate_delivery.args) # Common modern Pydantic-backed input-schema inspection: input_schema = estimate_delivery.get_input_schema() print(input_schema.model_json_schema())
For the illustrative function, the intended contract includes a required postcode string and an optional integer parcels field with a default of one. A simplified JSON-schema representation is:
JSON{ "type": "object", "properties": { "postcode": {"type": "string"}, "parcels": {"type": "integer", "default": 1} }, "required": ["postcode"] }
This is a conceptual excerpt, not observed SDK output. Actual schemas may include titles, descriptions, references and additional fields. An input schema used for local validation can differ from the model-facing schema, especially for injected parameters. Inspect both the actual schema and the provider-converted tool definition in a controlled integration environment.
Important distinctions:
- Python annotations are not general-purpose runtime enforcement by themselves.
- Automatic schema inference does not infer arbitrary constraints from an if statement.
- A return annotation does not automatically create or enforce a provider-facing output schema.
- Schema validation is not authorization.
- Some validators coerce compatible values instead of rejecting them. Test your desired strictness explicitly.
For instance, the inferred integer type does not necessarily enforce parcels between 1 and 10. That rule remains in the implementation until it is also represented in an explicit supported schema. The dedicated Pydantic-schema lesson explains field constraints, validation modes and custom argument schemas in depth.
4. Direct invocation: test a tool without a model#
A decorated tool exposes a runnable invocation interface. In supported LangChain versions, invoke accepts a dictionary of tool arguments. This allows deterministic development and debugging without an LLM request.
PYTHONone = estimate_delivery.invoke({"postcode": "12345"}) three = estimate_delivery.invoke({"postcode": "12345", "parcels": 3}) print(one) print(three)
Expected logical results:
{'currency': 'USD', 'cost_cents': 550}
{'currency': 'USD', 'cost_cents': 850}These follow from 400 cents plus 150 cents per parcel. They were verified using the standalone implementation in section 8, not by executing the LangChain SDK snippets.
Do not assume that a decorated function should still be called using the original plain-function syntax. Use the tool's documented invocation interface, or keep the domain function separate from its decorated wrapper so ordinary unit tests can exercise the underlying business logic directly.
For a production service, this separation can look like a plain estimate function that accepts a validated postal code and parcel count, plus a thin decorated function that delegates to that service. Test both layers independently.
Direct invocation with a simple argument dictionary commonly returns the function's logical result. Invocation with a structured tool-call envelope may instead produce a ToolMessage or another supported result representation. The exact return contract depends on the tool class, invocation form and configured response format.
5. Give tools a stable name and accurate metadata#
A tool's name is a dispatch identifier, not necessarily the same as the internal implementation function. Supported modern versions permit supplying a custom name through the decorator.
PYTHONfrom langchain.tools import tool @tool("delivery_cost_quote") def quote_delivery(postcode: str, parcels: int = 1) -> str: """Calculate a fictional delivery quote; does not place an order.""" if len(postcode) != 5 or not postcode.isascii() or not postcode.isdigit(): raise ValueError("invalid postcode") if not 1 <= parcels <= 10: raise ValueError("parcel count out of range") cents = 400 + 150 * parcels return f"Estimated cost: USD {cents // 100}.{cents % 100:02d}"
The model-facing name is intended to be delivery_cost_quote rather than quote_delivery. A descriptive stable name makes dispatch, traces and evaluations easier to maintain. Some decorator options also allow explicit descriptions, docstring parsing and custom schema configuration; check their availability and precedence in the installed version.
Treat tool names and input fields as interface contracts. Renaming a tool or removing an argument can break stored test fixtures, saved workflows or provider expectations. Avoid duplicate names within the same registered tool set.
The next lesson (#12) focuses on how alternative names and docstrings affect actual model selection. Here the emphasis is simply on understanding where metadata comes from and verifying the resulting object.
6. Register the tool with a LangChain agent#
Once a tool has been inspected and directly tested, provide it to the agent's approved tool list.
PYTHONfrom langchain.agents import create_agent agent = create_agent( model="openai:gpt-4o-mini", tools=[estimate_delivery], system_prompt=( "Calculate fictional delivery estimates using the available tool. " "Report the returned currency and cost accurately. " "Do not claim that a shipment has been created." ), ) result = agent.invoke({ "messages": [{ "role": "user", "content": "Estimate delivery for three parcels to 12345." }] }) print(result["messages"][-1].content)
Install the appropriate model integration and configure an approved credential through trusted runtime infrastructure before running the example. The model identifier is illustrative, not a live availability guarantee. This SDK example was not executed.
The expected task outcome is an estimate of USD 8.50, with no claim that a shipment was created. The model may produce different valid wording or ask for clarification. The decorator and the agent instruction do not guarantee that it will call the tool correctly.
The execution contract is:
The final validation shown is a recommended application responsibility, not an automatic guarantee of create_agent. In a real pricing application, verify returned amounts, relevant tax rules and quotation expiry independently.
Decorating versus binding versus executing#
These operations are easy to confuse.
| Operation | Responsibility |
|---|---|
| Apply @tool | Construct a callable tool object and its contract |
| Register via create_agent | Give a particular agent runtime access to the approved tool |
| Bind tools to a compatible chat model | Make tool specifications available for model-generated requests |
| Call the tool's invoke method | Execute the selected tool using provided arguments |
| Invoke the agent | Run model orchestration, potentially including tool execution |
Model binding alone does not execute external functions. A model response can contain a tool-call proposal; a dispatcher or agent runtime must execute it and return the correlated result.
7. Return values and validation boundaries#
A tool result is an observation for the application and potentially the model. It should be small, relevant and unambiguous. Typical simple tools return a string, a number or a serializable dictionary. More advanced response formats can separate model-visible content from application artifacts, but their configuration is covered in source question #16.
For the estimate_delivery example, a dictionary with currency and cost_cents preserves the exact amount. A string such as "cheap delivery" is less useful because it does not provide a verifiable amount. Conversely, returning an entire internal pricing configuration is unnecessary and may disclose sensitive information.
Do not assume the Python result is transported unchanged to every provider. The agent runtime and provider adapter can serialize it into message content or supported structured blocks. Check the actual result representation, size and confidentiality.
A safe tool call has several distinct checks:
Not every tool requires a user-specific permission check; a pure fictional calculation may be safe for all authorized application callers. Tools that read private records or mutate external systems require stronger authorization. For write-capable tools, use explicit operation approval where appropriate, idempotency and authoritative outcome verification.
Validation errors and external failures are not equivalent. Invalid arguments should be rejected without executing the operation. A read-only temporary service failure may be retried within a bounded policy. An uncertain write must be reconciled before another attempt. Do not disclose stack traces, credentials or internal records in an error returned to a model or user.
8. Locally tested Python implementation: decorator, inferred schema and direct invocation#
The following dependency-free example demonstrates the underlying registration pattern. It is deliberately a small custom teaching implementation, not a reproduction of LangChain, its Pydantic integration or its provider schema conversion. It supports ordinary fixed-argument functions with str and int input annotations and dictionary-style direct invocation.
PYTHONfrom inspect import signature, getdoc from typing import get_type_hints from dataclasses import dataclass @dataclass(frozen=True) class LocalTool: name: str description: str fn: object def schema(self): params = signature(self.fn).parameters hints = get_type_hints(self.fn) return { 'type': 'object', 'properties': {k: {'type': {str: 'string', int: 'integer'}[hints[k]]} for k in params}, 'required': [k for k, p in params.items() if p.default is p.empty], 'additionalProperties': False, } def invoke(self, args): bound = signature(self.fn).bind(**args) bound.apply_defaults() hints = get_type_hints(self.fn) for key, value in bound.arguments.items(): if type(value) is not hints[key]: raise TypeError('invalid argument type') return self.fn(*bound.args, **bound.kwargs) registry = {} def local_tool(fn): description = getdoc(fn) if not description or fn.__name__ in registry: raise ValueError('missing description or duplicate tool') wrapped = LocalTool(fn.__name__, description, fn) wrapped.schema() registry[wrapped.name] = wrapped return wrapped @local_tool def estimate_delivery(postcode: str, parcels: int = 1) -> dict: """Estimate fictional delivery cost in cents; no shipment is created.""" if len(postcode) != 5 or not postcode.isascii() or not postcode.isdigit(): raise ValueError('invalid postcode') if not 1 <= parcels <= 10: raise ValueError('parcel count out of range') return {'currency': 'USD', 'cost_cents': 400 + 150 * parcels} assert registry['estimate_delivery'] is estimate_delivery assert estimate_delivery.description.startswith('Estimate fictional') assert estimate_delivery.schema()['required'] == ['postcode'] assert estimate_delivery.schema()['properties']['parcels'] == {'type': 'integer'} assert estimate_delivery.invoke({'postcode': '12345'})['cost_cents'] == 550 assert estimate_delivery.invoke({'postcode': '12345', 'parcels': 3})['cost_cents'] == 850 for args, error in [({}, TypeError), ({'postcode': '12345', 'parcels': True}, TypeError), ({'postcode': '12345', 'extra': 1}, TypeError), ({'postcode': '12345', 'parcels': 0}, ValueError), ({'postcode': 'ABCDE'}, ValueError)]: try: estimate_delivery.invoke(args) except error: pass else: raise AssertionError('invalid request accepted') print('11 checks passed')
Actual local execution on Python 3.13.5: 11 checks passed.
| Check | Observed behavior |
|---|---|
| Registration | Decorated object is stored under its function name |
| Description | Extracted from the function docstring |
| Required input | postcode is required |
| Type metadata | parcels maps to integer |
| Default invocation | Returns 550 cents |
| Explicit parcel count | Returns 850 cents |
| Missing argument | TypeError |
| Boolean supplied as integer | TypeError under this teaching validator |
| Unexpected field | TypeError |
| Parcel count outside domain range | ValueError |
| Invalid postal code | ValueError |
The local implementation uses exact type comparisons, so True is rejected even though bool is a subclass of int in Python. Real LangChain/Pydantic validation can have different coercion and strictness behavior. The generated teaching schema omits default values and detailed descriptions on individual properties, whereas actual framework schemas may include them.
The teaching decorator stores its tools in a local registry at definition time. This is a demonstration design choice, not a claim that LangChain maintains a global tool registry automatically. A production registry should be application-owned, explicitly scoped and reviewed. The example is not suitable for arbitrary annotations, asynchronous functions, variadic arguments, untrusted Python code or concurrent registry mutation.
The tests verify the exact code shown, not SDK integration, provider tool-call support or model behavior.
9. Testing an actual LangChain tool in production#
Once the dependencies are installed in a controlled environment, run several layers of tests.
Direct tool tests#
Call the tool through its documented invoke interface using valid and invalid input dictionaries. Inspect the resulting object and schema. Verify required fields, defaults, type handling, boundary values and error behavior. Test that an unauthorized or malformed input cannot trigger an external operation.
Agent integration tests#
Use a deterministic model substitute or scripted tool requests supported by the installed LangChain version. Verify that the tool is exposed under the expected name, that valid arguments reach the implementation, that tool observations retain their call correlation, and that invalid calls fail safely.
Run a limited live-provider integration test with synthetic data only when approved. The provider's tool-name restrictions, JSON-schema subset, handling of optional fields and tool-response representation may differ from other providers. Passing direct invocation tests does not establish successful provider integration.
Outcome tests#
Evaluate the complete agent response, including whether it reported the actual tool result and distinguished a quotation from a completed shipment. A useful fixture asserts the numerical outcome and operation semantics, not a single exact natural-language sentence.
Record tool implementation revision, schema revision, installed package versions and test environment. Include tool-level latency, invocation count and controlled error categories without logging sensitive payloads. These records help determine whether a regression arises from a changed tool, model profile or runtime.
10. Production practices and common mistakes#
| Mistake | Corrective practice |
|---|---|
| Missing function docstring | Supply a specific reviewed description |
| Untyped arguments or ambiguous types | Use explicit annotations and inspect the inferred schema |
| Assuming annotations enforce every business rule | Validate domain constraints inside the service or explicit schema |
| Calling a decorated object like an ordinary function | Use its documented invoke interface or separate the domain function |
| Assuming decoration automatically exposes every tool | Register only the tools approved for that agent |
| Duplicate or changing tool names | Keep a stable, unique dispatch contract |
| Returning huge or sensitive payloads | Return minimal task-relevant observations |
| Treating model-generated identifiers as authorization | Resolve identity and enforce resource permissions outside the model |
| Using blocking or unbounded external calls | Bound deadlines, manage resources and select suitable execution interfaces |
| Testing only with real models | Use deterministic direct tests and separately approved integration tests |
Do not expose a general-purpose shell, unrestricted database query capability or broad administrative API when a narrow business tool will suffice. Define only the capabilities necessary for the task. An agent with fewer, well-tested tools is often easier to reason about than one with an extensive uncontrolled registry.
A decorated tool is also a dependency boundary. Avoid capturing a mutable global customer identity or embedding a secret in the docstring. Pass scoped dependencies using supported runtime mechanisms, which the later runtime-injection lesson explains. Keep read-only and write-capable operations separate, and do not silently change the behavior of an existing tool from estimation to execution.
Interview-ready answer#
I use LangChain's @tool decorator to turn a documented, typed Python function into a tool object with a stable name, description and inferred argument schema. I inspect the schema and test the tool directly with invoke before registering it with create_agent. The model receives the tool definition and proposes structured calls; the runtime dispatches approved calls and returns observations. I keep business validation, authorization and external side-effect controls independent of the model, return minimal useful results, and test the actual provider integration separately. Automatic schema inference is convenient but does not replace explicit domain constraints or output verification.
Official documentation research leads and verification status#
- LangChain tools
- LangChain agents
- LangChain models
- LangChain messages
- LangChain API reference
- Python inspect documentation
- Python typing documentation
Authorized offline research exception applied. These official documentation links are research leads, not live-accessed sources. Current framework signatures, provider behavior and link availability were not independently verified. The standard-library implementation was executed on Python 3.13.5 and all 11 checks passed. LangChain, langchain_core and LangGraph were not installed, so actual SDK snippets and model integration were not executed. The Mermaid diagrams use standard triple-backtick fences; live rendering and public website display were not verified. All delivery prices and postal-code constraints are fictional.
References
- 1.LangChain toolsdocs.langchain.com
- 2.LangChain agentsdocs.langchain.com
- 3.LangChain modelsdocs.langchain.com
- 4.LangChain messagesdocs.langchain.com
- 5.LangChain API referencereference.langchain.com
- 6.Python inspect documentationdocs.python.org
- 7.Python typing documentationdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps