Spring Boot + Spring AI Example (Chatbot Example)

Introduction

In this tutorial, we will guide you through the steps to integrate Spring AI into a Spring Boot application to create a chatbot. This example demonstrates how to set up the project, configure Spring AI, and create a chatbot that interacts with users using AI-generated responses. By the end of this tutorial, you will have a functional chatbot powered by Spring AI.

1. Setting Up the Project

Step 1: Create a New Spring Boot Project

Use Spring Initializr to create a new Spring Boot project. Include dependencies for Spring Web and Spring AI.

Using Spring Initializr:

  • Go to start.spring.io
  • Select:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 3.0.0 (or latest)
    • Dependencies: Spring Web
  • Generate the project and unzip it.

Step 2: Add Dependencies

In your project's pom.xml, add the necessary dependencies for Spring AI.

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>

2. Configuring Spring AI

Step 1: Add API Key to Configuration

Add your OpenAI API key to application.properties or application.yml.

For application.properties:

openai.api.key=your_openai_api_key

For application.yml:

openai:
  api:
    key: your_openai_api_key

Step 2: Configure Spring Beans

Create a configuration class to set up the necessary Spring beans, including the OpenAiClient and ChatClient.

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ai.openai.OpenAiClient;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.ChatClient;

@Configuration
public class AppConfig {

    @Bean
    public OpenAiClient openAiClient() {
        return new OpenAiClient();
    }

    @Bean
    public ChatClient chatClient(OpenAiClient openAiClient) {
        return new OpenAiChatClient(openAiClient);
    }
}

3. Creating the Chatbot Service

Step 1: Create a Chatbot Service

Create a service to handle interactions with the AI model.

package com.example.demo.service;

import org.springframework.ai.openai.ChatClient;
import org.springframework.ai.openai.model.ChatMessage;
import org.springframework.ai.openai.model.ChatRequest;
import org.springframework.ai.openai.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ChatbotService {

    private final ChatClient chatClient;

    @Autowired
    public ChatbotService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String getChatResponse(String userMessage) {
        ChatMessage userMsg = new ChatMessage("user", userMessage);

        ChatRequest request = new ChatRequest();
        request.setMessages(List.of(userMsg));

        ChatResponse response = chatClient.sendMessage(request);
        return response.getReply();
    }
}

Step 2: Create a Controller to Expose the Service

Create a controller to expose an endpoint for the chatbot.

package com.example.demo.controller;

import com.example.demo.service.ChatbotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ChatbotController {

    private final ChatbotService chatbotService;

    @Autowired
    public ChatbotController(ChatbotService chatbotService) {
        this.chatbotService = chatbotService;
    }

    @GetMapping("/chat")
    public String chat(@RequestParam String message) {
        return chatbotService.getChatResponse(message);
    }
}

4. Testing the Integration

Step 1: Run the Application

Run your Spring Boot application. Ensure the application starts without errors.

Step 2: Access the Chat Endpoint

Use Postman, curl, or your browser to test the endpoint. For example:

http://localhost:8080/chat?message=Hello, how are you?

You should receive a response generated by the AI model based on the provided message.

Understanding Spring Boot Autoconfiguration for Spring AI

What is Spring Boot Autoconfiguration?

Spring Boot autoconfiguration simplifies the process of setting up Spring applications by automatically configuring beans based on the classpath settings, other beans, and various property settings. This eliminates the need for boilerplate code and manual configuration.

How Spring AI Uses Autoconfiguration

When you include the spring-ai-openai-spring-boot-starter dependency, Spring Boot's autoconfiguration feature automatically configures the necessary beans for Spring AI. This means that Spring AI will:

  1. Detect the presence of Spring AI and OpenAI client libraries on the classpath.
  2. Read the properties defined in application.properties or application.yml (e.g., openai.api.key).
  3. Automatically configure and instantiate the OpenAiClient and ChatClient beans.

This automatic configuration reduces the setup time and effort, allowing developers to focus on building the core functionalities of their application.

Example of Autoconfiguration

With the spring-ai-openai-spring-boot-starter, you don't need to manually define and instantiate the beans for OpenAiClient and ChatClient. Simply including the starter dependency and providing the necessary configuration properties is enough to set up the AI components in your Spring Boot application.

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ai.openai.OpenAiClient;
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.ChatClient;

@Configuration
public class AppConfig {

    @Bean
    public OpenAiClient openAiClient() {
        return new OpenAiClient();
    }

    @Bean
    public ChatClient chatClient(OpenAiClient openAiClient) {
        return new OpenAiChatClient(openAiClient);
    }
}

Conclusion

This tutorial demonstrated how to set up and use Spring AI to create a chatbot in a Spring Boot application. You learned how to configure Spring AI, create a service to interact with the AI model, and expose an endpoint for user interaction. 

Additionally, we covered how Spring Boot autoconfiguration simplifies the setup process by automatically configuring necessary beans. This setup allows you to integrate AI-powered chat functionalities into your Spring Boot applications, enhancing user experience with intelligent and dynamic responses. 

Explore further customization and enhancements to leverage the full potential of AI in your projects.

Comments