The Guide to Call ChatGPT 3.5 Event Stream API in Spring Boot
Create a spring boot project
You can go to Spring Initializr to create a spring boot project
Setting your basic configurations. The following is my settings
- Project: Maven
- Language: Java
- Spring Boot: 2.7.9
- Project Metadata:
- Group: com.taogen
- Aritifact: chatgpt-demo
- Packaging: Jar
- Java: 8
You can set your own configurations according to your local environment.
After setting the project configurations, we need to add the following dependencies:
- Spring Web
- Lombok
Then we click the GENERATE button to download our project file.
After downloading the generated project file, we need to decompress the file and open the directory in our IDE. I prefer to use IntelliJ IDEA as my IDE.
Call the ChatGPT API in spring boot
Configuring your Open AI key in application.properties
openai.apiKey=${YOUR_OPEN_AI_KEY} |
Create the RestTemplateConfig.java
to build the RestTemplate
bean for API calls
|
Create a POJO ChatGpt3dot5Request.java
for building ChatGPT API requests
|
Create the controller ChatBotController.java
|
The ChatBotController
sends an HTTP request to ChatGPT API and reads its response stream line by line. Each line of the response has a similar structure. We extract the chat content by removing the prefix data:
, parsing the string to a JSON object, and retrieving the content value. This content is then written into the response of our chatbot API. The following is an example of the content of the ChatGPT API response.
Click to expand!
data: {"id":"chatcmpl-6zET7QIiAHSVeqoBwPNncxtIL3L6O","object":"chat.completion.chunk","created":1680051645,"model":"gpt-3.5-turbo-0301","choices":[{"delta":{"role":"assistant"},"index":0,"finish_reason":null}]} |
Call your spring boot application API
Send a “hello” prompt to ChatGPT API by your API
curl -d 'hello' -H 'Content-Type: application/json' -X POST http://localhost:8080/chatbot/conversation |
Hi there! How can I assist you today? |
Note: If ChatGPT is not available in your region, you will not be able to call the ChatGPT API and the request will time out. Your application may throw the following exception:
2023-03-16 14:40:22.680 ERROR 14704 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://api.openai.com/v1/engines/davinci-codex/completions": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect] with root cause |