Open In App

How to Install and Setup Spring AI?

Last Updated : 01 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Artificial intelligence (AI) is day-by-day becoming more important in modern applications. Spring AI makes the process easy to integrate AI into our Java-based projects. Spring AI is built on top of the popular Spring framework, and it simplifies the interaction between our applications and AI services by allowing us to quickly deploy models and make predictions. In this article, we will learn all the necessary steps for installation and full setup of Spring AI.

Spring AI is an extension of the Spring framework. It integrates with various AI models and platforms such as TensorFlow, OpenAI, and Hugging Face. It provides an integrated API for processing natural language processing (NLP) applications from various machine learning (ML) models. Spring AI model abstracts the complexity of configuring endpoints, calling external APIs, and maintaining security, and allows us to focus on building intelligent applications without compromising on low-level details.

Prerequisites For Implementation:

Before diving into Spring AI, ensure that the following prerequisites are met:

  • Java 11 or higher installed on your system.
  • Maven or Gradle for dependency management.
  • A Spring Boot project setup (version 2.5 or higher recommended).
  • Familiarity with the Spring Framework and a basic understanding of AI concepts.
  • An account or API key for an AI service provider like OpenAI or Hugging Face.

Step-by-Step Configuration

Step 1: Setting Up Spring Boot Project

Start by creating a new Spring Boot project if you do not already have one. You can do this using Spring Initializr or your preferred IDE. Here’s how to generate a project using Spring Initializr:

  • Go to Spring Initializr
  • Set Project to Maven or Gradle
  • Choose Spring Boot version (2.5 or higher)
  • Add necessary dependencies: Spring Web, Spring Boot Starter AI
  • Click on Generate to download project.
Project Metadata

Now, unzip downloaded project and open it in your IDE

Step 2: Adding Spring AI Dependencies

In your build.gradle (for Gradle), add the following Spring AI dependency:

implementation 'org.springframework.boot:spring-boot-starter-ai:1.0.0'

build.gradle:

build.gradle file

Run gradle build to resolve dependencies.

Build Successful

Step 3: Configuring API Access

Next, configure your API access. If you are using a service like OpenAI, you will need to set up authentication. Add the following properties to your application.properties or application.yml file:

For application.properties:

ai.provider=openai
ai.openai.api-key=your-openai-api-key

For application.yml:

ai:
provider: openai
openai:
api-key: your-openai-api-key

This configuration sets up Spring AI to use OpenAI and authenticates your application with the provided API key.

Step 4: Writing Your AI Service

Now, let’s create a simple service that utilizes AI. For example, we can write a service to generate text using OpenAI’s GPT-3 model.

Create a new class, AIService.java:

Java
package com.example.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ai.OpenAIClient;
import org.springframework.ai.model.CompletionRequest;

@Service
public class AIService {

    @Autowired
    private OpenAIClient openAIClient;

    public String generateText(String prompt) {
        // Create a request object for the AI model
        CompletionRequest request = new CompletionRequest();
        request.setPrompt(prompt);
        request.setMaxTokens(100); // Limit the response to 100 tokens

        // Call the OpenAI model and return the result
        return openAIClient.createCompletion(request).getChoices().get(0).getText();
    }
}

Code Explanation:

  • The OpenAIClient is injected using @Autowired to interact with the OpenAI API.
  • A CompletionRequest object is created, which takes the prompt (user input) and maxTokens to limit the response size.
  • The createCompletion method sends the request to OpenAI, and the response text is returned from the first choice.

Step 5: Creating REST API Endpoint

Let’s expose this functionality through a REST API so users can interact with the AI service.

In your AIController.java file:

Java
package com.example.demo.controller;

import com.example.demo.service.AIService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

    @Autowired
    private AIService aiService;

    @PostMapping("/generate")
    public String generateText(@RequestBody String prompt) {
        // Use the AIService to generate text based on the prompt
        return aiService.generateText(prompt);
    }
}

Code Explanation:

  • The @RestController annotation is used to define the REST API.
  • The /generate endpoint receives POST requests with the prompt as the request body, which is passed to AIService to generate AI-based text.

Step 6: Running Application

Finally run the Spring Boot application:

For Gradle:

./gradlew bootRun  // For Unix/Linux
gradlew.bat bootRun // For Windows

To test /api/ai/generate endpoint, follow below steps using Postman:

  • Open Postman and create new POST request.
  • Set URL to http://localhost:8080/api/ai/generate (assuming your app runs locally on port 8080).
  • In Body section select raw and choose JSON format. Add following JSON payload:
{
"prompt": "Tell me a joke"
}
  • Set request headers:
    • Content-Type: application/json
  • Send request: Postman will make request to your Spring Boot application's /generate endpoint by invoking AIService.
Request Body
using postman

Output:

Output

Next Article
Article Tags :

Similar Reads