i get an error when i run the code saying response.json is not a function on line 255, the code works in means of the call to openai, the model used and all the syntax. do not change anything except fixing the issue with the generate  func which creates an err 500. again the mehtod to use client and import OpenAI and use gpt-4o-mini are CORRECT and SHOULD NOT BE CHANGED OR REMOVED. fix the issue with the json format of the response ONLY and output only working code:

# app.py

import os
import json
from flask import Flask, request, jsonify
import openai
from openai import OpenAI
from openai import OpenAIError
from datetime import datetime
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS if needed

# Configure OpenAI API key
openai.api_key = os.environ.get("OPENAI_API_KEY")  # Ensure this is set correctly

# Log storage (in-memory; for production, use persistent storage)
llm_logs = []

# Directory to save UI states
SAVE_DIR = 'saved_ui_states'
os.makedirs(SAVE_DIR, exist_ok=True)

def generate_ui(application_name, current_ui=None, user_event=None):
    prompt = (
        "You are an assistant that generates complete GUI designs in a strict JSON format "
        "for web applications. The JSON must contain exactly three fields: 'html', 'css', and 'js', "
        "each containing their respective code as a string. Additionally, ensure that all interactive "
        "elements call a global JavaScript function `window.triggerEvent(eventType, eventData)` with appropriate "
        "event types and data. The design should be clean, professional, and responsive."
    )

    user_prompt = (
        f"Create a GUI for a '{application_name}' application with the following parameters:\n"
        f"Current UI JSON: {json.dumps(current_ui) if current_ui else 'None'}\n"
        f"User Event: {json.dumps(user_event) if user_event else 'None'}\n"
        "Ensure the JSON response has the fields 'html', 'css', and 'js'. The HTML should structure the application, "
        "CSS should style it professionally, and JS should handle interactions by calling `window.triggerEvent`."
    )

    try:
        # Log the request parameters
        log_entry_request = {
            'timestamp': datetime.utcnow().isoformat(),
            'event': 'LLM Request',
            'application_name': application_name,
            'current_ui': current_ui,
            'user_event': user_event,
            'prompt': user_prompt
        }
        llm_logs.append(log_entry_request)

        client = OpenAI()

        response = client.chat.completions.create(        
            model="gpt-4o-mini",  # Using the working model
            messages=[
                {"role": "system", "content": prompt},
                {"role": "user", "content": user_prompt},
            ],
            temperature=0.3,
            max_tokens=2000,
        )

        # Log the raw response from OpenAI
        log_entry_response = {
            'timestamp': datetime.utcnow().isoformat(),
            'event': 'LLM Response',
            'response': response
        }
        llm_logs.append(log_entry_response)
        content = client.chat.completions.choices[0].message.content.strip()
        #content = response.choices[0].message['content'].strip()
        json_start = content.find('{')
        if json_start == -1:
            raise ValueError("No JSON object found in the response.")
        json_str = content[json_start:]
        ui_json = json.loads(json_str)

        # Validate the JSON structure
        if not all(key in ui_json for key in ['html', 'css', 'js']):
            raise ValueError("JSON response does not contain all required fields ('html', 'css', 'js').")

        # Log the valid response
        log_entry_valid = {
            'timestamp': datetime.utcnow().isoformat(),
            'event': 'Valid UI Generated',
            'application_name': application_name,
            'response': ui_json
        }
        llm_logs.append(log_entry_valid)

        return ui_json
    except OpenAIError as e:
        error_message = f"OpenAI API error: {e}"
        print(error_message)
        append_log(error_message)
        return None
    except json.JSONDecodeError as e:
        # Log the received content for debugging
        error_message = f"JSON decode error: {e}"
        print(error_message)
        append_log(error_message)
        return None
    except Exception as e:
        error_message = f"Unexpected error generating UI: {e}"
        print(error_message)
        append_log(error_message)
        return None

