5.2. Quickstart with GPT
API Key
Create an account for OpenAI and log in to your account.
Click your icon on the top-right corner and select "View API keys":
Click the "+ Create new secret key" button and copy the API key:
Make sure to save this key in a local file. If you close the dialog without saving, you cannot retrieve the key again, in which case, you have to create a new one.
Create a file openai_api.txt
under the resources
directory and paste the API key to the file such that it contains only one line showing the key.
Add openai_api.txt
to the .gitignore
file:
Do not share this key with anyone or push it to any remote repository (including your private GitHub repository).
Using GPT API
Open the terminal in PyCharm and install the OpenAI package:
Create a function called api_key()
as follow:
#4
: specifies the path of the file containing the OpenAI API key.
Retrieve a response by creating a ChatCompletition
module:
#1
: the GPT model to use.#2
: the content to be sent to the GPT model.#3
: creates the chat completion model and retrieves the response.#5
: messages are stored in a list of dictionaries where each dictionary contains content from either theuser
or thesystem
.
Print the type of the response and the response itself that is in the JSON format:
#1
: the response type.#2
: the response in the JSON format.
Print only the content from the output:
Last updated