Hey there, fellow developer! Ready to supercharge your Java project with the power of AI? Let's dive into integrating the OpenAI API into your Java application. This guide will walk you through the process, assuming you're already comfortable with Java and just need the nitty-gritty details to get up and running.
Before we jump in, make sure you've got:
First things first, let's get our project set up:
pom.xml
:<dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.10.0</version> </dependency>
For Gradle users, pop this into your build.gradle
:
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
Now, let's set up our API client:
import okhttp3.OkHttpClient; import okhttp3.Request; public class OpenAIClient { private final OkHttpClient client = new OkHttpClient(); private final String apiKey; public OpenAIClient(String apiKey) { this.apiKey = apiKey; } // We'll add more methods here soon! }
Time to make some requests! Here's how to send a basic completion request:
import okhttp3.*; import org.json.JSONObject; public Response createCompletion(String prompt) throws IOException { MediaType mediaType = MediaType.parse("application/json"); JSONObject jsonBody = new JSONObject() .put("model", "text-davinci-002") .put("prompt", prompt) .put("max_tokens", 50); RequestBody body = RequestBody.create(jsonBody.toString(), mediaType); Request request = new Request.Builder() .url("https://api.openai.com/v1/completions") .post(body) .addHeader("Authorization", "Bearer " + apiKey) .build(); return client.newCall(request).execute(); }
Great! Now let's handle those responses:
public String handleResponse(Response response) throws IOException { if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } String responseBody = response.body().string(); JSONObject jsonResponse = new JSONObject(responseBody); return jsonResponse.getJSONArray("choices") .getJSONObject(0) .getString("text"); }
Now that we've got the basics down, let's implement some specific use cases:
public String getCompletion(String prompt) throws IOException { Response response = createCompletion(prompt); return handleResponse(response); }
public String getChatCompletion(String message) throws IOException { // Similar to createCompletion, but use the chat endpoint // and structure the message as per OpenAI's chat format }
public String generateImage(String prompt) throws IOException { // Use the images endpoint to generate an image // Return the URL of the generated image }
Remember to:
Don't forget to test! Here's a quick example:
@Test public void testCompletion() throws IOException { OpenAIClient client = new OpenAIClient("your-api-key"); String result = client.getCompletion("Write a haiku about coding"); assertNotNull(result); assertTrue(result.length() > 0); }
And there you have it! You've just built a solid OpenAI API integration in Java. Remember, this is just the beginning - there's so much more you can do with the API. Keep experimenting, and don't hesitate to dive into the OpenAI documentation for more advanced features.
Happy coding, and may your AI adventures be bug-free and endlessly creative!