@app.route('/')
def index():
    # HTML, CSS, and JS are all inlined here using triple double quotes
    return """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>AI App Generator</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                margin: 0;
                padding: 0;
                display: flex;
                flex-direction: column;
                align-items: center;
                min-height: 100vh;
            }
            .container {
                width: 90%;
                max-width: 1000px;
                margin-top: 30px;
            }
            .buttonsection {
                display: flex;
                justify-content: center;
                margin-bottom: 20px;
                gap: 10px;
            }
            .buttonsection button {
                padding: 10px 20px;
                font-size: 14px;
                border: none;
                background-color: #6c757d;
                color: white;
                cursor: pointer;
                border-radius: 4px;
            }
            .buttonsection button:hover {
                background-color: #5a6268;
            }
            .inputsection {
                display: flex;
                margin-bottom: 20px;
                gap: 10px;
            }
            .inputsection input {
                flex: 1;
                padding: 12px;
                font-size: 16px;
                border: 1px solid #ccc;
                border-radius: 4px;
                outline: none;
            }
            .inputsection button {
                padding: 12px 24px;
                font-size: 16px;
                border: none;
                background-color: #4285f4;
                color: white;
                cursor: pointer;
                border-radius: 4px;
            }
            .inputsection button:hover {
                background-color: #357ae8;
            }
            .generatedui {
                background-color: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                margin-bottom: 20px;
            }
            .logsection {
                background-color: #fff;
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                height: 300px;
                overflow-y: scroll;
                width: 100%;
            }
            .logentry {
                font-family: monospace;
                font-size: 12px;
                margin-bottom: 5px;
            }
            h1, h2 {
                text-align: center;
                color: #333;
            }
        </style>
        
    </head>
    <body>
    <script>
            let currentUI = null;
    
       
             // JSON UI File Formats
    
             // JSON format received from the LLM:
            // {
              //   "html": "<dv>...</dv>",
              //   "css": "<styl>...</styl>",
              //   "js": "<scrpt>...</scrpt>"
           //  }
    
             // JSON format saved by the application:
            // {
            //     "html": "<dv>...</dv>",
            //     "css": "<styl>...</styl>",
            //     "js": "<scrpt>...</scrpt>"
            //     "state": {
                     // Any additional state information, such as user inputs
            //     }
           //  }
        
    
            async function generateApp() {
                const appName = await document.getElementById('appInput').value.trim();
                if (!appName) {
                    alert('Please enter an application name.');
                    return;
                }
    
                appendLog(`Sending request to generate UI for "${appName}".`);
    
                // Send request to generate UI
                try {
                    const response = fetch('/generate', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({application_name: appName})
                    });
    
                    if (response.ok) {
                        const uiJson = await response.json();
                        if (uiJson.error) {
                            throw new Error(uiJson.error);
                        }
                        currentUI = uiJson;
                        renderUI(uiJson);
                        appendLog(`Generated UI for "${appName}".`);
                    } else {
                        const error = await response.json();
                        throw new Error(error.error || 'Unknown error occurred.');
                    }
                } catch (error) {
                    alert('Error: ' + error.message);
                    appendLog(`Error generating UI for "${appName}": ${error.message}`);
                }
            }
    
            function renderUI(uiJson) {
                const generatedUI = document.getElementById('generatedUI');
                generatedUI.innerHTML = ''; // Clear previous UI
    
                // Remove existing generated styles to prevent duplication
                const existingStyles = document.querySelectorAll('style.generated-style');
                existingStyles.forEach(style => style.remove());
    
                // Create style element
                const style = document.createElement('style');
                style.className = 'generated-style';
                style.innerHTML = uiJson.css;
                document.head.appendChild(style);
    
                // Create a container for the generated HTML
                const container = document.createElement('div');
                container.innerHTML = uiJson.html;
    
                // Append container to generatedUI div
                generatedUI.appendChild(container);
    
                // Execute the generated JS
                try {
                    const script = document.createElement('script');
                    script.text = uiJson.js;
                    document.body.appendChild(script);
                    appendLog('Executed generated JavaScript.');
                } catch (e) {
                    console.error('Error executing generated JS:', e);
                    appendLog('Error executing generated JavaScript.');
                }
            }
    
            async function handleEvent(eventType, eventData) {
                // Send event data to backend to get updated UI
                const response = await fetch('/event', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        event_type: eventType,
                        event_data: eventData
                    })
                });
    
                if (response.ok) {
                    const updatedUiJson = await response.json();
                    if (updatedUiJson.error) {
                        throw new Error(updatedUiJson.error);
                    }
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Handled event '${eventType}' with data: ${JSON.stringify(eventData)}`);
                } else {
                    const error = await response.json();
                    appendLog(`Error handling event '${eventType}': ${error.error}`);
                }
            }
    
            function appendLog(message) {
                const logs = document.getElementById('logs');
                const logEntry = document.createElement('div');
                logEntry.className = 'logentry';
                const timestamp = new Date().toLocaleString();
                logEntry.textContent = `[${timestamp}] ${message}`;
                logs.prepend(logEntry);
    
                // Send the log to the server
                fetch('/log', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({message: message})
                });
            }
    
            // Override the global triggerEvent function
            window.triggerEvent = function(eventType, eventData) {
                handleEvent(eventType, eventData);
            }
    
            // Function to refresh the current UI by requesting an improved version from the LLM
            async function refreshUI() {
                if (!currentUI) {
                    alert('No UI to refresh. Please generate an application first.');
                    return;
                }
    
                const appName = document.getElementById('appInput').value.trim() || 'DynamicApp';
    
                appendLog(`Sending request to refresh UI for "${appName}".`);
    
                const response = await fetch('/refresh', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        application_name: appName,
                        current_ui: currentUI
                    })
                });
    
                if (response.ok) {
                    const updatedUiJson = await response.json();
                    if (updatedUiJson.error) {
                        throw new Error(updatedUiJson.error);
                    }
                    currentUI = updatedUiJson;
                    renderUI(updatedUiJson);
                    appendLog(`Refreshed UI for "${appName}".`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error refreshing UI for "${appName}": ${error.error}`);
                }
            }
    
            // Function to clear the current UI
            function clearUI() {
                const generatedUI = document.getElementById('generatedUI');
                generatedUI.innerHTML = ''; // Clear UI
                currentUI = null;
                appendLog('Cleared the generated UI.');
            }
    
            // Function to save the current UI state to a JSON file
            async function saveUI() {
                if (!currentUI) {
                    alert('No UI to save.');
                    return;
                }
    
                const filename = prompt('Enter filename to save the UI (e.g., my_app.json):', `saved_ui_${Date.now()}.json`);
                if (!filename) {
                    alert('Save cancelled.');
                    return;
                }
    
                appendLog(`Sending request to save UI as "${filename}".`);
    
                const response = await fetch('/save', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        ui_json: currentUI,
                        filename: filename
                    })
                });
    
                if (response.ok) {
                    const res = await response.json();
                    appendLog(`Saved UI to ${res.filepath}`);
                    alert(`UI saved successfully to ${res.filepath}`);
                } else {
                    const error = await response.json();
                    alert('Error: ' + error.error);
                    appendLog(`Error saving UI: ${error.error}`);
                }
            }
    
            
        </script>
        <div class="container">
            <h1>AI App Generator</h1>
            <div class="buttonsection">
                <button onclick="refreshUI()">Refresh</button>
                <button onclick="clearUI()">Clear</button>
                <button onclick="saveUI()">Save</button>
            </div>
            <div class="inputsection">
                <input type="text" id="appInput" placeholder="Enter application name (e.g., Notepad, Music Player)">
                <button onclick="generateApp()">Send</button>
            </div>
            <div id="generatedUI" class="generatedui">
                <!-- Generated UI will appear here -->
            </div>
            <h2>LLM Interaction Logs</h2>
            <div id="logs" class="logsection">
                <!-- Logs will appear here -->
            </div>
        </div>        
    </body>
    </html>
    """
    
