Skip to content

Instantly share code, notes, and snippets.

@wircho
Last active January 15, 2023 21:18
Show Gist options
  • Save wircho/1a809b468041b9bf8134b8c0579b9d4a to your computer and use it in GitHub Desktop.
Save wircho/1a809b468041b9bf8134b8c0579b9d4a to your computer and use it in GitHub Desktop.
A chatgpt-wrapper-based Python script that asks ChatGPT questions stored in a Pandas series, and saves the answers in a CSV
import time
import pandas
from chatgpt_wrapper import ChatGPT
chat = ChatGPT()
def run_chat_loop(id_series, question_series, question_prefix, destination_path, pause_duration=1):
assert id_series.shape[0] == question_series.shape[0],\
f"Non matching shapes for id ({id_series.shape}) and question series ({question_series.shape})"
result = pandas.DataFrame({'id': pandas.Series(dtype='str'), 'answer': pandas.Series(dtype='str')})
try:
result = pandas.read_csv(destination_path)
except:
pass
print(f"Source series have length {id_series.shape[0]} and destination dataframe has length {result.shape[0]}")
for i in range(id_series.shape[0]):
id = id_series.loc[i]
if result[result['id'] == id].shape[0] > 0:
print(f"Answer for question #{i} with id {id} already exists in destination. Skipping.")
continue
print(f"Generating answer for question #{i} with id {id}...")
question = question_prefix + question_series.loc[i]
time.sleep(pause_duration)
print(f"Asking question: {question[:100]}")
answer = chat.ask(question)
print(f"Question answered. Appending answer...")
result = pandas.concat((result, pandas.DataFrame({'id': [id], 'answer': [answer]})), ignore_index=True)
print(f"Appended answer. Saving CSV...")
result.to_csv(destination_path)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment