ChatGPT as a Co-Author: Transforming 25 Python Examples into an Article
Empowering the content creation.
--
I created a list of Python examples on how to handle missing values in a Pandas DataFrame.
I was going to write an article using these examples. The process is actually straightforward: List the examples and explain what the code does.
Recently, I have been experimenting with ChatGPT and other LLMs so I wanted to give it a shot at this task as well.
I’ll use the OpenAI API through the openai
library for this task. Let’s first import the libraries and set up the API key.
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
openai.api_key = os.getenv('OPENAI_API_KEY')
OPENAI_API_KEY
is the environment variable that holds the API key, which can be obtained from the API Keys menu on OpenAI website.
The following is a helper function that can be used for querying the API:
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0,
)
return response.choices[0].message["content"]
Given a prompt, this function will return the output of the specified model, which is gpt-3.5-turbo by default. The temperature
parameter adjusts the randomness of the output. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
Prompt
Creating the prompt is quite important in querying ChatGPT, or other LLMs. There is an emerging profession around this concept called prompt engineering.
Here is the prompt I’ll use for this task:
prompt = f"""
You are an experienced Python tutor.
Your task is to write an article on how to handle missing values with the Python Pandas library.
You will be given 25 examples.
Create a subsection for each example.
For each example, explain what the code does in one or two sentences.
Also, show the output of the code in the examples.
Examples are given…