openai/openai-java

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.11.0

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

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