Spring Boot + Spring AI Example (Chatbot Example)

author: Sai K

Introduction

In this tutorial, we will guide you through the steps to integrate Spring AI into a Spring 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 wii have a fuctional 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.

add_dependencies_image

Step 1: Add API Key to Configuration

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

For application.properties:

add_dependencies_image

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 Chatbox Service

Step 1: Create a Chatbox Service

Create a service to Chatbox 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 a Controller to Expose the Service

    
        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: Acess the Chat Endpoint

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

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

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.