Skip to content

Commit fb30bfd

Browse files
committed
aoai via entra quickstarts in java
1 parent 35244a8 commit fb30bfd

File tree

1 file changed

+162
-67
lines changed

1 file changed

+162
-67
lines changed

articles/ai-services/openai/includes/dall-e-java.md

Lines changed: 162 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,12 @@
22
title: 'Quickstart: Use Azure OpenAI Service with the Java SDK to generate images'
33
titleSuffix: Azure OpenAI
44
description: Walkthrough on how to get started with Azure OpenAI and make your first image generation call with the Java SDK.
5-
#services: cognitive-services
65
manager: nitinme
76
ms.service: azure-ai-openai
87
ms.topic: include
98
author: PatrickFarley
109
ms.author: pafarley
11-
ms.date: 08/24/2023
10+
ms.date: 3/21/2025
1211
---
1312

1413
Use this guide to get started generating images with the Azure OpenAI SDK for Java.
@@ -19,103 +18,201 @@ Use this guide to get started generating images with the Azure OpenAI SDK for Ja
1918

2019
- An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services?azure-portal=true)
2120
- The current version of the [Java Development Kit (JDK)](https://www.microsoft.com/openjdk)
22-
- The [Gradle build tool](https://gradle.org/install/), or another dependency manager.
21+
- Install [Apache Maven](https://maven.apache.org/install.html).
2322
- An Azure OpenAI resource created in a supported region (see [Region availability](/azure/ai-services/openai/concepts/models#model-summary-table-and-region-availability)). For more information, see [Create a resource and deploy a model with Azure OpenAI](../how-to/create-resource.md).
2423

24+
### Microsoft Entra ID prerequisites
2525

26-
## Setup
26+
For the recommended keyless authentication with Microsoft Entra ID, you need to:
27+
- Install the [Azure CLI](/cli/azure/install-azure-cli) used for keyless authentication with Microsoft Entra ID.
28+
- 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**.
2729

28-
[!INCLUDE [get-key-endpoint](get-key-endpoint.md)]
30+
## Set up
2931

30-
[!INCLUDE [environment-variables](environment-variables.md)]
32+
1. Create a new folder `vision-quickstart` and go to that folder with the following command:
3133

34+
```shell
35+
mkdir vision-quickstart && cd vision-quickstart
36+
```
3237

33-
## Create a new Java application
38+
1. Install [Apache Maven](https://maven.apache.org/install.html). Then run `mvn -v` to confirm successful installation.
39+
1. Create a new `pom.xml` file in the root of your project, and copy the following code into it:
40+
41+
```xml
42+
<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">
43+
<modelVersion>4.0.0</modelVersion>
44+
<groupId>com.azure.samples</groupId>
45+
<artifactId>quickstart-dall-e</artifactId>
46+
<version>1.0.0-SNAPSHOT</version>
47+
<build>
48+
<sourceDirectory>src</sourceDirectory>
49+
<plugins>
50+
<plugin>
51+
<artifactId>maven-compiler-plugin</artifactId>
52+
<version>3.7.0</version>
53+
<configuration>
54+
<source>1.8</source>
55+
<target>1.8</target>
56+
</configuration>
57+
</plugin>
58+
</plugins>
59+
</build>
60+
<dependencies>
61+
<dependency>
62+
<groupId>com.azure</groupId>
63+
<artifactId>azure-ai-openai</artifactId>
64+
<version>1.0.0-beta.3</version>
65+
</dependency>
66+
<dependency>
67+
<groupId>com.azure</groupId>
68+
<artifactId>azure-core</artifactId>
69+
<version>1.53.0</version>
70+
</dependency>
71+
<dependency>
72+
<groupId>com.azure</groupId>
73+
<artifactId>azure-identity</artifactId>
74+
<version>1.15.1</version>
75+
</dependency>
76+
<dependency>
77+
<groupId>org.slf4j</groupId>
78+
<artifactId>slf4j-simple</artifactId>
79+
<version>1.7.9</version>
80+
</dependency>
81+
</dependencies>
82+
</project>
83+
```
3484

35-
Create a new Gradle project.
85+
1. Install the Azure OpenAI SDK and dependencies.
3686

37-
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
87+
```console
88+
mvn clean dependency:copy-dependencies
89+
```
3890

39-
```console
40-
mkdir myapp && cd myapp
41-
```
91+
1. For the **recommended** keyless authentication with Microsoft Entra ID, sign in to Azure with the following command:
4292

43-
Run the `gradle init` command from your working directory. This command will create essential build files for Gradle, including *build.gradle.kts*, which is used at runtime to create and configure your application.
93+
```console
94+
az login
95+
```
4496

45-
```console
46-
gradle init --type basic
47-
```
4897

49-
When prompted to choose a **DSL**, select **Kotlin**.
98+
## Retrieve resource information
99+
100+
[!INCLUDE [resource authentication](resource-authentication.md)]
50101

51-
## Install the Java SDK
102+
## Run the app
52103

104+
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.
53105

54-
This quickstart uses the Gradle dependency manager. You can find the client library and information for other dependency managers on the [Maven Central Repository](https://search.maven.org/artifact/com.microsoft.azure.cognitiveservices/azure-cognitiveservices-computervision).
106+
#### [Microsoft Entra ID](#tab/keyless)
107+
108+
```java
109+
OpenAIAsyncClient client = new OpenAIClientBuilder()
110+
.endpoint(endpoint)
111+
.credential(new DefaultAzureCredentialBuilder().build())
112+
.buildAsyncClient();
113+
```
55114
56-
Locate *build.gradle.kts* and open it with your preferred IDE or text editor. Then copy in the following build configuration. This configuration defines the project as a Java application whose entry point is the class **OpenAIQuickstart**. It imports the Azure AI Vision library.
115+
#### [API key](#tab/api-key)
57116
58-
```kotlin
59-
plugins {
60-
java
61-
application
62-
}
63-
application {
64-
mainClass.set("OpenAIQuickstart")
65-
}
66-
repositories {
67-
mavenCentral()
68-
}
69-
dependencies {
70-
implementation(group = "com.azure", name = "azure-ai-openai", version = "1.0.0-beta.3")
71-
implementation("org.slf4j:slf4j-simple:1.7.9")
72-
}
117+
```java
118+
OpenAIAsyncClient client = new OpenAIClientBuilder()
119+
.endpoint(endpoint)
120+
.credential(new AzureKeyCredential(key))
121+
.buildAsyncClient();
73122
```
123+
---
124+
125+
#### [Microsoft Entra ID](#tab/keyless)
126+
127+
Follow these steps to create a console application for speech recognition.
128+
129+
1. Create a new file named *Quickstart.java* in the same project root directory.
130+
1. Copy the following code into *Quickstart.java*:
74131
75-
## Generate images with DALL-E
132+
```java
133+
import com.azure.ai.openai.OpenAIAsyncClient;
134+
import com.azure.ai.openai.OpenAIClientBuilder;
135+
import com.azure.ai.openai.models.ImageGenerationOptions;
136+
import com.azure.ai.openai.models.ImageLocation;
137+
import com.azure.core.credential.AzureKeyCredential;
138+
import com.azure.core.models.ResponseError;
139+
140+
import java.util.concurrent.TimeUnit;
141+
142+
public class Quickstart {
76143
77-
1. Create a Java file.
144+
public static void main(String[] args) throws InterruptedException {
145+
146+
String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");
147+
148+
// Use the recommended keyless credential instead of the AzureKeyCredential credential.
149+
150+
OpenAIAsyncClient client = new OpenAIClientBuilder()
151+
.endpoint(endpoint)
152+
.credential(new DefaultAzureCredentialBuilder().build())
153+
.buildAsyncClient();
154+
155+
ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions(
156+
"A drawing of the Seattle skyline in the style of Van Gogh");
157+
client.getImages(imageGenerationOptions).subscribe(
158+
images -> {
159+
for (ImageLocation imageLocation : images.getData()) {
160+
ResponseError error = imageLocation.getError();
161+
if (error != null) {
162+
System.out.printf("Image generation operation failed. Error code: %s, error message: %s.%n",
163+
error.getCode(), error.getMessage());
164+
} else {
165+
System.out.printf(
166+
"Image location URL that provides temporary access to download the generated image is %s.%n",
167+
imageLocation.getUrl());
168+
}
169+
}
170+
},
171+
error -> System.err.println("There was an error getting images." + error),
172+
() -> System.out.println("Completed getImages."));
173+
174+
// The .subscribe() creation and assignment isn't a blocking call.
175+
// The thread sleeps so the program does not end before the send operation is complete.
176+
// Use .block() instead of .subscribe() for a synchronous call.
177+
TimeUnit.SECONDS.sleep(10);
178+
}
179+
}
180+
```
78181
79-
From your working directory, run the following command to create a project source folder:
182+
1. Run your new console application to generate an image:
80183
81184
```console
82-
mkdir -p src/main/java
185+
javac Quickstart.java -cp ".;target\dependency\*"
186+
java -cp ".;target\dependency\*" Quickstart
83187
```
84188
85-
Navigate to the new folder and create a file called *OpenAIQuickstart.java*.
189+
#### [API key](#tab/api-key)
86190
191+
Follow these steps to create a console application for speech recognition.
87192
88-
1. Open *OpenAIQuickstart.java* in your preferred editor or IDE and paste in the following code.
193+
1. Create a new file named *Quickstart.java* in the same project root directory.
194+
1. Copy the following code into *Quickstart.java*:
89195
90196
```java
91197
import com.azure.ai.openai.OpenAIAsyncClient;
92198
import com.azure.ai.openai.OpenAIClientBuilder;
93199
import com.azure.ai.openai.models.ImageGenerationOptions;
94200
import com.azure.ai.openai.models.ImageLocation;
95-
import com.azure.core.credential.AzureKeyCredential;
201+
import com.azure.identity.DefaultAzureCredentialBuilder;
96202
import com.azure.core.models.ResponseError;
97203
98204
import java.util.concurrent.TimeUnit;
99205
100-
/**
101-
* Sample demonstrates how to get the images for a given prompt.
102-
*/
103-
public class OpenAIQuickstart {
206+
public class Quickstart {
104207
105-
/**
106-
* Runs the sample algorithm and demonstrates how to get the images for a given prompt.
107-
*
108-
* @param args Unused. Arguments to the program.
109-
*/
110208
public static void main(String[] args) throws InterruptedException {
111209
112-
// Get key and endpoint from environment variables:
113-
String azureOpenaiKey = System.getenv("AZURE_OPENAI_API_KEY");
210+
String key = System.getenv("AZURE_OPENAI_API_KEY");
114211
String endpoint = System.getenv("AZURE_OPENAI_ENDPOINT");
115212
116213
OpenAIAsyncClient client = new OpenAIClientBuilder()
117214
.endpoint(endpoint)
118-
.credential(new AzureKeyCredential(azureOpenaiKey))
215+
.credential(new AzureKeyCredential(key))
119216
.buildAsyncClient();
120217
121218
ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions(
@@ -137,25 +234,23 @@ dependencies {
137234
error -> System.err.println("There was an error getting images." + error),
138235
() -> System.out.println("Completed getImages."));
139236
140-
// The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep
141-
// the thread so the program does not end before the send operation is complete. Using .block() instead of
142-
// .subscribe() will turn this into a synchronous call.
237+
// The .subscribe() creation and assignment isn't a blocking call.
238+
// The thread sleeps so the program does not end before the send operation is complete.
239+
// Use .block() instead of .subscribe() for a synchronous call.
143240
TimeUnit.SECONDS.sleep(10);
144241
}
145242
}
146243
```
147244
148-
1. Navigate back to the project root folder, and build the app with:
245+
1. Run your new console application to generate an image:
246+
247+
```console
248+
javac Quickstart.java -cp ".;target\dependency\*"
249+
java -cp ".;target\dependency\*" Quickstart
250+
```
251+
252+
---
149253
150-
```console
151-
gradle build
152-
```
153-
154-
Then, run it with the `gradle run` command:
155-
156-
```console
157-
gradle run
158-
```
159254
160255
161256
## Output

0 commit comments

Comments
 (0)