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

52lines · modecode

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