Skip to content

Commit e2358a1

Browse files
committed
update
1 parent 4bee84a commit e2358a1

File tree

2 files changed

+64
-260
lines changed

2 files changed

+64
-260
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ client := openai.NewClient(
216216

217217
OpenAIClient client = OpenAIOkHttpClient.builder()
218218
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
219-
.credential(AzureApiKeyCredential.create("{your-api-key}"))
219+
.apiKey(apiKey)
220220
.build();
221221
```
222222

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

Lines changed: 63 additions & 259 deletions
Original file line numberDiff line numberDiff line change
@@ -6,42 +6,35 @@ 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>
39-
```
4035

4136
## Authentication
4237

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-
4538
# [Microsoft Entra ID](#tab/secure)
4639

4740
Authentication with Microsoft Entra ID requires some initial setup:
@@ -58,258 +51,69 @@ Add the Azure Identity package:
5851

5952
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.
6053

61-
Authorization is easiest using DefaultAzureCredential. It finds the best credential to use in its running environment.
54+
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.
6255

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

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

7369
# [API Key](#tab/api-key)
7470

7571
```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();
72+
OpenAIClient client = OpenAIOkHttpClient.builder()
73+
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
74+
.apiKey(apiKey)
75+
.build();
8976
```
9077

9178
---
9279

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
80+
## Responses
14981

15082
```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
189-
190-
```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);
83+
package com.example;
84+
85+
import com.openai.client.OpenAIClient;
86+
import com.openai.client.okhttp.OpenAIOkHttpClient;
87+
import com.openai.models.ChatModel;
88+
import com.openai.models.responses.Response;
89+
import com.openai.models.responses.ResponseCreateParams;
90+
import com.azure.core.credential.AzureKeyCredential;
91+
92+
public class OpenAITest {
93+
public static void main(String[] args) {
94+
// Get API key from environment variable for security
95+
String apiKey = System.getenv("OPENAI_API_KEY");
96+
String resourceName = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
97+
String modelDeploymentName = "gpt-4.1"; //replace with you model deployment name
98+
99+
try {
100+
OpenAIClient client = OpenAIOkHttpClient.builder()
101+
.baseUrl(resourceName)
102+
.apiKey(apiKey)
103+
.build();
104+
105+
ResponseCreateParams params = ResponseCreateParams.builder()
106+
.input("Tell me about the bitter lesson?")
107+
.model(modelDeploymentName)
108+
.build();
109+
110+
Response response = client.responses().create(params);
111+
112+
System.out.println("Response: " + response);
113+
} catch (Exception e) {
114+
System.err.println("Error: " + e.getMessage());
115+
e.printStackTrace();
116+
}
200117
}
201118
}
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-
119+
```

0 commit comments

Comments
 (0)