Skip to content

Commit 09a6487

Browse files
Merge pull request #7455 from MicrosoftDocs/main
Auto Publish – main to live - 2025-10-02 22:09 UTC
2 parents 85061d8 + 7c4dd21 commit 09a6487

File tree

2 files changed

+68
-261
lines changed

2 files changed

+68
-261
lines changed

articles/ai-foundry/openai/api-version-lifecycle.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ Previously, Azure OpenAI received monthly updates of new API versions. Taking ad
2727

2828
Starting in August 2025, you can now opt in to our next generation v1 Azure OpenAI APIs which add support for:
2929

30-
- Ongoing access to the latest features with no need specify new `api-version`'s each month.
30+
- Ongoing access to the latest features with no need to specify new `api-version`'s each month.
3131
- Faster API release cycle with new features launching more frequently.
3232
- OpenAI client support with minimal code changes to swap between OpenAI and Azure OpenAI when using key-based authentication.
3333
- OpenAI client support for token based authentication and automatic token refresh without the need to take a dependency on a separate Azure OpenAI client.
@@ -208,6 +208,8 @@ client := openai.NewClient(
208208

209209
# [Java](#tab/Java)
210210

211+
[Java v1 examples](./supported-languages.md)
212+
211213
### v1 API
212214

213215
**API Key**:
@@ -216,7 +218,7 @@ client := openai.NewClient(
216218

217219
OpenAIClient client = OpenAIOkHttpClient.builder()
218220
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
219-
.credential(AzureApiKeyCredential.create("{your-api-key}"))
221+
.apiKey(apiKey)
220222
.build();
221223
```
222224

articles/ai-foundry/openai/includes/language-overview/java.md

Lines changed: 64 additions & 259 deletions
Original file line numberDiff line numberDiff line change
@@ -6,42 +6,36 @@ manager: nitinme
66
ms.service: azure-ai-foundry
77
ms.subservice: azure-ai-foundry-openai
88
ms.topic: include
9-
ms.date: 03/27/2025
9+
ms.date: 10/02/2025
1010
---
1111

1212

13-
[Source code](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/openai/azure-ai-openai) | [Artifact (Maven)](https://central.sonatype.com/artifact/com.azure/azure-ai-openai/1.0.0-beta.12) | [API reference documentation](../../reference.md) | [Package reference documentation](/java/api/overview/azure/ai-openai-readme?view=azure-java-preview&preserve-view=true) [Samples](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/openai/azure-ai-openai/src/samples)
13+
[Source code](https://github.com/openai/openai-java/blob/main/README.md) |[REST API reference documentation](../../latest.md) | [Package reference documentation](https://javadoc.io/doc/com.openai/openai-java/latest/index.html) | [Maven Central](https://central.sonatype.com/artifact/com.openai/openai-java/4.0.1)
1414

1515
## Azure OpenAI API version support
1616

17-
Unlike the Azure OpenAI client libraries for Python and JavaScript, to ensure compatibility the Azure OpenAI Java package is limited to targeting a specific subset of the Azure OpenAI API versions. Generally each Azure OpenAI Java package unlocks access to newer Azure OpenAI API release features. Having access to the latest API versions impacts feature availability.
17+
- v1 Generally Available (GA) API now allows access to both GA and Preview operations. To learn more, see the [API version lifecycle guide](../../api-version-lifecycle.md).
1818

19-
Version selection is controlled by the [`OpenAIServiceVersion`](/java/api/com.azure.ai.openai.openaiserviceversion?view=azure-java-preview&preserve-view=true) enum.
20-
21-
The latest Azure OpenAI preview API supported is:
22-
23-
-`2025-01-01-preview`
24-
25-
The latest stable (GA) release supported is:
19+
## Installation
2620

27-
-`2024-06-01`
21+
### Gradle
2822

29-
## Installation
23+
```kotlin
24+
implementation("com.openai:openai-java:4.0.1")
25+
```
3026

31-
### Package details
27+
### Maven
3228

33-
```XML
29+
```xml
3430
<dependency>
35-
<groupId>com.azure</groupId>
36-
<artifactId>azure-ai-openai</artifactId>
37-
<version>1.0.0-beta.16</version>
31+
<groupId>com.openai</groupId>
32+
<artifactId>openai-java</artifactId>
33+
<version>4.0.1</version>
3834
</dependency>
3935
```
4036

4137
## Authentication
4238

43-
In order to interact with the Azure OpenAI in Azure AI Foundry Models you'll need to create an instance of client class, [`OpenAIAsyncClient`](https://github.com/Azure/azure-sdk-for-java/blob/azure-ai-openai_1.0.0-beta.12/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIAsyncClient.java) or [`OpenAIClient`](https://github.com/Azure/azure-sdk-for-java/blob/azure-ai-openai_1.0.0-beta.12/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIClient.java) by using [`OpenAIClientBuilder`](https://github.com/Azure/azure-sdk-for-java/blob/azure-ai-openai_1.0.0-beta.12/sdk/openai/azure-ai-openai/src/main/java/com/azure/ai/openai/OpenAIClientBuilder.java). To configure a client for use with Azure OpenAI, provide a valid endpoint URI to an Azure OpenAI resource along with a corresponding key credential, token credential, or Azure Identity credential that's authorized to use the Azure OpenAI resource.
44-
4539
# [Microsoft Entra ID](#tab/secure)
4640

4741
Authentication with Microsoft Entra ID requires some initial setup:
@@ -52,264 +46,75 @@ Add the Azure Identity package:
5246
<dependency>
5347
<groupId>com.azure</groupId>
5448
<artifactId>azure-identity</artifactId>
55-
<version>1.13.3</version>
49+
<version>1.18.0</version>
5650
</dependency>
5751
```
5852

5953
After setup, you can choose which type of credential from `azure.identity` to use. As an example, `DefaultAzureCredential` can be used to authenticate the client: Set the values of the client ID, tenant ID, and client secret of the Microsoft Entra ID application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET.
6054

61-
Authorization is easiest using DefaultAzureCredential. It finds the best credential to use in its running environment.
55+
Authorization is easiest using `DefaultAzureCredential`. It finds the best credential to use in its running environment though use of `DefaultAzureCredential` is only recommended for testing, not for production.
6256

6357
```java
64-
TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
65-
OpenAIClient client = new OpenAIClientBuilder()
66-
.credential(defaultCredential)
67-
.endpoint("{endpoint}")
68-
.buildClient();
58+
Credential tokenCredential = BearerTokenCredential.create(
59+
AuthenticationUtil.getBearerTokenSupplier(
60+
new DefaultAzureCredentialBuilder().build(),
61+
"https://cognitiveservices.azure.com/.default"));
62+
OpenAIClient client = OpenAIOkHttpClient.builder()
63+
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
64+
.credential(tokenCredential)
65+
.build();
6966
```
7067

71-
For more information about Azure OpenAI keyless authentication, see [Use Azure OpenAI without keys](/azure/developer/ai/keyless-connections?tabs=java%2Cazure-cli).
68+
For more information about Azure OpenAI keyless authentication, see [Use Azure OpenAI without keys](/azure/developer/ai/keyless-connections?tabs=java%2Cazure-cli).
7269

7370
# [API Key](#tab/api-key)
7471

7572
```java
76-
OpenAIClient client = new OpenAIClientBuilder()
77-
.credential(new AzureKeyCredential("{key}"))
78-
.endpoint("{endpoint}")
79-
.buildClient();
80-
```
81-
82-
Async
83-
84-
```java
85-
OpenAIAsyncClient client = new OpenAIClientBuilder()
86-
.credential(new AzureKeyCredential("{key}"))
87-
.endpoint("{endpoint}")
88-
.buildAsyncClient();
73+
OpenAIClient client = OpenAIOkHttpClient.builder()
74+
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
75+
.apiKey(apiKey)
76+
.build();
8977
```
9078

9179
---
9280

93-
## Audio
94-
95-
### client.getAudioTranscription
96-
97-
```java
98-
String fileName = "{your-file-name}";
99-
Path filePath = Paths.get("{your-file-path}" + fileName);
100-
101-
byte[] file = BinaryData.fromFile(filePath).toBytes();
102-
AudioTranscriptionOptions transcriptionOptions = new AudioTranscriptionOptions(file)
103-
.setResponseFormat(AudioTranscriptionFormat.JSON);
104-
105-
AudioTranscription transcription = client.getAudioTranscription("{deploymentOrModelName}", fileName, transcriptionOptions);
106-
107-
System.out.println("Transcription: " + transcription.getText());
108-
```
109-
110-
### client.generateSpeechFromText
111-
112-
**Text to speech (TTS)**
113-
114-
```java
115-
String deploymentOrModelId = "{azure-open-ai-deployment-model-id}";
116-
SpeechGenerationOptions options = new SpeechGenerationOptions(
117-
"Today is a wonderful day to build something people love!",
118-
SpeechVoice.ALLOY);
119-
BinaryData speech = client.generateSpeechFromText(deploymentOrModelId, options);
120-
// Checkout your generated speech in the file system.
121-
Path path = Paths.get("{your-local-file-path}/speech.wav");
122-
Files.write(path, speech.toBytes());
123-
```
124-
125-
## Chat
126-
127-
### client.getChatCompletions
128-
129-
```java
130-
List<ChatRequestMessage> chatMessages = new ArrayList<>();
131-
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."));
132-
chatMessages.add(new ChatRequestUserMessage("Can you help me?"));
133-
chatMessages.add(new ChatRequestAssistantMessage("Of course, me hearty! What can I do for ye?"));
134-
chatMessages.add(new ChatRequestUserMessage("What's the best way to train a parrot?"));
135-
136-
ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}",
137-
new ChatCompletionsOptions(chatMessages));
138-
139-
System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
140-
for (ChatChoice choice : chatCompletions.getChoices()) {
141-
ChatResponseMessage message = choice.getMessage();
142-
System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
143-
System.out.println("Message:");
144-
System.out.println(message.getContent());
145-
}
146-
```
147-
148-
### Streaming
149-
150-
```java
151-
List<ChatRequestMessage> chatMessages = new ArrayList<>();
152-
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."));
153-
chatMessages.add(new ChatRequestUserMessage("Can you help me?"));
154-
chatMessages.add(new ChatRequestAssistantMessage("Of course, me hearty! What can I do for ye?"));
155-
chatMessages.add(new ChatRequestUserMessage("What's the best way to train a parrot?"));
156-
157-
ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}",
158-
new ChatCompletionsOptions(chatMessages));
159-
160-
System.out.printf("Model ID=%s is created at %s.%n", chatCompletions.getId(), chatCompletions.getCreatedAt());
161-
for (ChatChoice choice : chatCompletions.getChoices()) {
162-
ChatResponseMessage message = choice.getMessage();
163-
System.out.printf("Index: %d, Chat Role: %s.%n", choice.getIndex(), message.getRole());
164-
System.out.println("Message:");
165-
System.out.println(message.getContent());
166-
}
167-
```
168-
169-
### Chat completions with images
170-
171-
```java
172-
List<ChatRequestMessage> chatMessages = new ArrayList<>();
173-
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant that describes images"));
174-
chatMessages.add(new ChatRequestUserMessage(Arrays.asList(
175-
new ChatMessageTextContentItem("Please describe this image"),
176-
new ChatMessageImageContentItem(
177-
new ChatMessageImageUrl("https://raw.githubusercontent.com/MicrosoftDocs/azure-ai-docs/main/articles/ai-services/openai/media/how-to/generated-seattle.png"))
178-
)));
179-
180-
ChatCompletionsOptions chatCompletionsOptions = new ChatCompletionsOptions(chatMessages);
181-
ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}", chatCompletionsOptions);
182-
183-
System.out.println("Chat completion: " + chatCompletions.getChoices().get(0).getMessage().getContent());
184-
```
185-
186-
## Embeddings
187-
188-
### client.getEmbeddings
81+
## Responses
18982

19083
```java
191-
EmbeddingsOptions embeddingsOptions = new EmbeddingsOptions(
192-
Arrays.asList("Your text string goes here"));
193-
194-
Embeddings embeddings = client.getEmbeddings("{deploymentOrModelName}", embeddingsOptions);
195-
196-
for (EmbeddingItem item : embeddings.getData()) {
197-
System.out.printf("Index: %d.%n", item.getPromptIndex());
198-
for (Float embedding : item.getEmbedding()) {
199-
System.out.printf("%f;", embedding);
84+
package com.example;
85+
86+
import com.openai.client.OpenAIClient;
87+
import com.openai.client.okhttp.OpenAIOkHttpClient;
88+
import com.openai.models.ChatModel;
89+
import com.openai.models.responses.Response;
90+
import com.openai.models.responses.ResponseCreateParams;
91+
import com.azure.core.credential.AzureKeyCredential;
92+
93+
public class OpenAITest {
94+
public static void main(String[] args) {
95+
// Get API key from environment variable for security
96+
String apiKey = System.getenv("OPENAI_API_KEY");
97+
String resourceName = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
98+
String modelDeploymentName = "gpt-4.1"; //replace with you model deployment name
99+
100+
try {
101+
OpenAIClient client = OpenAIOkHttpClient.builder()
102+
.baseUrl(resourceName)
103+
.apiKey(apiKey)
104+
.build();
105+
106+
ResponseCreateParams params = ResponseCreateParams.builder()
107+
.input("Tell me about the bitter lesson?")
108+
.model(modelDeploymentName)
109+
.build();
110+
111+
Response response = client.responses().create(params);
112+
113+
System.out.println("Response: " + response);
114+
} catch (Exception e) {
115+
System.err.println("Error: " + e.getMessage());
116+
e.printStackTrace();
117+
}
200118
}
201119
}
202-
```
203-
204-
## Image generation
205-
206-
```java
207-
ImageGenerationOptions imageGenerationOptions = new ImageGenerationOptions(
208-
"A drawing of the Seattle skyline in the style of Van Gogh");
209-
ImageGenerations images = client.getImageGenerations("{deploymentOrModelName}", imageGenerationOptions);
210-
211-
for (ImageGenerationData imageGenerationData : images.getData()) {
212-
System.out.printf(
213-
"Image location URL that provides temporary access to download the generated image is %s.%n",
214-
imageGenerationData.getUrl());
215-
}
216-
```
217-
218-
## Handling errors
219-
220-
### Enable client logging
221-
222-
To troubleshoot issues with Azure OpenAI library, it's important to first enable logging to monitor the
223-
behavior of the application. The errors and warnings in the logs generally provide useful insights into what went wrong
224-
and sometimes include corrective actions to fix issues. The Azure client libraries for Java have two logging options:
225-
226-
* A built-in logging framework.
227-
* Support for logging using the [SLF4J](https://www.slf4j.org/) interface.
228-
229-
Refer to the instructions in this reference document on how to [configure logging in Azure SDK for Java][logging_overview].
230-
231-
### Enable HTTP request/response logging
232-
233-
Reviewing the HTTP request sent or response received over the wire to/from the Azure OpenAI can be
234-
useful in troubleshooting issues. To enable logging the HTTP request and response payload, the [OpenAIClient][openai_client]
235-
can be configured as shown below. If there's no SLF4J's `Logger` on the class path, set an environment variable
236-
[AZURE_LOG_LEVEL][azure_log_level] in your machine to enable logging.
237-
238-
```java readme-sample-enablehttplogging
239-
OpenAIClient openAIClient = new OpenAIClientBuilder()
240-
.endpoint("{endpoint}")
241-
.credential(new AzureKeyCredential("{key}"))
242-
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
243-
.buildClient();
244-
// or
245-
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build();
246-
OpenAIClient configurationClientAad = new OpenAIClientBuilder()
247-
.credential(credential)
248-
.endpoint("{endpoint}")
249-
.httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
250-
.buildClient();
251-
```
252-
253-
Alternatively, you can configure logging HTTP requests and responses for your entire application by setting the
254-
following environment variable. Note that this change will enable logging for every Azure client that supports logging
255-
HTTP request/response.
256-
257-
Environment variable name: `AZURE_HTTP_LOG_DETAIL_LEVEL`
258-
259-
| Value | Logging level |
260-
|------------------|----------------------------------------------------------------------|
261-
| none | HTTP request/response logging is disabled |
262-
| basic | Logs only URLs, HTTP methods, and time to finish the request. |
263-
| headers | Logs everything in BASIC, plus all the request and response headers. |
264-
| body | Logs everything in BASIC, plus all the request and response body. |
265-
| body_and_headers | Logs everything in HEADERS and BODY. |
266-
267-
> [!NOTE]
268-
> When logging the body of request and response, ensure that they don't contain confidential
269-
information. When logging headers, the client library has a default set of headers that are considered safe to log
270-
but this set can be updated by updating the log options in the builder as shown below.
271-
272-
```java
273-
clientBuilder.httpLogOptions(new HttpLogOptions().addAllowedHeaderName("safe-to-log-header-name"))
274-
```
275-
276-
### Troubleshooting exceptions
277-
Azure OpenAI methods throw a`[HttpResponseException` or its subclass on failure.
278-
The `HttpResponseException` thrown by the OpenAI client library includes detailed response error object
279-
that provides specific useful insights into what went wrong and includes corrective actions to fix common issues.
280-
This error information can be found inside the message property of the `HttpResponseException` object.
281-
282-
Here's the example of how to catch it with synchronous client
283-
284-
```java readme-sample-troubleshootingExceptions
285-
List<ChatRequestMessage> chatMessages = new ArrayList<>();
286-
chatMessages.add(new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."));
287-
chatMessages.add(new ChatRequestUserMessage("Can you help me?"));
288-
chatMessages.add(new ChatRequestAssistantMessage("Of course, me hearty! What can I do for ye?"));
289-
chatMessages.add(new ChatRequestUserMessage("What's the best way to train a parrot?"));
290-
291-
try {
292-
ChatCompletions chatCompletions = client.getChatCompletions("{deploymentOrModelName}",
293-
new ChatCompletionsOptions(chatMessages));
294-
} catch (HttpResponseException e) {
295-
System.out.println(e.getMessage());
296-
// Do something with the exception
297-
}
298-
```
299-
300-
With async clients, you can catch and handle exceptions in the error callbacks:
301-
302-
```java readme-sample-troubleshootingExceptions-async
303-
asyncClient.getChatCompletions("{deploymentOrModelName}", new ChatCompletionsOptions(chatMessages))
304-
.doOnSuccess(ignored -> System.out.println("Success!"))
305-
.doOnError(
306-
error -> error instanceof ResourceNotFoundException,
307-
error -> System.out.println("Exception: 'getChatCompletions' could not be performed."));
308-
```
309-
310-
### Authentication errors
311-
312-
Azure OpenAI supports Microsoft Entra ID authentication. `OpenAIClientBuilder`
313-
has method to set the `credential`. To provide a valid credential, you can use `azure-identity` dependency.
314-
315-
120+
```

0 commit comments

Comments
 (0)