Integrating ChatGPT with Spring Boot Using Spring AI

To integrate ChatGPT into a Spring Boot application, you can use the OpenAI API to send requests to ChatGPT and get responses. Below is an example of how you can create a simple Spring Boot service that integrates with OpenAI's API to use ChatGPT.



1: Set up your Spring Boot project

  1. Create a new Spring Boot project: You can create a Spring Boot project using Spring Initializr or through your IDE (like Eclipse or IntelliJ).

    • Choose your project metadata (Group, Artifact, Name, etc.)
    • Select dependencies:
      • Spring Web
      • Open AI
  2. Complete pom.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	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.4.1</version>
    		<relativePath/> <!-- lookup parent from repository -->
    	</parent>
    	<groupId>com.example</groupId>
    	<artifactId>demo</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<name>demo</name>
    	<description>Demo project for Spring Boot</description>
    	<properties>
    		<java.version>17</java.version>
    		<spring-ai.version>1.0.0-M4</spring-ai.version>
    	</properties>
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-web</artifactId>
    		</dependency>
    		<dependency>
    			<groupId>org.springframework.ai</groupId>
    			<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-test</artifactId>
    			<scope>test</scope>
    		</dependency>
    	</dependencies>
    	<dependencyManagement>
    		<dependencies>
    			<dependency>
    				<groupId>org.springframework.ai</groupId>
    				<artifactId>spring-ai-bom</artifactId>
    				<version>${spring-ai.version}</version>
    				<type>pom</type>
    				<scope>import</scope>
    			</dependency>
    		</dependencies>
    	</dependencyManagement>
    
    	<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>
    	</repositories>
    
    </project>
  3. Configuration: You'll need an API key from OpenAI to interact with their services. Get it from the OpenAI platform.

    In your application.properties or application.yml, add:

    spring.ai.openai.api-key=your-openai-api-key
    spring.ai.openai.model=gpt-3.5-turbo
    spring.ai.openai.api-url=https://api.openai.com/v1/completions

2. Service to Use OpenAI API

Now, create a service that interacts with the OpenAI API.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ai.openai.client.OpenAiClient;
import org.springframework.ai.openai.model.CompletionRequest;
import org.springframework.ai.openai.model.CompletionResponse;

@Service
public class OpenAiService {

    @Autowired
    private OpenAiClient openAiClient;

    public String generateText(String prompt) {
        CompletionRequest request = new CompletionRequest();
        request.setPrompt(prompt);
        request.setMaxTokens(100);

        CompletionResponse response = openAiClient.createCompletion(request);
        return response.getChoices().get(0).getText();
    }
}

3. Controller to Handle Requests

You can create a controller that exposes an endpoint for interacting with OpenAI.

import com.example.demo.service.OpenAiService;
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 OpenAiController {

    @Autowired
    private OpenAiService openAiService;

    @GetMapping("/generate-text")
    public String generateText(@RequestParam String prompt) {
        return openAiService.generateText(prompt);
    }
}

4. Run the Application

Make sure your Spring Boot application is correctly set up to run:

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Now, you can run the Spring Boot application. You should be able to hit the endpoint /generate-text?prompt=your+text+here to get a response from OpenAI.

5. Testing

You can test the endpoint using Postman or Curl:

curl -X GET "http://localhost:8080/generate-text?prompt=Hello+world"

This will return a response from the OpenAI API based on your prompt.

6. Error Handling and Improvements

You can also handle errors like API call failures, invalid responses, or empty prompts by enhancing the OpenAiService class with proper exception handling and validation logic.


That's it! You've now integrated OpenAI with your Spring Boot application.

Get Your Copy of Spring AI in Action Today!

🚀 Don’t miss out on this amazing opportunity to elevate your development skills with AI.
📖 Transform your Spring applications using cutting-edge AI technologies.

🎉 Unlock amazing savings of 34.04% with our exclusive offer!

👉 Click below to save big and shop now!
🔗 Grab Your 34.04% Discount Now!

👉 Click below to save big and shop now!
🔗 Grab Your 34.04% Discount Now!

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete