Build a ChatGPT-Powered Chatbot with JavaScript and Spring Boot
This guide walks you through preparing an OpenAI account, obtaining an API key, using the Completion endpoint with example JSON, calling the API from plain JavaScript/HTML, and integrating the same service into a Spring Boot application with Maven dependencies and Java code.
1. Preparation
(1) Register an OpenAI account.
(2) Create an API key; copy it immediately because it disappears after the dialog closes.
(3) Official API documentation: https://platform.openai.com/docs/api-reference/authentication
(4) API calls are billed, but OpenAI provides $18 of 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
}Key parameters:
model : optional, selects the language model (e.g., text-davinci-003 ).
prompt : required, the user’s input.
max_tokens : optional, default 16, limits the length of the generated text.
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, whether to stream partial results.
3. JavaScript Call
The following HTML/JavaScript creates a simple web page that sends a request to the OpenAI Completion endpoint and prints the answer character‑by‑character.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ChatGPT Demo</title>
<style>#chatgpt-response{font-family:Arial;font-size:20px;color:#0000FF;font-weight:bold}</style>
</head>
<body>
<h4>Describe your request (supports Chinese, English, Japanese, …)</h4>
<textarea id="chat-gpt-input" rows="3" placeholder="Enter description"></textarea>
<button onclick="callCHATGPT()">Answer</button>
<textarea id="chatgpt-response" rows="26" readonly></textarea>
<script>
async function callCHATGPT(){
const responseBox=document.getElementById('chatgpt-response');
responseBox.value='';
const 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"
});
const xhr=new XMLHttpRequest();
xhr.open('POST','https://api.openai.com/v1/completions',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 answer=json.choices[0].text;
let i=0;
const interval=setInterval(()=>{
responseBox.value+=answer[i++]||'';
if(i>=answer.length) clearInterval(interval);
},50);
}
};
await xhr.send(data);
}
</script>
</body>
</html>4. Spring Boot Integration
Create a Spring Boot project (e.g., version 2.7.6) and add the OpenAI Java client dependency:
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>service</artifactId>
<version>0.10.0</version>
</dependency>Java code to call the Completion API:
String token = "YOUR_API_KEY"; // replace with your actual 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);Remember to replace YOUR_API_KEY with the key you generated in step 2.
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.
