1 Nprut2jtpyzwh Dq1dkqna

ChatGTP Integration with Spring Boot Application

Zeeshan AdilLast Seen: Nov 14, 2023 @ 5:35pm 17NovUTC
Zeeshan Adil

14th November 2023 | 9 Views
Milyin » 473029 » ChatGTP Integration with Spring Boot Application

Info: This Creation is monetized via ads and affiliate links. We may earn from promoting certain products in our Creations, or when you engage with various Ad Units.

How was this Creation created: We are a completely AI-free platform, all Creations are checked to make sure content is original, human-written, and plagiarism free.


You might be familiar with the term “prompt” in ChatGPT. In the context of ChatGPT or similar language models, a prompt refers to the input or initial text provided by the user to generate a response. It’s the text or query that you input into the model to get a relevant output. The prompt essentially serves as an instruction or a starting point for the language model to understand and generate a coherent response. The quality and clarity of the prompt significantly influence the model’s ability to provide accurate and relevant information or responses.

What is ChatGTP?

I posed this question to ChatGPT to see what response it would generate.

ChatGPT is a type of generative AI that allows users to input prompts and receive outputs in the form of human-like images, text, or videos, all generated by artificial intelligence.

ChatGPT currently utilizes the GPT-3.5 model, featuring a refined algorithm through a fine-tuning process. However, the enhanced version, ChatGPT Plus, incorporates the GPT-4 model. This upgraded version boasts faster response times, supports internet plugins, and exhibits improved capabilities for handling intricate tasks like image description, image caption generation. OpenAI characterizes GPT-4 as being ten times more advanced than its forerunner, GPT-3.5. This advancement empowers the model to exhibit improved contextual understanding and nuanced distinctions, leading to responses that are more precise and coherent.


