Setup Google Colab
In this document, we will show you how to use a Google Colab Notebook to make requests to the OpenAI API. Using Google Colab is a great way to experiment with the OpenAI API without having to install any software on your local machine.
Prerequisites
Before you start, you will need:
- A free Google account
- An OpenAI API Key (from the previous section)
Step 1: Prepare Google Colab Notebook
Open a new notebook in Google Colab and install the OpenAI package:
!pip install openai
Step 2: Set API Key with Google Colab Secrets
To use your OpenAI API key securely, we recommend using Google Colab Secrets.
- Click on the key icon on the left
- Add new secret
- Add your API key there under the name
OPENAI_API_KEY
Then you can use the following code in your notebook:
from google.colab import userdata
= userdata.get('OPENAI_API_KEY') OPENAI_API_KEY
Step 3: Simple Request to GPT-3.5
from openai import OpenAI
= OpenAI(api_key=OPENAI_API_KEY)
client
= client.chat.completions.create(
response ="gpt-4o-mini",
model=[
messages"role": "user", "content": "Explain the code for an OpenAI API ChatCompletion in simple terms."}
{
]
)
print(response.choices[0].message.content)
Notes
- The API usage is billed per token. Check your usage regularly in the OpenAI Dashboard.