通过 Python 客户端 SDK 消费 Fabric 数据代理(预览版)

本文介绍如何使用 Python 客户端 SDK 通过交互式浏览器身份验证将 Fabric 数据代理添加到 Web 应用和其他客户端。 通过浏览器使用 Microsoft Entra ID 凭据登录后,数据代理将在您的权限下运行。 将数据代理添加到外部应用后,可以生成自定义接口、在现有工作流中嵌入见解、自动执行报表,以及让用户运行自然语言数据查询。 此方法提供数据代理功能,同时可以完全控制用户体验和应用体系结构。

重要

此功能目前为预览版

先决条件

在 VS Code 中设置环境

  1. 克隆或下载 Fabric 数据代理外部客户端存储库,然后在 VS Code 中打开它并运行示例客户端。

  2. 创建并激活 Python 虚拟环境(建议),然后安装所需的依赖项。

    python -m venv .venv
    
  3. 激活虚拟环境。

    .venv\Scripts\activate
    

安装依赖项

运行以下命令以安装依赖项:

pip install -r requirements.txt

注释

  • 通过随附的azure-identityrequirements.txt包,可以使用 Microsoft Entra ID 进行身份验证。
  • InteractiveBrowserCredentialazure-identity 包中打开浏览器,以便用户可以使用 Microsoft Entra ID 帐户登录。 将其用于允许交互式登录的本地开发或应用。

配置客户端

选择以下方法之一来设置所需的值(TENANT_IDDATA_AGENT_URL):

在 shell 中设置值。 将尖括号中的占位符文本替换为你自己的值。

export TENANT_ID=<your-azure-tenant-id>
export DATA_AGENT_URL=<your-fabric-data-agent-url>

请参阅文档以查找已发布的数据代理 URL。 按照说明查找租户 ID。

Authenticate

使用 InteractiveBrowserCredential 类在浏览器中使用 Microsoft Entra ID 进行身份验证。

from azure.identity import InteractiveBrowserCredential
from fabric_data_agent_client import FabricDataAgentClient
credential = InteractiveBrowserCredential()

创建数据代理客户端

client = FabricDataAgentClient(credential=credential)

注释

  • fabric-data-agent-client 包提供用于连接到 Fabric 数据代理的客户端 SDK。
  • Python 客户端使用交互式浏览器身份验证:运行脚本时,将打开默认浏览器,以便登录到托管 Fabric 数据代理的租户。

向数据代理提问

进行身份验证后,使用 Python 客户端与数据代理进行交互。

response = client.ask("What were the total sales last quarter?")
print(f"Response: {response}")

该方法 client.ask 将问题发送到数据代理,并返回包含答案的对象。 可以查看数据代理执行的步骤及其生成的相应查询以获取答案。

run_details = client.get_run_details("What were the total sales last quarter?")
messages = run_details.get('messages', {}).get('data', [])
assistant_messages = [msg for msg in messages if msg.get('role') == 'assistant']

print("Answer:", assistant_messages[-1])

可选:检查步骤及对应的查询

检查数据代理到达答案的步骤,包括执行过程中出现的任何错误。

for step in run_details['run_steps']['data']:
        tool_name = "N/A"
        if 'step_details' in step and step['step_details'] and 'tool_calls' in step['step_details']:
            tool_calls = step['step_details']['tool_calls']
            if tool_calls and len(tool_calls) > 0 and 'function' in tool_calls[0]:
                tool_name = tool_calls[0]['function'].get('name', 'N/A')
        print(f"Step ID: {step.get('id')}, Type: {step.get('type')}, Status: {step.get('status')}, Tool Name: {tool_name}")
        if 'error' in step:
            print(f"  Error: {step['error']}")

此输出可帮助你了解代理如何生成响应,并在 Python 客户端中使用数据时提供透明度。