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.

  1. Click on the key icon on the left
  2. Add new secret
  3. 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
OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')

Step 3: Simple Request to GPT-3.5


from openai import OpenAI
client = OpenAI(api_key=OPENAI_API_KEY)

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": "Explain the code for an OpenAI API ChatCompletion in simple terms."}
    ]
)

print(response.choices[0].message.content)

Notes

Further Reading

Back to top