Build Your Own ChatGPT-Powered Chatbot with JavaScript and Spring Boot
This guide walks you through creating a personal ChatGPT chatbot by first setting up an OpenAI account and API key, then demonstrating how to call the completions endpoint using plain JavaScript and HTML, followed by integrating the same API into a Spring Boot application with the official Java client library, including all necessary code snippets and configuration steps.
1. Preparation
(1) Register an OpenAI account.
(2) Create an API key (copy it immediately after creation).
(3) Official API documentation URL: https://platform.openai.com/docs/api-reference/authentication
(4) API calls are charged, but OpenAI provides $18 free credit for new users.
2. Completion API Example
Request method: POST
URL: https://api.openai.com/v1/completions
Request body (JSON):
{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0,
"top_p": 1,
"n": 1,
"stream": false
}Parameter explanations:
model : optional, the language model to use, e.g., text-davinci-003.
prompt : required, the user input.
max_tokens : optional, default 16, maximum number of tokens in the response.
temperature : optional, default 1, range 0‑2, controls randomness of the output.
top_p : optional, similar to temperature.
n : optional, default 1, number of completions to generate.
stream : optional, default false, whether to stream partial results.
3. JavaScript Front‑end Implementation
HTML structure includes a textarea for the user prompt, a button to trigger the request, and a readonly textarea to display the response.
<!doctype html>
<html lang="">
<head>
<meta charset="utf-8">
<title>AI - Chat</title>
<style>
#chatgpt-response {font-family: "宋体"; font-size: 20px; color: #0000FF; font-weight: bold;}
</style>
<script>
async function callCHATGPT() {
var responseText1 = document.getElementById("chatgpt-response");
responseText1.innerHTML = "";
async function printMessage(message) {
var responseText = document.getElementById("chatgpt-response");
var index = 0;
var interval = setInterval(function(){
responseText.innerHTML += message[index];
index++;
if (index >= message.length) { clearInterval(interval); }
}, 150);
}
var xhr = new XMLHttpRequest();
var url = "https://api.openai.com/v1/completions";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer API-KEY");
xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
var response = json.choices[0].text;
var responseText = document.getElementById("chatgpt-response");
var index = 0;
var interval = setInterval(function(){
responseText.innerHTML += response[index];
index++;
if (index >= response.length) { clearInterval(interval); }
}, 50);
}
};
var data = JSON.stringify({
"prompt": document.getElementById("chat-gpt-input").value,
"max_tokens": 2048,
"temperature": 0.5,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"model": "text-davinci-003"
});
await printMessage('正在思考,请等待......');
await xhr.send(data);
}
</script>
</head>
<body>
<div class="filter-menu text-center mb-40">
<h4>与 AI 对话,请描述您的需求(支持中文、英文等)</h4>
</div>
<textarea id="chat-gpt-input" placeholder="输入描述" rows="3"></textarea>
<button onclick="callCHATGPT()">回答</button>
<textarea id="chatgpt-response" rows="26" readonly></textarea>
</body>
</html>Replace "Bearer API-KEY" with your own API key.
4. Spring Boot Integration
Add the Maven dependency:
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>service</artifactId>
<version>0.10.0</version>
</dependency>Java code to call the API:
String token = "API-KEY"; // replace with your key
OpenAiService service = new OpenAiService(token);
CompletionRequest request = CompletionRequest.builder()
.model("text-davinci-003")
.prompt("今天天气怎么样?")
.temperature(0.5)
.maxTokens(2048)
.topP(1D)
.frequencyPenalty(0D)
.presencePenalty(0D)
.build();
service.createCompletion(request).getChoices().forEach(System.out::println);Run the Spring Boot application after replacing the API key.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
