创建动态列表工具输入#

工具输入选项可以使用动态列表即时生成。工具作者不是预定义静态选项,而是定义一个请求函数,该函数查询后端(如API)以检索实时选项。这使得能够灵活地与各种数据源集成以填充动态选项。例如,该函数可以调用存储API来列出当前文件。用户运行工具时看到的不是硬编码的列表,而是最新的选项。

先决条件#

  • 请确保您已安装最新版本的Prompt flow for VS Code(v1.3.1+)。

  • 请安装 promptflow 包并确保其版本为 1.0.0 或更高。

    pip install promptflow>=1.0.0
    

创建一个带有动态列表的工具输入#

创建一个列表函数#

要启用动态列表,工具作者需要定义一个具有以下结构的请求函数:

  • 类型:常规的Python函数,可以在工具文件中或单独的文件中

  • 输入:接受获取选项所需的参数

  • 输出:返回一个选项对象列表,格式为 List[Dict[str, Union[str, int, float, list, Dict]]]:

    • 必需的键:

      • value: 传递给工具函数的内部选项值

    • 可选的键:

      • display_value: 下拉菜单中显示的文本(默认为 value

      • hyperlink: 点击选项时打开的URL

      • description: 悬停时显示的工具提示文本

此函数可以调用后端以检索最新选项,并将它们返回到动态列表的标准字典结构中。必需和可选的键允许配置每个选项在工具输入下拉列表中的显示和行为方式。参见my_list_func作为示例。

def my_list_func(prefix: str = "", size: int = 10, **kwargs) -> List[Dict[str, Union[str, int, float, list, Dict]]]:
    """This is a dummy function to generate a list of items.

    :param prefix: prefix to add to each item.
    :param size: number of items to generate.
    :param kwargs: other parameters.
    :return: a list of items. Each item is a dict with the following keys:
        - value: for backend use. Required.
        - display_value: for UI display. Optional.
        - hyperlink: external link. Optional.
        - description: information icon tip. Optional.
    """
    import random

    words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "kiwi", "lemon"]
    result = []
    for i in range(size):
        random_word = f"{random.choice(words)}{i}"
        cur_item = {
            "value": random_word,
            "display_value": f"{prefix}_{random_word}",
            "hyperlink": f'https://www.bing.com/search?q={random_word}',
            "description": f"this is {i} item",
        }
        result.append(cur_item)

    return result

使用列表函数配置工具输入#

在工具YAML的inputs部分,为您希望使其动态的输入添加以下属性:

  • dynamic_list:

    • func_path: 列表函数的路径(模块名.函数名)。

    • func_kwargs: 传递给函数的参数,可以引用其他输入值。

  • allow_manual_entry: 允许用户手动输入值。默认为 false。

  • is_multi_select: 允许用户选择多个值。默认为 false。

参见tool_with_dynamic_list_input.yaml作为示例。

my_tool_package.tools.tool_with_dynamic_list_input.my_tool:
  function: my_tool
  inputs:
    input_text:
      type:
      - list
      dynamic_list:
        func_path: my_tool_package.tools.tool_with_dynamic_list_input.my_list_func
        func_kwargs: 
        - name: prefix  # argument name to be passed to the function
          type: 
          - string
          # if optional is not specified, default to false.
          # this is for UX pre-validaton. If optional is false, but no input. UX can throw error in advanced.
          optional: true
          reference: ${inputs.input_prefix}  # dynamic reference to another input parameter
        - name: size  # another argument name to be passed to the function
          type: 
          - int
          optional: true
          default: 10
      # enum and dynamic list may need below setting.
      # allow user to enter input value manually, default false.
      allow_manual_entry: true
      # allow user to select multiple values, default false.
      is_multi_select: true
    # used to filter 
    input_prefix:
      type:
      - string
  module: my_tool_package.tools.tool_with_dynamic_list_input
  name: My Tool with Dynamic List Input
  description: This is my tool with dynamic list input
  type: python

在VS Code中使用该工具#

一旦你打包并分享了你的工具,你可以按照工具包指南在VS Code中使用它。你可以尝试my-tools-package进行快速测试。

pip install my-tools-package>=0.0.8

dynamic list tool input selected dynamic list tool input selected

注意:如果您的动态列表函数调用Azure API,您需要登录到Azure并设置默认工作区。否则,工具输入将为空,您将无法选择任何内容。有关更多详细信息,请参阅常见问题解答

常见问题解答#

我是一个工具作者,想在我的工具输入中动态列出Azure资源。我应该注意什么?#

  1. 在列表函数签名中明确azure工作空间三元组“subscription_id”、“resource_group_name”、“workspace_name”。如果它们在函数签名中,系统会帮助将工作空间三元组附加到函数输入参数中。参见list_endpoint_names作为示例。

def list_endpoint_names(subscription_id: str = None,
                        resource_group_name: str = None, 
                        workspace_name: str = None,
                        prefix: str = "") -> List[Dict[str, str]]:
    """This is an example to show how to get Azure ML resource in tool input list function.

    :param subscription_id: Azure subscription id.
    :param resource_group_name: Azure resource group name.
    :param workspace_name: Azure ML workspace name.
    :param prefix: prefix to add to each item.
    """
    # return an empty list if workspace triad is not available.
    if not subscription_id or not resource_group_name or not workspace_name:
        return []

    from azure.ai.ml import MLClient
    from azure.identity import DefaultAzureCredential

    credential = DefaultAzureCredential()
    credential.get_token("https://management.azure.com/.default")

    ml_client = MLClient(
        credential=credential,
        subscription_id=subscription_id,
        resource_group_name=resource_group_name,
        workspace_name=workspace_name)
    result = []
    for ep in ml_client.online_endpoints.list():
        hyperlink = (
            f"https://ml.azure.com/endpoints/realtime/{ep.name}/detail?wsid=/subscriptions/"
            f"{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft."
            f"MachineLearningServices/workspaces/{workspace_name}"
        )
        cur_item = {
            "value": ep.name,
            "display_value": f"{prefix}_{ep.name}",
            # external link to jump to the endpoint page.
            "hyperlink": hyperlink,
            "description": f"this is endpoint: {ep.name}",
        }
        result.append(cur_item)
    return result
  1. 在您的工具文档中注明,如果您的工具用户希望在本地使用该工具,他们应登录到azure并将ws triple设置为默认值。否则,工具输入将为空,用户无法选择任何内容。

az login
az account set --subscription <subscription_id>
az configure --defaults group=<resource_group_name> workspace=<workspace_name>

安装azure依赖项。

pip install azure-ai-ml
pip install my-tools-package[azure]>=0.0.8

dynamic list function azure

我是一个工具用户,无法在动态列表工具输入中看到任何选项。我该怎么办?#

如果您在动态列表工具输入中看不到任何选项,您可能会在输入字段下方看到一条错误消息,内容如下:

“由于XXX无法检索结果。请联系工具作者/支持团队以获取故障排除帮助。”

如果发生这种情况,请按照以下故障排除步骤操作:

  • 注意显示的确切错误信息。这提供了动态列表未能填充的原因的详细信息。

  • 检查工具文档以了解任何先决条件或特殊说明。例如,如果动态列表功能需要Azure凭据,请确保已安装azure依赖项,登录并设置默认工作区。

    pip install azure-ai-ml
    
    az login
    az account set --subscription 
    az configure --defaults group= workspace=
    
  • 联系工具作者/支持团队并报告问题。提供错误信息以便他们调查根本原因。