如何修改LangChain中StructuredTool的args_schema以移除指定属性?
修改LangChain StructuredTool的args_schema移除指定属性
要移除StructuredTool的args_schema中的某个属性(比如示例里的attribute2),同时保留原有工具功能,你可以用以下几种方式实现:
方式一:动态生成新的Pydantic模型创建工具
利用Pydantic的create_model方法,基于原模型生成排除指定字段的新模型,再用这个新模型作为工具的args_schema:
from pydantic import BaseModel, create_model from langchain.tools import StructuredTool # 原有的参数schema class OriginalModel(BaseModel): attribute1: str attribute2: str # 工具核心函数(注意:如果移除了attribute2,需要给参数加默认值避免调用报错) def my_tool_function(attribute1: str, attribute2: str = ""): return f"处理结果:{attribute1}, {attribute2}" # 生成移除attribute2后的新模型 FilteredModel = create_model( "FilteredModel", **{ field_name: (field.type_, field.default) for field_name, field in OriginalModel.__fields__.items() if field_name != "attribute2" } ) # 创建工具时指定新的args_schema my_tool = StructuredTool.from_function( func=my_tool_function, args_schema=FilteredModel, name="my_process_tool" )
方式二:修改已创建工具的args_schema
如果工具已经创建完成,想要动态调整其args_schema,可以直接重新生成新模型并赋值给工具的args_schema属性:
# 假设已有一个创建好的工具instance # 生成过滤后的新模型 UpdatedModel = create_model( "UpdatedModel", **{ field_name: (field.type_, field.default) for field_name, field in my_tool.args_schema.__fields__.items() if field_name != "attribute2" } ) # 替换工具的args_schema my_tool.args_schema = UpdatedModel
注意事项
- 工具函数的参数要和新的schema匹配:如果移除了某个必填字段,需要给函数中对应的参数设置默认值,否则调用工具时会因为参数缺失报错。
- 不要直接修改原模型的字段:原模型可能被其他工具或逻辑复用,动态生成新模型的方式更安全,不会影响其他代码。
内容的提问来源于stack exchange,提问作者Chiquelo
相关产品推荐
相关产品推荐

