openai/openai-java

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
56c5038156005a322b2b2c69f9b4c30bc5e9a80d

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 · modeblame

a99e891eShawn Fang1 years ago1package 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
18private AzureApiKeyExampleAsync() {}
19
20public static void main(String[] args) {
21OpenAIOkHttpClientAsync.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
26asyncClientBuilder
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
32OpenAIClientAsync client = asyncClientBuilder.build();
33
34ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
35.addMessage(ChatCompletionMessageParam.ofChatCompletionUserMessageParam(
36ChatCompletionUserMessageParam.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
43ChatCompletion chatCompletion =
44client.chat().completions().create(params).join();
45
46List<ChatCompletion.Choice> choices = chatCompletion.choices();
47for (ChatCompletion.Choice choice : choices) {
48System.out.println("Choice content: " + choice.message().content().get());
49}
50
51JsonValue filterResult = chatCompletion._additionalProperties().get("prompt_filter_results");
52System.out.println("Content filter results: " + filterResult);
53}
54}