openai/openai-java

Public

mirrored fromhttps://github.com/openai/openai-javaAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
5b4ce66977dc372219fcac511adcd04314f76aa5

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/AzureApiKeyExampleAsync.java

54lines · modecode

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