Quickstart: Generate images with Azure OpenAI Service
Note
The image generation API creates an image from a text prompt. It doesn't edit or create variations from existing images.
Use this guide to get started generating images with Azure OpenAI in your browser with Azure AI Foundry.
Prerequisites
- An Azure subscription. Create one for free.
- An Azure OpenAI resource created in a supported region. See Region availability. For more information, see Create a resource and deploy a model with Azure OpenAI.
Go to Azure AI Foundry
Browse to Azure AI Foundry and sign in with the credentials associated with your Azure OpenAI resource. During or after the sign-in workflow, select the appropriate directory, Azure subscription, and Azure OpenAI resource.
From the Azure AI Foundry landing page, create or select a new project. Navigate to the Models + endpoints page on the left nav. Select Deploy model and then choose one of the DALL-E models from the list. Complete the deployment process.
On the model's page, select Open in playground.
Try out image generation
Start exploring Azure OpenAI capabilities with a no-code approach through the Images playground. Enter your image prompt into the text box and select Generate. When the AI-generated image is ready, it appears on the page.
Note
The image generation APIs come with a content moderation filter. If Azure OpenAI recognizes your prompt as harmful content, it doesn't return a generated image. For more information, see Content filtering.
In the Images playground, you can also view Python and cURL code samples, which are prefilled according to your settings. Select View code near the top of the page. You can use this code to write an application that completes the same task.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- Try examples in the Azure OpenAI Samples GitHub repository.
- See the API reference
Use this guide to get started calling the Azure OpenAI Service image generation REST APIs by using Python.
Prerequisites
- An Azure subscription. Create one for free.
- Python 3.8 or later version.
- The following Python libraries installed:
os
,requests
,json
. - An Azure OpenAI resource created in a supported region. See Region availability.
- Then, you need to deploy a
dalle3
model with your Azure resource. For more information, see Create a resource and deploy a model with Azure OpenAI.
Setup
Retrieve key and endpoint
To successfully call the Azure OpenAI APIs, you need the following information about your Azure OpenAI resource:
Variable | Name | Value |
---|---|---|
Endpoint | api_base |
The endpoint value is located under Keys and Endpoint for your resource in the Azure portal. You can also find the endpoint via the Deployments page in Azure AI Foundry portal. An example endpoint is: https://docs-test-001.openai.azure.com/ . |
Key | api_key |
The key value is also located under Keys and Endpoint for your resource in the Azure portal. Azure generates two keys for your resource. You can use either value. |
Go to your resource in the Azure portal. On the navigation pane, select Keys and Endpoint under Resource Management. Copy the Endpoint value and an access key value. You can use either the KEY 1 or KEY 2 value. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
Environment variables
Create and assign persistent environment variables for your key and endpoint.
Important
We recommend Microsoft Entra ID authentication with managed identities for Azure resources to avoid storing credentials with your applications that run in the cloud.
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If using API keys, store them securely in Azure Key Vault, rotate the keys regularly, and restrict access to Azure Key Vault using role based access control and network access restrictions. For more information about using API keys securely in your apps, see API keys with Azure Key Vault.
For more information about AI services security, see Authenticate requests to Azure AI services.
setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE"
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE"
Create a new Python application
Create a new Python file named quickstart.py. Open the new file in your preferred editor or IDE.
Replace the contents of quickstart.py with the following code. Change the value of
prompt
to your preferred text.You also need to replace
<dalle3>
in the URL with the deployment name you chose when you deployed the DALL-E 3 model. Entering the model name will result in an error unless you chose a deployment name that is identical to the underlying model name. If you encounter an error, double check to make sure that you don't have a doubling of the/
at the separation between your endpoint and/openai/deployments
.import requests import time import os api_base = os.environ['AZURE_OPENAI_ENDPOINT'] # Enter your endpoint here api_key = os.environ['AZURE_OPENAI_API_KEY'] # Enter your API key here api_version = '2024-02-01' url = f"{api_base}/openai/deployments/<dalle3>/images/generations?api-version={api_version}" headers= { "api-key": api_key, "Content-Type": "application/json" } body = { # Enter your prompt text here "prompt": "A multi-colored umbrella on the beach, disposable camera", "size": "1024x1024", # supported values are “1792x1024”, “1024x1024” and “1024x1792” "n": 1, #The number of images to generate. Only n=1 is supported for DALL-E 3. "quality": "hd", # Options are “hd” and “standard”; defaults to standard "style": "vivid" # Options are “natural” and “vivid”; defaults to “vivid” } submission = requests.post(url, headers=headers, json=body) image_url = submission.json()['data'][0]['url'] print(image_url)
The script makes a synchronous image generation API call.
Important
Remember to remove the key from your code when you're done, and never post your key publicly. For production, use a secure way of storing and accessing your credentials. For more information, see Azure Key Vault.
Run the application with the
python
command:python quickstart.py
Wait a few moments to get the response.
Output
The output from a successful image generation API call looks like the following example. The url
field contains a URL where you can download the generated image. The URL stays active for 24 hours.
{
"created": 1698116662,
"data": [
{
"url": "<URL_to_generated_image>",
"revised_prompt": "<prompt_that_was_used>"
}
]
}
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it doesn't generate an image. For more information, see Content filtering. For examples of error responses, see the DALL-E how-to guide.
The system returns an operation status of Failed
and the error.code
value in the message is set to contentFilter
. Here's an example:
{
"created": 1698435368,
"error":
{
"code": "contentFilter",
"message": "Your task failed as a result of our safety system."
}
}
It's also possible that the generated image itself is filtered. In this case, the error message is set to Generated image was filtered as a result of our safety system.
. Here's an example:
{
"created": 1698435368,
"error":
{
"code": "contentFilter",
"message": "Generated image was filtered as a result of our safety system."
}
}
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- Try examples in the Azure OpenAI Samples GitHub repository.
- See the API reference
Use this guide to get started generating images with the Azure OpenAI SDK for Python.
Library source code | Package | Samples
Prerequisites
- An Azure subscription. Create one for free.
- Python 3.8 or later version.
- An Azure OpenAI resource created in a compatible region. See Region availability.
- Then, you need to deploy a
dalle3
model with your Azure resource. For more information, see Create a resource and deploy a model with Azure OpenAI.
Setup
Retrieve key and endpoint
To successfully call the Azure OpenAI APIs, you need the following information about your Azure OpenAI resource:
Variable | Name | Value |
---|---|---|
Endpoint | api_base |
The endpoint value is located under Keys and Endpoint for your resource in the Azure portal. You can also find the endpoint via the Deployments page in Azure AI Foundry portal. An example endpoint is: https://docs-test-001.openai.azure.com/ . |
Key | api_key |
The key value is also located under Keys and Endpoint for your resource in the Azure portal. Azure generates two keys for your resource. You can use either value. |
Go to your resource in the Azure portal. On the navigation pane, select Keys and Endpoint under Resource Management. Copy the Endpoint value and an access key value. You can use either the KEY 1 or KEY 2 value. Always having two keys allows you to securely rotate and regenerate keys without causing a service disruption.
Environment variables
Create and assign persistent environment variables for your key and endpoint.
Important
We recommend Microsoft Entra ID authentication with managed identities for Azure resources to avoid storing credentials with your applications that run in the cloud.
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If using API keys, store them securely in Azure Key Vault, rotate the keys regularly, and restrict access to Azure Key Vault using role based access control and network access restrictions. For more information about using API keys securely in your apps, see API keys with Azure Key Vault.
For more information about AI services security, see Authenticate requests to Azure AI services.
setx AZURE_OPENAI_API_KEY "REPLACE_WITH_YOUR_KEY_VALUE_HERE"
setx AZURE_OPENAI_ENDPOINT "REPLACE_WITH_YOUR_ENDPOINT_HERE"
Install the Python SDK
Open a command prompt and browse to your project folder. Install the OpenAI Python SDK by using the following command:
pip install openai
Install the following libraries as well:
pip install requests
pip install pillow
Generate images with DALL-E
Create a new python file, quickstart.py. Open it in your preferred editor or IDE.
Replace the contents of quickstart.py with the following code.
from openai import AzureOpenAI
import os
import requests
from PIL import Image
import json
client = AzureOpenAI(
api_version="2024-02-01",
api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ['AZURE_OPENAI_ENDPOINT']
)
result = client.images.generate(
model="dalle3", # the name of your DALL-E 3 deployment
prompt="a close-up of a bear walking throughthe forest",
n=1
)
json_response = json.loads(result.model_dump_json())
# Set the directory for the stored image
image_dir = os.path.join(os.curdir, 'images')
# If the directory doesn't exist, create it
if not os.path.isdir(image_dir):
os.mkdir(image_dir)
# Initialize the image path (note the filetype should be png)
image_path = os.path.join(image_dir, 'generated_image.png')
# Retrieve the generated image
image_url = json_response["data"][0]["url"] # extract image URL from response
generated_image = requests.get(image_url).content # download the image
with open(image_path, "wb") as image_file:
image_file.write(generated_image)
# Display the image in the default image viewer
image = Image.open(image_path)
image.show()
- Enter your endpoint URL and key in the appropriate fields.
- Change the value of
prompt
to your preferred text. - Change the value of
model
to the name of your deployed DALL-E 3 model.
Important
Remember to remove the key from your code when you're done, and never post your key publicly. For production, use a secure way of storing and accessing your credentials. For more information, see Azure Key Vault.
Run the application with the python
command:
python quickstart.py
Wait a few moments to get the response.
Output
Azure OpenAI stores the output image in the generated_image.png file in your specified directory. The script also displays the image in your default image viewer.
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it doesn't generate an image. For more information, see Content filtering.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- Try examples in the Azure OpenAI Samples GitHub repository.
- See the API reference
Use this guide to get started generating images with the Azure OpenAI SDK for C#.
Library source code | Package (NuGet) | Samples
Prerequisites
- An Azure subscription - Create one for free
- The .NET 7 SDK
- An Azure OpenAI resource created in a supported region (see Region availability). For more information, see Create a resource and deploy a model with Azure OpenAI.
Microsoft Entra ID prerequisites
For the recommended keyless authentication with Microsoft Entra ID, you need to:
- Install the Azure CLI used for keyless authentication with Microsoft Entra ID.
- Assign the
Cognitive Services User
role to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Set up
Create a new folder
vision-quickstart
and go to the quickstart folder with the following command:mkdir vision-quickstart && cd vision-quickstart
Create a new console application with the following command:
dotnet new console
Install the OpenAI .NET client library with the dotnet add package command:
dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.6
For the recommended keyless authentication with Microsoft Entra ID, install the Azure.Identity package with:
dotnet add package Azure.Identity
For the recommended keyless authentication with Microsoft Entra ID, sign in to Azure with the following command:
az login
Retrieve resource information
You need to retrieve the following information to authenticate your application with your Azure OpenAI resource:
Variable name | Value |
---|---|
AZURE_OPENAI_ENDPOINT |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. |
AZURE_OPENAI_DEPLOYMENT_NAME |
This value will correspond to the custom name you chose for your deployment when you deployed a model. This value can be found under Resource Management > Model Deployments in the Azure portal. |
OPENAI_API_VERSION |
Learn more about API Versions. You can change the version in code or use an environment variable. |
Learn more about keyless authentication and setting environment variables.
Run the quickstart
The sample code in this quickstart uses Microsoft Entra ID for the recommended keyless authentication. If you prefer to use an API key, you can replace the DefaultAzureCredential
object with an AzureKeyCredential
object.
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential());
To run the quickstart, follow these steps:
Replace the contents of
Program.cs
with the following code and update the placeholder values with your own.using Azure; using Azure.AI.OpenAI; using OpenAI.Images; using static System.Environment; string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<your-resource-name>.openai.azure.com/"; string key = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY") ?? "<your-key>"; // Use the recommended keyless credential instead of the AzureKeyCredential credential. AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential()); //AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key)); // This must match the custom deployment name you chose for your model ImageClient chatClient = openAIClient.GetImageClient("dalle-3"); var imageGeneration = await chatClient.GenerateImageAsync( "a happy monkey sitting in a tree, in watercolor", new ImageGenerationOptions() { Size = GeneratedImageSize.W1024xH1024 } ); Console.WriteLine(imageGeneration.Value.ImageUri);
Run the application using the
dotnet run
command or the run button at the top of Visual Studio:dotnet run
Output
The URL of the generated image is printed to the console.
<SAS URL>
Note
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it won't return a generated image. For more information, see the content filter article.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- For more examples check out the Azure OpenAI Samples GitHub repository.
Use this guide to get started generating images with the Azure OpenAI SDK for Java.
Library source code | Artifact (Maven) | Samples
Prerequisites
- An Azure subscription - Create one for free
- The current version of the Java Development Kit (JDK)
- Install Apache Maven.
- An Azure OpenAI resource created in a supported region (see Region availability). For more information, see Create a resource and deploy a model with Azure OpenAI.
Microsoft Entra ID prerequisites
For the recommended keyless authentication with Microsoft Entra ID, you need to:
- Install the Azure CLI used for keyless authentication with Microsoft Entra ID.
- Assign the
Cognitive Services User
role to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Set up
Create a new folder
vision-quickstart
and go to the quickstart folder with the following command:mkdir vision-quickstart && cd vision-quickstart
Install Apache Maven. Then run
mvn -v
to confirm successful installation.Create a new
pom.xml
file in the root of your project, and copy the following code into it:<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.azure.samples</groupId> <artifactId>quickstart-dall-e</artifactId> <version>1.0.0-SNAPSHOT</version> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.7.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.azure</groupId> <artifactId>azure-ai-openai</artifactId> <version>1.0.0-beta.3</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-core</artifactId> <version>1.53.0</version> </dependency> <dependency> <groupId>com.azure</groupId> <artifactId>azure-identity</artifactId> <version>1.15.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.9</version> </dependency> </dependencies> </project>
Install the Azure OpenAI SDK and dependencies.
mvn clean dependency:copy-dependencies
For the recommended keyless authentication with Microsoft Entra ID, sign in to Azure with the following command:
az login
Retrieve resource information
You need to retrieve the following information to authenticate your application with your Azure OpenAI resource:
Variable name | Value |
---|---|
AZURE_OPENAI_ENDPOINT |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. |
AZURE_OPENAI_DEPLOYMENT_NAME |
This value will correspond to the custom name you chose for your deployment when you deployed a model. This value can be found under Resource Management > Model Deployments in the Azure portal. |
OPENAI_API_VERSION |
Learn more about API Versions. You can change the version in code or use an environment variable. |
Learn more about keyless authentication and setting environment variables.
Run the app
The sample code in this quickstart uses Microsoft Entra ID for the recommended keyless authentication. If you prefer to use an API key, you can replace the DefaultAzureCredential
object with an AzureKeyCredential
object.
OpenAIAsyncClient client = new OpenAIClientBuilder()
.endpoint(endpoint)
.credential(new DefaultAzureCredentialBuilder().build())
.buildAsyncClient();
Follow these steps to create a console application for speech recognition.
Create a new file named Quickstart.java in the same project root directory.
Copy the following code into Quickstart.java:
import com.azure.ai.openai.OpenAIAsyncClient; import com.azure.ai.openai.OpenAIClientBuilder; import com.azure.ai.openai.models.ImageGenerationOptions; import com.azure.ai.openai.models.ImageLocation; import com.azure.core.credential.AzureKeyCredential; import com.azure.core.models.ResponseError; import java.util.concurrent.TimeUnit; public class Quickstart { public static void main(String[] args) throws InterruptedException { String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT"); // Use the recommended keyless credential instead of the AzureKeyCredential credential. OpenAIAsyncClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new DefaultAzureCredentialBuilder().build()) .buildAsyncClient(); ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions( "A drawing of the Seattle skyline in the style of Van Gogh"); client.getImages(imageGenerationOptions).subscribe( images -> { for (ImageLocation imageLocation : images.getData()) { ResponseError error = imageLocation.getError(); if (error != null) { System.out.printf("Image generation operation failed. Error code: %s, error message: %s.%n", error.getCode(), error.getMessage()); } else { System.out.printf( "Image location URL that provides temporary access to download the generated image is %s.%n", imageLocation.getUrl()); } } }, error -> System.err.println("There was an error getting images." + error), () -> System.out.println("Completed getImages.")); // The .subscribe() creation and assignment isn't a blocking call. // The thread sleeps so the program does not end before the send operation is complete. // Use .block() instead of .subscribe() for a synchronous call. TimeUnit.SECONDS.sleep(10); } }
Run your new console application to generate an image:
javac Quickstart.java -cp ".;target\dependency\*" java -cp ".;target\dependency\*" Quickstart
Output
The URL of the generated image is printed to the console.
Image location URL that provides temporary access to download the generated image is <SAS URL>.
Completed getImages.
Note
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it won't return a generated image. For more information, see the content filter article.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- For more examples, check out the Azure OpenAI Samples GitHub repository
Use this guide to get started generating images with the Azure OpenAI SDK for JavaScript.
Reference documentation | Source code | Package (npm) | Samples
Prerequisites
- An Azure subscription - Create one for free
- LTS versions of Node.js
- Azure CLI used for passwordless authentication in a local development environment, create the necessary context by signing in with the Azure CLI.
- An Azure OpenAI resource created in a supported region (see Region availability). For more information, see Create a resource and deploy a model with Azure OpenAI.
Microsoft Entra ID prerequisites
For the recommended keyless authentication with Microsoft Entra ID, you need to:
- Install the Azure CLI used for keyless authentication with Microsoft Entra ID.
- Assign the
Cognitive Services User
role to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Set up
Create a new folder
image-quickstart
and go to the quickstart folder with the following command:mkdir image-quickstart && cd image-quickstart
Create the
package.json
with the following command:npm init -y
Install the OpenAI client library for JavaScript with:
npm install openai
For the recommended passwordless authentication:
npm install @azure/identity
Retrieve resource information
You need to retrieve the following information to authenticate your application with your Azure OpenAI resource:
Variable name | Value |
---|---|
AZURE_OPENAI_ENDPOINT |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. |
AZURE_OPENAI_DEPLOYMENT_NAME |
This value will correspond to the custom name you chose for your deployment when you deployed a model. This value can be found under Resource Management > Model Deployments in the Azure portal. |
OPENAI_API_VERSION |
Learn more about API Versions. You can change the version in code or use an environment variable. |
Learn more about keyless authentication and setting environment variables.
Caution
To use the recommended keyless authentication with the SDK, make sure that the AZURE_OPENAI_API_KEY
environment variable isn't set.
Generate images with DALL-E
Create the
index.js
file with the following code:const { AzureOpenAI } = require("openai"); const { DefaultAzureCredential, getBearerTokenProvider } = require("@azure/identity"); // You will need to set these environment variables or edit the following values const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; // Required Azure OpenAI deployment name and API version const apiVersion = process.env.OPENAI_API_VERSION || "2024-07-01"; const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "dall-e-3"; // The prompt to generate images from const prompt = "a monkey eating a banana"; const numberOfImagesToGenerate = 1; // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); function getClient(): AzureOpenAI { return new AzureOpenAI({ endpoint, azureADTokenProvider, apiVersion, deployment: deploymentName, }); } async function main() { console.log("== Image Generation =="); const client = getClient(); const results = await client.images.generate({ prompt, size: "1024x1024", n: numberOfImagesToGenerate, model: "", style: "vivid", // or "natural" }); for (const image of results.data) { console.log(`Image generation result URL: ${image.url}`); } } main().catch((err) => { console.error("The sample encountered an error:", err); });
Sign in to Azure with the following command:
az login
Run the JavaScript file.
node index.js
Output
The URL of the generated image is printed to the console.
== Batch Image Generation ==
Image generation result URL: <SAS URL>
Image generation result URL: <SAS URL>
Note
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it won't return a generated image. For more information, see the content filter article.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- For more examples check out the Azure OpenAI Samples GitHub repository.
Use this guide to get started generating images with the Azure OpenAI SDK for JavaScript.
Reference documentation | Source code | Package (npm) | Samples
Prerequisites
- An Azure subscription - Create one for free
- LTS versions of Node.js
- TypeScript
- Azure CLI used for passwordless authentication in a local development environment, create the necessary context by signing in with the Azure CLI.
- An Azure OpenAI resource created in a supported region (see Region availability). For more information, see Create a resource and deploy a model with Azure OpenAI.
Microsoft Entra ID prerequisites
For the recommended keyless authentication with Microsoft Entra ID, you need to:
- Install the Azure CLI used for keyless authentication with Microsoft Entra ID.
- Assign the
Cognitive Services User
role to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Set up
Create a new folder
image-quickstart
and go to the quickstart folder with the following command:mkdir image-quickstart && cd image-quickstart
Create the
package.json
with the following command:npm init -y
Update the
package.json
to ECMAScript with the following command:npm pkg set type=module
Install the OpenAI client library for JavaScript with:
npm install openai
For the recommended passwordless authentication:
npm install @azure/identity
Retrieve resource information
You need to retrieve the following information to authenticate your application with your Azure OpenAI resource:
Variable name | Value |
---|---|
AZURE_OPENAI_ENDPOINT |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. |
AZURE_OPENAI_DEPLOYMENT_NAME |
This value will correspond to the custom name you chose for your deployment when you deployed a model. This value can be found under Resource Management > Model Deployments in the Azure portal. |
OPENAI_API_VERSION |
Learn more about API Versions. You can change the version in code or use an environment variable. |
Learn more about keyless authentication and setting environment variables.
Caution
To use the recommended keyless authentication with the SDK, make sure that the AZURE_OPENAI_API_KEY
environment variable isn't set.
Generate images with DALL-E
Create the
index.ts
file with the following code:import { AzureOpenAI } from "openai"; import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; // You will need to set these environment variables or edit the following values const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; // Required Azure OpenAI deployment name and API version const apiVersion = process.env.OPENAI_API_VERSION || "2024-07-01"; const deploymentName = process.env.AZURE_OPENAI_DEPLOYMENT_NAME || "dall-e-3"; // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://cognitiveservices.azure.com/.default"; const azureADTokenProvider = getBearerTokenProvider(credential, scope); function getClient(): AzureOpenAI { return new AzureOpenAI({ endpoint, azureADTokenProvider, apiVersion, deployment: deploymentName, }); } async function main() { console.log("== Image Generation =="); const client = getClient(); const results = await client.images.generate({ prompt, size: "1024x1024", n: numberOfImagesToGenerate, model: "", style: "vivid", // or "natural" }); for (const image of results.data) { console.log(`Image generation result URL: ${image.url}`); } } main().catch((err) => { console.error("The sample encountered an error:", err); });
Create the
tsconfig.json
file to transpile the TypeScript code and copy the following code for ECMAScript.{ "compilerOptions": { "module": "NodeNext", "target": "ES2022", // Supports top-level await "moduleResolution": "NodeNext", "skipLibCheck": true, // Avoid type errors from node_modules "strict": true // Enable strict type-checking options }, "include": ["*.ts"] }
Transpile from TypeScript to JavaScript.
tsc
Sign in to Azure with the following command:
az login
Run the code with the following command:
node index.js
Output
The URL of the generated image is printed to the console.
== Batch Image Generation ==
Image generation result URL: <SAS URL>
Image generation result URL: <SAS URL>
Note
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it won't return a generated image. For more information, see the content filter article.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource. Before deleting the resource, you must first delete any deployed models.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- For more examples check out the Azure OpenAI Samples GitHub repository.
Use this guide to get started generating images with the Azure OpenAI SDK for Go.
Library source code | Package | Samples
Prerequisites
- An Azure subscription - Create one for free
- Go 1.8+
- An Azure OpenAI resource created in a supported region (see Region availability). For more information, see Create a resource and deploy a model with Azure OpenAI.
Microsoft Entra ID prerequisites
For the recommended keyless authentication with Microsoft Entra ID, you need to:
- Install the Azure CLI used for keyless authentication with Microsoft Entra ID.
- Assign the
Cognitive Services User
role to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Set up
Create a new folder
dall-e-quickstart
and go to the quickstart folder with the following command:mkdir dall-e-quickstart && cd dall-e-quickstart
For the recommended keyless authentication with Microsoft Entra ID, sign in to Azure with the following command:
az login
Retrieve resource information
You need to retrieve the following information to authenticate your application with your Azure OpenAI resource:
Variable name | Value |
---|---|
AZURE_OPENAI_ENDPOINT |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. |
AZURE_OPENAI_DEPLOYMENT_NAME |
This value will correspond to the custom name you chose for your deployment when you deployed a model. This value can be found under Resource Management > Model Deployments in the Azure portal. |
OPENAI_API_VERSION |
Learn more about API Versions. You can change the version in code or use an environment variable. |
Learn more about keyless authentication and setting environment variables.
Run the quickstart
The sample code in this quickstart uses Microsoft Entra ID for the recommended keyless authentication. If you prefer to use an API key, you can replace the NewDefaultAzureCredential
implementation with NewKeyCredential
.
azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
credential, err := azidentity.NewDefaultAzureCredential(nil)
client, err := azopenai.NewClient(azureOpenAIEndpoint, credential, nil)
To run the sample:
Create a new file named quickstart.go. Copy the following code into the quickstart.go file.
package main import ( "context" "fmt" "net/http" "os" "log" "github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai" "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" ) func main() { azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT") modelDeploymentID := "dall-e-3" credential, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { log.Printf("ERROR: %s", err) return } client, err := azopenai.NewClient( azureOpenAIEndpoint, credential, nil) if err != nil { log.Printf("ERROR: %s", err) return } resp, err := client.GetImageGenerations(context.TODO(), azopenai.ImageGenerationOptions{ Prompt: to.Ptr("A painting of a cat in the style of Dali."), ResponseFormat: to.Ptr(azopenai.ImageGenerationResponseFormatURL), DeploymentName: to.Ptr(modelDeploymentID), }, nil) if err != nil { // Implement application specific error handling logic. log.Printf("ERROR: %s", err) return } for _, generatedImage := range resp.Data { // The underlying type for the generatedImage is determined by the value of // ImageGenerationOptions.ResponseFormat. // In this example we use `azopenai.ImageGenerationResponseFormatURL`, // so the underlying type will be ImageLocation. resp, err := http.Head(*generatedImage.URL) if err != nil { // Implement application specific error handling logic. log.Printf("ERROR: %s", err) return } fmt.Fprintf(os.Stderr, "Image generated, HEAD request on URL returned %d\nImage URL: %s\n", resp.StatusCode, *generatedImage.URL) } }
Run the following command to create a new Go module:
go mod init quickstart.go
Run
go mod tidy
to install the required dependencies:go mod tidy
Run the following command to run the sample:
go run quickstart.go
Output
The URL of the generated image is printed to the console.
Image generated, HEAD request on URL returned 200
Image URL: <SAS URL>
Note
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it won't return a generated image. For more information, see the content filter article.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- For more examples check out the Azure OpenAI Samples GitHub repository.
Use this guide to get started calling the Azure OpenAI Service image generation APIs with PowerShell.
Prerequisites
- An Azure subscription. Create one for free.
- For this task, the latest version of PowerShell 7 is recommended because the examples use new features not available in Windows PowerShell 5.1.
- An Azure OpenAI resource created in a supported region (see Region availability). For more information, see Create a resource and deploy a model with Azure OpenAI.
Microsoft Entra ID prerequisites
For the recommended keyless authentication with Microsoft Entra ID, you need to:
- Install the Azure CLI used for keyless authentication with Microsoft Entra ID.
- Assign the
Cognitive Services User
role to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Retrieve resource information
You need to retrieve the following information to authenticate your application with your Azure OpenAI resource:
Variable name | Value |
---|---|
AZURE_OPENAI_ENDPOINT |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. |
AZURE_OPENAI_DEPLOYMENT_NAME |
This value will correspond to the custom name you chose for your deployment when you deployed a model. This value can be found under Resource Management > Model Deployments in the Azure portal. |
OPENAI_API_VERSION |
Learn more about API Versions. You can change the version in code or use an environment variable. |
Learn more about keyless authentication and setting environment variables.
Generate images
For the recommended keyless authentication with Microsoft Entra ID, sign in to Azure with the following command:
az login
Create a new PowerShell file called quickstart.ps1. Then open it up in your preferred editor or IDE.
Replace the contents of quickstart.ps1 with the following code. Enter your endpoint URL and key in the appropriate fields. Change the value of
prompt
to your preferred text.# Azure OpenAI metadata variables $openai = @{ api_base = $Env:AZURE_OPENAI_ENDPOINT api_version = '2023-06-01-preview' # This can change in the future. } # Use the recommended keyless authentication via bearer token. $headers = [ordered]@{ #'api-key' = $Env:AZURE_OPENAI_API_KEY 'Authorization' = "Bearer $($Env:DEFAULT_AZURE_CREDENTIAL_TOKEN)" } # Text to describe image $prompt = 'A painting of a dog' # Adjust these values to fine-tune completions $body = [ordered]@{ prompt = $prompt size = '1024x1024' n = 1 } | ConvertTo-Json # Call the API to generate the image and retrieve the response $url = "$($openai.api_base)/openai/images/generations:submit?api-version=$($openai.api_version)" $submission = Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType 'application/json' -ResponseHeadersVariable submissionHeaders $operation_location = $submissionHeaders['operation-location'][0] $status = '' while ($status -ne 'succeeded') { Start-Sleep -Seconds 1 $response = Invoke-RestMethod -Uri $operation_location -Headers $headers $status = $response.status } # Set the directory for the stored image $image_dir = Join-Path -Path $pwd -ChildPath 'images' # If the directory doesn't exist, create it if (-not(Resolve-Path $image_dir -ErrorAction Ignore)) { New-Item -Path $image_dir -ItemType Directory } # Initialize the image path (note the filetype should be png) $image_path = Join-Path -Path $image_dir -ChildPath 'generated_image.png' # Retrieve the generated image $image_url = $response.result.data[0].url # extract image URL from response $generated_image = Invoke-WebRequest -Uri $image_url -OutFile $image_path # download the image return $image_path
Important
For production, use a secure way of storing and accessing your credentials like The PowerShell Secret Management with Azure Key Vault. For more information about credential security, see the Azure AI services security article.
Run the script using PowerShell:
./quickstart.ps1
The script loops until the generated image is ready.
Output
PowerShell requests the image from Azure OpenAI and stores the output image in the generated_image.png file in your specified directory. For convenience, the full path for the file is returned at the end of the script.
The image generation APIs come with a content moderation filter. If the service recognizes your prompt as harmful content, it doesn't generate an image. For more information, see Content filtering.
Clean up resources
If you want to clean up and remove an Azure OpenAI resource, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Next steps
- Explore the image generation APIs in more depth with the DALL-E how-to guide.
- Try examples in the Azure OpenAI Samples GitHub repository.