使用 Azure AI 搭配 .NET 產生影像
建立簡單的 .NET 8.0 主控台聊天應用程式,以開始使用語意核心。 應用程式會在本機執行,並使用 OpenAI dell-e-3
模型來產生明信片,邀請您的朋友一起徒步旅行! 請遵循下列步驟來佈建 Azure OpenAI,並了解如何使用語意核心。
建立簡單的 .NET 8.0 主控台聊天應用程式,以開始使用 .NET Azure OpenAI SDK。 應用程式會在本機執行,並使用 OpenAI dell-e-3
模型來產生明信片,邀請您的朋友一起徒步旅行! 請遵循下列步驟來佈建 Azure OpenAI,並了解如何使用 .NET Azure OpenAI SDK。
必要條件
- .NET 8.0 SDK - 安裝 .NET 8.0 SDK
- Azure 訂用帳戶 - 建立免費帳戶
- Azure 開發人員 CLI - 安裝或更新 Azure 開發人員 CLI
- 存取 Azure OpenAI 服務。
- 在 Windows 上,需要 PowerShell
v7+
。 若要驗證您的版本,請在終端機中執行pwsh
。 其應該會傳回目前的版本。 如果傳回錯誤,請執行下列命令:dotnet tool update --global PowerShell
。
部署 Azure 資源
請確定您遵循必要條件來存取 Azure OpenAI 服務以及 Azure 開發人員 CLI,然後遵循下列指南來設定開始使用範例應用程式。
複製存放庫:dotnet/ai-samples
從終端機或命令提示字元,瀏覽至快速入門目錄。
這會佈建 Azure OpenAI 資源。 建立 Azure OpenAI 服務並部署模型可能需要幾分鐘的時間。
azd up
注意
如果您已經有可用的 Azure OpenAI 服務,就可以跳過部署,並在 Program.cs 中使用該值 (最好來自 IConfiguration
)。
疑難排解
在 Windows 上,執行 azd up
之後,您可能會收到下列錯誤訊息:
postprovision.ps1 未以數位方式簽署。 指令碼不會在系統上執行
執行指令碼 postprovision.ps1 以設定應用程式中使用的 .NET 使用者密碼。 若要避免此錯誤,請執行下列 PowerShell 命令:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
然後重新執行 azd up
命令。
另一個可能的錯誤:
「pwsh」並未經辨識為內部或外部命令、可執行程式或批次檔案。 警告:「postprovision」攔截失敗,結束代碼為:「1」,路徑:「.\infra\post-script\postprovision.ps1」。 :結束代碼:1 執行將會繼續,因為 ContinueOnError 已設定為 true。
執行指令碼 postprovision.ps1 以設定應用程式中使用的 .NET 使用者密碼。 若要避免此錯誤,請使用下列 PowerShell 命令手動執行指令碼:
.\infra\post-script\postprovision.ps1
.NET AI 應用程式現在已設定使用者祕密,而且可以進行測試。
嘗試產生徒步旅行影像範例
- 從終端機或命令提示字元中,瀏覽至
semantic-kernel\05-HikeImages
目錄。
- 從終端機或命令提示字元中,瀏覽至
azure-openai-sdk\05-HikeImages
目錄。
現在是嘗試使用主控台應用程式的好時機。 輸入下列命令以執行應用程式:
dotnet run
如果您收到錯誤訊息,Azure OpenAI 資源可能尚未完成部署。 請稍候幾分鐘再試一次。
了解程式碼
我們的應用程式使用 NuGet 上提供的 Microsoft.SemanticKernel
套件,向 Azure 中部署的 Azure OpenAI 服務傳送和接收要求。
整個應用程式都包含在 Program.cs 檔案中。 前幾行程式碼會載入應用程式佈建期間在 dotnet user-secrets
中設定的秘密和組態值。
// == Retrieve the local secrets saved during the Azure deployment ==========
var config = new ConfigurationBuilder()
.AddUserSecrets<Program>()
.Build();
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
string deployment = config["AZURE_OPENAI_GPT_NAME"];
string key = config["AZURE_OPENAI_KEY"];
AzureOpenAITextToImageService
服務促進要求和回應。
AzureOpenAITextToImageService textToImageService = new(deployment, endpoint, key, null);
建立 textToImageService
服務之後,我們會透過新增系統提示為模型提供更多內容。 產生影像的良好提示需要清楚的描述:影像中的內容、要使用的特定色彩、樣式 (繪圖、繪畫、現實或卡通)。 模型會使用此提示來產生影像。 若要讓模型根據使用者要求產生回應,請使用 GenerateImageAsync
函式,並指定大小和品質。
// Generate the image
string imageUrl = await textToImageService.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!'
""", 1024, 1024);
Console.WriteLine($"The generated image is ready at:\n{imageUrl}");
自訂提示以將模型所產生的影像個人化。
了解程式碼
我們的應用程式使用 NuGet 上提供的 Azure.AI.OpenAI
用戶端 SDK,向 Azure 中部署的 Azure OpenAI 服務傳送和接收要求。
整個應用程式都包含在 Program.cs 檔案中。 前幾行程式碼會載入應用程式佈建期間在 dotnet user-secrets
中設定的秘密和組態值。
// == Retrieve the local secrets saved during the Azure deployment ==========
var config = new ConfigurationBuilder()
.AddUserSecrets<Program>()
.Build();
string openAIEndpoint = config["AZURE_OPENAI_ENDPOINT"];
string openAIDeploymentName = config["AZURE_OPENAI_GPT_NAME"];
string openAiKey = config["AZURE_OPENAI_KEY"];
// == Creating the AIClient ==========
var endpoint = new Uri(openAIEndpoint);
var credentials = new AzureKeyCredential(openAiKey);
OpenAIClient
類別促進要求和回應。 ChatCompletionOptions
指定模型將回應參數的方式。
var openAIClient = new OpenAIClient(endpoint, credentials);
var completionOptions = new ChatCompletionsOptions
{
MaxTokens = 400,
Temperature = 1f,
FrequencyPenalty = 0.0f,
PresencePenalty = 0.0f,
NucleusSamplingFactor = 0.95f, // Top P
DeploymentName = openAIDeploymentName
};
建立 OpenAIClient
用戶端之後,我們會透過新增系統提示,為模型提供更多內容。 產生影像的良好提示需要清楚的描述:影像中的內容、要使用的特定色彩、樣式 (繪圖、繪畫、現實或卡通)。 模型會使用此提示來產生影像。
string imagePrompt = """
A postal card with an happy hiker waving, there 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!'
""";
若要讓模型根據使用者要求產生回應,請使用 GetImageGenerationsAsync
函式,並指定大小和品質。
Response<ImageGenerations> response = await openAIClient.GetImageGenerationsAsync(
new ImageGenerationOptions()
{
DeploymentName = openAIDalleName,
Prompt = imagePrompt,
Size = ImageSize.Size1024x1024,
Quality = ImageGenerationQuality.Standard
});
ImageGenerationData generatedImage = response.Value.Data[0];
if (!string.IsNullOrEmpty(generatedImage.RevisedPrompt))
{
Console.WriteLine($"\n\nInput prompt automatically revised to:\n {generatedImage.RevisedPrompt}");
}
Console.WriteLine($"\n\nThe generated image is ready at:\n {generatedImage.Url.AbsoluteUri}");
自訂提示以將模型所產生的影像個人化。
清除資源
當您不再需要範例應用程式或資源時,請移除對應的部署和所有資源。
azd down
下一步
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應