Build Your Own ChatGPT‑Powered Chatbot with JavaScript and Spring Boot
This guide walks you through registering for an OpenAI account, creating an API key, understanding the completion endpoint parameters, and implementing a ChatGPT‑driven chatbot using plain JavaScript/HTML as well as a Spring Boot backend, complete with code samples and configuration steps.
1. Preparation
Register an OpenAI account and generate an API key for HTTP authentication. The key must be copied immediately because it cannot be retrieved later.
Official API documentation: Authentication . OpenAI provides $18 of free credit for testing.
2. Completion API Example
The completion endpoint supports the most common question‑answer use case.
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
}Key parameters:
model : language model to use (e.g., text-davinci-003).
prompt : required user input.
max_tokens : optional, default 16, controls the maximum length of the response.
temperature : optional, default 1, range 0‑2; higher values produce more random output.
top_p : optional, works similarly to temperature.
n : optional, default 1; number of completions to generate per prompt.
stream : optional, default false; if true, partial results are streamed.
3. Obtaining an API‑Key
Visit https://platform.openai.com/account/api-keys , log in, and create a new API key. Store it securely because it will not be shown again.
4. JavaScript Front‑End Integration
Use plain HTML and JavaScript to call the API. Replace API-KEY with your own key.
<!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 = "";
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;
printMessage(response);
}
};
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 xhr.send(data);
}
</script>
</head>
<body>
<h4>Chat with AI – describe your request (supports Chinese, English, Japanese, etc.)</h4>
<textarea id="chat-gpt-input" placeholder="Enter description" rows="3"></textarea>
<button onclick="callCHATGPT()">Answer</button>
<textarea id="chatgpt-response" rows="26" readonly></textarea>
</body>
</html>After replacing the placeholder key, open the HTML file in a browser and test the interaction.
5. Spring Boot Backend Integration
Create a Spring Boot 2.7.6 project and add the OpenAI Java client dependency:
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>service</artifactId>
<version>0.10.0</version>
</dependency>Use the library to call the completion 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(1)
.frequencyPenalty(0)
.presencePenalty(0)
.build();
service.createCompletion(request).getChoices().forEach(System.out::println);Run the Spring Boot application and invoke the endpoint from your front‑end code.
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.
