Artificial Intelligence (AI) is becoming an integral part of modern applications, enhancing functionalities with features like natural language processing, machine learning predictions, and automation. Spring AI is a new project from the Spring ecosystem that simplifies AI integration in Spring Boot applications. It provides support for generative AI models, embeddings, and model inference, making it easier for developers to integrate AI-driven features into their applications.

This guide will walk you through integrating AI into a Spring Boot application using Spring AI. We will cover dependencies, configuration, and example implementations for leveraging AI functionalities.

Prerequisites

Before diving into the implementation, ensure you have the following:

  • Java 17 or later (Spring Boot 3+ requires Java 17)
  • Maven or Gradle for dependency management
  • Spring Boot 3+
  • An OpenAI API key (or any supported AI provider API key)

Adding Dependencies

To integrate AI with Spring Boot using Spring AI, you need to add the required dependencies. Modify your pom.xml (for Maven) to include the necessary libraries:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai</artifactId>
    <version>0.7.0</version>
</dependency>

For Gradle users, add the following dependency:

implementation 'org.springframework.ai:spring-ai-openai:0.7.0'

This dependency enables integration with OpenAI models, such as GPT-4.

Configuring Spring AI

Spring AI requires API keys for interacting with AI models. You need to configure the API key in your application.properties or application.yml file.

Using application.properties

spring.ai.openai.api-key=your_openai_api_key

Using application.yml

spring:
  ai:
    openai:
      api-key: your_openai_api_key

This configuration allows Spring AI to communicate with OpenAI services.

Implementing AI Service

Once dependencies and configurations are set up, create a service class to interact with the AI model.

import org.springframework.ai.chat.ChatClient;
import org.springframework.stereotype.Service;

@Service
public class AiService {
    private final ChatClient chatClient;

    public AiService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String getAIResponse(String prompt) {
        return chatClient.call(prompt);
    }
}

The ChatClient is an interface provided by Spring AI, making it easy to send prompts and receive AI-generated responses.

Creating a REST Controller

To expose AI functionality via REST APIs, create a controller class.

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

@RestController
@RequestMapping("/ai")
public class AiController {
    private final AiService aiService;

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

    @GetMapping("/chat")
    public String chatWithAI(@RequestParam String prompt) {
        return aiService.getAIResponse(prompt);
    }
}

With this setup, you can interact with AI models via http://localhost:8080/ai/chat?prompt=Hello.

Handling AI-Powered Text Generation

Spring AI supports more advanced features such as text completion and embeddings. Below is an example of generating text using AI models.

import org.springframework.ai.chat.model.ChatRequest;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.stereotype.Service;

@Service
public class TextGenerationService {
    private final ChatClient chatClient;

    public TextGenerationService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String generateText(String input) {
        ChatRequest request = new ChatRequest(input);
        ChatResponse response = chatClient.call(request);
        return response.getChoices().get(0).getMessage();
    }
}

This implementation enables AI-powered text generation by sending prompts to an AI model.

Implementing AI-Powered Summarization

Another practical AI feature is text summarization. Spring AI can be used to summarize large texts effectively.

@Service
public class SummarizationService {
    private final ChatClient chatClient;

    public SummarizationService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String summarizeText(String text) {
        String prompt = "Summarize the following text: " + text;
        return chatClient.call(prompt);
    }
}

To use this service, call summarizeText() with the input text.

Running and Testing the Application

To test the integration, start your Spring Boot application using:

mvn spring-boot:run

You can now access AI-powered features via REST endpoints. For example:

curl "http://localhost:8080/ai/chat?prompt=Tell me a joke"

Conclusion

Spring AI simplifies the integration of artificial intelligence into Spring Boot applications. With minimal configuration, developers can leverage powerful AI models for text generation, summarization, and more. By integrating AI into Spring Boot, you can build intelligent applications that enhance user experience and automate tasks effectively.

This guide demonstrated how to set up Spring AI, configure it, and build RESTful APIs that utilize AI models. As AI continues to evolve, Spring AI will likely expand its capabilities, making it an essential tool for modern application development.

For further advancements, consider integrating other AI models, optimizing prompts, and exploring Spring AI’s support for embeddings and vector databases.