在Azure中使用基于类的弹性流程进行聊天#
学习目标 - 完成本教程后,您应该能够:
使用Python类定义的流程提交批处理运行,并在Azure中进行评估。
0. 安装依赖包#
%%capture --no-stderr
%pip install -r ./requirements-azure.txt
1. 连接到工作区#
配置凭证#
我们正在使用DefaultAzureCredential来获取对工作区的访问权限。
DefaultAzureAzureCredential应该能够处理大多数Azure SDK认证场景。
如果这对您不起作用,请参考更多可用的凭据:configure credential example, azure-identity reference doc.
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 弹性流,它内部使用了连接 open_ai_connection,如果之前没有添加过,我们需要设置这个连接。
按照此说明准备您的Azure OpenAI资源,并获取您的api_key(如果您还没有)。
请前往工作区门户,点击Prompt flow -> Connections -> Create,然后按照指示创建您自己的连接。
了解更多关于connections的信息。
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中完成的批量运行,用于以“data.jsonl”作为输入的web分类流程。
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])
下一步#
到目前为止,你已经成功运行了你的聊天流程并对其进行了评估。这太棒了!
你可以查看更多示例:
Stream Chat: 演示如何创建一个能够记住之前交互并使用对话历史生成下一条消息的聊天机器人。