@app.route('/generate', methods=['POST'])
def generate():
    data = request.get_json()
    application_name = data.get('application_name')
    current_ui = data.get('current_ui')
    user_event = data.get('user_event')

    if not application_name:
        error_msg = 'No application name provided.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    ui_json = generate_ui(application_name, current_ui, user_event)
    if ui_json:
        return jsonify(ui_json)
    else:
        error_msg = 'Failed to generate UI.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 500

@app.route('/refresh', methods=['POST'])
def refresh():
    data = request.get_json()
    application_name = data.get('application_name', 'DynamicApp')
    current_ui = data.get('current_ui')

    if not current_ui:
        error_msg = 'No current UI provided for refresh.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    ui_json = generate_ui(application_name, current_ui=current_ui)
    if ui_json:
        return jsonify(ui_json)
    else:
        error_msg = 'Failed to refresh UI.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 500

@app.route('/save', methods=['POST'])
def save_ui():
    data = request.get_json()
    ui_json = data.get('ui_json')
    filename = data.get('filename', f'saved_ui_{datetime.utcnow().isoformat()}.json')

    if not ui_json:
        error_msg = 'No UI JSON provided to save.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    try:
        filepath = os.path.join(SAVE_DIR, filename)
        with open(filepath, 'w') as f:
            json.dump(ui_json, f, indent=4)
        success_msg = f"UI saved to {filepath}"
        append_log(success_msg)
        return jsonify({'status': 'UI saved successfully.', 'filepath': filepath}), 200
    except Exception as e:
        error_msg = f"Error saving UI: {e}"
        print(error_msg)
        append_log(error_msg)
        return jsonify({'error': 'Failed to save UI.'}), 500

