如何为LangChain Tool的func直接传递自定义参数?
在LangChain Tool中为func传递自定义参数的实现方法
你可以通过以下几种方式实现给Tool的func传入自定义参数,无需修改对话模型的调用逻辑:
方法1:使用functools.partial绑定固定参数
利用functools.partial提前把固定参数(如username、conversation_name)绑定到目标函数上,让Tool调用时只需要传入模型生成的prompt参数。
示例代码:
from functools import partial from langchain.tools import Tool # 绑定固定参数到函数 bound_generate_img = partial(realistic_vision_v1_4, username="your_username", conversation_name="chat_001") # 创建Tool实例 realistic_vision_tool = Tool( name="realistic_vision_V1.4 image generating", func=bound_generate_img, description="""Use when you want to generate an image of something with realistic_vision model. Input like "a dog standing on a rock" is decent for this tool so input not-so-detailed prompts to this tool. If an image is generated, tool will return "Successfully generated image.". Say something like "Generated. Hope it helps." if you use this tool. Always input english prompts for the input, even if the user is not speaking english. Enter the inputs in english to this tool.""" )
方法2:使用lambda函数包装
用lambda函数接收模型传递的prompt参数,再调用原函数时带上自定义的固定参数。
示例代码:
from langchain.tools import Tool # 创建Tool实例,用lambda包装函数调用 realistic_vision_tool = Tool( name="realistic_vision_V1.4 image generating", func=lambda prompt: realistic_vision_v1_4(prompt, username="your_username", conversation_name="chat_001"), description="""Use when you want to generate an image of something with realistic_vision model. Input like "a dog standing on a rock" is decent for this tool so input not-so-detailed prompts to this tool. If an image is generated, tool will return "Successfully generated image.". Say something like "Generated. Hope it helps." if you use this tool. Always input english prompts for the input, even if the user is not speaking english. Enter the inputs in english to this tool.""" )
方法3:自定义Tool子类(更灵活的场景)
如果需要更灵活的参数管理,可以自定义Tool子类,在初始化时传入自定义参数,重写_call方法来调用目标函数。
示例代码:
from langchain.tools import Tool class ImageGenTool(Tool): def __init__(self, username: str, conversation_name: str, **kwargs): super().__init__(**kwargs) self.username = username self.conversation_name = conversation_name def _call(self, prompt: str) -> str: return realistic_vision_v1_4(prompt, self.username, self.conversation_name) # 创建自定义Tool实例 realistic_vision_tool = ImageGenTool( username="your_username", conversation_name="chat_001", name="realistic_vision_V1.4 image generating", description="""Use when you want to generate an image of something with realistic_vision model. Input like "a dog standing on a rock" is decent for this tool so input not-so-detailed prompts to this tool. If an image is generated, tool will return "Successfully generated image.". Say something like "Generated. Hope it helps." if you use this tool. Always input english prompts for the input, even if the user is not speaking english. Enter the inputs in english to this tool.""" )
以上三种方法都能实现给Tool的func传入自定义参数,根据你的场景选择合适的方式即可。
内容的提问来源于stack exchange,提问作者Just One Question
相关产品推荐
相关产品推荐

