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

  1. Create Project Folder: Create a new folder for your project (e.g., 'chatbot').
  2. Create templates Folder: 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

  1. Open Terminal/Command Prompt: Navigate to your project folder.
  2. Install Flask: pip install flask
  3. Install OpenAI: pip install openai

Step 6: Run the Application

  1. Open Terminal/Command Prompt: Navigate to your project folder.
  2. Start Flask Server: python app.py
  3. 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:

  1. main.py:

    • Imports openai for API access and os for environment variables.
    • Sets openai.api_key to your OpenAI API key (obtained from https://platform.openai.com/account/api-keys).
    • Defines generate_answer() to use OpenAI's Completion.create() function to generate text based on the provided prompt.
  2. app.py:

    • Imports Flask, render_template to serve HTML, and request to handle user input.
    • Creates a Flask app instance.
    • @app.route('/') defines the home route, serving index.html when the server is accessed.
    • @app.route('/answer', methods=['POST']) defines the route to handle POST requests with user prompts. It uses generate_answer() to get a response and then renders index.html with the generated answer.

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.

Build a Functional Chatbot with OpenAI, HTML, and Flask

原文地址: https://www.cveoy.top/t/topic/lCBa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录