2026/6/30 6:21:35

020-Pydantic-Model-Usage

020-Pydantic-Model-Usage Agent 工具开发Pydantic 模型使用指南摘要掌握使用 Pydantic BaseModel 定义复杂工具参数Schema实现嵌套结构、字段验证和类型安全。引言想象一下你给 Agent 一个「查询天气」的工具但 LLM 传来的参数可能是location: “北京” 或 “BJ” 或 “beijing” 或{city: 北京}units: “celsius” 或 “摄氏” 或1include_forecast:true或1或根本没有这个字段没有 schema 约束Agent 就像在玩猜谜游戏。而Pydantic 模型就是我们的「定海神针」让工具参数从混沌走向有序。核心概念什么是 args_schemaargs_schema是 tool 装饰器的一个参数用于显式声明工具期望的参数结构。当 Agent 调用工具时LangChain 会根据 schema 生成 JSON Schema让 LLM 知道需要哪些参数每个参数的类型每个参数的约束条件每个参数的含义描述为什么用 Pydantic 而不是 JSON Schema特性PydanticJSON Schema类型注解Python 原生JSON 格式验证逻辑内置ge、le等需额外定义IDE 支持自动补全、类型检查无嵌套结构自然支持复杂默认值Field(default...)default: ...代码示例基础用法简单参数frompydanticimportBaseModelfromlangchain.toolsimporttool# 定义输入模型classTextInput(BaseModel):text:str# 简单字符串字段tool(text_analyzer,args_schemaTextInput)defanalyze_text(input_data:TextInput)-dict:分析文本的统计信息。return{length:len(input_data.text),words:len(input_data.text.split()),lines:input_data.text.count(\n)1}进阶用法字段约束与描述fromtypingimportAnnotatedfrompydanticimportFieldtooldefprocess_number(value:Annotated[int,Field(ge0,le100,description0-100 的整数)])-str:处理数值。returnf处理结果:{value*2}关键点Annotated[T, Field(...)]为类型添加元数据和约束ge0greater than or equal小于等于le100less than or equal大于等于高阶用法嵌套结构frompydanticimportBaseModel,FieldfromtypingimportLiteralclassItem(BaseModel):商品项name:strField(description商品名称)quantity:intField(ge1,description数量至少1)price:floatField(ge0,description单价元)classOrderInput(BaseModel):订单输入items:list[Item]Field(description商品列表)shipping_method:Literal[standard,express,overnight]Field(defaultstandard,description配送方式)tool(args_schemaOrderInput)defcreate_order(items:list[Item],shipping_method:strstandard)-str:创建订单totalsum(item.quantity*item.priceforiteminitems)returnf订单已创建总计{total:.2f}元配送方式:{shipping_method}生产级示例天气查询工具frompydanticimportBaseModel,FieldfromtypingimportLiteralfromlangchain.toolsimporttoolclassWeatherInput(BaseModel):天气查询输入location:strField(description城市名称或坐标如 Beijing 或 39.9,116.4)units:Literal[celsius,fahrenheit]Field(defaultcelsius,description温度单位)include_forecast:boolField(defaultFalse,description是否包含3天预报)tool(args_schemaWeatherInput)defget_weather(location:str,units:strcelsius,include_forecast:boolFalse)-str:获取指定位置的当前天气和可选预报。 Args: location: 城市名称或 GPS 坐标 units: 温度单位celsius 或 fahrenheit include_forecast: 是否包含3天预报 Returns: 格式化的天气报告字符串 temp25ifunitscelsiuselse77forecast\n预报: 明天晴第3天有雨ifinclude_forecastelsereturnf{location}天气:{temp}°{units[0].upper()}{forecast}实战应用完整调用示例fromlangchain_openaiimportChatOpenAI# 初始化模型llmChatOpenAI(modelgpt-4o)# 创建带 Pydantic schema 的工具weather_toolget_weather# 绑定工具到模型llm_with_toolsllm.bind_tools([weather_tool])# 调用resultllm_with_tools.invoke(北京今天天气怎么样需要带伞吗)print(result.tool_calls)输出示例[{name:get_weather,args:{location:北京},id:call_9d0ea643333741feb6326fce,type:tool_call}]验证失败处理frompydanticimportValidationError# 模拟 LLM 传入无效参数invalid_input{location:北京,units:kelvin}# kelvin 不是有效值try:weatherWeatherInput(**invalid_input)exceptValidationErrorase:print(f验证失败:{e.errors()})[{type:literal_error,loc:(units,),msg:Input should be celsius or fahrenheit,input:kelvin,ctx:{expected:celsius or fahrenheit},url:https://errors.pydantic.dev/2.11/v/literal_error}]最佳实践始终定义 args_schema显式声明比隐式更可靠每个字段都要 description这是 LLM 理解的唯一途径使用 Literal 而非字符串限定可选值减少 LLM 幻觉添加数值约束ge、le、min_length等防止异常输入嵌套结构要扁平避免过深的嵌套保持 schema 可读性总结Pydantic 模型是 Agent 工具开发的瑞士军刀类型安全Python 原生类型注解IDE 自动补全自动验证输入不符合约束Pydantic 帮你拦截清晰描述每个字段的 description 就是给 LLM 的说明书嵌套结构复杂业务场景也能优雅处理掌握 Pydantic 模型让你的 Agent 工具从「能用」升级到「好用」。