Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Azure OpenAI image generation models
Important
The DALL-E image generation model dall-e-3 was retired on March 4, 2026, and is no longer available for new deployments. Existing deployments are non-functional. Use gpt-image-1 or gpt-image-1.5 for image generation instead. See the image generation how-to guide for updated instructions.
OpenAI's image generation models create images from user-provided text prompts and optional images. This article explains how to use these models, configure options, and benefit from advanced image generation capabilities in Azure.
You can do image generation via image generation API or responses API. Or you can experiment with image generation in the Foundry portal
Use the tabs at the start of this page to select your preferred API approach and model.
Models and capabilities
Use this table to learn the differences between the different image generation models, and to help you choose the best model for your image generation needs.
| Aspect | GPT-Image-1.5 | GPT-Image-1 | GPT-Image-1-Mini |
|---|---|---|---|
| Availability | Limited access preview (Apply for GPT-image-1.5 access) | Limited access preview (Apply for GPT-image-1 access) | Limited access preview (Apply for GPT-image-1 access) |
| Strengths | Best for realism, instruction following, multimodal context, and improved speed/cost | Best for realism, instruction following, and multimodal context | Best for fast prototyping, bulk generation, or cost-sensitive use cases |
| Input / Output Modalities & Format | Accepts text + image inputs; outputs images only in base64 (no URL option). | Accepts text + image inputs; outputs images only in base64 (no URL option). | Accepts text + image inputs; outputs images only in base64 (no URL option). |
| Image Sizes / Resolutions | 1024×1024, 1024×1536, 1536×1024 | 1024×1024, 1024×1536, 1536×1024 | 1024×1024, 1024×1536, 1536×1024 |
| Quality Options | low, medium, high (default = high) |
low, medium, high (default = high) |
low, medium, high (default = medium) |
| Number of Images per Request | 1–10 images per request (n parameter) |
1–10 images per request (n parameter) |
1–10 images per request (n parameter) |
| Editing (inpainting / variations) | ✅ Supports inpainting and variations with mask + prompt | ✅ Supports inpainting and variations with mask + prompt | ✅ Supports inpainting and variations with mask + prompt |
| Face Preservation | ✅ Advanced face preservation for realistic, consistent results | ✅ Advanced face preservation for realistic, consistent results | ❌ No dedicated face preservation; better for non-portrait/general creative imagery |
| Performance & Cost | High-fidelity, realism-optimized model; improved efficiency and latency over GPT-Image-1 | High-fidelity, realism-optimized model; higher latency and cost | Cost-efficient and faster for large-scale or iterative generation |
Quickstart
Use this guide to get started calling the Azure OpenAI in Microsoft Foundry Models 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
gpt-image-1-series 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 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"
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_API_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
export AZURE_OPENAI_API_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE"
export 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
promptto your preferred text. Also setdeploymentto the deployment name you chose when you deployed the GPT-image-1 series model.import os import requests import base64 from PIL import Image from io import BytesIO # set environment variables endpoint = os.getenv("AZURE_OPENAI_ENDPOINT") subscription_key = os.getenv("AZURE_OPENAI_API_KEY") deployment = "gpt-image-1.5" # the name of your GPT-image-1 series deployment api_version = "2025-04-01-preview" # or later version def decode_and_save_image(b64_data, output_filename): image = Image.open(BytesIO(base64.b64decode(b64_data))) image.show() image.save(output_filename) def save_all_images_from_response(response_data, filename_prefix): for idx, item in enumerate(response_data['data']): b64_img = item['b64_json'] filename = f"{filename_prefix}_{idx+1}.png" decode_and_save_image(b64_img, filename) print(f"Image saved to: '{filename}'") base_path = f'openai/deployments/{deployment}/images' params = f'?api-version={api_version}' generation_url = f"{endpoint}{base_path}/generations{params}" generation_body = { "prompt": "girl falling asleep", "n": 1, "size": "1024x1024", "quality": "medium", "output_format": "png" } generation_response = requests.post( generation_url, headers={ 'Api-Key': subscription_key, 'Content-Type': 'application/json', }, json=generation_body ).json() save_all_images_from_response(generation_response, "generated_image") # In addition to generating images, you can edit them. edit_url = f"{endpoint}{base_path}/edits{params}" edit_body = { "prompt": "girl falling asleep", "n": 1, "size": "1024x1024", "quality": "medium" } files = { "image": ("generated_image_1.png", open("generated_image_1.png", "rb"), "image/png"), # You can use a mask to specify which parts of the image you want to edit. # The mask must be the same size as the input image. # "mask": ("mask.png", open("mask.png", "rb"), "image/png"), } edit_response = requests.post( edit_url, headers={'Api-Key': subscription_key}, data=edit_body, files=files ).json() save_all_images_from_response(edit_response, "edited_image")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
pythoncommand:python quickstart.pyWait a few moments to get the response.
Output
The output from a successful image generation API call looks like the following example. The b64_json field contains the base64-encoded output image data.
{
"created": 1698116662,
"data": [
{
"b64_json": "<base64 image data>"
}
]
}
A successful response includes:
- A
createdtimestamp (Unix epoch time) - A
dataarray with at least one image object- Either ab64_json(base64-encoded image data) value for each generated image
Common errors
| Error | Cause | Resolution |
|---|---|---|
DeploymentNotFound |
The deployment name doesn't exist or is misspelled | Verify the deployment name in the Azure portal or Foundry portal |
401 Unauthorized |
Invalid or missing API key | Check that your AZURE_OPENAI_API_KEY environment variable is set correctly |
429 Too Many Requests |
Rate limit exceeded | Implement retry logic with exponential backoff |
content_policy_violation |
Prompt or generated output blocked by content filter | Modify the prompt to comply with the content policy |
InvalidPayload |
Missing required parameters or invalid values | Check that prompt, size, and n are correctly specified |
The Image 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 Image generation 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.
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.
- Access the Azure OpenAI resource endpoint and keys in the Azure portal.
- A deployed image generation model:
- GPT-image-1 series: Deploy a
gpt-image-1-series model. Available in limited access. - GPT-image-1 series: Deploy a
gpt-image-1model. Requires limited access registration.
- GPT-image-1 series: Deploy a
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 Microsoft 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"
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_API_KEY', 'REPLACE_WITH_YOUR_KEY_VALUE_HERE', 'User')
[System.Environment]::SetEnvironmentVariable('AZURE_OPENAI_ENDPOINT', 'REPLACE_WITH_YOUR_ENDPOINT_HERE', 'User')
export AZURE_OPENAI_API_KEY="REPLACE_WITH_YOUR_KEY_VALUE_HERE"
export 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
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="2025-04-01-preview",
api_key=os.environ["AZURE_OPENAI_API_KEY"],
azure_endpoint=os.environ['AZURE_OPENAI_ENDPOINT']
)
result = client.images.generate(
model="gpt-image-1", # the name of your GPT-image-1 series deployment
prompt="a close-up of a bear walking through the 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()
- Make sure the
AZURE_OPENAI_ENDPOINTandAZURE_OPENAI_API_KEYenvironment variables are set. - Change the value of
promptto your preferred text. - Change the value of
modelto the name of your deployed GPT-image-1 series 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.
A successful response includes:
- A
createdtimestamp - A
dataarray with at least one image object - Either a
url(temporary link valid for 24 hours) orb64_json(base64-encoded image data)
Common errors
| Error | Cause | Resolution |
|---|---|---|
DeploymentNotFound |
The deployment name doesn't exist or is misspelled | Verify the deployment name in the Azure portal or Foundry portal |
AuthenticationError |
Invalid or missing API key | Check that your AZURE_OPENAI_API_KEY environment variable is set correctly |
RateLimitError |
Rate limit exceeded | Implement retry logic with exponential backoff |
content_policy_violation |
Prompt or generated output blocked by content filter | Modify the prompt to comply with the content policy |
The Image 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.
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 Userrole 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-quickstartand go to the quickstart folder with the following command:mkdir image-quickstart && cd image-quickstartCreate a new console application with the following command:
dotnet new consoleInstall the OpenAI .NET client library with the dotnet add package command:
dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.6For the recommended keyless authentication with Microsoft Entra ID, install the Azure.Identity package with:
dotnet add package Azure.IdentityFor 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. |
Learn more about keyless authentication and setting environment variables.
| 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_API_KEY |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. You can use either KEY1 or KEY2. |
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. |
Learn more about finding API keys and setting environment variables.
Important
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If you use an API key, store it securely in Azure Key Vault. 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.
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());
AzureOpenAIClient openAIClient = new AzureOpenAIClient(new Uri(endpoint), new AzureKeyCredential(key));
To run the quickstart, follow these steps:
Replace the contents of
Program.cswith 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("gpt-image-1"); 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 runcommand 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 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.
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 Userrole 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-quickstartand go to the quickstart folder with the following command:mkdir image-quickstart && cd image-quickstartInstall Apache Maven. Then run
mvn -vto confirm successful installation.Create a new
pom.xmlfile 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-image-generation</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-dependenciesFor 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. |
Learn more about keyless authentication and setting environment variables.
| 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_API_KEY |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. You can use either KEY1 or KEY2. |
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. |
Learn more about finding API keys and setting environment variables.
Important
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If you use an API key, store it securely in Azure Key Vault. 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.
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();
OpenAIAsyncClient client = new OpenAIClientBuilder()
.endpoint(endpoint)
.credential(new AzureKeyCredential(key))
.buildAsyncClient();
Follow these steps to create a console application for image generation.
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
Follow these steps to create a console application for image generation.
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.identity.DefaultAzureCredentialBuilder; import com.azure.core.models.ResponseError; import java.util.concurrent.TimeUnit; public class Quickstart { public static void main(String[] args) throws InterruptedException { String key = System.getenv("AZURE_OPENAI_API_KEY"); String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT"); OpenAIAsyncClient client = new OpenAIClientBuilder() .endpoint(endpoint) .credential(new AzureKeyCredential(key)) .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 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.
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 Userrole to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Setup
Create a new folder
image-quickstartand go to the quickstart folder with the following command:mkdir image-quickstart && cd image-quickstartCreate the
package.jsonwith the following command:npm init -yInstall the OpenAI client library for JavaScript with:
npm install openaiFor 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. |
Learn more about keyless authentication and setting environment variables.
| 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_API_KEY |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. You can use either KEY1 or KEY2. |
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. |
Learn more about finding API keys and setting environment variables.
Important
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If you use an API key, store it securely in Azure Key Vault. 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.
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
Create the
index.jsfile 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 || "gpt-image-1"; // 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://ai.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 loginRun the JavaScript file.
node index.js
Create the
index.jsfile with the following code:const { AzureOpenAI } = require("openai"); // You will need to set these environment variables or edit the following values const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; const apiKey = process.env.AZURE_OPENAI_API_KEY || "Your API key"; // 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 || "gpt-image-1"; // The prompt to generate images from const prompt = "a monkey eating a banana"; const numberOfImagesToGenerate = 1; function getClient() { return new AzureOpenAI({ endpoint, apiKey, 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); });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 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.
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 Userrole to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Setup
Create a new folder
image-quickstartand go to the quickstart folder with the following command:mkdir image-quickstart && cd image-quickstartCreate the
package.jsonwith the following command:npm init -yUpdate the
package.jsonto ECMAScript with the following command:npm pkg set type=moduleInstall the OpenAI client library for JavaScript with:
npm install openaiFor 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. |
Learn more about keyless authentication and setting environment variables.
| 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_API_KEY |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. You can use either KEY1 or KEY2. |
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. |
Learn more about finding API keys and setting environment variables.
Important
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If you use an API key, store it securely in Azure Key Vault. 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.
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
Create the
index.tsfile 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 || "gpt-image-1"; // keyless authentication const credential = new DefaultAzureCredential(); const scope = "https://ai.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.jsonfile 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.
tscSign in to Azure with the following command:
az loginRun the code with the following command:
node index.js
Create the
index.tsfile with the following code:import { AzureOpenAI } from "openai"; // You will need to set these environment variables or edit the following values const endpoint = process.env.AZURE_OPENAI_ENDPOINT || "Your endpoint"; const apiKey = process.env.AZURE_OPENAI_API_KEY || "Your API key"; // 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 || "gpt-image-1"; // The prompt to generate images from const prompt = "a monkey eating a banana"; const numberOfImagesToGenerate = 1; function getClient(): AzureOpenAI { return new AzureOpenAI({ endpoint, apiKey, 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.jsonfile 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.
tscRun 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 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.
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 Userrole to your user account. You can assign roles in the Azure portal under Access control (IAM) > Add role assignment.
Setup
Create a new folder
dall-e-quickstartand go to the quickstart folder with the following command:mkdir dall-e-quickstart && cd dall-e-quickstartFor 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. |
Learn more about keyless authentication and setting environment variables.
| 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_API_KEY |
This value can be found in the Keys and Endpoint section when examining your resource from the Azure portal. You can use either KEY1 or KEY2. |
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. |
Learn more about finding API keys and setting environment variables.
Important
Use API keys with caution. Don't include the API key directly in your code, and never post it publicly. If you use an API key, store it securely in Azure Key Vault. 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.
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)
azureOpenAIEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
azureOpenAIKey := os.Getenv("AZURE_OPENAI_API_KEY")
credential := azcore.NewKeyCredential(azureOpenAIKey)
client, err := azopenai.NewClientWithKeyCredential(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/azur
