LangChain Tools API Reference
In LangChain, the large language model is mainly responsible for understanding questions and generating answers, while Tools give the model the ability to perform specific operations.
For example, an Agent can use tools to query databases, search knowledge bases, compute mathematical expressions, or call external APIs.
LangChain 1.x provides a unified Tools API, the most commonly used are @tool the decorator and BaseTool the tool abstraction.
This chapter systematically covers the parameters of @tool, BaseTool attributes and methods, Pydantic parameter validation, ToolRuntime dependency injection, tool return values, exception handling, and the Agent tool calling flow.
1. What is a LangChain Tool?
A Tool is a function or operation interface provided for the model to call.
A Tool usually contains:
- **name:** the tool name, helping the model identify the function.
- **description:** the tool description, telling the model when to use it.
- **args_schema:** the structure of the tool's parameters.
- **Execution logic:** the Python code that actually performs the query, calculation, or other operation.
For example:
用户:帮我计算 25 + 17
↓
Agent
↓
选择 add_numbers
↓
执行工具
↓
返回 42
↓
模型生成回答
Tool calling has two important steps:
- The model generates a ToolCall, proposing which tool to call and what parameters to pass.
- The Agent or application executes the tool and returns the result via a ToolMessage.
**Note:** simply using model.bind_tools() does not automatically execute the Python function. If you want to automatically execute the tool loop, you usually use create_agent()。
2. The @tool Decorator
@tool is the simplest way to create a LangChain Tool.
It can convert an ordinary Python function into a BaseTool object and infer the tool's input parameters from the function signature.
Basic Syntax
from langchain.tools import tool
@tool
def tool_name(param: str) -> str:
"""描述工具的用途。"""
return f"结果:{param}"
The function's docstring is very important, because the model decides when to call the tool based on the tool name, description, and parameter Schema.
Example: Creating Your First Tool
Example
from
langchain.
tools
import
tool
@
tool
def
greet
(
name:
str
)
str
:
"""Generate a greeting based on the user's name."""
return
f
"Hello, {name}!"
(
greet.
name
)
(
greet.
description
)
(
greet.
invoke
(
{
"name"
:
"Xiao Ming"
}
)
)
Running result:
greet
根据用户姓名生成一句问候语。
你好,小明!
Here, greet is no longer just an ordinary Python function, but a LangChain Tool with a name, description, parameter Schema, and calling interface.
3. Complete @tool Parameters
The current LangChain @tool decorator supports the following main parameters:
| Parameters | Default value | Description |
|---|---|---|
name_or_callable |
None | The tool name or the function to be converted |
runnable |
None | Convert a Runnable into a tool |
description |
None | Custom tool description, defaults to the docstring |
return_direct |
False | Whether to directly end the Agent tool loop after the tool returns |
args_schema |
None | Pydantic or JSON Schema parameter definition |
infer_schema |
True | Whether to infer the parameter Schema from the function signature |
response_format |
"content" | The organization form of the tool's return value |
parse_docstring |
False | Whether to parse Google-style parameter documentation |
error_on_invalid_docstring |
True | Whether to raise an exception when docstring parsing fails |
extras |
None | Add provider-specific tool fields |
Common forms include:
@tool
@tool("custom_name")
@tool(description="自定义工具描述")
@tool(args_schema=MyInput)
@tool(return_direct=True)
**Note:** custom tool names usually use @tool("custom_name")rather than assuming the current @tool decorator has a separate name keyword argument.
4. Custom Tool Names
By default, the tool name is the Python function name.
If you want to change the name, you can pass a string to @tool.
Example
Example
from
langchain.
tools
import
tool
@
tool
(
"search_python_docs"
)
def
search_docs
(
keyword
:
str
)
str
:
"""Search mock Python documentation."""
return
f
"Find reference materials about {keyword}"
(
search_docs.
name
)
(
search_docs.
invoke
(
{
"keyword"
:
"Decorator"
}
)
)
Output:
search_python_docs
找到关于 装饰器 的参考资料
It is recommended to use clear snake_case names, for example:
search_knowledge
get_weather
query_order
calculate_sum
send_email
Avoid tool names that contain spaces, special symbols, or have ambiguous meanings.
5. Custom Tool Descriptions
The tool description affects the model's tool selection.
For example, if you just write:
"""查询数据"""
the model may not know in what situations to use it.
A better description should explain the purpose, scope of application, and returned content.
Example: Custom description
Example
@
tool
(
"search_course"
,
description
=
"Find courses in the mock programming course catalog. Use when the user asks about Python, Java, or other courses."
)
def
find_course
(
keyword
:
str
)
str
:
"""Find a course."""
return
f
"Mock query result: {keyword} introductory course"
(
find_course.
description
)
description When explicitly specified, this description takes precedence over the function docstring.
**Recommendation:** a tool description should include "what the tool can do" and "when to call it", but do not write the tool description as a lengthy system prompt.
6. infer_schema: Automatically Generating Parameter Schema
By default:
infer_schema=True
LangChain generates the parameter Schema based on the Python function's type annotations and signature.
Example
Example
@
tool
def
calculate_sum
(
a:
int
,
b:
int
)
int
:
"""Calculate the sum of two integers."""
return
a + b
(
calculate_sum.
args
)
(
calculate_sum.
invoke
(
{
"a"
:
10
,
"b"
:
25
}
)
)
You might get:
{
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"}
}
35
The parameter structure is automatically generated from the function definition.
It is recommended to add clear type annotations to tool functions, otherwise the model may have difficulty accurately understanding the parameter requirements.
7. args_schema: Pydantic Parameter Validation
When tool parameters are complex, you can use Pydantic to define the input structure.
For example, a course query tool needs:
- The course keyword cannot be empty.
- The query count is 1 to 20.
- The course category can only be Python, Java, or JavaScript.
You can use the BaseModel、Field and Literal implementation based on the dynamic type of the object.
Example: Parameter Validation
Example
from
typing
import
Literal
from
pydantic
import
BaseModel
,
Field
from
langchain.
tools
import
tool
class
SearchInput
(
BaseModel
)
:
keyword
:
str
=
Field
(
min_length
=
1
,
description
=
"Course search keyword"
)
category: Literal
[
"Python"
,
"Java"
,
"JavaScript"
]
=
Field
(
description
=
"Course category"
)
limit:
int
=
Field
(
default
=
5
,
ge
=
1
,
le
=
20
,
description
=
"Maximum number of results to return"
)
@
tool
(
args_schema
=
SearchInput
)
def
search_course
(
keyword
:
str
,
category:
str
,
limit:
int
=
5
)
str
:
"""Search mock programming courses by category and keyword."""
return
f
"Search {category} / {keyword}, up to {limit} results"
result
=
search_course.
invoke
(
{
"keyword"
:
"Beginner"
,
"category"
:
"Python"
,
"limit"
:
10
}
)
(
result
)
Running result:
搜索 Python / 入门,最多 10 条
If you pass in:
{
"keyword": "",
"category": "PHP",
"limit": 100
}
a Pydantic parameter validation error may be triggered, because these values do not conform to the Schema.
**Note:** Pydantic can validate parameter types and value ranges, but it cannot replace user permission checks or actual business rule validation.
8. parse_docstring: Parsing Parameter Descriptions
Tool functions can use Google-style docstrings to describe parameters.
Enable:
parse_docstring=True
then LangChain will try to extract the descriptions in Args into the tool Schema.
Example
Example
@
tool
(
parse_docstring
=
True
)
def
search_article
(
keyword
:
str
,
limit:
int
=
5
)
str
:
"""Search mock tutorial articles.
Args:
keyword: the keyword to query.
limit: the maximum number of articles to return.
"""
return
f
"Query {keyword}, up to {limit} articles"
(
search_article.
args
)
Note that the format of the docstring must meet the parsing requirements.
If the format is incorrect, and:
error_on_invalid_docstring=True
a ValueError may be thrown when creating the tool.
For tools with complex inputs, it is recommended to prefer Pydantic args_schema.
9. return_direct: Directly Returning Tool Results
Normally, after the Agent calls a tool, it returns the tool result to the model, and then the model generates the final reply.
模型请求工具
↓
执行工具
↓
工具返回结果
↓
再次调用模型
↓
最终回答
If set as follows:
return_direct=True
After the tool executes, the Agent can directly end the current tool loop, without another normal model reply.
Example: Direct Return
Example
from
langchain.
tools
import
tool
from
langchain.
agents
import
create_agent
@
tool
(
return_direct
=
True
)
def
get_order_status
(
order_id:
str
)
str
:
"""Query mock order status."""
return
f
"Mock order {order_id}: completed"
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
get_order_status
]
,
system_prompt
=
"Use get_order_status when the user asks about mock orders."
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please query mock order ORD-001."
}
]
}
)
(
result
[
"messages"
]
[
1
]
.
content
)
If the model calls this tool, the Agent can end execution after the tool returns.
Note:return_direct=True does not mean agent.invoke() the return value directly becomes a string.
create_agent() usually still returns the Agent State, and the tool result can be read from its messages.
In addition, for parallel tool calls and complex Middleware, the final execution behavior still needs to be judged based on the actual Agent configuration.
10. response_format: Tool Return Value Format
The @tool's response_format supports two common forms:
| Value | Description |
|---|---|
"content" |
The tool returns the result as ToolMessage.content |
"content_and_artifact" |
The tool returns a (content, artifact) tuple |
The default value is:
response_format="content"
Applicable to ordinary strings, dictionaries, and other tool results.
Example: content_and_artifact
Sometimes, we want the model to see only the necessary summary, while the program keeps more complete raw data.
Example
from
langchain.
tools
import
tool
@
tool
(
response_format
=
"content_and_artifact"
)
def
search_docs
(
keyword
:
str
)
:
"""Search mock documents, returning a summary and raw materials."""
documents
=
[
{
"id"
:
"doc-001"
,
"title"
:
"Python functions"
,
"content"
:
"Python functions are used to encapsulate repeated logic."
}
]
content
=
f
"Found {len(documents)} materials about {keyword}."
return
content
,
documents
tool_call
=
{
"type"
:
"tool_call"
,
"name"
:
"search_docs"
,
"args"
:
{
"keyword"
:
"Python"
}
,
"id"
:
"call_docs_001"
}
result
=
search_docs.
invoke
(
tool_call
)
(
"Content for the model:"
,
result.
content
)
(
"Raw materials:"
,
result.
artifact
)
Here, a tool call input with tool_call_id is used, so a ToolMessage is returned, from which you can read:
result.content
result.artifact
Where:
content: mainly provided for the model to read.artifact: additional raw data that the application can keep and process.
**Note:** artifact should not be treated as a secret safe. It may still be stored in running state or tracing data, and sensitive content requires separate access control.
11. Main BaseTool Attributes
Tools created via @tool are usually concrete implementations of BaseTool.
BaseTool provides unified interfaces for tool description, parameter validation, invocation, and error handling.
| property | Description |
|---|---|
name |
Tool name |
description |
Tool function description |
args_schema |
Tool input Schema |
args |
Parameter structure available to the model |
tool_call_schema |
Tool calling Schema provided to the model |
return_direct |
Whether to directly end the Agent tool loop |
response_format |
Tool result format |
handle_tool_error |
ToolException handling configuration |
handle_validation_error |
Parameter validation exception handling configuration |
tags |
Tracing tags |
metadata |
Additional tool metadata |
Example: Viewing Tool Attributes
Example
@
tool
def
multiply
(
a:
int
,
b:
int
)
int
:
"""Calculate the product of two integers."""
return
a * b
(
"Name:"
,
multiply.
name
)
(
"Description:"
,
multiply.
description
)
(
"Arguments:"
,
multiply.
args
)
(
"Direct return:"
,
multiply.
return_direct
)
(
"Return format:"
,
multiply.
response_format
)
12. Common BaseTool Methods
| Method | Description |
|---|---|
invoke(input, config=None) |
Execute the tool synchronously |
ainvoke(input, config=None) |
Execute the tool asynchronously |
run(tool_input) |
Low-level synchronous execution interface |
arun(tool_input) |
Low-level asynchronous execution interface |
get_input_schema() |
Get the input Schema |
model_copy() |
Copy the tool configuration object |
Example: invoke()
Example
result
=
multiply.
invoke
(
{
"a"
:
6
,
"b"
:
7
}
)
(
result
)
Running result:
42
Example: ainvoke()
Example
import
asyncio
async
def
main
(
)
:
result
=
await multiply.
ainvoke
(
{
"a"
:
8
,
"b"
:
9
}
)
(
result
)
asyncio.
run
(
main
(
)
)
Output:
72
For simple tools, using invoke() or ainvoke() directly is most convenient.
13. ToolRuntime: Unified Runtime Dependency Injection
In LangChain 1.x, it is recommended to use ToolRuntime to obtain the context during tool execution.
Older examples may have used:
InjectedState
InjectedStore
InjectedToolCallId
These interfaces belong to an earlier dependency injection pattern.
New projects are recommended to uniformly use:
from langchain.tools import ToolRuntime
Main ToolRuntime Attributes
| property | Purpose |
|---|---|
runtime.state |
Read the current Agent state |
runtime.context |
Read the trusted runtime context |
runtime.store |
Access cross-session long-term storage |
runtime.tool_call_id |
Get the current tool call ID |
runtime.config |
Read the RunnableConfig |
runtime.stream_writer |
Send custom streaming progress |
runtime.execution_info |
Read execution identifiers and retry information (version requirements apply) |
runtime.server_info |
Service metadata in the LangGraph Server environment |
The ToolRuntime parameter is injected when the Agent executes the tool, and is not exposed to the model as a normal tool parameter.
14. ToolRuntime.state: Reading Conversation State
If a tool needs to check the number of messages in the current session, it can through runtime.state .
Example: Reading the Current Message Count
Example
from
langchain.
tools
import
tool
,
ToolRuntime
@
tool
def
count_messages
(
runtime: ToolRuntime
)
str
:
"""Count the number of messages in the current conversation state."""
messages
=
runtime.
state
.
get
(
"messages"
,
[
]
)
return
f
"There are {len(messages)} messages in total."
Here, the tool parameter Schema seen by the model does not include runtime.
If the tool is called in an Agent, LangGraph will automatically provide the corresponding state.
**Note:** such tools usually need to be called within the execution context of an Agent or ToolNode. Do not assume, as with ordinary tools, that count_messages.invoke({}) the correct runtime state can always be obtained independently.
15. ToolRuntime.context: Injecting Trusted User Information
For businesses such as user profiles and order queries, you need to know who is currently calling the tool.
Such identity information should not be generated by the model, but provided by the backend authentication system.
can be used via context_schema and ToolRuntime implemented in combination.
Example: Getting the Current User Profile
Example
from
dataclasses
import
dataclass
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
@
dataclass
class
UserContext:
user_id:
str
profiles
=
{
"user_001"
:
{
"name"
:
"Xiao Ming"
,
"level"
:
"Python beginner"
}
}
@
tool
def
get_my_profile
(
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Query the mock learning materials of the currently authenticated user."""
user_id
=
runtime.
context
.
user_id
profile
=
profiles.
get
(
user_id
)
if
not
profile
:
return
"No profile found for the current user."
return
f
"Name: {profile['name']}, learning stage: {profile['level']}"
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
get_my_profile
]
,
context_schema
=
UserContext
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to view my learning materials."
}
]
}
,
context
=
UserContext
(
user_id
=
"user_001"
)
)
(
result
[
"messages"
]
[
1
]
.
content
)
Here, user_id comes from the Agent caller, not from a model tool parameter.
**Security reminder:** a real website must generate context based on the logged-in user, and must not allow the browser to pass in an arbitrary user_id to query other people's information.
16. ToolRuntime.store: Cross-Session Storage
ToolRuntime can also access the Store configured through the Agent.
Store is suitable for saving preferences and long-term data shared across sessions.
Example: Reading User Preferences
Example
from
langgraph.
store
.
memory
import
InMemoryStore
from
langchain.
tools
import
tool
,
ToolRuntime
store
=
InMemoryStore
(
)
store.
put
(
(
"users"
,
"user_001"
)
,
"preference"
,
{
"language"
:
"Python"
}
)
@
tool
def
get_preference
(
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Read the current user's learning preferences."""
if
runtime.
store
is
None
:
return
"Long-term storage is not configured."
user_id
=
runtime.
context
.
user_id
item
=
runtime.
store
.
get
(
(
"users"
,
user_id
)
,
"preference"
)
return
str
(
item.
value
)
if
item
else
"No preferences saved."
Here, you need to pass the Store to create_agent(), and get the current user ID through the trusted context.
Complete creation method:
agent = create_agent(
model="deepseek:deepseek-chat",
tools=[get_preference],
context_schema=UserContext,
store=store
)
**Note:** InMemoryStore is only suitable for teaching and local testing. When cross-process persistence is needed, use a persistent Store implementation such as PostgreSQL.
17. ToolRuntime.tool_call_id: Getting the Call ID
Each time the model calls a tool, an ID is usually assigned to the ToolCall.
This ID is used to associate:
AIMessage.tool_calls
↓
ToolMessage
↓
相同 tool_call_id
A tool can get the current call ID through the following attribute:
runtime.tool_call_id
This ID is especially important when a tool needs to return a Command to update the Agent state.
18. Tools Updating Agent State: Command
An ordinary tool returns a string, which only passes the result to the model.
If you want to modify other fields in the Agent State, you can through Command(update=...) return a state update.
At the same time, you should return a ToolMessage matching the current tool call ID, to avoid unfinished tool calls in the message history.
Example: Setting User Preferences
Example
from
typing
import
NotRequired
from
langchain.
agents
import
AgentState
,
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
from
langchain.
messages
import
ToolMessage
from
langgraph.
types
import
Command
class
CustomState
(
AgentState
)
:
preferred_language: NotRequired
[
str
]
@
tool
def
set_language
(
language:
str
,
runtime: ToolRuntime
[
None
,
CustomState
]
)
Command:
"""Save the preferred programming language of the current session to the Agent state."""
return
Command
(
update
=
{
"preferred_language"
: language
,
"messages"
:
[
ToolMessage
(
content
=
f
"Preferred programming language has been set to {language}"
,
tool_call_id
=
runtime.
tool_call_id
,
name
=
"set_language"
)
]
}
)
agent
=
create_agent
(
model
=
"deepseek:deepseek-chat"
,
tools
=
[
set_language
]
,
state_schema
=
CustomState
)
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please call the tool to set my preferred programming language to Python."
}
]
}
)
(
"Current state:"
,
result.
get
(
"preferred_language"
)
)
If the model calls set_language, the tool will update the state field:
preferred_language = "Python"
**Note:** ordinary tool return values are not automatically written to arbitrary custom State fields. You need to explicitly return a Command or update the state through other graph nodes.
19. ToolRuntime.stream_writer: Tool Execution Progress
For tools that take a long time to execute, you can send custom progress messages during execution.
This is suitable for tasks such as file parsing, batch processing, and knowledge base indexing.
Example: Sending Custom Progress
Example
from
langchain.
tools
import
tool
,
ToolRuntime
@
tool
def
process_documents
(
runtime: ToolRuntime
)
str
:
"""Simulate processing multiple knowledge base documents."""
runtime.
stream_writer
(
{
"progress"
:
0
,
"message"
:
"Start processing"
}
)
runtime.
stream_writer
(
{
"progress"
:
50
,
"message"
:
"Building index"
}
)
runtime.
stream_writer
(
{
"progress"
:
100
,
"message"
:
"Processing complete"
}
)
return
"Documents simulated as processed"
The Agent can use:
stream_mode="custom"
to receive custom events.
**Note:** stream_writer should be used within the LangGraph execution context. These progress data are for demonstration only and do not represent real task completion.
20. ToolException: Tool Business Exceptions
Two common types of errors may occur during tool execution:
- Business exceptions: for example, an invalid course ID or invalid query conditions.
- System exceptions: for example, a broken database connection or network timeout.
LangChain provides ToolExceptioncan represent a tool execution error.
But ToolException does not mean the exception will necessarily be automatically converted into a readable result.
The actual behavior depends on handle_tool_error or the Agent Middleware configuration.
Example: ToolException
Example
from
langchain.
tools
import
tool
,
ToolException
@
tool
def
get_course
(
course_id:
int
)
str
:
"""Query a mock course by a specified ID."""
if
course_id
<=
0
:
raise
ToolException
(
"Course ID must be greater than 0"
)
return
f
"Mock course {course_id}: Python introductory"
get_course.
handle_tool_error
=
True
(
get_course.
invoke
(
{
"course_id"
: -
1
}
)
)
After the tool is configured with handle_tool_error=True, it can return the ToolException error message as the tool result.
For example:
课程 ID 必须大于 0
If the corresponding handling is not enabled, the exception may continue to be thrown upward.
21. handle_tool_error and handle_validation_error
BaseTool provides two easily confused configurations:
| Parameters | Purpose |
|---|---|
handle_tool_error |
Handle ToolException thrown during tool execution |
handle_validation_error |
Handle Pydantic parameter validation exceptions |
For example:
Example
from
pydantic
import
BaseModel
,
Field
from
langchain.
tools
import
tool
,
ToolException
class
QueryInput
(
BaseModel
)
:
course_id:
int
=
Field
(
gt
=
0
)
@
tool
(
args_schema
=
QueryInput
)
def
query_course
(
course_id:
int
)
str
:
"""Query a mock course by ID."""
if
course_id
==
999
:
raise
ToolException
(
"Course does not exist"
)
return
f
"Course number: {course_id}"
query_course.
handle_tool_error
=
True
query_course.
handle_validation_error
=
"Course number must be a positive integer"
(
query_course.
invoke
(
{
"course_id"
:
1
}
)
)
(
query_course.
invoke
(
{
"course_id"
: -
1
}
)
)
(
query_course.
invoke
(
{
"course_id"
:
999
}
)
)
Sample output:
课程编号:1
课程编号必须是正整数
课程不存在
The two configurations can handle parameter validation errors and ToolExceptions actively thrown by the tool, respectively.
**Note:** they cannot handle all Python exceptions. For database exceptions, network errors, etc., you can also use ToolRetryMiddleware or ToolErrorMiddleware.
22. How to Migrate from Legacy InjectedState / InjectedStore?
Early LangGraph examples may have used dependency injection markers:
| Old interface | Recommended replacement |
|---|---|
InjectedState |
ToolRuntime.state |
InjectedStore |
ToolRuntime.store |
InjectedToolCallId |
ToolRuntime.tool_call_id |
InjectedToolArg |
Prefer ToolRuntime or specific runtime interfaces |
Old approach
from typing import Annotated
from langgraph.prebuilt import InjectedState
@tool
def count_messages(
state: Annotated[dict, InjectedState]
) -> str:
return str(len(state["messages"]))
New approach
from langchain.tools import tool, ToolRuntime
@tool
def count_messages(runtime: ToolRuntime) -> str:
"""统计当前对话消息数量。"""
return str(len(runtime.state["messages"]))
The new approach is more unified and also makes it easier to get context, store, and tool_call_id.
For legacy LangGraph projects under maintenance, immediate migration is not necessarily required, but new LangChain 1.x projects are recommended to use ToolRuntime.
23. Reserved Names in Tool Parameters
LangChain's tool execution system automatically injects certain runtime parameters.
Therefore, ordinary business parameters should not use these names:
| Name | Problem |
|---|---|
config |
Conflicts with automatic injection of RunnableConfig |
runtime |
Reserved for ToolRuntime |
run_manager |
Conflicts with the internal callback management mechanism |
callbacks |
Conflicts with internal callback parameters |
For example, it is not recommended:
@tool
def search_docs(config: str) -> str:
"""搜索文档。"""
return config
Recommended:
@tool
def search_docs(query: str) -> str:
"""搜索文档。"""
return query
If you really need to get the RunnableConfig, you should access it through the corresponding attribute provided by ToolRuntime.
24. The Calling Relationship Between Tools and Agents
Calling a tool directly and calling a tool within an Agent do not behave exactly the same.
| How to call | Execution behavior |
|---|---|
tool.invoke() |
The application directly executes the tool |
model.bind_tools() |
The model can produce a ToolCall, but does not automatically execute the tool |
agent.invoke() |
The Agent can automatically manage the tool execution loop |
Typical Agent tool calling flow:
用户消息
↓
AIMessage(tool_calls)
↓
匹配工具名称
↓
校验 args_schema
↓
注入 ToolRuntime
↓
执行 Python 工具
↓
生成 ToolMessage
↓
返回模型
↓
最终回答
The content returned by a tool is by default model reference data and should not be given system instruction authority.
25. Complete Example: Creating a Multi-Tool Agent
The following demonstrates, through a directly runnable example:
- Creating tools with @tool.
- Pydantic parameter validation.
- return_direct configuration.
- Reading BaseTool attributes.
- ToolException exception handling.
- ToolRuntime.context。
- Combining multiple tools with create_agent().
Filename:tools_api_demo.py
Install dependencies:
pip install -U langchain langchain-deepseek pydantic python-dotenv
in .env Configure in :
DEEPSEEK_API_KEY=your_deepseek_api_key
Complete example
from
dataclasses
import
dataclass
from
typing
import
Literal
from
dotenv
import
load_dotenv
from
pydantic
import
BaseModel
,
Field
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
,
ToolRuntime
,
ToolException
from
langchain_deepseek
import
ChatDeepSeek
load_dotenv
(
)
========== 1. Ordinary Tool ==========
@
tool
def
add_numbers
(
a:
int
,
b:
int
)
int
:
"""Calculate the sum of two integers."""
return
a + b
========== 2. Parameter Validation Tool ==========
class
CourseInput
(
BaseModel
)
:
language: Literal
[
"Python"
,
"Java"
]
=
Field
(
description
=
"Programming Language"
)
level: Literal
[
"beginner"
,
"advanced"
]
=
Field
(
default
=
"beginner"
,
description
=
"Learning difficulty"
)
@
tool
(
args_schema
=
CourseInput
)
def
search_course
(
language:
str
,
level:
str
=
"beginner"
)
str
:
"""Search for simulated programming courses."""
return
f
"Found {language} / {level} mock courses"
========== 3. Direct Return Tool ==========
@
tool
(
return_direct
=
True
)
def
get_demo_status
(
)
str
:
"""Return the mock system status."""
return
"Mock system is running normally"
========== 4. ToolException ==========
@
tool
def
get_course_by_id
(
course_id:
int
)
str
:
"""Query a mock course by course number."""
if
course_id
<=
0
:
raise
ToolException
(
"Course ID must be greater than 0"
)
return
f
"Mock course {course_id}: Python introductory"
get_course_by_id.
handle_tool_error
=
True
========== 5. ToolRuntime Context ==========
@
dataclass
class
UserContext:
user_id:
str
@
tool
def
get_current_user
(
runtime: ToolRuntime
[
UserContext
]
)
str
:
"""Query the mock ID of the current user."""
return
f
"Current user: {runtime.context.user_id}"
========== 6. Directly Test Tools ==========
(
"Tool name:"
,
add_numbers.
name
)
(
"Tool description:"
,
add_numbers.
description
)
(
"Parameter Schema:"
,
add_numbers.
args
)
(
"Calculation result: "
,
add_numbers.
invoke
(
{
"a"
:
12
,
"b"
:
30
}
)
)
(
"Course query:"
,
search_course.
invoke
(
{
"language"
:
"Python"
,
"level"
:
"beginner"
}
)
)
(
"Error handling:"
,
get_course_by_id.
invoke
(
{
"course_id"
: -
1
}
)
)
========== 7. Create the Agent ==========
agent
=
create_agent
(
model
=
ChatDeepSeek
(
model
=
"deepseek-chat"
,
temperature
=
0
)
,
tools
=
[
add_numbers
,
search_course
,
get_demo_status
,
get_course_by_id
,
get_current_user
]
,
context_schema
=
UserContext
,
system_prompt
=
"""You are a programming learning assistant.
Select the appropriate tool based on the question.
Use add_numbers for calculation questions.
Use search_course for course queries.
Use get_current_user when querying the current user.
Do not fabricate real courses or system status."""
)
========== 8. Test the Agent ==========
questions
=
[
"Please use a tool to calculate 12 + 30."
,
"Please use a tool to search for Python introductory courses."
,
"Please use a tool to view the current user ID."
]
for
question
in
questions:
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: question
}
]
}
,
context
=
UserContext
(
user_id
=
"student-001"
)
)
(
"\nQuestion:"
,
question
)
(
"Answer:"
,
result
[
"messages"
]
[
1
]
.
content
)
tool_msgs
=
[
msg
for
msg
in
result
[
"messages"
]
if
msg.
type
==
"tool"
]
(
"Tool execution count:"
,
len
(
tool_msgs
)
)
In this example, the first few tools can be tested directly using invoke().
while get_current_user requires the Agent to inject ToolRuntime and should not be called directly without a runtime context.
At the same time, whether the Agent calls a certain tool still depends on the tool call requests actually produced by the model.
26. Common Questions
1. What is the difference between @tool and an ordinary Python function?
@tool converts a function into a LangChain Tool with a name, description, parameter Schema, and unified calling interface.
2. Must @tool have a docstring?
A description should usually be provided. You can use the function docstring or explicitly set description.
3. How to Change the Tool Name?
You can use the @tool("custom_name")。
4. What happens if args_schema is not filled in?
By default, tool parameters are automatically inferred from the function signature and type annotations.
5. Can Pydantic prevent all wrong parameters?
No. It is mainly responsible for data format and constraint validation; business permissions and actual data validity still need to be checked separately.
6. Does return_direct=True directly return a string?
In an Agent it can skip the subsequent normal model reply, but create_agent.invoke() usually still returns the Agent State.
7. What is the difference between ToolCall and ToolMessage?
A ToolCall is a tool call request proposed by the model; a ToolMessage is the result message after the tool executes.
8. Is ToolRuntime generated by the model itself?
No. ToolRuntime is automatically injected by the LangChain execution environment and is not exposed as a normal tool parameter to the model.
9. Can InjectedState and InjectedStore still be used?
They may still be used in legacy projects, but new tutorials recommend the unified interface provided by ToolRuntime.
10. What is the difference between ToolRuntime.state and context?
state holds the state during execution; context provides trusted external information for the current call.
11. Does ToolRuntime.store automatically save chat history?
No. Store is mainly used for long-term data; chat state is usually managed by the Checkpointer.
12. How Can a Tool Modify AgentState?
You can return Command(update=...) and include a ToolMessage matching the current tool call.
13. Does ToolException automatically retry?
No. The handling method needs to be determined based on handle_tool_error or Middleware settings.
14. What is the difference between handle_tool_error and handle_validation_error?
The former handles ToolExceptions during tool execution, while the latter handles input parameter validation errors.
15. What does response_format="content_and_artifact" do?
It allows a tool to return both content for the model and additional raw data for the application to process.
16. Can a Tool Send Execution Progress?
Yes. Send custom stream events through ToolRuntime.stream_writer.
17. What Security Issues Should Be Noted in Tool Calling?
You need to validate parameters, verify identity and permissions, limit resource consumption, and add confirmation and idempotency protection for side-effect operations such as email, payment, and deletion.
18. Will a Tool Necessarily Be Called by the Model?
Not necessarily. Tool selection is decided by the model; business flows that need to be enforced should use deterministic workflows.
Summary
The LangChain Tools API is the foundation for Agent interaction with external systems.
This chapter mainly introduced:
@tool: convert a Python function into a tool.args_schema: define parameters through Pydantic or JSON Schema.infer_schema: automatically infer tool parameters.parse_docstring: parse parameter documentation.return_direct: directly end the tool execution loop.response_format: configure the tool return structure.BaseTool: unified tool abstraction interface.invoke()andainvoke(): synchronous and asynchronous execution.ToolRuntime: runtime dependency injection.runtime.state: read the current state.runtime.context: read the trusted user context.runtime.store: access cross-session long-term storage.runtime.tool_call_id: associate tool requests with results.Command: modify the Agent State.ToolException: handle tool execution exceptions.handle_tool_errorandhandle_validation_error: handle errors by category.
The most common way to write a tool:
from langchain.tools import tool
@tool
def search_course(keyword: str) -> str:
"""搜索模拟编程课程。"""
return f"找到与 {keyword} 相关的课程"
Register in the Agent:
agent = create_agent(
model="deepseek:deepseek-chat",
tools=[search_course]
)
**Core principle:** let the model be responsible for selecting tools, let the Tool be responsible for performing verifiable operations, and let ToolRuntime provide trusted context. When real orders, payments, sending emails, or file deletions are involved, the application must be responsible for permission checks, idempotency control, and necessary human approval.