Using the OpenAI API with Java
Integrating AI into Java applications has become significantly easier with the introduction of the OpenAI Java client. The OpenAI Java client offers native support for interacting with OpenAI’s APIs including Completions, Chat, Assistants, Embeddings, and more. With this client, Java developers can easily build AI-driven features into their apps using OpenAI’s powerful large language models like GPT-4 and GPT-3.5. Let us delve into understanding how to use the Java OpenAI API client effectively.
1. What is OpenAI?
OpenAI is a leading artificial intelligence research organization and company that focuses on developing safe and beneficial AI technologies. It is known for creating cutting-edge AI models such as ChatGPT, Codex (used in GitHub Copilot), and DALL·E. These models power a variety of applications including conversational agents, code-generation tools, and AI-based image synthesis platforms.
OpenAI’s broader mission is to ensure that artificial general intelligence (AGI)—highly autonomous systems that outperform humans at most economically valuable work—benefit all of humanity. To that end, OpenAI provides APIs that developers can use to integrate powerful AI features into their applications, accessible through a well-documented OpenAI API platform.
1.1 How to Generate an OpenAI API Token?
To use OpenAI services programmatically—such as through a Java client—you will need an API token. This token allows secure and authenticated access to the OpenAI API endpoints.
- Navigate to the OpenAI API Keys page.
- If you are not already logged in, sign in using your OpenAI account credentials.
- Click on the button labeled “Create new secret key”.
- Once the key is generated, copy it immediately and store it in a secure location, such as an environment variable or encrypted configuration file.
This API token will be required in your Java application when initializing the OpenAIClient
. It authorizes your app to make requests to OpenAI’s endpoints for completions, chat, assistants, and more. Keep in mind that the token is sensitive; do not hardcode it in your source files or expose it publicly.
2. Code Example
This section walks you through how to use the Java OpenAI API client to perform various types of requests to OpenAI’s models.
2.1 Code Dependencies
To use the OpenAI Java SDK, you first need to include the appropriate Maven dependency in your pom.xml
file. This will allow your application to access the OpenAI API through the official Java client library, enabling interactions such as completions, chat-based responses, and assistant-driven conversations.
<dependency> <groupId>com.openai</groupId> <artifactId>openai</artifactId> <version>latest__jar__version</version> </dependency>
2.2 Code Example
Below is a comprehensive Java program that demonstrates how to integrate and interact with various capabilities of the OpenAI API using the official Java client. The example covers three main use cases: simple text completion, chat-based conversational completion, and assistant-driven threaded conversation using GPT-4.
import com.openai.OpenAI; import com.openai.OpenAIClient; import com.openai.api.completion.*; import com.openai.api.chat.*; import com.openai.api.assistants.*; import com.openai.api.threads.*; import java.util.List; /** * Demonstrates usage of the Java OpenAI API Client. * * This class showcases how to perform three types of interactions with OpenAI's services: * 1. Simple text completion using the Completion API. * 2. Conversational interaction using Chat Completion. * 3. Stateful assistant interaction using Threads and the Assistants API. */ public class Main { /** * The entry point of the Java program. * * @param args command-line arguments (not used) * @throws InterruptedException if the thread waiting on assistant completion is interrupted */ public static void main(String[] args) throws InterruptedException { // Replace with your actual OpenAI API key String apiKey = "your-api-key-here"; // Initialize the OpenAI client with the API key OpenAIClient client = OpenAI.builder() .apiKey(apiKey) .build(); try { // -------------------- 1. Simple Completion -------------------- // Create a completion request with a static prompt using the "text-davinci-003" model CompletionRequest simpleRequest = CompletionRequest.builder() .model("text-davinci-003") .prompt("What is the capital of France?") .maxTokens(10) // Limit the number of tokens in the response .build(); // Send the request and get the response CompletionResponse simpleResponse = client.createCompletion(simpleRequest); System.out.println("Simple Completion Output:"); System.out.println(simpleResponse.getChoices().get(0).getText().trim()); // -------------------- 2. Conversational Chat Completion -------------------- // Create a user message for chat-based conversation ChatMessage userMsg = ChatMessage.userMessage("Who won the FIFA World Cup in 2018?"); ChatCompletionRequest chatRequest = ChatCompletionRequest.builder() .model("gpt-3.5-turbo") .messages(List.of(userMsg)) // Pass the message as a list .build(); // Send the chat request and retrieve the response ChatCompletionResponse chatResponse = client.createChatCompletion(chatRequest); System.out.println("\nChat Completion Output:"); System.out.println(chatResponse.getChoices().get(0).getMessage().getContent()); // -------------------- 3. Assistant-Based Interaction -------------------- // Create an Assistant using the GPT-4 model with tutoring instructions Assistant assistant = client.createAssistant( AssistantRequest.builder() .model("gpt-4") .name("TutorBot") .instructions("You are a math tutor. Explain answers in simple terms.") .build() ); // Create a new thread for the assistant interaction Thread thread = client.createThread(CreateThreadRequest.builder().build()); // Add a user message to the thread asking a math question client.addMessage(thread.getId(), MessageRequest.builder() .role("user") .content("What is 7 multiplied by 8?") .build() ); // Create a run that connects the thread with the assistant Run run = client.createRun(thread.getId(), RunRequest.builder() .assistantId(assistant.getId()) .build() ); // Wait until the assistant completes its response generation System.out.println("\nWaiting for assistant response..."); Run finalRun = client.waitForRunCompletion(thread.getId(), run.getId()); // Retrieve all messages from the conversation thread List<Message> messages = client.listMessages(thread.getId()); // Display the full assistant conversation System.out.println("\nAssistant Conversation:"); for (Message msg : messages) { System.out.println(msg.getRole() + ": " + msg.getContent()); } } catch (Exception e) { // Handle any runtime errors (e.g., network issues, bad requests) e.printStackTrace(); } } }
2.2.1 Code Explanation
This Java program demonstrates how to work with the OpenAI API through the official Java OpenAI API client. It is structured into three distinct sections, each showcasing a different interaction type. The program begins by importing necessary classes and initializing an OpenAIClient
using an API key.
In the first section, a basic text completion is executed using the text-davinci-003
model. The prompt “What is the capital of France?” is sent, and a short response is generated with a maximum of 10 tokens. This demonstrates the simplest usage of the completion API, ideal for short factual answers.
In the second section, the code performs a chat-based interaction using the gpt-3.5-turbo
model. Here, the user sends a natural language message about the 2018 FIFA World Cup, and the model responds in a conversational tone. This demonstrates how the chat API handles multi-turn conversations.
The third section showcases an advanced use case with the Assistants API. It creates an assistant called “TutorBot” using the gpt-4
model and instructs it to explain math problems in simple terms. A new thread is created to manage the conversation, a message is added from the user, and a run is initiated to let the assistant respond contextually. The assistant processes the input asynchronously, and once completed, all messages in the conversation thread are retrieved and printed. This pattern is useful for scenarios where multi-step interactions or persistent context are needed.
Exception handling is included to catch and print any runtime errors, ensuring the application fails gracefully if any issues arise with the API or network.
2.2.2 Code Output
Upon successful execution, the program will output responses from each interaction, giving a clear understanding of how each part of the API behaves.
Simple Completion Output: Paris Chat Completion Output: France won the FIFA World Cup in 2018. Waiting for assistant response... Assistant Conversation: user: What is 7 multiplied by 8? assistant: 7 multiplied by 8 is 56. This is because 7 added to itself 8 times equals 56.
3. Conclusion
The OpenAI Java SDK opens the doors to integrating powerful AI features directly into Java applications. Whether you’re building a chatbot, automation tool, or custom assistant, the API gives you rich capabilities with minimal boilerplate. With features like Completion and Assistants, you can build both simple and complex AI-driven apps quickly. Don’t forget to handle exceptions, consider rate limits, and secure your API tokens properly when moving to production.