使用文件路径作为工具输入#
用户有时需要在工具中引用本地文件以实现特定逻辑。为了简化此过程,我们引入了 FilePath
输入类型。此输入类型使用户能够选择现有文件或创建新文件,然后将其传递给工具,从而允许工具访问文件内容。
本指南将详细介绍如何使用 FilePath
作为工具输入。我们还将演示在流中利用此类工具时的用户体验。
先决条件#
请安装 promptflow 包并确保其版本为 0.1.0b8 或更高版本。
pip install promptflow>=0.1.0b8
请确保您的 VS Code 版 Prompt flow 已更新到版本 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)
工具 YAML 中的
FilePath
输入格式,如 此示例 所示。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
。单击选择器图标以打开用于选择现有文件或创建新文件作为输入的 UI。
使用文件路径作为脚本工具输入#
我们还可以在脚本工具中直接使用 FilePath
输入类型,而无需创建包工具。
在 VS Code 扩展中启动一个空流,并在可视化编辑器页面中向其中添加一个名为“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)
返回到流可视化编辑器页面,单击选择器图标以启动用于选择现有文件或创建新文件作为输入的 UI,这里我们以 此文件 为例。
常见问题#
此功能有哪些实际用例?#
FilePath
输入支持多种有用的工作流
动态加载模块 - 如演示所示,您可以从用户选择的特定脚本文件加载 Python 模块。这允许灵活的自定义逻辑。
加载任意数据文件 - 该工具可以从 .csv、.txt、.json 等文件加载数据。这提供了一种将外部数据轻松注入工具的方法。
总而言之,FilePath
输入使工具能够灵活地访问用户在运行时提供的外部文件。这解锁了许多有用的场景,例如上述场景。