Build a Functional Chatbot with OpenAI, HTML, and Flask
Build a Functional Chatbot with OpenAI, HTML, and Flask
This guide walks you through building a simple chatbot using OpenAI's API, HTML for the user interface, and Flask to connect them. We'll cover installation, coding, and deployment in a clear, step-by-step manner.
Prerequisites:
- Basic knowledge of HTML, Python, and Flask.
- Python 3.6 or higher installed.
Step 1: Project Setup
- Create Project Folder: Create a new folder for your project (e.g., 'chatbot').
- Create
templatesFolder: Inside the project folder, create a subfolder named 'templates'.
Step 2: HTML File (index.html)
Save the following code in templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Chatbot</title>
</head>
<body>
<h1>Chatbot</h1>
<label for='prompt'>Enter your message:</label>
<input type='text' id='prompt' name='prompt'><br><br>
<label for='answer'>Bot's answer:</label>
<input type='text' id='answer' name='answer' readonly>
</body>
</html>
Step 3: Python Program (main.py)
Save the following code in main.py:
import openai
import os
openai.api_key = 'YOUR_API_KEY_HERE' # Replace with your OpenAI API key
def generate_answer(prompt):
response = openai.Completion.create(
engine='davinci',
prompt=prompt,
temperature=0.5,
max_tokens=1000,
top_p=1,
frequency_penalty=0,
presence_penalty=0
)
answer = response.choices[0].text.strip()
return answer
Step 4: Flask Application (app.py)
Save the following code in app.py:
from flask import Flask, render_template, request
from main import generate_answer
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/answer', methods=['POST'])
def answer():
prompt = request.form['prompt']
answer = generate_answer(prompt)
return render_template('index.html', answer=answer)
if __name__ == '__main__':
app.run(debug=True)
Step 5: Install Dependencies
- Open Terminal/Command Prompt: Navigate to your project folder.
- Install Flask:
pip install flask - Install OpenAI:
pip install openai
Step 6: Run the Application
- Open Terminal/Command Prompt: Navigate to your project folder.
- Start Flask Server:
python app.py - Access in Browser: Open your web browser and go to
http://127.0.0.1:5000/
How it works:
index.html: Provides the user interface with input fields for the prompt and answer.main.py: Contains the logic for interacting with the OpenAI API and generating responses to user prompts.app.py: Uses Flask to connect the HTML frontend with the Python backend, handling requests and responses between them.
Explanation:
-
main.py:- Imports
openaifor API access andosfor environment variables. - Sets
openai.api_keyto your OpenAI API key (obtained from https://platform.openai.com/account/api-keys). - Defines
generate_answer()to use OpenAI'sCompletion.create()function to generate text based on the provided prompt.
- Imports
-
app.py:- Imports Flask,
render_templateto serve HTML, andrequestto handle user input. - Creates a Flask app instance.
@app.route('/')defines the home route, servingindex.htmlwhen the server is accessed.@app.route('/answer', methods=['POST'])defines the route to handle POST requests with user prompts. It usesgenerate_answer()to get a response and then rendersindex.htmlwith the generated answer.
- Imports Flask,
Conclusion:
By following these steps, you've built a basic chatbot that interacts with OpenAI, providing a simple but functional user interface through HTML and Flask. This foundation can be further expanded upon to add more complex features and functionality to your chatbot.
原文地址: https://www.cveoy.top/t/topic/lCBa 著作权归作者所有。请勿转载和采集!