Step-by-Step Guide to Building a Simple Chat Application with GPT-4o-mini API
This guide explains how to create a simple chat application using the OpenAI API and Flask, a Python web framework. You'll learn to set up your development environment, integrate the OpenAI API for generating responses, and build a web interface for user interaction.
Prerequisites
- Basic knowledge of Python
- OpenAI API Key (available from OpenAI's website)
- Flask (Python web framework)
- HTML/CSS knowledge for the frontend
Step 1: Set Up Your Development Environment
-
Install Python if it is not already installed. Download it from python.org.
-
Set up a virtual environment:
python -m venv myenv source myenv/bin/activate # On Windows use `myenv\Scripts\activate`
-
Install necessary libraries:
pip install openai flask
Step 2: Create the Flask App
-
Create a directory for the project:
mkdir openai_chat_app cd openai_chat_app
-
Create a Python file (
app.py
) for the Flask app:from flask import Flask, request, render_template import openai app = Flask(__name__) # Set your OpenAI [API](/glossary/api) key openai.api_key = 'your_openai_api_key' @app.route('/') def index(): return render_template('index.html') @app.route('/chat', methods=['POST']) def chat(): user_input = request.form['user_input'] response = openai.ChatCompletion.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": user_input} ] ) chat_response = response.choices[0].message['content'] return render_template('index.html', user_input=user_input, chat_response=chat_response) if __name__ == '__main__': app.run(debug=True)
Step 3: Create the HTML Template
- Create a
templates
directory and anindex.html
file inside it:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>OpenAI Chat App</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } .chat-box { max-width: 600px; margin: auto; } textarea { width: 100%; height: 100px; } .response { margin-top: 20px; } </style> </head> <body> <div class="chat-box"> <h1>Chat with OpenAI</h1> <form action="/chat" method="POST"> <textarea name="user_input" placeholder="Type your message here..."></textarea> <button type="submit">Send</button> </form> {% if user_input %} <div class="response"> <h2>Your Input:</h2> <p>{{ user_input }}</p> <h2>OpenAI's Response:</h2> <p>{{ chat_response }}</p> </div> {% endif %} </div> </body> </html>
Step 4: Run the App
-
Run your Flask app:
python app.py
-
Open your browser and go to
http://127.0.0.1:5000/
. You will see a chat interface for user text input and AI responses.
You have successfully built a basic chat application using the OpenAI API with Flask. This app allows users to interact with the AI model, providing a foundation for developing more advanced applications.
(Edited on September 4, 2024)