Generate images using AI with .NET
Get started with AI by creating a simple .NET 8 console chat application. The application will run locally and use the OpenAI dall-e-3
model to generate postal card images so you can invite your friends for a hike! Follow these steps to get access to OpenAI and learn how to use Semantic Kernel.
Prerequisites
- .NET 8.0 SDK - Install the .NET 8.0 SDK.
- An API key from OpenAI so you can run this sample.
- On Windows, PowerShell
v7+
is required. To validate your version, runpwsh
in a terminal. It should return the current version. If it returns an error, execute the following command:dotnet tool update --global PowerShell
.
Get started with AI by creating a simple .NET 8 console chat application. The application will run locally and use the OpenAI dall-e-3
model to generate postal card images so you can invite your friends for a hike! Follow these steps to provision Azure OpenAI and learn how to use the .NET Azure OpenAI SDK.
Prerequisites
- .NET 8 SDK - Install the .NET 8 SDK.
- An Azure subscription - Create one for free.
- Access to Azure OpenAI service.
- Azure Developer CLI (Optional) - Install or update the Azure Developer CLI.
Get the sample project
Clone the sample repository
You can create your own app using the steps in the sections ahead, or you can clone the GitHub repository that contains the completed sample apps for all of the quickstarts. If you plan to use Azure OpenAI, the sample repo is also structured as an Azure Developer CLI template that can provision an Azure OpenAI resource for you.
git clone https://github.com/dotnet/ai-samples.git
Create the Azure OpenAI service
The sample GitHub repository is structured as an Azure Developer CLI (azd
) template, which azd
can use to provision the Azure OpenAI service and model for you.
From a terminal or command prompt, navigate to the
src\quickstarts\azure-openai
directory of the sample repo.Run the
azd up
command to provision the Azure OpenAI resources. It might take several minutes to create the Azure OpenAI service and deploy the model.azd up
azd
also configures the required user secrets for the sample app, such as the Azure OpenAI endpoint and model name.
Try the the hiking images sample
Clone the repository: dotnet/ai-samples
Run the following commands to configure your OpenAI API key as a secret for the sample app:
dotnet user-secrets init dotnet user-secrets set OpenAIKey <your-openai-key>
Use the
dotnet run
command to run the app:dotnet run
From a terminal or command prompt, navigate to the
azure-openai\semantic-kernel\05-HikeImages
directory.Use the
dotnet run
command to run the app:dotnet run
Tip
If you get an error message, the Azure OpenAI resources might not have finished deploying. Wait a couple of minutes and try again.
Explore the code
The application uses the Microsoft.SemanticKernel
package to send and receive requests to the OpenAI service.
The Program.cs file contains all of the app code. The first several lines of code set configuration values and get the OpenAI Key that was previously set using the dotnet user-secrets
command.
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string key = config["OpenAIKey"];
The OpenAITextToImageService
service facilitates the requests and responses.
OpenAITextToImageService textToImageService = new(key, null);
The application uses the Microsoft.SemanticKernel
package to send and receive requests to the Azure OpenAI service.
The Program.cs file contains all of the app code. The first several lines of code load secrets and configuration values that were set in the dotnet user-secrets
for you during the application provisioning.
// Retrieve the local secrets saved during the Azure deployment
var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
string endpoint = config["AZURE_OPENAI_ENDPOINT"];
string deployment = config["AZURE_OPENAI_GPT_NAME"];
The AzureOpenAITextToImageService
service facilitates the requests and responses.
AzureOpenAITextToImageService textToImageService = new(deployment, endpoint, new DefaultAzureCredential(), null);
Provide context and instructions to the model by adding a system prompt. A good image generation prompt requires a clear description of what the image is, which colors to use, the intended style, and other descriptors.
The GenerateImageAsync
function instructs the model to generate a response based on the user prompt and image size and quality configurations.
// Generate the image
string imageUrl = await textToImageService.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!'
""", 1024, 1024);
Console.WriteLine($"The generated image is ready at:\n{imageUrl}");
Customize the prompt to personalize the images generated by the model.
Clean up resources
When you no longer need the sample application or resources, remove the corresponding deployment and all resources.
azd down
Troubleshoot
On Windows, you might get the following error messages after running azd up
:
postprovision.ps1 is not digitally signed. The script will not execute on the system
The script postprovision.ps1 is executed to set the .NET user secrets used in the application. To avoid this error, run the following PowerShell command:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
Then re-run the azd up
command.
Another possible error:
'pwsh' is not recognized as an internal or external command, operable program or batch file. WARNING: 'postprovision' hook failed with exit code: '1', Path: '.\infra\post-script\postprovision.ps1'. : exit code: 1 Execution will continue since ContinueOnError has been set to true.
The script postprovision.ps1 is executed to set the .NET user secrets used in the application. To avoid this error, manually run the script using the following PowerShell command:
.\infra\post-script\postprovision.ps1
The .NET AI apps now have the user secrets configured and they can be tested.