openai/openai-java

Public

mirrored from https://github.com/openai/openai-javaAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
f4fc7a57893d3a3bd8612ecbe25b8963bc867a60

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

openai-azure-java-example/src/main/java/com.openai.azure.examples/AzureEntraIDExampleAsync.java

59lines · modeblame

a99e891eShawn Fang1 years ago1package com.openai.azure.examples;
2
3import com.azure.identity.AuthenticationUtil;
4import com.azure.identity.DefaultAzureCredentialBuilder;
5import com.openai.client.OpenAIClientAsync;
6import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
7import com.openai.core.JsonValue;
8import com.openai.credential.BearerTokenCredential;
9import com.openai.models.ChatCompletion;
10import com.openai.models.ChatCompletionCreateParams;
11import com.openai.models.ChatCompletionMessageParam;
12import com.openai.models.ChatCompletionUserMessageParam;
13import java.util.List;
14
15/**
16* This example demonstrates how to use the Azure Entra ID to authenticate with the OpenAI API, asynchronously.
17*/
18public final class AzureEntraIDExampleAsync {
19
20private AzureEntraIDExampleAsync() {}
21
22public static void main(String[] args) {
23OpenAIOkHttpClientAsync.Builder asyncClientBuilder = OpenAIOkHttpClientAsync.builder();
24
25/* Azure-specific code starts here */
26// You can either set 'endpoint' directly in the builder.
27// or set the env var "AZURE_OPENAI_ENDPOINT" and use fromEnv() method instead
28asyncClientBuilder
29.baseUrl(System.getenv("AZURE_OPENAI_ENDPOINT"))
30.credential(BearerTokenCredential.create(
31AuthenticationUtil.getBearerTokenSupplier(
32new DefaultAzureCredentialBuilder().build(), "https://cognitiveservices.azure.com/.default")
33));
34/* Azure-specific code ends here */
35
36// All code from this line down is general-purpose OpenAI code
37OpenAIClientAsync asyncClient = asyncClientBuilder.build();
38
39ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
40.addMessage(ChatCompletionMessageParam.ofChatCompletionUserMessageParam(
41ChatCompletionUserMessageParam.builder()
42.role(ChatCompletionUserMessageParam.Role.USER)
43.content(ChatCompletionUserMessageParam.Content.ofTextContent("Who won the world series in 2020?"))
44.build()))
45.model("gpt-4o")
46.build();
47
48ChatCompletion chatCompletion =
49asyncClient.chat().completions().create(params).join();
50
51List<ChatCompletion.Choice> choices = chatCompletion.choices();
52for (ChatCompletion.Choice choice : choices) {
53System.out.println("Choice content: " + choice.message().content().get());
54}
55
56JsonValue filterResult = chatCompletion._additionalProperties().get("prompt_filter_results");
57System.out.println("Content filter results: " + filterResult);
58}
59}