Building a Chatbot with Spring Boot and ChatGPT API: A Step-by-Step Tutorial
Integrating advanced large language models into applications can unlock powerful conversational capabilities. In this tutorial, we will explore how to seamlessly integrate the cutting-edge ChatGPT API with Spring Boot, a popular Java framework for building robust web applications. By combining the versatility of Spring Boot with the natural language processing capabilities of ChatGPT, we can create intelligent chatbots that can engage in dynamic and human-like conversations.
Throughout this step-by-step guide, we will cover the essential tasks required to integrate the ChatGPT API with Spring Boot effectively. We will start by setting up a Spring Boot project and adding the necessary dependencies. Then, we’ll delve into creating a controller class to handle HTTP requests and implement the ChatGPT API integration using Spring’s RestTemplate
. We’ll also address aspects such as API credential management, input validation, and error handling.
By the end of this tutorial, you’ll have a solid understanding of how to leverage Spring Boot’s power and flexibility to create chatbot applications powered by the ChatGPT API and generative ai. So let’s dive in and start building intelligent conversational experiences with Spring Boot and ChatGPT!
Code example is available in github.
Table Of Content
Set Up a Spring Boot Project
- Start by creating a new Java Spring Boot project. You can use the Spring Initializr (https://start.spring.io/) to generate a basic project structure with Maven or Gradle.
Add Required Dependencies
- Open your project’s
pom.xml
(if you’re using Maven) orbuild.gradle
(if you’re using Gradle) file and add the necessary dependencies:- For making HTTP requests, include the
spring-boot-starter-web
dependency. - For handling JSON, include the
jackson-databind
dependency.
- For making HTTP requests, include the
Now your pom file should look like below
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.1.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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Create a Controller Class
- Create a new Java class, such as
ChatController
, and annotate it with@RestController
to indicate that it will handle HTTP requests. - Define a POST endpoint that will receive user messages and return responses from the ChatGPT API.
RequestDto Class:
public class RequestDto {
private String message;
private Integer maxTokens;
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getMaxTokens() {
return this.maxTokens;
}
public void setMaxTokens(Integer maxTokens) {
this.maxTokens = maxTokens;
}
}
Controller Class:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
@Controller
@RequestMapping("/chat")
public class ChatController {
@Value("${chatgpt.api.key}")
private String apiKey;
private final String chatGptApiUrl = "https://api.openai.com/v1/chat/completions";
@PostMapping
@ResponseBody
public String chatWithGpt(@RequestBody RequestDto requestDto) {
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(apiKey);
headers.setContentType(MediaType.APPLICATION_JSON);
String requestBody = "{ \"prompt\": \"" + requestDto.message() + "\", \"max_tokens\": requestDto.maxTokens() }";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(chatGptApiUrl, HttpMethod.POST, requestEntity, String.class);
if (responseEntity.getStatusCode() == HttpStatus.OK) {
return responseEntity.getBody();
} else {
return "Error occurred while communicating with the ChatGPT API.";
}
}
}
In the code above, we have created a ChatController
class with a single chatWithGpt
method that handles the POST requests to the /chat
endpoint. The @Value("${chatgpt.api.key}")
annotation reads the API key from the application configuration.
Inside the chatWithGpt
method, we construct an HTTP request to the ChatGPT API by setting the necessary headers and including the user message in the request body. We then use RestTemplate
to send the request and receive the response.
If the API returns a successful response (HTTP 200 OK), we return the generated response from the API to the client. Otherwise, we provide an error message.
Implement the ChatGPT API Integration
- Use the
RestTemplate
class (provided by Spring) to make HTTP POST requests to the ChatGPT API endpoint. - In the
ChatController
class, create a method that accepts a user message and returns a response from the ChatGPT API. - Inside the method, construct an HTTP request to the ChatGPT API using
RestTemplate
. - Set the required headers (e.g.,
Authorization
) and include the user message in the request body. - Send the request and receive the response.
- Extract the generated response from the API and return it to the client.
Configure API Credentials
- Obtain your ChatGPT API credentials from OpenAI. You’ll need an API key for authentication.
- Store the API key securely, such as in an environment variable or a configuration file.
- In your Spring Boot project, access the API key from the configuration and set it as a header in the API requests.
- In
application.properties
file includechatgpt.api.key
and add your chatgpt api key
Test the Endpoint
- Run your Spring Boot application and make a POST request to your
/chat
endpoint, passing a user message in the request body. - Verify that you receive a response from the ChatGPT API.
Curl Request:
curl --location 'http://localhost:8080/chat' \
--header 'Content-Type: application/json' \
--data '{
"message": "hi",
"maxTokens": 50
}'
Handle Input Validation and Error Scenarios
- Implement appropriate input validation to ensure the user message is provided correctly and meets any required constraints.
- Handle potential errors, such as when the ChatGPT API returns an error response. You can parse the API response and provide meaningful error messages to the client.
That’s it! With these steps, you can integrate the ChatGPT API with Spring Boot and create a chatbot-like functionality. Remember to ensure the proper handling of sensitive information, such as API keys, and follow best practices for securing your application.
You’re a true beacon of knowledge.