i have a very simple task, the code below used to generate using openai a coherent harmonic html of a UI which would be integrated seamlessly into the HTML display section of the app, and below it display in text both the Output to the llm before sent to the llm and the llms responses.

dont change the llm call api the actual technical call is ok, deal with the instructions you send to the LLM try to send him accurate instructions and harmonize the code to receive the code you requsted be tolerant if the <html> is not in the first line of the file keep looking once you find it look for the </html> and truc everything above the <head> and below the </head>

this is the code i trust you to make a great job and fix it and improve it 
import os
import json
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from dotenv import load_dotenv
import requests
import openai

load_dotenv()

app = Flask(__name__, static_folder='static', static_url_path='/static')
CORS(app)

# Configuration for OpenAI and Fallback LLMs
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
OPENAI_MODEL = os.getenv('OPENAI_MODEL')
OPENAI_API_URL = os.getenv('OPENAI_API_URL')

# Fallback LLM 1
API_KEY_FALLBACK1 = os.getenv('API_KEY_FALLBACK1')
API_MODEL_FALLBACK1 = os.getenv('API_MODEL_FALLBACK1')
API_BASE_FALLBACK1 = os.getenv('API_BASE_FALLBACK1')

# Fallback LLM 2
API_KEY_FALLBACK2 = os.getenv('API_KEY_FALLBACK2')
API_MODEL_FALLBACK2 = os.getenv('API_MODEL_FALLBACK2')
API_BASE_FALLBACK2 = os.getenv('API_BASE_FALLBACK2')

@app.route('/')
def index():
    return send_from_directory('static', 'index.html')

def generate_with_openai(prompt):
    openai.api_key = OPENAI_API_KEY
    response = openai.Completion.create(
        engine=OPENAI_MODEL,
        prompt=prompt,
        max_tokens=1500,
        n=1,
        stop=None,
        temperature=0.5,
    )
    return response.choices[0].text.strip()

def generate_with_fallback1(prompt):
    headers = {
        'Authorization': f'Bearer {API_KEY_FALLBACK1}',
        'Content-Type': 'application/json'
    }
    payload = {
        "model": API_MODEL_FALLBACK1,
        "prompt": prompt,
        "max_tokens": 1500,
        "temperature": 0.5,
    }
    response = requests.post(f"{API_BASE_FALLBACK1}/v1/completions", headers=headers, json=payload)
    if response.status_code == 200:
        return response.json()['choices'][0]['text'].strip()
    else:
        raise Exception(f"Fallback1 Error: {response.text}")

def generate_with_fallback2(prompt):
    headers = {
        'Authorization': f'Bearer {API_KEY_FALLBACK2}',
        'Content-Type': 'application/json'
    }
    payload = {
        "model": API_MODEL_FALLBACK2,
        "prompt": prompt,
        "max_tokens": 1500,
        "temperature": 0.5,
    }
    response = requests.post(f"{API_BASE_FALLBACK2}/v1/completions", headers=headers, json=payload)
    if response.status_code == 200:
        return response.json()['choices'][0]['text'].strip()
    else:
        raise Exception(f"Fallback2 Error: {response.text}")

def generate_gui_code(prompt):
    try:
        return generate_with_openai(prompt)
    except Exception:
        try:
            return generate_with_fallback1(prompt)
        except Exception:
            try:
                return generate_with_fallback2(prompt)
            except Exception as e:
                return f"// Error generating code: {str(e)}"

@app.route('/generate-gui', methods=['POST'])
def generate_gui():
    data = request.json
    user_request = data.get('request')

    prompt = f"""
    Create a React component for the following application with a clean UI using fine lines and gradient colors. The component should be highly reactive and lightweight, optimized for fast rendering.

    Application: {user_request}

    Ensure the component includes all necessary functionalities as per the specification, handles user interactions, and integrates seamlessly with the backend for data saving and loading.
    """

    generated_code = generate_gui_code(prompt)

    app_name = ''.join(e for e in user_request if e.isalnum())
    gui_filename = f"{app_name}_GUI.json"
    gui_path = os.path.join('app', 'generated_guis')
    os.makedirs(gui_path, exist_ok=True)
    with open(os.path.join(gui_path, gui_filename), 'w') as f:
        json.dump({"app_name": app_name, "gui_code": generated_code}, f, indent=4)

    return jsonify({"gui_code": generated_code, "gui_filename": gui_filename})

