Hey there, fellow Java enthusiast! Ready to dive into the exciting world of AI with Google's Gemini API? You're in for a treat. We'll be using the nifty ai-java-sdk package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get our project set up:
pom.xml
:<dependency> <groupId>dev.ai.google</groupId> <artifactId>generative-ai-java</artifactId> <version>0.1.0</version> </dependency>
For Gradle users, pop this into your build.gradle
:
implementation 'dev.ai.google:generative-ai-java:0.1.0'
Now, let's get that Gemini client up and running:
import com.google.cloud.vertexai.VertexAI; import com.google.cloud.vertexai.generativeai.GenerativeModel; public class GeminiApiExample { public static void main(String[] args) { String apiKey = "YOUR_API_KEY_HERE"; GenerativeModel model = GenerativeModel.builder() .setModelName("gemini-pro") .setApiKey(apiKey) .build(); } }
Time to put Gemini to work! Here are a few examples to get you started:
String prompt = "Write a haiku about coding in Java"; GenerateContentResponse response = model.generateContent(prompt); System.out.println(response.getText());
String imagePath = "path/to/your/image.jpg"; byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath)); Content content = Content.newBuilder() .setMimeType("image/jpeg") .setData(ByteString.copyFrom(imageBytes)) .build(); GenerateContentResponse response = model.generateContent(content); System.out.println(response.getText());
Gemini's responses are JSON-based, but our SDK does the heavy lifting for us. Still, it's good to be prepared:
try { GenerateContentResponse response = model.generateContent(prompt); System.out.println(response.getText()); } catch (ApiException e) { System.err.println("Error: " + e.getMessage()); }
Ready to level up? Let's look at streaming responses:
StreamGenerateContentResponse streamResponse = model.generateContentStream(prompt); streamResponse.getContents().forEach(content -> { System.out.println(content.getText()); });
A few tips to keep your Gemini integration smooth:
And there you have it! You're now equipped to harness the power of Gemini in your Java projects. Remember, this is just the beginning – there's so much more you can do with this API. Keep experimenting, and don't be afraid to push the boundaries!
Want to see it all in action? Check out our GitHub repo for complete, runnable examples. Happy coding!