Python#
介绍#
用户通过Python工具被赋予能力,可以在PromptFlow中提供定制的代码片段作为独立的可执行节点。 用户可以轻松创建Python工具,编辑代码,并轻松验证结果。
输入#
名称 |
类型 |
描述 |
是否必需 |
---|---|---|---|
代码 |
字符串 |
Python代码片段 |
是 |
输入 |
- |
工具函数参数及其赋值的列表 |
- |
类型#
类型 |
Python 示例 |
描述 |
---|---|---|
int |
param: int |
整数类型 |
bool |
参数: bool |
布尔类型 |
字符串 |
参数: str |
字符串类型 |
double |
参数: float |
双精度类型 |
列表 |
参数: 列表 或 参数: List[T] |
列表类型 |
对象 |
参数: 字典 或 参数: 字典[K, V] |
对象类型 |
参数: CustomConnection |
连接类型,将特别处理 |
带有Connection
类型注解的参数将被视为连接输入,这意味着:
Promptflow 扩展将显示一个选择器来选择连接。
在执行期间,promptflow 将尝试找到与传入参数值名称相同的连接。
请注意,Union[...]
类型注释 仅 支持用于连接类型,
例如,param: Union[CustomConnection, OpenAIConnection]
。
输出#
Python工具函数的返回值。
如何编写Python工具?#
指南#
Python工具代码应包含完整的Python代码,包括任何必要的模块导入。
Python工具代码必须包含一个用@tool装饰的函数(工具函数),作为执行的入口点。@tool装饰器在代码片段中只能应用一次。
下面的示例定义了Python工具“my_python_tool”,并使用@tool进行装饰
Python工具函数参数必须在‘Inputs’部分赋值
下面的示例定义了输入“message”并赋值为“world”
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 中的示例值 |
传递给函数的值 |
---|---|---|---|
消息 |
字符串 |
“world” |
“world” |
my_conn |
CustomConnection |
“my_conn” |
CustomConnection 对象 |
Promptflow 将在执行时尝试找到名为 'my_conn' 的连接。
输出#
"hello world"
关键字参数支持#
从PromptFlow的1.0.0版本和Prompt flow for VS Code的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
时,你可以通过+Add input
按钮插入可变数量的输入。