We’ll call the create chat completion API  (POST https://api.openai.com/v1/chat/completions) to generate responses to a prompt. Let’s explore the OpenAI ChatGTP API.

What request do we need to send to invoke the OpenAI API?

Upon accessing the “Create Chat Completion” API link, the following information regarding endpoint, request, and response is visible.

Endpoint: POST https://api.openai.com/v1/chat/completions

Go to Playgroud and type any message e.g. “What is spring boot?”

Now click on “View Code”. You will see the curl command for your prompt “What is spring boot?”. 

Copy the command and import it in postman client. 

This is request which we are passing to get the response from OpenAI completion API.

Examining the essential request parameters for the API:

1. Model: This parameter designates the version of the model to which requests will be sent. Various model versions exist, and for this purpose, we’ll utilize the gpt-3.5-turbo model, the latest publicly available version.

2. Messages: Messages serve as prompts for the model. Each message comprises two essential fields: “role” and “content.” The “role” field specifies the message sender, denoted as “user” in requests and “assistant” in responses. The “content” field contains the actual message content.

Model and Message are mandatory parameters to be included in API request.

Additional optional parameters include:

3. n: The default value is 1, representing the number of responses to generate for each input message.

4. temperature: The default value is 1, and it should be within the range of 0 to 2. This parameter regulates the randomness of the response. Higher values increase randomness, whereas lower values enhance focus and determinism.

5. max_tokens: By default, there is no limit, but this parameter allows you to specify the maximum number of tokens to generate in the response. It proves useful in managing very large responses and controlling costs.

When making the aforementioned request in Postman, authentication failure will occur unless the OpenAI API Key is passed as a bearer token. It is essential to include the OpenAI API Key as a bearer token to authenticate the OpenAI ChatGPT completion API.

Create OpenAI API Key

Sign up & create your own OpenAI API key here.

Let’s set up the spring boot application now… 😊

Project Structure as below:

We need following dependencies in pom.xml


Create ChatBotRequest, ChatBotResponse & Message DTOs under dtos package:

public class ChatBotRequest {

private String model;
private List<Message> messages;
private int n;
private double temperature;
private int max_tokens;


public class ChatBotResponse {

private List<Choice> choices;

public static class Choice {
private int index;
private Message message;


public class Message {

private String role;
private String content;


Add below configurations in application.properties file:



RestTemplate Configuration:

Create a class OpenAIChatGtpConfig under configurations package:

public class OpenAIChatGtpConfig {

private String openaiApiKey;

public RestTemplate restTemplate() {

RestTemplate restTemplate = new RestTemplate();

restTemplate.getInterceptors().add((request, body, execution) -> {
request.getHeaders().add("Authorization", "Bearer " + openaiApiKey);
return execution.execute(request, body);

return restTemplate;
  1. @Value("${openai.chatgtp.api.key}"): This annotation is used to inject values from the application’s properties file. In this case, it retrieves the API key for OpenAI from the property file.
  2. restTemplate.getInterceptors().add(...): Configures an interceptor for the RestTemplate. The interceptor is added to the list of interceptors and is responsible for modifying the HTTP request before it is sent.
  3. The interceptor ((request, body, execution) -> { ... }) adds an “Authorization” header to the HTTP request. The header contains the OpenAI API key in the format “Bearer {apiKey}”.

In summary, this configuration class sets up a RestTemplate bean with an interceptor that adds the OpenAI API key to the “Authorization” header, ensuring that subsequent HTTP requests made by this RestTemplate are authenticated.

API Controller

Now, we can proceed to create the REST controller responsible for utilizing the previously configured `RestTemplate` to make API requests and handling the corresponding API responses.

Create a class ChatBotController under controllers package:

public class ChatBotController {

private RestTemplate restTemplate;

private String model;

private int maxCompletions;

private double temperature;

private int maxTokens;

private String apiUrl;

public BotResponse chat( @RequestParam("prompt") String prompt) {

BotRequest request = new BotRequest(model,
List.of(new Message("user", prompt)),

BotResponse response = restTemplate.postForObject(apiUrl, request, BotResponse.class);
return response;

We have done with coding now. Let’s test the application….

What can we achieve using the OpenAI ChatGPT Completion API?

Here are some of the things you can achieve using the OpenAI Completion API with models like ChatGPT:

  1. Natural Language Generation: You can generate human-like text for various purposes, such as content creation, creative writing, and more.
  2. Text Summarization: You can use the model to summarize long texts or articles, condensing the information into shorter, more digestible forms.
  3. Language Translation: Translate text from one language to another.
  4. Text Completion: You can use ChatGPT to complete sentences or paragraphs, making it useful for filling in missing parts of text.
  5. Question Answering: You can ask the model questions, and it can provide answers based on the context it has been given.
  6. Conversational Agents: Develop chatbots, virtual assistants, or other conversational AI applications for customer support, information retrieval, or engagement with users.
  7. Code Generation: Generate code snippets or assist in programming tasks by providing code examples, explanations, and solutions.
  8. Data Entry and Form Filling: Automatically fill in forms or complete data entry tasks using the model.
  9. Creative Writing: Generate poetry, stories, or other creative content.
  10. Language Understanding: Analyze and understand the intent and sentiment in user queries or messages.
  11. Simulate Characters: Create dialogues and interactions between fictional characters for storytelling or game development.
  12. Educational Assistance: Provide explanations and answers to students’ questions or help with homework.
  13. Content Recommendations: Suggest content, products, or services to users based on their preferences and queries.
  14. Drafting Emails or Documents: Assist in composing emails, reports, or other written documents.
  15. Simulate User Behavior: Generate user reviews, comments, or feedback for testing and training purposes.

These are just some examples of what you can achieve with the OpenAI Completion API and models like ChatGPT. The versatility of the models makes them valuable for a wide range of applications in various industries, including education, healthcare, customer service, content generation, and more. Keep in mind that the quality of the generated text may vary based on the specific use case and the input data provided to the model.

You can find the source code here…


Reach out to me on LinkedIn. Let’s connect:  https://www.linkedin.com/in/zeeshan-adil-a94b3867/

Zeeshan AdilLast Seen: Nov 14, 2023 @ 5:35pm 17NovUTC

Zeeshan Adil



You may also like

Leave a Reply