Build AI-Powered Applications with Spring Boot & Vertex AI Gemini: Step-by-Step Guide

In this guide, we will walk through the process of integrating Vertex AI Gemini into a Spring Boot application using the spring-ai-vertex-ai-gemini-spring-boot-starter dependency. This starter simplifies communication with Google Cloud's Vertex AI, enabling developers to leverage its advanced AI capabilities, such as natural language processing, machine learning model predictions, and more.

Here's a short explanation of the flow:

  1. Postman: Acts as the client sending an HTTP request.
  2. Spring Boot Application: Contains the core components:
    • AiController: Receives the HTTP request from Postman.
    • AiService: Handles business logic and interacts with Vertex AI.
  3. Vertex AI API: The external service on Google Cloud, which the Spring Boot application communicates with to process AI-related tasks.
  4. Flow:
    • Postman sends a request to the AiController.
    • The AiController invokes the AiService.
    • The AiService sends a request to the Vertex AI API for AI processing.
    • Vertex AI returns a response to the AiService.
    • The AiService sends data back to the AiController.
    • The AiController returns an HTTP response to Postman.

This diagram outlines the interactions between components in a Spring Boot application using Vertex AI for AI services.

We will cover the following steps:

  1. Project Initialization: Setting up a new Spring Boot project from scratch using Spring Initializr.
  2. Dependency Management: Adding the required Maven dependency for the Vertex AI integration.
  3. Configuration: Setting up the necessary API keys, project details, and properties for authentication and communication with Vertex AI.
  4. Implementation: Writing a service and REST controller to interact with Vertex AI for generating responses.
  5. Testing: Running the application and verifying its functionality using Postman or curl.

By the end of this guide, you will have a fully functional Spring Boot application capable of interacting with Vertex AI, laying the foundation for building intelligent, AI-powered features in your application.


1. Initialize a Spring Boot Project

Using Spring Initializr:

  1. Go to Spring Initializr.

  2. Select the following:

    • Project: Maven
    • Language: Java
    • Spring Boot Version: Choose the latest compatible version.
    • Dependencies:
      • Spring Web
      • Vertex AI Gemini
  3. Download the project and extract it.


2. Complete pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-ai-vertex-ai-gemini-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-ai-vertex-ai-gemini-demo</name>
    <description>Demo project for Spring Boot</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>17</java.version>
        <spring-ai.version>1.0.0-M5</spring-ai.version>
    </properties>
    <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.ai</groupId>
                <artifactId>spring-ai-bom</artifactId>
                <version>${spring-ai.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

Run mvn clean install to download the dependency.


3. Configure API Keys and Properties

Add the required properties for Vertex AI to your application.properties or application.yml file. These usually include:

# Vertex AI API configurations
spring.ai.vertex.api-key=<your-api-key>
spring.ai.vertex.project-id=<your-project-id>
spring.ai.vertex.model-id=<model-id>
spring.ai.vertex.endpoint=https://<your-endpoint>

You can obtain these values from the Google Cloud Console:

  1. Navigate to APIs & Services > Credentials to get your API key.
  2. Find the Project ID in the project settings.
  3. Locate the Model ID in the Vertex AI Models section.
  4. Use the endpoint for the specific Vertex AI region (e.g., us-central1-aiplatform.googleapis.com).

4. Code Example

Create a Service to Interact with Vertex AI:

import org.springframework.ai.vertex.VertexAiService;
import org.springframework.stereotype.Service;

@Service
public class AiService {

    private final VertexAiService vertexAiService;

    public AiService(VertexAiService vertexAiService) {
        this.vertexAiService = vertexAiService;
    }

    public String generateResponse(String input) {
        // Replace with your specific method to interact with Vertex AI
        return vertexAiService.chat(input).getResponse();
    }
}

Create a Controller to Expose an API:

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/ai")
public class AiController {

    private final AiService aiService;

    public AiController(AiService aiService) {
        this.aiService = aiService;
    }

    @PostMapping("/chat")
    public String chatWithAi(@RequestBody String input) {
        return aiService.generateResponse(input);
    }
}

5. Run the Application

  1. Start the Spring Boot application using mvn spring-boot:run or from your IDE.
  2. Test the endpoint using tools like Postman or curl:
    curl -X POST -H "Content-Type: application/json" -d '{"input": "Hello, AI!"}' http://localhost:8080/api/ai/chat
    

6. Debugging and Logs

Enable logging to debug API calls:

logging.level.org.springframework.ai=DEBUG

This example demonstrates how to set up and integrate Vertex AI with Spring Boot. 


To access the source code or download the project, visit the GitHub repository:

🔗 GitHub - Spring AI Demo Project

Feel free to clone or fork the repository to get started quickly!


Get Your Copy of Spring AI in Action Today!

🚀 Don’t miss out on this amazing opportunity to elevate your development skills with AI.
📖 Transform your Spring applications using cutting-edge AI technologies.

🎉 Unlock amazing savings of 34.04% with our exclusive offer!

👉 Click below to save big and shop now!
🔗 Grab Your 34.04% Discount Now!

👉 Click below to save big and shop now!
🔗 Grab Your 34.04% Discount Now!

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example