You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pydantic schema作为@tool的args_schema时触发ValidationError问题

解决LangChain @tool装饰器使用Pydantic Schema时的ValidationError错误

问题描述

按照DeepLearning.AI课程指导,尝试将Pydantic Schema作为@tool装饰器的args_schema参数值时,出现以下错误:

错误信息:

ValidationError: 1 validation error for StructuredTool
args_schema subclass of BaseModel expected (type=type_error.subclass; expected_class=BaseModel)

原代码:

from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description="Thing to search for")

@tool(args_schema=SearchInput)
def search(query: str) -> str:
    """Searches for weather online"""
    return "21c"

解决方法

问题根源在于LangChain的StructuredTool对args_schema要求使用其内部兼容的Pydantic v1 BaseModel,而非直接使用pydantic库(可能是v2版本)的BaseModel。只需替换BaseModel和Field的导入源即可解决:

修正后的代码:

from langchain.pydantic_v1 import BaseModel, Field
from langchain.tools import tool  # 确保导入正确的tool装饰器

class SearchInput(BaseModel):
    query: str = Field(description="要搜索的内容")

@tool(args_schema=SearchInput)
def search(query: str) -> str:
    """在线搜索天气信息"""
    return "21℃"

补充说明

如果项目依赖Pydantic v2,同时需要使用LangChain的工具装饰器,必须使用langchain.pydantic_v1中的BaseModel类,避免因版本不兼容导致的继承校验失败。

内容的提问来源于stack exchange,提问作者Eduardo Hilário

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 17:05:57