DEV Community

dan
dan

Posted on • Edited on

How to Set Up the OpenAI API with Python and Flask

I found it intriguing to develop a user-friendly front end for OpenAI's API to enhance customization. This project marks the initial stages of that project.

The primary focus was on establishing a strong foundation, given my intent to integrate this tool into my daily routine. By following this guide, you can create a simple web interface for interacting with OpenAI's chatGPT. As a learner myself, I understand some of the challenges in finding guides, so I tailored this content with beginners in mind but also short and to the point.

Moving forward, my goal is to expand this project by adding features like a chat history and individual user accounts. This serves as the first installment of the project.

How to Set Up the OpenAI API with Python and Flask

Create your project folder.



mkdir homeGPT
cd homeGPT

Enter fullscreen mode Exit fullscreen mode




Create your virtual environment




python3 -m venv homeGPT

Enter fullscreen mode Exit fullscreen mode




Activate the virtual environment




source homeGPT/bin/activate

Enter fullscreen mode Exit fullscreen mode




Install flask, requests, python-dotenv




pip install flask requests python-dotenv

Enter fullscreen mode Exit fullscreen mode




Create file app.py. I use vim.




vim app.py

Enter fullscreen mode Exit fullscreen mode




Add this code to app.py




from flask import Flask, render_template, request
import os
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv() # Load environment variables from .env
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
client = OpenAI(api_key=OPENAI_API_KEY)

app = Flask(name)

@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
prompt = request.form['prompt']
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
{"role": "user", "content": prompt}
]
)
return render_template('home.html', prompt=prompt, response=response.choices[0].message.content)
else:
return render_template('home.html')

if name == 'main':
app.run(debug=True)

Enter fullscreen mode Exit fullscreen mode




Create a templates folder




mkdir templates

Enter fullscreen mode Exit fullscreen mode




Create a file home.html within templates




vim home.html

Enter fullscreen mode Exit fullscreen mode




Add this code to home.html




<!DOCTYPE html>
<html>
<head>
<title>HomeGPT</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h1>HomeGPT</h1>
<form method="POST">
<div class="form-group">
<input type="text" name="prompt" class="form-control" placeholder="Enter your prompt">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

    {% if response %}
        &lt;div class="mt-3"&gt;
            &lt;h2&gt;The AI Says:&lt;/h2&gt;
            &lt;pre class="bg-light p-3"&gt;{{ response }}&lt;/pre&gt;
        &lt;/div&gt;
    {% endif %}
&lt;/div&gt;
Enter fullscreen mode Exit fullscreen mode

</body>
</html>

Enter fullscreen mode Exit fullscreen mode




Your file structure should look like this.




project_folder/
├── app.py
├── templates/
│ └── home.html

Enter fullscreen mode Exit fullscreen mode




Grab your OpenAI API key Link

Set it as an environment variable



vim ~/.bashrc

Enter fullscreen mode Exit fullscreen mode




Add this line at the end with your own api key.




export OPENAI_API_KEY="yourAPIkey"

Enter fullscreen mode Exit fullscreen mode




This will let you use your new key.




source ~/.bashrc

Enter fullscreen mode Exit fullscreen mode




Now let's test, you should see your api key.




echo $OPENAI_API_KEY

Enter fullscreen mode Exit fullscreen mode




Startup the app




flask run

Enter fullscreen mode Exit fullscreen mode




Assuming no errors, you should see this!

homegpt

Top comments (0)