你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Python 工具

Python 工具使你能够在提示流中将自定义代码片段作为自包含可执行节点提供。 可以轻松创建 Python 工具、编辑代码和验证结果。

输入

名称 Type 描述 必需
代码 字符串 Python 代码片段
输入 - 工具函数参数及其赋值列表 -

类型

类型 Python 示例 说明
int param: int 整数类型
bool param: bool 布尔类型
string param: str 字符串类型
double param: float Double 类型
list param: list 或 param: List[T] 列表类型
object param: dict 或 param: Dict[K, V] 对象类型
Connection param: CustomConnection 专门处理连接类型

具有 Connection 类型注释的参数被视为连接输入,这意味着:

  • 提示流扩展显示用于选择连接的选择器。
  • 在执行期间,提示流尝试从传入的参数值中找到具有相同名称的连接。

注意

类型Union[...]批注仅支持连接类型,例如param: Union[CustomConnection, OpenAIConnection]

输出

输出是 Python 工具函数的返回。

使用 Python 工具进行写入

使用以下准则通过 Python 工具编写。

准则

  • Python 工具代码应包含完整的 Python 代码,包括任何必要的模块导入。

  • Python 工具代码必须包含用 @tool (工具函数)修饰的函数,该函数充当执行入口点。 @tool仅在代码片段中应用修饰器一次。

    下一部分中的示例定义了用 Python 工具修饰的 @toolPython 工具my_python_tool

  • 必须在节中 Inputs 分配 Python 工具函数参数。

    下一部分中的示例定义输入 message 并分配它 world

  • Python 工具函数有一个返回。

    下一节中的示例返回一个串联字符串。

代码

以下代码片段显示了工具函数的基本结构。 提示流读取函数并从函数参数和类型注释中提取输入。

from promptflow import tool
from promptflow.connections import CustomConnection

# The inputs section will change based on the arguments of the tool function, after you save the code
# Adding type to arguments and return value will help the system show the types properly
# Please update the function name/signature per need
@tool
def my_python_tool(message: str, my_conn: CustomConnection) -> str:
    my_conn_dict = dict(my_conn)
    # Do some function call with my_conn_dict...
    return 'hello ' + message

输入

名称 类型 流 YAML 中的示例值 传递给函数的值
message string world world
my_conn CustomConnection my_conn (属于CustomConnection 对象)的父级。

提示流尝试查找在执行期间命名 my_conn 的连接。

输出

"hello world"

Python 工具中的自定义连接

如果要开发需要通过身份验证调用外部服务的 Python 工具,请在提示流中使用自定义连接。 可以使用它安全地存储访问密钥,然后将其检索到 Python 代码中。

创建自定义连接

创建自定义连接,用于存储所有大型语言模型 API 密钥或其他所需凭据。

  1. 转到工作区中的提示流,然后转到“连接”选项卡。

  2. 选择“创建自定义”。>

    Screenshot that shows flows on the Connections tab highlighting the Custom button in the drop-down menu.

  3. 在右窗格中,可以定义连接名称。 可以通过选择“ 添加键值对”来添加多个键值对来存储凭据和密钥。

    Screenshot that shows adding a custom connection point and the Add key-value pairs button.

注意

若要将一个键值对设置为机密,请选择“机密”检查框。 此选项对密钥值进行加密和存储。 确保至少将一个键值对设置为机密。 否则,不会成功创建连接。

在 Python 中使用自定义连接

若要在 Python 代码中使用自定义连接,请执行以下操作:

  1. 在 Python 节点的代码部分中,导入自定义连接库 from promptflow.connections import CustomConnection。 在工具函数中定义类型的 CustomConnection 输入参数。

    Screenshot that shows the doc search chain node highlighting the custom connection.

  2. 分析输入部分的输入,然后在“值”下拉列表中选择目标自定义连接。

    Screenshot that shows the chain node highlighting the connection.

例如:

from promptflow import tool
from promptflow.connections import CustomConnection

@tool
def my_python_tool(message: str, myconn: CustomConnection) -> str:
    # Get authentication key-values from the custom connection
    connection_key1_value = myconn.key1
    connection_key2_value = myconn.key2