@app.route('/load', methods=['POST'])
def load_ui():
    data = request.get_json()
    filepath = data.get('filepath')

    if not filepath or not os.path.isfile(filepath):
        error_msg = 'Invalid or missing filepath.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    try:
        with open(filepath, 'r') as f:
            ui_json = json.load(f)
        success_msg = f"UI loaded from {filepath}"
        append_log(success_msg)
        return jsonify(ui_json), 200
    except Exception as e:
        error_msg = f"Error loading UI: {e}"
        print(error_msg)
        append_log(error_msg)
        return jsonify({'error': 'Failed to load UI.'}), 500

@app.route('/event', methods=['POST'])
def handle_event():
    data = request.get_json()
    event_type = data.get('event_type')
    event_data = data.get('event_data')

    if not event_type:
        error_msg = 'No event type provided.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 400

    # Log the received event
    log_entry = {
        'timestamp': datetime.utcnow().isoformat(),
        'event': 'User Event',
        'event_type': event_type,
        'event_data': event_data
    }
    llm_logs.append(log_entry)

    # Retrieve the latest UI JSON from logs
    last_ui = None
    for log in reversed(llm_logs):
        if log.get('event') == 'Valid UI Generated' and log.get('response'):
            last_ui = log['response']
            break

    user_event = {
        'event_type': event_type,
        'event_data': event_data
    }

    # Generate updated UI based on the event
    updated_ui = generate_ui("DynamicApp", current_ui=last_ui, user_event=user_event)

    if updated_ui:
        success_msg = f"Event '{event_type}' handled with data: {event_data}"
        append_log(success_msg)
        return jsonify(updated_ui)
    else:
        error_msg = 'Failed to update UI based on event.'
        append_log(error_msg)
        return jsonify({'error': error_msg}), 500

@app.route('/logs', methods=['GET'])
def get_logs():
    return jsonify(llm_logs[-100:]), 200  # Return last 100 logs

@app.route('/log', methods=['POST'])
def receive_log():
    data = request.get_json()
    message = data.get('message')
    if not message:
        return jsonify({'error': 'No log message provided.'}), 400

    append_log(message)
    return jsonify({'status': 'Log received.'}), 200

@app.errorhandler(Exception)
def handle_exception(e):
    # Log the exception
    error_message = f"Unhandled exception: {e}"
    print(error_message)
    append_log(error_message)
    # Return JSON response
    return jsonify({'error': 'An unexpected error occurred.'}), 500

def append_log(message):
    log_entry = {
        'timestamp': datetime.utcnow().isoformat(),
        'message': message
    }
    llm_logs.append(log_entry)

if __name__ == '__main__':
    app.run(debug=True)