import json
import os
def create_json(group_id, user_uid):
# Create a Json file and store value []
uuid = group_id + "_" + user_uid
group_data_path = os.path.join(os.environ['GROUP_DATA_DIR'], group_id)
user_data_path = os.path.join(group_data_path, user_uid)
if not os.path.exists(group_data_path):
os.makedirs(group_data_path)
if not os.path.exists(user_data_path):
os.makedirs(user_data_path)
file_path = os.path.join(user_data_path, f"{uuid}.json")
# Check if file exists
if os.path.exists(file_path):
pass
else:
data = []
# Write the empty list to the JSON file
with open(file_path, 'w') as json_file:
json.dump(data, json_file)
def update_json(group_id, user_uid, data):
# Read existing JSON data from the file
uuid = group_id + "_" + user_uid
group_data_path = os.path.join(os.environ['GROUP_DATA_DIR'], group_id)
user_data_path = os.path.join(group_data_path, user_uid)
file_path = os.path.join(user_data_path, f"{uuid}.json")
try:
with open(file_path, 'r') as json_file:
existing_data = json.load(json_file)
except FileNotFoundError:
# If the file doesn't exist, initialize with an empty list
existing_data = []
# Append new values to the existing data
existing_data.extend(data)
# If length of existing data is greater than 6, only keep the last 6
if len(existing_data) > 6:
existing_data = existing_data[-6:]
# Write the updated data back to the JSON file
with open(file_path, 'w') as json_file:
json.dump(existing_data, json_file)
def read_json(group_id, user_uid):
uuid = group_id + "_" + user_uid
group_data_path = os.path.join(os.environ['GROUP_DATA_DIR'], group_id)
user_data_path = os.path.join(group_data_path, user_uid)
file_path = os.path.join(user_data_path, f"{uuid}.json")
try:
with open(file_path, 'r') as json_file:
data = json.load(json_file)
return data
except FileNotFoundError:
print(f"File not found at location: {file_path}")
return []
except json.JSONDecodeError:
print(f"Error decoding JSON from file at location: {file_path}")
return None
def save_response(response, group_id, user_uid, query_text):
histroy = [{'role': 'user', 'message': query_text}, {'role': 'assistant', 'message': str(response)}]
update_json(group_id, user_uid,histroy)