LangChain @tool
核对 @tool 装饰器语法、Google 风格文档字符串解析、类型注解与 Pydantic args_schema 校验、content_and_artifact、异步工具及多工具协作机制,并在本地离线隔离环境中基于 langchain 1.4.9 与 pydantic 2.14.3 实测验证。
学完这一章,你能够
- 核对 @tool 装饰器语法、Google 风格文档字符串解析、类型注解与 Pydantic args_schema 校验、content_and_artifact、异步工具及多工具协作机制,并在本地离线隔离环境中基于 langchain 1.4.9 与 pydantic 2.14.3 实测验证。
工具定位与 @tool 基本语法
工具(Tool)是 LangChain Agent 访问外部数据与执行确定性计算的桥梁,可用于数据库查询、接口请求、数值计算或文件操作。使用 @tool 装饰器即可把普通 Python 函数封装为包含元数据与执行接口的工具对象,本章覆盖参数定义、文档字符串解析、Pydantic 校验、Agent 注册与多工具协作。
在函数定义前加上 @tool 后,原函数会被转换为 LangChain BaseTool 对象,具备 name、description、args、args_schema 以及同步 invoke()、异步 ainvoke() 接口(详见下表)。本站实测调用 hello_tool.invoke({'name': '小明'}) 返回问候文本且 name 为 'hello_tool'、args_schema 非空;直接按普通函数方式调用 hello_tool('小明') 会抛出 TypeError。其中名称、描述与参数结构供模型判断是否发起调用,执行接口负责运行底层 Python 逻辑。
文档字符串、类型注解与 Pydantic 参数校验
模型依靠 docstring 理解工具职责、调用时机与参数含义。默认情况下 @tool 不会把 Google 风格 docstring 中的 Args 小节拆成各字段独立描述;开启 @tool(parse_docstring=True) 后,本站实测 get_course_info.args['language']['description'] 准确提取为“编程语言名称,例如 Python、Java。”,level 默认值为“入门”。若开启解析但 Args 参数名与签名不匹配,或既无 docstring 又未传 description,实测均立即抛出 ValueError。
@tool 会依据 Python 类型注解(str、int、float、bool、Literal、list 等)自动生成参数 Schema。在本地模拟课程检索实测中,keyword 与 Literal['入门', '进阶', '高级'] 类型的 level 为必填项,max_results 默认 5、free_only 默认 True:查询入门 Python 课程返回“Python 基础、Python 入门练习”,关闭 free_only 查询高级课程返回“Python 高级实战”,全程仅检索内存模拟列表,不连接外部网站。
Python 函数默认参数同样适用于 @tool:无默认值为必填字段,有默认值可省略(注意示例中的 level 仅标记请求级别而未做数据过滤,真实业务需按字段实际筛选)。工程上应避免为用户身份、权限或支付金额等敏感参数设置宽松默认值。
需要限制字符串长度、数值上下界或枚举集合时,可通过 args_schema 绑定 Pydantic BaseModel。本站实测 CourseSearchInput(keyword 长度 1~50、category 限定四类枚举、page 范围 1~100)在合法输入下正常执行,传入 category='invalid' 或 page=0 均在函数体运行前触发 ValidationError;调用 CourseSearchInput.model_json_schema() 可导出完整 JSON Schema(required=['keyword'],page.minimum=1)。需强调 Pydantic 校验只防格式越界,不能替代鉴权、SQL 参数化或路径白名单等安全边界。
@tool 可选参数、Artifact、异步与工具定义对比
@tool 还支持自定义工具名、description、infer_schema、parse_docstring、return_direct 与 response_format 等选项(详见参数表)。实测 @tool('search_python_docs', description='...') 会把对外工具名覆盖为 search_python_docs 而底层函数仍为 search_docs;@tool(return_direct=True) 标记 return_direct 属性为 True,仅提示支持的 Agent 执行框架直接结束循环,手动 tool.invoke() 仍返回原字符串。
当工具需要同时向模型提供简短摘要、向应用程序保留完整结构化载荷时,可设置 response_format='content_and_artifact' 并返回 (content, artifact) 二元组。本站实测揭示了两类调用路径的封装差异:直接执行 search_documents.invoke({'keyword': 'Python'}) 仅返回 str 类型的摘要文本;而传入完整 ToolCall 字典(含 id='call_doc_001' 与 type='tool_call')时,LangChain 封装为 ToolMessage,其 content 为摘要、artifact 保留完整 2 条记录且 tool_call_id 精确对应。
对于 I/O 密集型操作,可用 async def 定义异步工具并配合 ainvoke() 运行:本站通过 asyncio.run(async_search.ainvoke({'keyword': 'Python'})) 实测返回“异步搜索结果:Python”。需注意把阻塞库代码直接放进 async def 并不会自动非阻塞,网络与数据库访问仍须使用异步客户端。
面对资源不存在等可恢复业务错误,工具可直接返回清晰提示(如实测查询不存在课程返回“未找到课程:不存在的课程。请检查名称或重新搜索。”),程序级异常则可配合 ToolException 与错误处理策略,且严禁向模型泄露密钥、内部路径或完整堆栈。下表对比了 @tool、StructuredTool(实测 StructuredTool.from_function 计算 6*7=42)、Pydantic 模型类与 JSON Schema 字典的适用场景:需注意仅传 Pydantic 类或 JSON Schema 给 bind_tools() 只声明接口协议,不含 Python 执行体。
Agent 工具注册、多工具协作与常见问题
定义好的可执行工具通过 create_agent(model=..., tools=[...]) 注册给 Agent。本站使用离线可复现的 ScriptedChatModel 驱动 create_agent 实测两工具接力:模型先请求 get_stock_price(symbol='AAPL') 获“185.50 USD”,再据此请求 convert_currency(185.50, 'USD', 'CNY') 获“1344.88 CNY(模拟汇率 7.25)”,3 次模型往返后汇总输出。真实云端模型调用时,工具选择顺序与次数并非固定,若业务强制要求执行某步骤,应在确定性工作流或代码层编排而非仅靠提示词。
在完整工程项目(如 langchain_tools_demo.py)中,需先安装 langchain、对应提供商集成包、pydantic 与 python-dotenv,并通过 .env 配置密钥再组合 Pydantic 参数校验与多工具 Agent;所有教学演示数据均来自内存列表,不代表真实网站行情或课程目录。
常见问题要点:(1)@tool 仅封装工具对象,不立即执行函数体;(2)模型未调用工具时需排查工具描述、模型 Tool Calling 支持与 tools 注册,强制步骤交由代码编排;(3)缺少 docstring 且未设 description 会触发 ValueError;(4)首参数字符串可自定义工具名;(5)简单函数无需手动写 args_schema;(6)Pydantic 类本身不是可执行工具;(7)参数校验不能替代应用层权限与安全控制;(8)通过 .args、.name、.description 与 model_json_schema() 检查接口;(9)同轮多工具并发取决于模型与执行框架,有依赖时需显式串行;(10)返回值不限于字符串,但传给模型的内容宜简洁。
总结而言,@tool 将 Python 函数转换为具备标准 Schema 与调用契约的组件:模型负责决定何时发起工具请求,LangChain 负责调度与校验,工具函数负责真正执行业务逻辑。
BaseTool 常用属性与执行接口
| 属性或方法 | 说明 |
|---|---|
| name | 工具唯一名称,默认取函数名,可在 @tool 首参覆盖。 |
| description | 工具说明文本,默认取 docstring,可用 description 参数覆盖。 |
| args | 面向调用参数生成的 JSON Schema properties 字典。 |
| args_schema | 用于输入校验的 Pydantic 模型类或 JSON Schema 定义。 |
| invoke() | 同步执行工具入口(接受参数字典或完整 ToolCall)。 |
| ainvoke() | 异步执行工具入口,适用于协程与异步 Web 服务。 |
@tool 装饰器常用配置参数
| 参数 | 默认值 | 说明 |
|---|---|---|
| description | None | 显式指定工具描述,优先级高于函数文档字符串。 |
| args_schema | None | 显式指定 Pydantic 模型或 Schema 字典以约束入参。 |
| infer_schema | True | 是否依据函数类型注解与签名自动推断参数 Schema。 |
| parse_docstring | False | 是否解析 Google 风格 docstring 的 Args 参数说明(格式不符抛 ValueError)。 |
| return_direct | False | 指示支持的 Agent 执行框架在工具完成后直接返回结果。 |
| response_format | content | 设为 'content_and_artifact' 时按 (content, artifact) 分离模型摘要与程序数据。 |
LangChain 工具定义与 Schema 声明方式对比
| 定义方式 | 特点 | 适用场景 |
|---|---|---|
| @tool | 依据 Python 函数快速生成可执行 BaseTool 对象。 | 常规 Agent 工具开发。 |
| @tool(args_schema=...) | 绑定 Pydantic 模型提供范围、长度与枚举校验。 | 多参数或需要严格输入约束的业务工具。 |
| StructuredTool | 通过 StructuredTool.from_function 显式构造同步/异步工具。 | 动态组装函数或需要精细控制同步/协程实现时。 |
| Pydantic 模型类 | 仅声明结构与参数 Schema,不包含 Python 执行体。 | 配合 model.bind_tools() 生成工具调用协议或结构化输出。 |
| JSON Schema / 字典 | 直接以字典描述工具名称与参数协议。 | 复用外部配置或兼容模型提供商原生工具定义。 |
离线实测 @tool 装饰器、parse_docstring、Pydantic 校验、Artifact、异步调用与多工具协作
"""Offline deterministic runtime lab for LangChain Chapter 11 (tool-basics)."""
import asyncio
import json
import platform
from typing import Any, Literal
from langchain.agents import create_agent
from langchain.tools import tool
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, BaseMessage, ToolMessage
from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.tools import StructuredTool
from pydantic import BaseModel, Field, ValidationError
class ScriptedChatModel(BaseChatModel):
responses: list[AIMessage] = Field(default_factory=list)
call_index: int = 0
bound_tool_names: list[str] = Field(default_factory=list)
@property
def _llm_type(self) -> str:
return "scripted-offline-chat"
def bind_tools(self, tools, **kwargs):
self.bound_tool_names = [getattr(t, "name", str(t)) for t in tools]
return self
def _generate(
self,
messages: list[BaseMessage],
stop: list[str] | None = None,
run_manager: Any = None,
**kwargs: Any,
) -> ChatResult:
idx = min(self.call_index, len(self.responses) - 1)
self.call_index += 1
return ChatResult(generations=[ChatGeneration(message=self.responses[idx])])
def case_tool_decorator_schema_and_docstring() -> dict:
@tool
def hello_tool(name: str) -> str:
"""向指定的人打招呼。
Args:
name: 要打招呼的人的名字。
"""
return f"你好,{name}!欢迎来到蓝色天空网模拟环境。"
hello_out = hello_tool.invoke({"name": "小明"})
direct_call_error = None
try:
hello_tool("小明") # type: ignore[operator]
except TypeError as exc:
direct_call_error = type(exc).__name__
@tool(parse_docstring=True)
def get_course_info(language: str, level: str = "入门") -> str:
"""查询指定编程语言的模拟课程信息。
Args:
language: 编程语言名称,例如 Python、Java。
level: 学习难度,默认为入门。
"""
return f"查询 {language} 的{level}课程"
bad_docstring_err = None
try:
@tool(parse_docstring=True)
def broken_doc(language: str) -> str:
"""查询课程。
Args:
missing_arg: 不存在于函数签名中的参数。
"""
return language
except ValueError as exc:
bad_docstring_err = type(exc).__name__
no_doc_err = None
try:
@tool
def no_docstring_fn(x: str) -> str:
return x
except ValueError as exc:
no_doc_err = type(exc).__name__
@tool("search_python_docs", description="在本地模拟文档中查询 Python 相关知识")
def search_docs(keyword: str) -> str:
"""根据关键词查找文档。"""
return f"模拟搜索:{keyword}"
actual = {
"hello_name": hello_tool.name,
"hello_output": hello_out,
"hello_has_args_schema": hello_tool.args_schema is not None,
"direct_call_error": direct_call_error,
"parsed_lang_desc": get_course_info.args["language"].get("description"),
"parsed_level_default": get_course_info.args["level"].get("default"),
"bad_docstring_error": bad_docstring_err,
"no_docstring_error": no_doc_err,
"custom_name": search_docs.name,
"custom_desc": search_docs.description,
"custom_out": search_docs.invoke({"keyword": "装饰器"}),
}
expected = {
"hello_name": "hello_tool",
"hello_output": "你好,小明!欢迎来到蓝色天空网模拟环境。",
"hello_has_args_schema": True,
"direct_call_error": "TypeError",
"parsed_lang_desc": "编程语言名称,例如 Python、Java。",
"parsed_level_default": "入门",
"bad_docstring_error": "ValueError",
"no_docstring_error": "ValueError",
"custom_name": "search_python_docs",
"custom_desc": "在本地模拟文档中查询 Python 相关知识",
"custom_out": "模拟搜索:装饰器",
}
return {
"name": "tool_decorator_schema_and_docstring",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_typed_params_defaults_and_pydantic_schema() -> dict:
@tool(parse_docstring=True)
def search_courses(
keyword: str,
level: Literal["入门", "进阶", "高级"],
max_results: int = 5,
free_only: bool = True,
) -> str:
"""搜索模拟课程列表。
Args:
keyword: 搜索关键词。
level: 课程难度级别。
max_results: 最多返回多少条,范围为1到20。
free_only: 是否只返回免费课程。
"""
courses = [
{"title": "Python 基础", "keyword": "python", "level": "入门", "free": True},
{"title": "Python 入门练习", "keyword": "python", "level": "入门", "free": True},
{"title": "Python 数据分析", "keyword": "python", "level": "进阶", "free": True},
{"title": "Python 高级实战", "keyword": "python", "level": "高级", "free": False},
{"title": "HTML 基础", "keyword": "html", "level": "入门", "free": True},
]
if not 1 <= max_results <= 20:
return "max_results 必须在1到20之间"
results = [
c["title"]
for c in courses
if keyword.lower() in c["keyword"]
and c["level"] == level
and (not free_only or c["free"])
][:max_results]
return "搜索结果:" + "、".join(results) if results else "未找到符合条件的模拟课程"
out_intro = search_courses.invoke({"keyword": "python", "level": "入门"})
out_adv = search_courses.invoke({"keyword": "python", "level": "高级", "free_only": False})
class CourseSearchInput(BaseModel):
"""课程搜索参数。"""
keyword: str = Field(min_length=1, max_length=50, description="搜索关键词")
category: Literal["all", "frontend", "backend", "data"] = Field(
default="all", description="课程类别"
)
page: int = Field(default=1, ge=1, le=100, description="页码,从1开始")
@tool(args_schema=CourseSearchInput)
def search_course_strict(keyword: str, category: str = "all", page: int = 1) -> str:
"""搜索模拟课程数据。"""
return f"搜索关键词:{keyword};分类:{category};页码:{page}"
valid_out = search_course_strict.invoke({"keyword": "Python", "category": "backend", "page": 1})
invalid_cat_err = None
try:
search_course_strict.invoke({"keyword": "Python", "category": "invalid"})
except ValidationError as exc:
invalid_cat_err = type(exc).__name__
invalid_page_err = None
try:
search_course_strict.invoke({"keyword": "Python", "page": 0})
except ValidationError as exc:
invalid_page_err = type(exc).__name__
json_schema = CourseSearchInput.model_json_schema()
def multiply_fn(a: int, b: int) -> int:
return a * b
st_tool = StructuredTool.from_function(
func=multiply_fn,
name="multiply_numbers",
description="计算两个整数的乘积。",
)
st_out = st_tool.invoke({"a": 6, "b": 7})
actual = {
"out_intro": out_intro,
"out_adv": out_adv,
"valid_out": valid_out,
"invalid_category_error": invalid_cat_err,
"invalid_page_error": invalid_page_err,
"schema_required": json_schema["required"],
"schema_page_min": json_schema["properties"]["page"]["minimum"],
"structured_tool_name": st_tool.name,
"structured_tool_out": st_out,
}
expected = {
"out_intro": "搜索结果:Python 基础、Python 入门练习",
"out_adv": "搜索结果:Python 高级实战",
"valid_out": "搜索关键词:Python;分类:backend;页码:1",
"invalid_category_error": "ValidationError",
"invalid_page_error": "ValidationError",
"schema_required": ["keyword"],
"schema_page_min": 1,
"structured_tool_name": "multiply_numbers",
"structured_tool_out": 42,
}
return {
"name": "typed_params_defaults_and_pydantic_schema",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_content_and_artifact_and_async_tool() -> dict:
@tool(response_format="content_and_artifact")
def search_documents(keyword: str):
"""查询模拟文档并返回摘要与完整记录。"""
records = [
{"id": 1, "title": "Python 基础教程"},
{"id": 2, "title": "Python 数据分析"},
]
content = f"找到与 {keyword} 相关的 {len(records)} 条模拟记录"
artifact = {"keyword": keyword, "records": records}
return content, artifact
direct_val = search_documents.invoke({"keyword": "Python"})
tc_msg = search_documents.invoke(
{
"name": "search_documents",
"args": {"keyword": "Python"},
"id": "call_doc_001",
"type": "tool_call",
}
)
@tool(return_direct=True)
def get_help(topic: str) -> str:
"""获取帮助内容。"""
return f"帮助主题:{topic}"
@tool
async def async_search(keyword: str) -> str:
"""执行异步模拟搜索。"""
await asyncio.sleep(0.01)
return f"异步搜索结果:{keyword}"
async_out = asyncio.run(async_search.ainvoke({"keyword": "Python"}))
actual = {
"direct_type": type(direct_val).__name__,
"direct_val": direct_val,
"tc_type": type(tc_msg).__name__,
"tc_content": tc_msg.content,
"tc_artifact_count": len(tc_msg.artifact["records"]),
"tc_id": tc_msg.tool_call_id,
"return_direct_flag": get_help.return_direct,
"return_direct_invoke": get_help.invoke({"topic": "参数校验"}),
"async_out": async_out,
}
expected = {
"direct_type": "str",
"direct_val": "找到与 Python 相关的 2 条模拟记录",
"tc_type": "ToolMessage",
"tc_content": "找到与 Python 相关的 2 条模拟记录",
"tc_artifact_count": 2,
"tc_id": "call_doc_001",
"return_direct_flag": True,
"return_direct_invoke": "帮助主题:参数校验",
"async_out": "异步搜索结果:Python",
}
return {
"name": "content_and_artifact_and_async_tool",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def case_agent_multi_tool_collaboration_and_error_message() -> dict:
@tool
def get_stock_price(symbol: str) -> str:
"""查询指定股票的模拟美元价格。"""
prices = {"AAPL": 185.50, "GOOGL": 142.30, "TSLA": 245.80}
price = prices.get(symbol.upper())
if price is None:
return "没有找到该股票的模拟价格"
return f"{symbol.upper()} 的模拟价格为 {price:.2f} USD"
@tool
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
"""根据固定的模拟汇率换算货币金额。"""
rates = {("USD", "CNY"): 7.25}
src, dst = from_currency.upper(), to_currency.upper()
if src == dst:
return f"{amount:.2f} {dst}"
rate = rates.get((src, dst))
if rate is None:
return "不支持指定的模拟货币换算"
return f"{amount:.2f} {src} = {amount * rate:.2f} {dst}(模拟汇率 {rate})"
@tool
def get_course_detail(course_name: str) -> str:
"""获取指定模拟课程的详细信息。"""
courses = {"Python 基础": "适合初学者", "Java 基础": "介绍 Java 基础语法"}
if course_name not in courses:
return f"未找到课程:{course_name}。请检查名称或重新搜索。"
return courses[course_name]
model = ScriptedChatModel(
responses=[
AIMessage(
content="",
tool_calls=[
{
"name": "get_stock_price",
"args": {"symbol": "AAPL"},
"id": "call_stock_1",
"type": "tool_call",
}
],
),
AIMessage(
content="",
tool_calls=[
{
"name": "convert_currency",
"args": {"amount": 185.50, "from_currency": "USD", "to_currency": "CNY"},
"id": "call_fx_1",
"type": "tool_call",
}
],
),
AIMessage(content="AAPL 模拟价格为 185.50 USD,按 7.25 模拟汇率换算为 1344.88 CNY。"),
]
)
agent = create_agent(
model=model,
tools=[get_stock_price, convert_currency],
system_prompt="金融数据演示助手(全部使用模拟数据)。",
)
res = agent.invoke(
{"messages": [{"role": "user", "content": "查询 AAPL 模拟价格并换算成人民币"}]}
)
tool_msgs = [(m.name, m.content) for m in res["messages"] if isinstance(m, ToolMessage)]
missing_course_msg = get_course_detail.invoke({"course_name": "不存在的课程"})
actual = {
"bound_tools": model.bound_tool_names,
"model_calls": model.call_index,
"tool_messages": tool_msgs,
"final_answer": res["messages"][-1].content,
"missing_course_msg": missing_course_msg,
}
expected = {
"bound_tools": ["get_stock_price", "convert_currency"],
"model_calls": 3,
"tool_messages": [
("get_stock_price", "AAPL 的模拟价格为 185.50 USD"),
("convert_currency", "185.50 USD = 1344.88 CNY(模拟汇率 7.25)"),
],
"final_answer": "AAPL 模拟价格为 185.50 USD,按 7.25 模拟汇率换算为 1344.88 CNY。",
"missing_course_msg": "未找到课程:不存在的课程。请检查名称或重新搜索。",
}
return {
"name": "agent_multi_tool_collaboration_and_error_message",
"passed": actual == expected,
"expected": expected,
"actual": actual,
}
def main() -> None:
cases = [
case_tool_decorator_schema_and_docstring(),
case_typed_params_defaults_and_pydantic_schema(),
case_content_and_artifact_and_async_tool(),
case_agent_multi_tool_collaboration_and_error_message(),
]
print(
json.dumps(
{
"version": platform.python_version(),
"system": platform.system(),
"cases": cases,
},
ensure_ascii=False,
indent=2,
)
)
if __name__ == "__main__":
main()
- 核对 @tool 直接调用抛 TypeError、parse_docstring 正常解析与错参抛 ValueError、CourseSearchInput 拦截非法枚举/页码、content_and_artifact 在直调与 ToolCall 下的差异、ainvoke 异步执行及多工具接力计算。
所需环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
当前源码 SHA256:c44f88f46646ce1eb9a03792fd8397887abb3070a99614b9287a7dda5eb8e5a8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。
ZIP SHA256:9f2577c73815a870cf0e12faa71989780d388065742fa4fe5ee5c89ca8d4a095
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 response_format='content_and_artifact' 的工具在直接调用 tool.invoke({'keyword': 'Python'}) 与传入完整 ToolCall 字典时返回类型不同?
展开参考解答
直接传入参数字典时 invoke() 仅返回面向模型的 content 文本;传入包含 id 与 type='tool_call' 的完整 ToolCall 字典(或由 Agent Tools 节点调用)时,LangChain 才会将其封装为同时携带 content 与 artifact 属性的 ToolMessage。