You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure OpenAI连接Azure DB(MFA),用C#获取自然语言查询结果及所需NuGet包

通过Azure OpenAI连接启用MFA的Azure数据库并获取动态查询结果

核心实现步骤

1. 适配Azure AD MFA的数据库权限配置

  • 确保目标Azure数据库(如Azure SQL DB)已启用Azure AD身份认证,并强制要求MFA。
  • 为用于连接数据库的身份(用户账户或托管身份)分配对应数据库角色权限(如db_datareader、db_datawriter),该身份需已启用MFA。

2. 用Azure OpenAI Function Calling实现动态查询

  • 定义数据库查询函数:在代码中实现可执行SQL查询的函数,使用支持MFA的认证方式连接数据库。
  • 配置Function Calling:将上述函数注册到Azure OpenAI的对话请求中,引导模型将自然语言需求转换为合法SQL语句,调用函数执行查询后返回结果。

关键连接逻辑(支持MFA)

使用Active Directory Interactive认证方式的连接字符串,触发MFA验证流程:

string connectionString = "Server=tcp:{your-server}.database.windows.net,1433;Database={your-db-name};Authentication=Active Directory Interactive;";
C#开发所需NuGet包

以下是实现该场景的核心NuGet包:

  • Azure.AI.OpenAI:用于与Azure OpenAI服务交互,支持Function Calling功能。
  • Microsoft.Data.SqlClient:用于连接Azure SQL数据库,原生支持Active Directory Interactive认证(适配MFA)。
  • System.ComponentModel.Annotations(可选):为Function的参数添加元数据注解,帮助模型理解参数要求。
  • Newtonsoft.Json(可选):简化JSON格式的函数请求/响应数据处理。

代码示例片段

数据库查询函数实现

using Microsoft.Data.SqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;

public static async Task<List<Dictionary<string, object>>> ExecuteDbQuery(string sqlQuery)
{
    var results = new List<Dictionary<string, object>>();
    string connectionString = "Server=tcp:your-server.database.windows.net,1433;Database=your-db;Authentication=Active Directory Interactive;";
    
    using (var conn = new SqlConnection(connectionString))
    {
        await conn.OpenAsync();
        using (var cmd = new SqlCommand(sqlQuery, conn))
        {
            using (var reader = await cmd.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    var row = new Dictionary<string, object>();
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i);
                    }
                    results.Add(row);
                }
            }
        }
    }
    return results;
}

Azure OpenAI Function Calling配置

using Azure.AI.OpenAI;
using System.Threading.Tasks;

public static async Task RunOpenAIChat()
{
    var openAIClient = new OpenAIClient(
        new System.Uri("https://your-openai-resource.openai.azure.com/"),
        new Azure.AzureKeyCredential("your-openai-api-key"));

    var queryFunction = new FunctionDefinition("execute_db_query")
    {
        Description = "接收合法SQL语句,执行并返回Azure数据库的查询结果",
        Parameters = BinaryData.FromObjectAsJson(new
        {
            Type = "object",
            Properties = new
            {
                sqlQuery = new { Type = "string", Description = "符合数据库语法的SQL查询语句" }
            },
            Required = new[] { "sqlQuery" }
        })
    };

    var chatOptions = new ChatCompletionsOptions
    {
        Messages = { new ChatMessage(ChatRole.User, "统计本月已完成的订单数量") },
        Functions = { queryFunction },
        FunctionCall = "auto"
    };

    var response = await openAIClient.GetChatCompletionsAsync("your-gpt-deployment-name", chatOptions);
    
    // 解析函数调用请求,执行查询并将结果返回给OpenAI模型
    var functionCall = response.Value.Choices[0].Message.FunctionCall;
    if (functionCall != null && functionCall.Name == "execute_db_query")
    {
        var sqlQuery = functionCall.Arguments["sqlQuery"].ToString();
        var dbResults = await ExecuteDbQuery(sqlQuery);
        
        // 将结果作为系统消息返回给模型,生成自然语言回答
        chatOptions.Messages.Add(response.Value.Choices[0].Message);
        chatOptions.Messages.Add(new ChatMessage(ChatRole.Function, System.Text.Json.JsonSerializer.Serialize(dbResults), "execute_db_query"));
        var finalResponse = await openAIClient.GetChatCompletionsAsync("your-gpt-deployment-name", chatOptions);
        // 输出最终自然语言结果
        Console.WriteLine(finalResponse.Value.Choices[0].Message.Content);
    }
}

内容的提问来源于stack exchange,提问作者Shivani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:53:18