3.3.1 方式1:使用Pydantic模型定义
当工具的参数变得复杂,需要枚举值、范围限制或更复杂的业务逻辑验证时,Pydantic 模型是理想的选择,提供强大的类型检查和数据验证。
使用Pydantic 的主要优势在于能够精确控制工具参数的格式和验证规则,让大模型更准确地理解如何调用工具。
3.3.1.1 pydantic类型的定义
① BaseModel基类
通过继承核心基类BaseModel 定义数据模型,从而声明字段结构、类型约束、默认值以0及校验规则。
from pydantic import BaseModel
class WeatherInput(BaseModel):
city: str
print(WeatherInput(city="北京"))
注意:BaseModel子类初始化时,不接收位置参数,字段值必须以关键字参数的形式传入,否则报错。
from pydantic import BaseModel
class WeatherInput(BaseModel):
city: str
print(WeatherInput("北京"))
报错如下
TypeError
......
TypeError: BaseModel.__init__() takes 1 positional argument but 2 were
given
这是因为BaseModel的初始化函数签名如下
def __init__(self, /, **data: Any) -> None:
由此可知,所有关键字参数都会被收集到字典data 中,然后data 会按照参数类型注解进行校验,失败时抛出异常。
② Field
Field() :用来“ 定制字段”的函数,可用于设置默认值、描述等。
举例1:设置默认值
from pydantic import BaseModel, Field
class WeatherInput(BaseModel):
city: str = Field(
default= "北京"
)
print(WeatherInput())
输出
city=’北京’
举例2:设置参数的描述信息
每个字段的 description 参数至关重要,它直接影响大模型理解参数含义的能力。
from pydantic import BaseModel, Field
class WeatherInput(BaseModel):
city: str = Field(
default= “北京”,
description=”城市”
)
include_forecast: bool = Field(
default=False,
description=”是否包含未来五日天气预报”
)
print(WeatherInput())
输出
city=’北京’ include_1 forecast=False
③ Literal
可以使用 Literal类型限定参数为固定选项。
Literal :表示字段不能是任意某种类型的值,而只能是几个固定字面量之一。
举例1:
from pydantic import BaseModel
from typing import Literal
class WeatherInput(BaseModel):
city: str
unit: Literal["celsius", "fahrenheit"]
print("===============> 合法 <===============")
print(WeatherInput(city="北京", unit="celsius"))
print("===============> 非法 <===============")
try:
print(WeatherInput(city="北京", unit="kelvin"))
except Exception as e:
print("报错类型:", type(e).__name__)
print(e)
输出
===============> 合法 <===============
city=’北京’ unit=’celsius’
===============> 非法 <===============
报错类型: ValidationError
1 validation error for WeatherInput
unit
Input should be ‘celsius’ or ‘fahrenheit’ [type=literal_error,
input_value=’kelvin’, input_type=str]
For further information visit
https://errors.pydantic.dev/2.12/v/literal_error
举例2:
from pydantic import BaseModel, Field
class WeatherInput(BaseModel):
city: str = Field(
default= "北京",
description="城市"
)
unit: Literal["celsius", "fahrenheit"] = Field(
default="celsius",
description="气温单位"
)
include_forecast: bool = Field(
default=False,
description="是否包含未来五日天气预报"
)
print(WeatherInput())
输出
city=’北京’ unit=’celsius’ include_1 forecast=False
3.3.1.2 使用Pydantic定义args_schema
通过 @tool(args_schema=PydanticModelCls) 将这个 Pydantic 模型与工具函数关联。
利用 Pydantic 的类型系统进行参数验证,当大模型需要调用工具前,Pydantic 会自动验证参数的类型和有效性。
举例:
from pydantic import BaseModel, Field
from langchain.tools import tool
from langchain_core.utils.function_calling import convert_to_openai_tool
class WeatherInput(BaseModel):
city: str = Field(
default= "北京",
description="城市"
)
unit: Literal["celsius", "fahrenheit"] = Field(
default="celsius",
description="气温单位"
)
include_forecast: bool = Field(
default=False,
description="是否包含未来五日天气预报"
)
@tool(args_schema=WeatherInput)
def get_weather(city: str, unit: str = "celsius", include_forecast: bool =
False) -> str:
"""获取当日天气,可选未来五日天气预报"""
temp = 22 if unit == "celsius" else 72
result = f'{city}当天气温: {temp} {"摄氏度" if unit == "celsius" else "华氏
度"}'
if include_forecast:
result += "\n未来五天都是晴天"
return result
convert_to_openai_tool(get_weather)
3.3.2 方式2:使用Json Schema定义
在 LangChain 中,还可以直接使用 JSON Schema 字典来定义工具的参数模式。这种方式提供了极大的灵活性。
因为工具参数模式可以基于数据库配置或用户输入在运行时动态生成,所以这种方式特别适合参数结构需要动态生成的场景。
举例:
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取当日天气,可选未来五日天气预报",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"},
"units": {"type": "string"},
"include_forecast": {"type": "boolean"}
},
"required": ["location", "units", "include_forecast"]
},
}
}
应该传递给args_schema的只有parameters 对应的JSON字符串,即
![图片[1]-3.3 自定义args_schema-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-657.png)
举例:
通过 @tool(args_schema=json_schema_dict) 将一个符合 JSON Schema 标准的字典与工具函数关联。
![图片[2]-3.3 自定义args_schema-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-658.png)
![图片[3]-3.3 自定义args_schema-大赛人网](https://www.dsrw.com/wp-content/uploads/2026/11/image-659.png)
















请登录后查看评论内容