Viewing File: /home/ubuntu/codegamaai-test/general_bot/src/utils.py

import json
import os

def create_json(uuid):
     #Create a Json file and store value []
    file_path = os.path.join(os.environ['USER_DATA_DIR'], 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(uuid, data):
    # Read existing JSON data from the file
    file_path = os.path.join(os.environ['USER_DATA_DIR'], 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(uuid):
    file_path = os.path.join(os.environ['USER_DATA_DIR'], 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, uuid, query_text):
    
    histroy = [{'role': 'user', 'content': query_text}, {'role': 'assistant', 'content': str(response)}]

    update_json(uuid,histroy)

Back to Directory File Manager