-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatGPTRequest.py
More file actions
87 lines (67 loc) · 2.63 KB
/
ChatGPTRequest.py
File metadata and controls
87 lines (67 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import csv
import openai
import time
import multiprocessing
from openai import ChatCompletion
with open("key.txt") as f:
openai.api_key = f.read().strip()
# Read the CSV file with proper encoding
with open('input.csv', 'r', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
rows = list(reader)
# Function to process a single row
def process_row(row, index):
if index == 1:
# Skip the header row
return None
prompt = row[0].strip()
try:
# Create the response
response = ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
time.sleep(2) # Pause for 2 seconds to avoid rate limiting
# Extract the generated response
generated_response = response['choices'][0]['message']['content']
# Create a new row with the prompt and generated response
new_row = {
'Prompt': prompt,
'Response': generated_response
}
print(f"#{index}: Generated response for prompt: {prompt}")
return new_row
except openai.error.OpenAIError as e:
# Handle OpenAI API errors
error_message = str(e)
new_row = {
'Prompt': prompt,
'Response': f"OpenAI API Error: {error_message}"
}
print(f"#{index}: Error for prompt: {prompt} - OpenAI API Error: {error_message}")
return new_row
except Exception as e:
# Handle other exceptions
error_message = str(e)
new_row = {
'Prompt': prompt,
'Response': f"Error: {error_message}"
}
print(f"#{index}: Error for prompt: {prompt} - Error: {error_message}")
return new_row
if __name__ == '__main__':
# Create a multiprocessing Pool
pool = multiprocessing.Pool()
# Process each row in parallel and collect the results
results = [pool.apply_async(process_row, (row, index)) for index, row in enumerate(rows[1:], 2)]
updated_rows = [res.get() for res in results if res.get() is not None] # Exclude None values
# Close the multiprocessing Pool
pool.close()
pool.join()
# Write the updated rows to the CSV file with proper encoding
fieldnames = ['Prompt', 'Response'] # Set the desired fieldnames for the CSV file
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(updated_rows)
print("Responses written to CSV file.")