@app.route('/regenerate-gui', methods=['POST'])
def regenerate_gui():
    data = request.json
    user_request = data.get('request')
    fallback_choice = data.get('fallback', 0)

    prompt = f"""
    Create a React component for the following application with a clean UI using fine lines and gradient colors. The component should be highly reactive and lightweight, optimized for fast rendering.

    Application: {user_request}

    Ensure the component includes all necessary functionalities as per the specification, handles user interactions, and integrates seamlessly with the backend for data saving and loading.
    """

    try:
        if fallback_choice == 1:
            generated_code = generate_with_fallback1(prompt)
        elif fallback_choice == 2:
            generated_code = generate_with_fallback2(prompt)
        else:
            generated_code = generate_with_openai(prompt)
    except Exception as e:
        generated_code = f"// Error regenerating code: {str(e)}"

    app_name = ''.join(e for e in user_request if e.isalnum())
    gui_filename = f"{app_name}_GUI.json"
    gui_path = os.path.join('app', 'generated_guis')
    os.makedirs(gui_path, exist_ok=True)
    with open(os.path.join(gui_path, gui_filename), 'w') as f:
        json.dump({"app_name": app_name, "gui_code": generated_code}, f, indent=4)

    return jsonify({"gui_code": generated_code, "gui_filename": gui_filename})

@app.route('/save-data', methods=['POST'])
def save_data():
    data = request.json
    app_name = data.get('app_name')
    user_data = data.get('data')

    data_dir = os.path.join('app', 'user_data')
    os.makedirs(data_dir, exist_ok=True)
    data_filename = f"{app_name}_data.json"
    data_path = os.path.join(data_dir, data_filename)

    if os.path.exists(data_path):
        with open(data_path, 'r') as f:
            try:
                existing_data = json.load(f)
            except json.JSONDecodeError:
                existing_data = []
    else:
        existing_data = []

    existing_data.append(user_data)

    with open(data_path, 'w') as f:
        json.dump(existing_data, f, indent=4)

    return jsonify({"message": f"Data saved to {data_filename}"}), 200

@app.route('/load-gui', methods=['POST'])
def load_gui():
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    if file and file.filename.endswith('.json'):
        try:
            content = json.load(file)
            gui_code = content.get('gui_code')
            gui_filename = content.get('gui_filename')
            return jsonify({"gui_code": gui_code, "gui_filename": gui_filename}), 200
        except json.JSONDecodeError:
            return jsonify({"error": "Invalid JSON file"}), 400
    else:
        return jsonify({"error": "Invalid file type"}), 400

