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

ReAct Agent调用多输入工具时出现ValidationError问题求助

解决LangChain ReAct Agent调用工具时参数传递失败的ValidationError问题

可能的原因及解决方案

1. 工具定义时未正确绑定必填参数(最常见)

如果你的get_financial_info工具是通过@tool装饰器或StructuredTool创建的,必须确保所有必填参数(co/fundamental/yr)都被明确定义,且参数校验规则正确。

错误示例(参数缺失):

from langchain.tools import tool

@tool
def get_financial_info(co: str):
    # 仅定义了co参数,未声明fundamental和yr,导致校验失败
    pass

正确示例(用Pydantic规范参数):

from langchain.tools import tool
from pydantic import BaseModel, Field

# 用Pydantic模型明确所有必填参数的结构和描述
class FinancialInfoInput(BaseModel):
    co: str = Field(description="公司名称,例如Tesla")
    fundamental: str = Field(description="财务指标,例如sales、profit")
    yr: str = Field(description="财年,例如FY22")

@tool(args_schema=FinancialInfoInput)
def get_financial_info(co: str, fundamental: str, yr: str):
    # 业务逻辑:根据参数返回对应财务数据
    return f"{co} {yr}年的{fundamental}数据为XXX"

如果用StructuredTool手动创建工具:

from langchain.tools import StructuredTool

def get_financial_info_func(co: str, fundamental: str, yr: str):
    return f"{co} {yr}年的{fundamental}数据为XXX"

get_financial_info = StructuredTool.from_function(
    func=get_financial_info_func,
    args_schema=FinancialInfoInput,
    description="获取指定公司指定财年的财务指标数据"
)

2. 单独调用工具时的参数传递错误

你提到单独调用get_financial_info.invoke({"co":"Tesla"})报错,是因为工具本身要求fundamental和yr为必填项,必须传全参数:

# 正确的单独调用方式
get_financial_info.invoke({"co": "Tesla", "fundamental": "sales", "yr": "FY22"})

若需让参数可选,可在Pydantic模型中设置默认值:

class FinancialInfoInput(BaseModel):
    co: str = Field(description="公司名称")
    fundamental: str = Field(default="sales", description="财务指标")
    yr: str = Field(default="FY23", description="财年")

3. Agent输出解析器的格式验证

虽然你说Action Input格式正确,但可手动验证解析器是否能正确识别参数:

from langchain.agents.output_parsers import ReActSingleInputOutputParser

parser = ReActSingleInputOutputParser()
# 模拟Agent生成的输出内容
agent_output = """Thought: 需要获取Tesla FY22的sales数据
Action: get_financial_info
Action Input: {"co": "Tesla", "fundamental": "sales", "yr": "FY22"}"""

parsed_result = parser.parse(agent_output)
print(parsed_result.action_input)  # 应输出完整的参数字典

如果解析结果异常,需调整Agent的提示词模板,强制要求输出标准JSON格式的Action Input。

4. 依赖版本兼容性问题

LangChain不同版本对工具参数的处理逻辑可能有差异,建议升级到稳定版本:

pip install --upgrade langchain openai

验证步骤

  1. 先单独测试工具传全参数的情况,确保工具本身能正常运行
  2. 检查工具的参数定义(Pydantic模型或装饰器配置)是否包含所有必填字段
  3. 验证Agent输出解析器能否正确将Action Input转为参数字典
  4. 确认Agent提示词中明确要求输出符合格式的JSON参数

内容的提问来源于stack exchange,提问作者user6027414

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:11:13