How to Build a ChatGPT‑Powered Chatbot Using the OpenAI API (HTML/JS and Spring Boot Examples)
This guide walks you through registering an OpenAI account, obtaining an API key, understanding the completions endpoint parameters, and implementing a ChatGPT chatbot with both a plain JavaScript/HTML front‑end and a Spring Boot back‑end, including full code samples.
After experiencing the power of ChatGPT, you may want to create your own chatbot; this article explains how to do it using the OpenAI API.
Preparation : register an OpenAI account, create an API key (keep it saved immediately), note that OpenAI provides $18 of free credit, and refer to the authentication documentation at https://platform.openai.com/docs/api-reference/authentication.
Completion API example : send a POST request to https://api.openai.com/v1/completions with a JSON body. The request parameters are:
Field
Description
model
e.g.,
text-davinci-003prompt
required, the user input
max_tokens
optional, default 16, maximum token count of the response
temperature
optional, default 1, range 0‑2, controls randomness
top_p
optional, works like
temperaturen
optional, default 1, number of completions to generate
stream
optional, default false, whether to stream partial results
Example JSON payload:
{
"model": "text-davinci-003",
"prompt": "Say this is a test",
"max_tokens": 7,
"temperature": 0,
"top_p": 1,
"n": 1,
"stream": false
}API documentation: https://platform.openai.com/docs/api-reference/completions/create.
JavaScript implementation : a single HTML file creates a simple chat UI and calls the API via XMLHttpRequest . The script builds the request body, sends it with the Authorization: Bearer YOUR_API_KEY header, and displays the response character by character.
<!doctype html>
<html class="no-js" 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() {
const xhr = new XMLHttpRequest();
const url = "https://api.openai.com/v1/completions";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer YOUR_API_KEY");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const json = JSON.parse(xhr.responseText);
const response = json.choices[0].text;
// display response gradually
const responseText = document.getElementById("chatgpt-response");
let index = 0;
const interval = setInterval(() => {
responseText.innerHTML += response[index];
index++;
if (index >= response.length) clearInterval(interval);
}, 50);
}
};
const data = JSON.stringify({
prompt: document.getElementById("chat-gpt-input").value,
max_tokens: 2048,
temperature: 0.5,
top_p: 1,
model: "text-davinci-003"
});
xhr.send(data);
}
</script>
</head>
<body>
<textarea id="chat-gpt-input" placeholder="输入描述" rows="3"></textarea>
<button onclick="callCHATGPT()">回答</button>
<textarea id="chatgpt-response" readonly rows="26"></textarea>
</body>
</html>Spring Boot integration : create a Spring Boot 2.7.6 project, add the dependency com.theokanning.openai-gpt3-java:service:0.10.0 , and use the following Java code to call the completion API.
String token = "YOUR_API_KEY"; // or System.getenv("OPENAI_TOKEN");
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);Remember to replace YOUR_API_KEY in both the JavaScript and Java examples before running them.
The article also includes screenshots of the UI and promotional images for a WeChat architecture community, which are not required for the technical steps.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
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.