How to use OpenAI with Spring Boot?

In this article, I will be creating a new REST API using Spring Boot to interact with OpenAI. Simply you can ask something from it and get the result. This is a very simple application that demonstrates how you can use OpenAI API with Spring Boot.

What is ChatGPT?

ChatGPT is one of the most popular terms today. ChatGPT is the result of AI technology based on GPT architecture. Here is the statement generated by ChatGPT
ChatGPT is a pre-trained language model developed by OpenAI. It is based on the GPT (Generative Pre-trained Transformer) architecture and is trained on a large dataset of conversational text. It is designed to generate human-like text in response to prompts and can be fine-tuned for various language tasks such as question answering, text completion, and dialogue generation. ChatGPT is a variant of the GPT-3 model, which is trained on a much larger dataset and has 175 billion parameters. It is considered one of the most powerful language models currently available, with the ability to generate human-like text, complete tasks like translation, summarization and more.

Find out more, What is ChatGPT?

Required dependencies

Let's create the Controller

Service implementation

I am using RestTemplate to make the API simple. As you can see, the API KEY is used as the Bearer token. You can generate it from

In this example, I am using OpenAI Create completion API.

You will see a few attributes like model, max_token, temperature, and top_p. Those are OpenAI attributes.


The model is a machine learning model. In this example, I am using the popular model called text-davinci-002. This model is used to predict data.

Max token

This is used to specify the max number of tokens generated by the model.


The temperature parameter in GPT-3 is a hyperparameter that controls the randomness or creativity of the model’s outputs.

Lower temperatures give more conservative and predictable output, while higher temperatures give more creative and varied output.

Top P

The top p parameter specifies a sampling threshold during inference time. It is actually another way to control the randomness and creativity of the text.

Request Objects

Response Objects

Configuration file

You can add the relevant API KEY for your account.

The final output

I tested this in Postman. Here is the way how it looks.

Please find the GitHub link for the application.

How to use OpenAI with Spring Boot? How to use OpenAI with Spring Boot? Reviewed by Ravi Yasas on 2:48 AM Rating: 5

No comments:

Powered by Blogger.