Hey there, fellow Java dev! Ready to supercharge your projects with some AI magic? Let's dive into integrating ChatGPT's API using the nifty chatgpt
package. Trust me, it's easier than you might think!
Before we jump in, make sure you've got:
First things first, let's get our project set up:
pom.xml
:<dependency> <groupId>com.theokanning.openai-gpt3-java</groupId> <artifactId>service</artifactId> <version>0.12.0</version> </dependency>
For Gradle users, pop this into your build.gradle
:
implementation 'com.theokanning.openai-gpt3-java:service:0.12.0'
Now, let's get that ChatGPT client up and running:
import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.CompletionRequest; public class ChatGPTExample { public static void main(String[] args) { String token = "your-api-key-here"; OpenAiService service = new OpenAiService(token); // We're ready to roll! } }
Time to chat with our AI friend:
CompletionRequest completionRequest = CompletionRequest.builder() .prompt("Hello, ChatGPT!") .model("text-davinci-003") .echo(true) .build(); service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
Want to tweak things a bit? No problem!
CompletionRequest completionRequest = CompletionRequest.builder() .prompt("Write a haiku about Java programming") .model("text-davinci-003") .maxTokens(50) .temperature(0.7) .build();
Always wrap your API calls in a try-catch block:
try { service.createCompletion(completionRequest); } catch (Exception e) { System.err.println("Oops! Something went wrong: " + e.getMessage()); }
And remember, respect those rate limits! Nobody likes a spammer.
Here's a quick chatbot implementation:
Scanner scanner = new Scanner(System.in); while (true) { System.out.print("You: "); String input = scanner.nextLine(); if (input.equalsIgnoreCase("exit")) break; CompletionRequest request = CompletionRequest.builder() .prompt(input) .model("text-davinci-003") .build(); String response = service.createCompletion(request).getChoices().get(0).getText(); System.out.println("ChatGPT: " + response.trim()); }
And there you have it! You're now equipped to harness the power of ChatGPT in your Java projects. The possibilities are endless – from chatbots to content generation and beyond. Keep experimenting and have fun with it!
For more in-depth info, check out the official OpenAI documentation and the chatgpt package GitHub repo.
Happy coding, and may your AI adventures be bug-free! 🚀