在 Azure 中使用基于类的 Flex Flow 进行聊天#

作者:  头像 头像在 GitHub 上打开

学习目标 - 完成本教程后,您应该能够

  • 提交使用 Python 类定义的流的批处理运行,并在 Azure 中对其进行评估。

0. 安装依赖包#

%%capture --no-stderr
%pip install -r ./requirements-azure.txt

1. 连接到工作区#

配置凭据#

我们使用 DefaultAzureCredential 来获取对工作区的访问权限。DefaultAzureCredential 应该能够处理大多数 Azure SDK 身份验证场景。

如果它对您不起作用,请参考更多可用的凭据:配置凭据示例azure-identity 参考文档

from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential

try:
    credential = DefaultAzureCredential()
    # Check if given credential can get token successfully.
    credential.get_token("https://management.azure.com/.default")
except Exception as ex:
    # Fall back to InteractiveBrowserCredential in case DefaultAzureCredential not work
    credential = InteractiveBrowserCredential()

获取工作区的句柄#

我们使用配置文件连接到工作区。

from promptflow.azure import PFClient

# Get a handle to workspace
pf = PFClient.from_config(credential=credential)

创建必要的连接#

连接有助于安全地存储和管理与 LLM 和其他外部工具(例如 Azure 内容安全)交互所需的密钥或其他敏感凭据。

在本笔记本中,我们将使用流 basic flex flow,它内部使用连接 open_ai_connection,如果之前没有添加,我们需要设置该连接。

遵循此说明准备您的 Azure OpenAI 资源,如果您没有 api_key,请获取一个。

请前往工作区门户,点击 Prompt flow -> Connections -> Create,然后按照说明创建您自己的连接。了解更多关于连接的信息。

2. 将函数作为流与多行数据批量运行#

创建一个 flow.flex.yaml 文件来定义一个流,其入口指向我们定义的 Python 函数。

# show the flow.flex.yaml content
with open("flow.flex.yaml") as fin:
    print(fin.read())
from promptflow.core import AzureOpenAIModelConfiguration

# create the model config to be used in below flow calls
config = AzureOpenAIModelConfiguration(
    connection="open_ai_connection", azure_deployment="gpt-4o"
)

使用数据文件(包含多行测试数据)进行批量运行#

flow = "."  # path to the flow directory
data = "./data.jsonl"  # path to the data file

# create run with the flow and data
base_run = pf.run(
    flow=flow,
    init={
        "model_config": config,
    },
    data=data,
    column_mapping={
        "question": "${data.question}",
        "chat_history": "${data.chat_history}",
    },
    stream=True,
)
details = pf.get_details(base_run)
details.head(10)

3. 评估您的流#

然后您可以使用评估方法来评估您的流。评估方法也是流,通常使用 LLM 断言生成的输出符合某些预期。

对之前的批量运行进行评估#

base_run 是我们在上面第 2 步中完成的批量运行,用于 web-classification 流,输入为“data.jsonl”。

eval_flow = "../eval-checklist/flow.flex.yaml"
config = AzureOpenAIModelConfiguration(
    connection="open_ai_connection", azure_deployment="gpt-4o"
)
eval_run = pf.run(
    flow=eval_flow,
    init={
        "model_config": config,
    },
    data="./data.jsonl",  # path to the data file
    run=base_run,  # specify base_run as the run you want to evaluate
    column_mapping={
        "answer": "${run.outputs.output}",
        "statements": "${data.statements}",
    },
    stream=True,
)
details = pf.get_details(eval_run)
details.head(10)
import json

metrics = pf.get_metrics(eval_run)
print(json.dumps(metrics, indent=4))
pf.visualize([base_run, eval_run])

后续步骤#

至此,您已成功运行聊天流并对其进行了评估。太棒了!

您可以查看更多示例

  • 流式聊天:演示如何创建一个聊天机器人,该机器人可以记住以前的交互并使用对话历史来生成下一条消息。