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:

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:
.idea/
venv/
/resources/openai_api.txt
Using GPT API
Open the terminal in PyCharm and install the OpenAI package:
(venv) $ pip install openai
Create a function called api_key()
as follow:
import openai
PATH_API_KEY = 'resources/openai_api.txt'
openai.api_key_path = PATH_API_KEY
#4
: specifies the path of the file containing the OpenAI API key.
Retrieve a response by creating a ChatCompletition
module:
model = 'gpt-3.5-turbo'
content = 'Say something inspiring'
response = openai.ChatCompletion.create(
model=model,
messages=[{'role': 'user', 'content': content}]
)
#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:
<class 'openai.openai_object.OpenAIObject'>
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "\n\n\"Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle.\"",
"role": "assistant"
}
}
],
"created": 1678893623,
"id": "chatcmpl-6uNDL6Qfh7MjxpLxH3NW7UPJXS3tN",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 26,
"prompt_tokens": 10,
"total_tokens": 36
}
}
#1
: the response type.#2
: the response in the JSON format.
Print only the content from the output:
output = response['choices'][0]['message']['content'].strip()
print(output)
"Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle."
Last updated
Was this helpful?