使用文件路径作为工具输入#
用户有时需要在工具中引用本地文件以实现特定逻辑。为了简化这一过程,我们引入了FilePath
输入类型。此输入类型允许用户选择现有文件或创建新文件,然后将其传递给工具,使工具能够访问文件内容。
在本指南中,我们将详细介绍如何使用FilePath
作为工具输入。我们还将展示在流程中使用此类工具时的用户体验。
先决条件#
请安装 promptflow 包并确保其版本为 0.1.0b8 或更高。
pip install promptflow>=0.1.0b8
请确保您的Prompt flow for VS Code已更新至1.1.0或更高版本。
使用文件路径作为包工具输入#
如何使用文件路径输入创建包工具#
这里我们使用一个现有的工具包作为示例。如果你想创建自己的工具,请参考创建和使用工具包。
为您的工具添加一个
FilePath
输入,如此示例所示。import importlib from pathlib import Path from promptflow.core import tool # 1. import the FilePath type from promptflow.contracts.types import FilePath # 2. add a FilePath input for your tool method @tool def my_tool(input_file: FilePath, input_text: str) -> str: # 3. customise your own code to handle and use the input_file here new_module = importlib.import_module(Path(input_file).stem) return new_module.hello(input_text)
FilePath
在工具YAML中的输入格式,如此示例所示。my_tool_package.tools.tool_with_file_path_input.my_tool: function: my_tool inputs: # yaml format for FilePath input input_file: type: - file_path input_text: type: - string module: my_tool_package.tools.tool_with_file_path_input name: Tool with FilePath Input description: This is a tool to demonstrate the usage of FilePath input type: python
[!注意] 工具 yaml 文件可以使用 Python 脚本生成。有关更多详细信息,请参阅 创建自定义工具包。
在VS Code扩展中使用带有文件路径输入的工具#
按照步骤构建并安装您的工具包和从VS Code扩展中使用您的工具。
这里我们使用一个现有的流程来演示体验,在VS Code扩展中打开这个流程:
有一个名为“Tool_with_FilePath_Input”的节点,它有一个
file_path
类型的输入,称为input_file
。点击选择器图标以打开用于选择现有文件或创建新文件作为输入的界面。
使用文件路径作为脚本工具输入#
我们也可以直接在脚本工具中使用FilePath
输入类型,从而无需创建包工具。
在VS Code扩展中启动一个空流程,并在Visual Editor页面中添加一个名为‘python_node_with_filepath’的Python节点。
选择节点中的链接
python_node_with_filepath.py
来修改python方法,以包含一个FilePath
输入,如下所示,并保存代码更改。import importlib from pathlib import Path from promptflow.core import tool # 1. import the FilePath type from promptflow.contracts.types import FilePath # 2. add a FilePath input for your tool method @tool def my_tool(input_file: FilePath, input_text: str) -> str: # 3. customise your own code to handle and use the input_file here new_module = importlib.import_module(Path(input_file).stem) return new_module.hello(input_text)
返回到流程可视化编辑器页面,点击选择器图标以启动用于选择现有文件或创建新文件作为输入的界面,这里我们选择此文件作为示例。
常见问题#
这个功能有哪些实际应用场景?#
FilePath
输入支持几种有用的工作流程:
动态加载模块 - 如演示所示,您可以从用户选择的特定脚本文件中加载Python模块。这允许灵活的自定义逻辑。
加载任意数据文件 - 该工具可以从.csv、.txt、.json等文件中加载数据。这提供了一种将外部数据注入工具的简便方法。
因此,总结来说,FilePath
输入允许工具在运行时灵活访问用户提供的外部文件。这解锁了许多有用的场景,如上所述。