custom-chatgpt / my_functions /save_response.py
daveckw's picture
Edited
d9814cc
raw
history blame
1.97 kB
import os
import os.path
import datetime
import json
import codecs
# Get the current date
today = datetime.date.today()
# Convert the date to a string using the strftime() method
date_string = today.strftime("%Y-%m-%d")
# Print the date string
print(date_string)
def save_response(input_text, response):
# Open the responses.txt file using the UTF-8 encoding
with codecs.open("responses.txt", "a", "utf-8") as file:
# Write or append text to the file
response_txt = (
date_string
+ "\n"
+ "Input: "
+ input_text
+ "\n"
+ "Response: "
+ response.response
+ "\n\nSource:"
+ response.get_formatted_sources()
+ "\n------------------------\n\n"
)
file.write(response_txt + "\n")
# Save as JSON format
response_json = {
"date": date_string,
"input": input_text,
"response": response.response,
"source": response.get_formatted_sources(),
}
# Check if the responses.json file exists
if os.path.isfile("responses.json"):
# Open the existing JSON file in read mode using the UTF-8 encoding
with codecs.open("responses.json", "r", "utf-8") as f:
# Load the existing JSON data into memory and parse it
data = json.load(f)
else:
# The file doesn't exist, initialize the data with an empty list
data = []
# Append the new JSON object to the existing data
if isinstance(data, list):
# The existing data is a list, so we can append to it
data.append(response_json)
else:
# The existing data is not a list, so we create a new list
data = [data, response_json]
# Open the JSON file in write mode using the UTF-8 encoding and write the updated data to it
with open("responses.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False)