Python#

介绍#

Python 工具使用户能够将自定义代码片段作为自包含的可执行节点在 PromptFlow 中使用。用户可以轻松创建 Python 工具、编辑代码并验证结果。

输入#

名称

类型

描述

必填

代码

字符串

Python 代码片段

输入

-

工具函数参数及其赋值列表

-

类型#

类型

Python 示例

描述

int

参数: int

整数类型

bool

参数: bool

布尔类型

字符串

参数: str

字符串类型

双精度浮点数

参数: float

双精度浮点数类型

列表

参数: list 或 参数: List[T]

列表类型

object

参数: dict 或 参数: Dict[K, V]

对象类型

连接

参数: CustomConnection

连接类型,将特别处理

带有 Connection 类型注解的参数将被视为连接输入,这意味着

  • Promptflow 扩展将显示一个选择器来选择连接。

  • 在执行时,promptflow 将尝试查找与传入参数值同名的连接。

请注意,Union[...] 类型注解支持连接类型,例如 param: Union[CustomConnection, OpenAIConnection]

输出#

Python 工具函数的返回值。

如何编写 Python 工具?#

指南#

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

  2. Python 工具代码必须包含一个用 @tool 装饰的函数(工具函数),作为执行的入口点。@tool 装饰器应在代码片段中只应用一次。

    以下示例定义了用 @tool 装饰的 Python 工具“my_python_tool”

  3. Python 工具函数参数必须在“Inputs”部分赋值

    以下示例定义了输入“message”并赋值为“world”

  4. Python 工具函数应有返回值

    以下示例返回一个连接的字符串

代码#

以下代码片段展示了工具函数的基本结构。Promptflow 将读取该函数并从函数参数和类型注解中提取输入。

from promptflow.core 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

输入#

名称

类型

Flow Yaml 中的示例值

传递给函数的值

message

字符串

“world”

“world”

my_conn

CustomConnection

“my_conn”

CustomConnection 对象

Promptflow 将在执行时尝试查找名为“my_conn”的连接。

输出#

"hello world"

关键字参数支持#

从 PromptFlow 1.0.0 版本和 适用于 VS Code 的 Prompt flow 1.4.0 版本开始,我们引入了对 Python 工具中关键字参数 (kwargs) 的支持。

from promptflow.core import tool


@tool
def print_test(normal_input: str, **kwargs):
    for key, value in kwargs.items():
        print(f"Key {key}'s value is {value}")
    return len(kwargs)

当您在 Python 工具中像上面代码一样添加 kwargs 时,您可以通过 +添加 输入 按钮插入可变数量的输入。

Screenshot of the kwargs On VScode Prompt Flow extension