atsushi-ambo
Posted on March 18, 2023
The official OpenAI web site has a description of how to use the API, so I built it along with a sample application.
Prerequisite
Python already installed. If you have not installed it, click here.
Prepare the code for the application
Clone the following repository and install the application files. Or, download the zip file from the official website.
% git clone https://github.com/openai/openai-quickstart-python.git
Add an API key
Change the directory to the cloned repository. Create a new .env file.
% cd openai-quickstart-python
% cp .env.example .env
Confirm that you created the file.The username is hidden for security reasons.
% ls -l
total 56
416B Mar 12 16:57 .
160B Mar 12 16:37 ..
213B Mar 12 17:04 .env
162B Mar 8 12:06 .env.example
115B Mar 8 12:06 .gitignore
1.0K Mar 8 12:06 LICENSE
1.2K Mar 8 12:06 README.md
96B Mar 12 16:57 __pycache__
940B Mar 8 12:06 app.py
413B Mar 8 12:06 requirements.txt
128B Mar 8 12:06 static
96B Mar 8 12:06 templates
192B Mar 12 16:49 venv
You can create an API key on the official page.
Then add that key to the newly created .env file.
% code .env
FLASK_APP=app
FLASK_ENV=development
# Once you add your API key below, make sure to not share it with anyone! The API key should remain private.
OPENAI_API_KEY="Put the key here"
Run the application
Run the following command to start the application. The Python command varies depending on the version.
python3 -m venv venv
. venv/bin/activate
pip3 install -r requirements.txt
flask run
* Serving Flask app 'app' (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 177-654-623
I was able to launch the application. Go to http://127.0.0.1:5000/ in your browser to see the app. Enter the name of the animal and it will suggest 3 superhero animal names!
This concludes the construction of the application. The next step is to look at the code.
Check the code
If you open the app.py file, you can see the code. The actual API request is sent at response = openai. I am using the code command in the VS Code to open the file.
% code app.py
import os
import openai
from flask import Flask, redirect, render_template, request, url_for
app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")
@app.route("/", methods=("GET", "POST"))
def index():
if request.method == "POST":
animal = request.form["animal"]
response = openai.Completion.create(
model="text-davinci-003",
prompt=generate_prompt(animal),
temperature=0.6,
)
return redirect(url_for("index", result=response.choices[0].text))
result = request.args.get("result")
return render_template("index.html", result=result)
def generate_prompt(animal):
return """Suggest three names for an animal that is a superhero.
Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: {}
Names:""".format(
animal.capitalize()
)
I am not familiar with the coding. so I asked ChatGPT what this code is about. It seems to me that ChatGPT can explain this very well.
Here's a breakdown of the code:
1.Importing required libraries:
import os
import openai
from flask import Flask, redirect, render_template, request, url_for
os is a Python standard library that provides a way of interacting with the operating system. openai is a Python library for interacting with OpenAI's API. Flask is a Python web framework, and render_template, request, and url_for are functions from Flask that are used to render HTML templates, handle incoming requests, and generate URLs, respectively.
2.Creating a Flask app and setting up OpenAI API key:
app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")
Here, we create a Flask app object and set the OpenAI API key by getting the value of the OPENAI_API_KEY environment variable.
3.Defining the index route:
@app.route("/", methods=("GET", "POST"))
def index():
if request.method == "POST":
animal = request.form["animal"]
response = openai.Completion.create(
model="text-davinci-003",
prompt=generate_prompt(animal),
temperature=0.6,
)
return redirect(url_for("index", result=response.choices[0].text))
result = request.args.get("result")
return render_template("index.html", result=result)
This function is executed when a user navigates to the homepage of the web app. If the user submits a form with an animal name, the function generates three superhero names for that animal using the OpenAI API and returns the results. If the user navigates to the homepage without submitting a form, the function renders the index template with the previous results.
4.Defining the generate_prompt function:
def generate_prompt(animal):
return """Suggest three names for an animal that is a superhero.
Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: {}
Names:""".format(
animal.capitalize()
)
This function takes an animal name as an argument and returns a string prompt that will be passed to the OpenAI API. The prompt provides examples of superhero names for cats and dogs, and the given animal's name is inserted at the end.
Overall, this web app takes an animal name as input and generates three superhero names for that animal using the OpenAI API.
Posted on March 18, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 26, 2024