openai/openai-java
Publicmirrored fromhttps://github.com/openai/openai-javaAvailable
openai-azure-java-example/src/main/java/com.openai.azure.examples/AzureApiKeyExample.java
52lines · modecode
| 1 | package com.openai.azure.examples; |
| 2 | |
| 3 | import com.openai.azure.credential.AzureApiKeyCredential; |
| 4 | import com.openai.client.OpenAIClient; |
| 5 | import com.openai.client.okhttp.OpenAIOkHttpClient; |
| 6 | import com.openai.core.JsonValue; |
| 7 | import com.openai.models.ChatCompletion; |
| 8 | import com.openai.models.ChatCompletionCreateParams; |
| 9 | import com.openai.models.ChatCompletionMessageParam; |
| 10 | import com.openai.models.ChatCompletionUserMessageParam; |
| 11 | import java.util.List; |
| 12 | |
| 13 | /** |
| 14 | * This example demonstrates how to use the Azure API key to authenticate with the OpenAI API. |
| 15 | */ |
| 16 | public 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 | |