Toll Free:

1800 889 7020

Spring AI: A Chat Completion Tutorial – Building Smart Applications

With technology, artificial intelligence (AI) integration in applications has become innovative and efficient. The Spring AI Project is an influential add-on framework based on Spring, making it easy to bring AI capabilities to Spring-based applications. In this article, we take a brief look at Spring AI and guide you to demonstrate a chat completion article.

1. What is Spring AI?

The Spring AI Project was an extension project to the Spring framework where additional capabilities in the form of tools and libraries that assist in the integration of AI into applications were introduced. It connects AI models with end-user programs ensuring easy use and maximum flexibility and offers rich support for many AI services and frameworks. Whether one is working with machine learning models, natural language processing, or computer vision, the Spring AI will help embed all the other AI capabilities into applications in the most effortless manner possible.

2. How to generate an OpenAI API key?

We will now understand how to obtain an OpenAI key. We’ll use an OpenAI model to generate an image.

  • Create an Account or Sign In: Go to the OpenAI website and either sign up for a new account or log in to your existing one.
  • Access API Keys: After logging in, head to the API Keys section within your account dashboard.
  • Generate a New API Key: Select the option to create a new API key. Assign a name or description to the key for easy reference.
  • Generate and Save the Key: Click the Generate Key button. Make sure to copy the newly created API key and store it in a safe place, as you will need it to access OpenAI’s services.

3. Code example

3.1 Dependencies

Add the following dependencies to your pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         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.2.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>myexample</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.ai</groupId>
            <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
            <version>0.8.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <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>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <releases>
                <enabled>false</enabled>
            </releases>
        </repository>
    </repositories>

</project>

3.2 Update the application properties

Add the following properties to the application.properties file. Remember to replace the OpenAI key.

# Spring Boot Application Properties
spring.application.name=springaichatapplication
spring.main.banner-mode=off
server.port=9090

# OpenAI API Key
spring.ai.openai.api-key=your-openai-api-key

3.3 Creating the Controller

The BasicChatController class is a REST controller in a Spring Boot application, responsible for handling HTTP requests related to chat completion. The controller method calls the openAiClient.call(…) to get a response from the OpenAI API and return a Map containing the response.

package myexample.demo.controller;

import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/chat")
public class BasicChatController {

    private final OpenAiChatClient chatClient;

    @Autowired
    public BasicChatController(OpenAiChatClient chatClient) {
        this.chatClient = chatClient;
    }

    /**
     * Handles GET requests to the /greet endpoint.
     *
     * @param message the message to be sent to the OpenAI chat client. Defaults to "Tell a random good morning fact" if not provided.
     * @return a map containing the response generated by the OpenAI chat client.
     */
    // http://localhost:9090/chat/greet?message=Tell%20a%20random%20good%20morning%20fact
    // http://localhost:9090/chat/greet?message=Hello
    @GetMapping("/greet")
    public Map chat(@RequestParam(value = "message", defaultValue = "Tell a random good morning fact") String message) {
        System.out.println("Message: " + message);
        return Map.of("Generated by OpenAI", chatClient.call(message));
    }
}

3.4 Create the Main file

Create a Spring Boot application to initialize the application.

package myexample.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringaichatapplicationApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringaichatapplicationApplication.class, args);
        System.out.println("Spring AI Chat Application Started...");
    }
}

3.5 Run the application and Demo

Now start the application and open the Postman tool to hit the api endpoint. Import the below curl GET request in the Postman tool. You’re free to change the prompt with a valid instruction.

curl 'http://localhost:9090/chat/greet?message=Hello'

If everything goes well the chat completion response will be returned from OpenAI and sent to the client as a json response.

{
    "Generated by OpenAI": "Hello! How can I assist you today?"
}

4. Conclusion

In conclusion, as AI continues to reshape the technological landscape, tools like Spring AI are essential for seamlessly integrating AI into applications. By leveraging Spring AI, Java developers can easily add advanced AI capabilities to their Spring-based projects, enabling innovative solutions like generating images from user prompts, chat completion bots, and more. If you’re looking to implement AI-driven solutions in your applications, hire Java developers who specialize in Spring AI to ensure the seamless integration of these advanced capabilities.

5. Download the code

You can download the full code here: Download

Cleveland

Scroll to Top