@app.route('/static/index.html')
def serve_index():
    return """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic App Generator</title>
    <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            margin: 0; 
            padding: 0; 
            height: 100vh; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
        }
        .input-container { 
            display: flex; 
            align-items: center; 
            background: white; 
            padding: 20px; 
            border-radius: 8px; 
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            position: relative;
            transition: all 0.3s ease;
            resize: both;
            overflow: auto;
            width: 400px;
        }
        .input-container input { 
            flex: 1; 
            padding: 10px 15px; 
            font-size: 16px; 
            border: 1px solid #ccc; 
            border-radius: 4px; 
            outline: none; 
            transition: border 0.3s ease;
            min-width: 200px;
        }
        .input-container input:focus { 
            border-color: #007BFF; 
        }
        .input-container button { 
            padding: 10px 15px; 
            font-size: 16px; 
            cursor: pointer; 
            margin-left: 10px;
            background-color: #007BFF;
            color: white;
            border: none;
            border-radius: 4px;
            transition: background-color 0.3s ease;
        }
        .input-container button:hover { 
            background-color: #0056b3; 
        }
        .paperclip { 
            margin-left: 10px; 
            cursor: pointer; 
            font-size: 20px;
            position: relative;
            transition: color 0.3s ease;
        }
        .paperclip:hover { 
            color: #007BFF; 
        }
        .paperclip input { 
            position: absolute; 
            left: 0; 
            top: 0; 
            opacity: 0; 
            cursor: pointer; 
            width: 100%; 
            height: 100%; 
        }
        #dynamic-gui { 
            margin-top: 30px; 
            width: 80%;
            max-width: 800px;
        }
        .regenerate-button { 
            margin-top: 20px; 
            padding: 10px 20px; 
            cursor: pointer; 
            background-color: #28a745; 
            color: white; 
            border: none; 
            border-radius: 4px; 
            transition: background-color 0.3s ease;
        }
        .regenerate-button:hover { 
            background-color: #1e7e34; 
        }
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border-left-color: #007BFF;
            animation: spin 1s ease infinite;
            margin-left: 10px;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <script type="text/javascript">
        class App extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    userRequest: '',
                    guiCode: '',
                    guiFilename: '',
                    editing: false,
                    data: {},
                    fallback: 0,
                    loading: false
                };
                this.handleChange = this.handleChange.bind(this);
                this.handleSubmit = this.handleSubmit.bind(this);
                this.handleFileUpload = this.handleFileUpload.bind(this);
                this.handleSave = this.handleSave.bind(this);
                this.handleRegenerate = this.handleRegenerate.bind(this);
            }

            handleChange(e) {
                this.setState({ userRequest: e.target.value });
            }

            handleSubmit() {
                const { userRequest } = this.state;
                if (!userRequest.trim()) {
                    alert('Please enter a valid request.');
                    return;
                }
                this.setState({ loading: true });
                axios.post('/generate-gui', { request: userRequest })
                    .then(response => {
                        this.setState({ 
                            guiCode: response.data.gui_code, 
                            guiFilename: response.data.gui_filename,
                            editing: true,
                            fallback: 0,
                            loading: false
                        });
                    })
                    .catch(error => {
                        console.error(error);
                        alert('Error generating GUI.');
                        this.setState({ loading: false });
                    });
            }

            handleFileUpload(e) {
                const file = e.target.files[0];
                if (file) {
                    this.setState({ loading: true });
                    const formData = new FormData();
                    formData.append('file', file);
                    axios.post('/load-gui', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    })
                    .then(response => {
                        this.setState({ 
                            guiCode: response.data.gui_code, 
                            guiFilename: response.data.gui_filename,
                            editing: true,
                            fallback: 0,
                            loading: false
                        });
                    })
                    .catch(error => {
                        console.error(error);
                        alert('Error loading GUI.');
                        this.setState({ loading: false });
                    });
                }
            }

            handleSave(data) {
                const { guiFilename } = this.state;
                const appName = guiFilename.replace('_GUI.json','');
                this.setState({ loading: true });
                axios.post('/save-data', { app_name: appName, data: data })
                    .then(response => {
                        if (confirm(`${response.data.message}. Keep Editing? (Y/n)`)) {
                            // Continue editing
                        } else {
                            this.setState({ editing: false, guiCode: '', guiFilename: '', loading: false });
                        }
                    })
                    .catch(error => {
                        console.error(error);
                        alert('Error saving data.');
                        this.setState({ loading: false });
                    });
            }

            handleRegenerate() {
                const { userRequest, fallback } = this.state;
                const nextFallback = fallback < 2 ? fallback + 1 : 0;
                this.setState({ loading: true });
                axios.post('/regenerate-gui', { request: userRequest, fallback: nextFallback })
                    .then(response => {
                        this.setState({ 
                            guiCode: response.data.gui_code, 
                            guiFilename: response.data.gui_filename,
                            fallback: nextFallback,
                            loading: false
                        });
                    })
                    .catch(error => {
                        console.error(error);
                        alert('Error regenerating GUI.');
                        this.setState({ loading: false });
                    });
            }

            renderDynamicGUI() {
                const { guiCode, loading } = this.state;
                if (!guiCode) return null;
                try {
                    const GeneratedComponent = new Function('React', 'props', guiCode + '; return GeneratedComponent;')(React, { onSave: this.handleSave });
                    return React.createElement(GeneratedComponent, { onSave: this.handleSave });
                } catch (e) {
                    console.error(e);
                    return <div>Error rendering GUI.</div>;
                }
            }

            render() {
                return (
                    <div>
                        {this.state.loading && (
                            <div className="loading-overlay">
                                <div className="spinner"></div>
                            </div>
                        )}
                        {!this.state.editing && (
                            <div className="input-container">
                                <input 
                                    type="text" 
                                    value={this.state.userRequest} 
                                    onChange={this.handleChange} 
                                    placeholder="Enter app request..." 
                                />
                                <button onClick={this.handleSubmit}>Send</button>
                                <label className="paperclip">
                                    📎
                                    <input type="file" accept=".json" onChange={this.handleFileUpload} />
                                </label>
                            </div>
                        )}
                        <div id="dynamic-gui">
                            {this.state.editing && this.renderDynamicGUI()}
                            {this.state.editing && (
                                <button className="regenerate-button" onClick={this.handleRegenerate}>
                                    Regenerate
                                </button>
                            )}
                        </div>
                    </div>
                );
            }
        }

        ReactDOM.render(<App />, document.getElementById('root'));
    </script>
</body>
</html>
    """

if __name__ == '__main__':
    os.makedirs(os.path.join('app', 'generated_guis'), exist_ok=True)
    os.makedirs(os.path.join('app', 'user_data'), exist_ok=True)
    app.run(host='0.0.0.0', port=5000, debug=True)