Build a Simple OpenAI Chatbot with HTML, Flask, and Python
Build a Simple OpenAI Chatbot with HTML, Flask, and Python
This guide provides a step-by-step tutorial on creating a basic chatbot using HTML for the user interface, Flask for web framework, and Python to interact with the OpenAI API. The project will involve three files:
- index.html: Handles the user interface with input and output fields.
- main.py: Contains the Python code to connect to the OpenAI API and generate responses.
- app.py: Runs the Flask application that serves the HTML file and handles communication between the user interface and the Python code.
1. Project Setup and Files
- Create a new directory: This directory will hold all project files.
- Create three files:
index.html,main.py, andapp.pyin the directory.
2. HTML File: index.html
<!DOCTYPE html>
<html>
<head>
<title>OpenAI Chatbot</title>
</head>
<body>
<h1>OpenAI Chatbot</h1>
<label for='prompt'>Prompt:</label>
<input type='text' id='prompt' name='prompt'><br><br>
<label for='response'>Response:</label>
<input type='text' id='response' name='response' readonly>
<button onclick='getResponse()'>Get Response</button>
<script>
function getResponse() {
var prompt = document.getElementById('prompt').value;
var xhr = new XMLHttpRequest();
xhr.open('GET', '/get-response?prompt=' + prompt, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('response').value = xhr.responseText;
}
};
xhr.send();
}
</script>
</body>
</html>
Explanation:
- The HTML code creates a simple web page with:
- A heading:
<h1>OpenAI Chatbot</h1> - Two textboxes:
prompt: For the user to enter their question or prompt.response: To display the AI's response. (Setreadonlyto prevent direct user input).
- A button:
Get Responsethat triggers thegetResponse()function when clicked.
- A heading:
- The
getResponse()JavaScript function does the following:- Gets the prompt value from the
prompttextbox. - Sends a GET request to the
/get-responseendpoint of the Flask application (which will be handled by themain.pyfile). - Updates the
responsetextbox with the received response from the Flask application.
- Gets the prompt value from the
3. Python Program: main.py
import openai
from flask import Flask, request
app = Flask(__name__)
# Replace 'YOUR_API_KEY' with your actual OpenAI API key
openai.api_key = 'YOUR_API_KEY'
def generate_response(prompt):
response = openai.Completion.create(
engine='davinci',
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5
)
return response.choices[0].text.strip()
@app.route('/get-response')
def get_response():
prompt = request.args.get('prompt')
response = generate_response(prompt)
return response
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- Import necessary libraries:
openaifor interacting with the OpenAI API andFlaskfor the web framework. - Initialize Flask app:
app = Flask(__name__) - Set OpenAI API Key: Replace
'YOUR_API_KEY'with your actual OpenAI API key. generate_response(prompt)function:- Takes the user's prompt as input.
- Sends a request to the OpenAI API (using the
davinciengine by default) to generate a response. - Returns the generated response text after stripping any extra whitespace.
@app.route('/get-response'): This decorator defines the/get-responseendpoint for the Flask application.get_response()function:- Retrieves the prompt value from the request using
request.args.get('prompt'). - Calls
generate_response()to get the AI's response to the prompt. - Returns the generated response to the HTML file (which is handled by the JavaScript code).
- Retrieves the prompt value from the request using
if __name__ == '__main__':: This runs the Flask application when themain.pyfile is executed directly.
4. Flask Application: app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
Explanation:
- Import necessary libraries:
Flaskandrender_templatefor serving the HTML file. - Initialize Flask app:
app = Flask(__name__) @app.route('/'): This decorator defines the root URL/for the Flask application.index()function: Renders theindex.htmlfile and returns it to the user.
if __name__ == '__main__':: This runs the Flask application when theapp.pyfile is executed directly.
5. Installation and Running
-
Install Flask:
pip install flask -
Install OpenAI:
pip install openai -
Get Your OpenAI API Key: Sign up for an OpenAI account at https://beta.openai.com/ and find your API key in the API Keys section of your account settings.
-
Run the App:
-
Open a terminal or command prompt and navigate to the directory where your files are stored.
-
Run the following command:
python app.py
-
-
Open the Chatbot:
- Your chatbot will be accessible at
http://localhost:5000/in your web browser.
- Your chatbot will be accessible at
-
Interact:
- Enter a prompt in the
Prompttextbox. - Click the
Get Responsebutton. - The AI's response will appear in the
Responsetextbox.
- Enter a prompt in the
Conclusion
You've now built a functional OpenAI chatbot! You can experiment with different prompts and see how the chatbot responds. Feel free to customize the code and user interface further. Happy chatting!
原文地址: https://www.cveoy.top/t/topic/lCAY 著作权归作者所有。请勿转载和采集!