Member-only story
Using ChatGPT in Jupyter Notebooks
A Simple Implementation to Use OpenAI Chat Completions in Jupyter Notebooks
While working on a research project in JupyterLab, I found myself too frequently jumping back and forth between ChatGPT and the notebook. My research has to do with prompt engineering, so capturing the ongoing dialog is important. This encouraged me to write a small Python class, allowing me to conduct my full workflow in Jupyter.
Here’s how you can configure it in your notebook, too!
Install Packages, Load Environment Variables
Firstly, install the required dependencies in your Jupyter Notebook. This includes the OpenAI library for interacting with OpenAI models and python-dotenv for handling environment variables securely.
# Install required modules and set required tokens
!pip install openai python-dotenv
# Load the .env file in a Jupyter notebook:
%load_ext dotenv
%dotenv
I use the python-dotenv
package to manage environment variables in a local .env
file. This is an important step to protect your OpenAI API Key and Organization ID when sharing or committing the notebook to Git.
For your .env
file, it needs to contain (at a minimum) the following values.