搭配使用 AI 和 .NET 生成图像

在本快速入门中,你将了解如何创建 .NET 控制台应用,以使用 OpenAI 或 Azure OpenAI DALLe AI 模型生成图像,这些模型专门用于根据文本提示生成图像。

先决条件

先决条件

注释

你还可以使用语义内核完成本文中的任务。 语义内核是一种轻型开源 SDK,可用于生成 AI 代理并将最新的 AI 模型集成到 .NET 应用中。

创建应用

完成以下步骤,创建 .NET 控制台应用以连接到 AI 模型。

  1. 在计算机上的空目录中,使用 dotnet new 命令创建新的控制台应用:

    dotnet new console -o ImagesAI
    
  2. 将目录更改为应用文件夹:

    cd ImagesAI
    
  3. 安装所需的包:

    dotnet add package Azure.AI.OpenAI
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
    dotnet add package OpenAI
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
  4. 在 Visual Studio Code 或所选编辑器中打开应用。

    code .
    

创建 AI 服务

  1. 若要预配 Azure OpenAI 服务和模型,请完成 创建和部署 Azure OpenAI 服务资源 文章中的步骤。

  2. 在终端或命令提示符下,导航到项目目录的根目录。

  3. 运行以下命令为示例应用配置 Azure OpenAI 终结点和模型名称:

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-Azure-OpenAI-model-name>
    

配置应用

  1. 从终端或命令提示符导航到 .NET 项目的根目录。

  2. 运行以下命令,将 OpenAI API 密钥配置为示例应用的机密:

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-OpenAI-key>
    dotnet user-secrets set ModelName <your-OpenAI-model-name>
    

添加应用代码

  1. Program.cs 文件中,添加以下代码以连接并向 AI 模型进行身份验证。

    using Microsoft.Extensions.Configuration;
    using OpenAI.Images;
    using System.ClientModel;
    using Azure.AI.OpenAI;
    using Azure.Identity;
    
    // Retrieve the local secrets saved during the Azure deployment. If you skipped the deployment
    // because you already have an Azure OpenAI available, edit the following lines to use your information,
    // e.g. string openAIEndpoint = "https://cog-demo123.openai.azure.com/";
    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string deployment = config["AZURE_OPENAI_DALLE_NAME"];
    
    // Create the Azure OpenAI ImageClient
    ImageClient client =
        new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
            .GetImageClient(deployment);
    
    // Generate the image
    GeneratedImage generatedImage = await client.GenerateImageAsync("""
        A postal card with an happy hiker waving and a beautiful mountain in the background.
        There is a trail visible in the foreground.
        The postal card has text in red saying: 'You are invited for a hike!'
        """, new ImageGenerationOptions { Size = GeneratedImageSize.W1024xH1024 });
    
    Console.WriteLine($"The generated image is ready at:\n{generatedImage.ImageUri}");
    

    注释

    DefaultAzureCredential 从本地工具中搜寻身份验证凭据。 如果不使用 azd 模板来预配 Azure OpenAI 资源,则需要将 Azure AI Developer 角色分配给用于登录到 Visual Studio 或 Azure CLI 的帐户。 有关详细信息,请参阅使用 .NET 向 Azure AI 服务进行身份验证

    // Licensed to the .NET Foundation under one or more agreements.
    // The .NET Foundation licenses this file to you under the MIT license.
    // See the LICENSE file in the project root for more information.
    using Microsoft.Extensions.Configuration;
    using OpenAI.Images;
    // Retrieve the local secrets that were set from the command line, using:
    // dotnet user-secrets init
    // dotnet user-secrets set OpenAIKey <your-openai-key>
    var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string key = config["OpenAIKey"];
    string modelName = config["ModelName"];
    
    // Create the OpenAI ImageClient
    ImageClient client = new(modelName, key);
    
    // Generate the image
    GeneratedImage generatedImage = await client.GenerateImageAsync("""
        A postal card with a happy hiker waving and a beautiful mountain in the background.
        There is a trail visible in the foreground.
        The postal card has text in red saying: 'You are invited for a hike!'
        """,
        new ImageGenerationOptions 
        {
            Size = GeneratedImageSize.W1024xH1024 
        });
    
    Console.WriteLine($"The generated image is ready at:\n{generatedImage.ImageUri}");
    

    前面的代码:

    • 从项目用户机密中读取基本配置值以连接到 AI 模型。
    • 创建一个 OpenAI.Images.ImageClient 用于连接到 AI 模型。
    • 向描述所需图像的模型发送提示。
    • 将生成的图像的 URL 打印到控制台输出。
  2. 运行应用:

    dotnet run
    

    导航到控制台输出中的图像 URL 以查看生成的图像。 自定义提示的文本内容以创建新图像或修改原始图像。

清理资源

如果不再需要它们,请删除 Azure OpenAI 资源和 GPT-4 模型部署。

  1. Azure 门户中,导航到 Azure OpenAI 资源。
  2. 选择 Azure OpenAI 资源,然后选择 删除

后续步骤