Intelligent Java Applications using Spring AI and Gemini
In this tutorial, we will develop a simple Chat Client application using Spring AI integrated with Google Gemini, a powerful language model from Google. As Java developers familiar with the Spring framework, using Spring AI makes it easier to build intelligent applications without vendor lock-in.
We’ll create a similar application as the one listed in this previous tutorial:
Create a new Spring Boot project
Create a new Spring Boot project using Spring Initializr (https://start.spring.io/) or your IDE.
Selections:
- Project: Maven
- Language: Java
- Spring Boot: 3.4.1 (select the latest version)
- Enter your project metadata (package name, artifact name) as desired
- Java: 23 (or latest available)
Dependencies:
Spring Web
: For creating REST endpoints.Vertex AI Gemini
: For integrating with Google’s language models.
Check the pom.xml file
Ensure your pom.xml
includes the necessary dependencies for Google Gemini integration:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-vertex-ai-gemini-spring-boot-starter</artifactId>
</dependency>
</dependencies>
The dependency spring-ai-vertex-ai-gemini-spring-boot-starter
provides the necessary components and auto-configuration for using Gemini’s API within a Spring Boot application, similar to what spring-ai-openai-spring-boot-starter
provides for OpenAI.
Configuring the Project
When using Google’s AI in a Spring AI project, we need to configure two properties in the application.properties
(or yaml) file:
spring.ai.vertex.ai.gemini.projectId=${GEMINI_PROJECT_ID}
spring.ai.vertex.ai.gemini.location=us-east4
Although the project Id can be shared, it is a good practice to also pass this value as an environment variable in case you are using different projects for different environments (DEV, QA, PROD).
So, how do we get this information?
First, you’ll need to create a Google Cloud account. If you don’t have one yet, you can get $300 in credits for free to get started: https://cloud.google.com/gcp:
Then, go to the console, and create a new project if you don’t have one yet on the Google Cloud Console:
Once the project is created, you will need to:
- Enable billing for the project
- Enable Vertex API for the project, by clicking on
Enable all Recommended APIs
:
Next, we’ll need to install the gcloud CLI tool.
Installing Google Cloud CLI
Follow the step by step listed in the documentation to install gcloud
locally https://cloud.google.com/sdk/docs/install-sdk.
Once installed, initialize the CLI:
./google-cloud-sdk/bin/gcloud init
Login and select the project you created to use with Gemini:
Pick cloud project to use:
[1] [my-project-1]
[2] [my-project-2]
...
Please enter your numeric choice:
If you only have one project, gcloud init
selects it for you.
Take note of your project ID to use in the properties file, and also select the region closest to you. You can find all locations available here: https://cloud.google.com/gemini/docs/locations.
With the configuration done, we’re ready to start coding.
Creating the SimpleChatService class
To get started, we’ll create a SimpleChatService
that contains the ChatClient
model and a method we can invoke from the controller:
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
@Service
public class SimpleChatService {
private final ChatClient chatClient;
public SimpleChatService(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
public String chat(String message) {
return this.chatClient.prompt()
.user(message)
.call()
.content();
}
}
Where:
- The
ChatClient
offers an API for communicating with an AI Model. It supports both a synchronous and streaming programming model. - The
ChatClient
is created using aChatClient.Builder
object. You can obtain an autoconfiguredChatClient.Builder
instance for any ChatModel Spring Boot autoconfiguration or create one programmatically. - The
chat method
receives amessage
. We’ll use thePrompt
object from theChatClient
and set the user input, passing the received message. Thecall()
method sends a request to the AI model, and thecontent()
method returns the AI model’s response as a String.
Note that the code is exactly the same as the previous tutorial. Again, using Spring AI makes it easier to build intelligent applications without vendor lock-in.
Creating the GoogleGeminiChatController
Create a controller and add the following code to it:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/google-gemini")
public class GoogleGeminiChatController {
private final SimpleChatService simpleChatService;
public GoogleGeminiChatController(SimpleChatService simpleChatService) {
this.simpleChatService = simpleChatService;
}
@PostMapping("/chat")
public ChatResponse chat(@RequestBody String message) {
return new ChatResponse(this.simpleChatService.chat(message));
}
}
This controller handles POST requests to the /api/google-gemini/chat
endpoint, extracting the message from the request body.
The ChatResponse
is a record
so we can format the output:
public record ChatResponse(String message) {}
6: Testing via HTTP request
If you are using IntelliJ IDEA Ultimate, you can create a file api.http
with the following content (this is very convenient for HTTP request testing):
POST http://localhost:8080/api/google-gemini/chat
Content-Type: application/json
{
"message": "Tell me a joke"
}
Alternatively, you can also use PostMan or similar tools to simulate the HTTP request.
If we submit the request, we might get something like the following output:
{
"message": "Why don't scientists trust atoms? \n\nBecause they make up everything! \n \nLet me know if you'd like to hear another one! 😄 \n"
}
Summary
You have successfully built a basic Java application using Spring AI and Google Gemini. Explore further by checking
- The official Spring AI Documentation: https://docs.spring.io/spring-ai/reference/api/chat/google-vertexai.html
- And Google Gemini API Docs: https://ai.google/
Happy coding!