rewrite this code completly:
1. dont change anything related to open ai or embeddings or api.
2. you can improve the design
3. rewrite all business logic and optimize and find and fix bugs and make it perfect for prod

# app.py
import os
import base64
import subprocess
import sys
import pandas as pd

from flask import Flask, request, jsonify, render_template_string
from openai import OpenAI

app = Flask(__name__)

# ============================
# OpenAI API Configuration
# ============================

openai_api_key = os.environ.get('OPENAI_API_KEY')
if not openai_api_key:
    raise ValueError("Please set the OPENAI_API_KEY environment variable.")

client = OpenAI(api_key=openai_api_key)

# ============================
# Helper Functions
# ============================

def extract_code_blocks(text):
    """Extracts code blocks enclosed in triple backticks from the given text."""
    # Handled in JavaScript
    return []

def get_embedding(text, model="text-embedding-3-small"):
    """Generates an embedding for the given text using OpenAI."""
    text = text.replace("\n", " ")
    try:
        embedding_response = client.embeddings.create(input=[text], model=model)
        embedding = embedding_response.data[0].embedding
        return embedding
    except Exception as e:
        return f"Error generating embedding: {str(e)}"

def get_available_models():
    """Returns a predefined list of chat models."""
    return ["gpt-4o-mini"]

# ============================
# Routes
# ============================

@app.route('/')
def index():
    model_options = get_available_models()
    return render_template_string(r"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>LLM Code Runner</title>
        <style>
            body {
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                display: flex;
                flex-direction: row;
                height: 100vh;
                margin: 0;
                padding: 0;
                background: linear-gradient(135deg, #1e1e2f, #27293d);
                color: #ffffff;
            }
            .panel {
                padding: 20px;
                box-sizing: border-box;
                overflow-y: auto;
            }
            #left-panel {
                width: 25%;
                border-right: 1px solid #444;
                background-color: #2e2e42;
            }
            #main-panel {
                width: 50%;
                border-right: 1px solid #444;
                display: flex;
                flex-direction: column;
                background-color: #1e1e2f;
            }
            #chat-panel {
                width: 25%;
                display: flex;
                flex-direction: column;
                padding: 20px;
                box-sizing: border-box;
                background-color: #2e2e42;
                border-left: 1px solid #444;
            }
            h2, h3 {
                margin-top: 0;
                color: #f0f0f0;
            }
            .button-group button {
                width: 30px;
                height: 30px;
                margin-left: 5px;
                border: none;
                background-color: #007BFF;
                color: #fff;
                border-radius: 3px;
                cursor: pointer;
                font-size: 16px;
                transition: background-color 0.3s;
            }
            .button-group button:hover {
                background-color: #0056b3;
            }
            #tabs {
                flex-grow: 1;
                overflow-y: auto;
                padding: 10px;
                border: 1px solid #444;
                border-radius: 5px;
                background-color: #2e2e42;
                margin-bottom: 20px;
            }
            .tab {
                border: 1px solid #555;
                padding: 10px;
                margin-bottom: 10px;
                border-radius: 5px;
                background-color: #3a3a58;
                position: relative;
            }
            .tab h3 {
                margin-bottom: 10px;
                font-size: 16px;
                color: #f0f0f0;
            }
            .tab pre {
                background-color: #44445a;
                padding: 10px;
                border-radius: 5px;
                overflow-x: auto;
                color: #e0e0e0;
                white-space: pre-wrap;
                word-wrap: break-word;
            }
            #terminal-output {
                height: 200px;
                overflow-y: scroll;
                background-color: #000;
                color: #0f0;
                padding: 10px;
                border-radius: 5px;
                margin-top: 10px;
                white-space: pre-wrap;
                font-family: 'Courier New', Courier, monospace;
            }
            #log-panel {
                height: 200px;
                overflow-y: scroll;
                background-color: #3a3a58;
                padding: 10px;
                border-radius: 5px;
                border: 1px solid #555;
                margin-top: 10px;
                white-space: pre-wrap;
                color: #e0e0e0;
            }
            textarea {
                width: 100%;
                resize: none;
                padding: 10px;
                border: 1px solid #555;
                border-radius: 5px;
                box-sizing: border-box;
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                font-size: 14px;
                background-color: #2e2e42;
                color: #f0f0f0;
            }
            button.send-button, button.run-button {
                width: 120px;
                height: 40px;
                margin-top: 10px;
                border: none;
                background-color: #28a745;
                color: #fff;
                border-radius: 5px;
                cursor: pointer;
                font-size: 16px;
                transition: background-color 0.3s;
            }
            button.send-button:hover, button.run-button:hover {
                background-color: #218838;
            }
            button#send-button {
                background-color: #007BFF;
            }
            button#send-button:hover {
                background-color: #0056b3;
            }
            input[type="file"] {
                margin-top: 10px;
                color: #f0f0f0;
            }
            .error {
                color: #dc3545;
            }
            .success {
                color: #28a745;
            }
        </style>
    </head>
    <body>
        <!-- Left Panel -->
        <div id="left-panel" class="panel">
            <h2>Settings</h2>
            <label for="model-select">Model:</label>
            <select id="model-select" style="width: 100%; padding: 5px; margin-top: 5px; background-color: #3a3a58; color: #f0f0f0; border: 1px solid #555; border-radius: 5px;">
                {% for model in model_options %}
                    <option value="{{ model }}">{{ model }}</option>
                {% endfor %}
            </select>
            <br><br>
            <label for="max-tokens">Max Tokens:</label>
            <div style="display: flex; align-items: center; margin-top: 5px;">
                <input type="text" id="max-tokens" value="1000" style="width: 80px; padding: 5px; background-color: #3a3a58; color: #f0f0f0; border: 1px solid #555; border-radius: 5px;">
                <div class="button-group" style="margin-left: 10px;">
                    <button id="decrease-tokens">-</button>
                    <button id="increase-tokens">+</button>
                </div>
            </div>
            <br>
            <h3>Log Panel</h3>
            <div id="log-panel"></div>
        </div>

        <!-- Main Panel -->
        <div id="main-panel" class="panel">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h2>Code and Files</h2>
                <button id="run-code" class="run-button">▶ Run Code</button>
            </div>
            <div id="tabs"></div>
            <h3>Terminal Output</h3>
            <div id="terminal-output"></div>
        </div>

        <!-- Chat Panel -->
        <div id="chat-panel" class="panel">
            <h2>Chat Interface</h2>
            <div id="chat-output" style="flex-grow: 1; overflow-y: auto; border: 1px solid #555; padding: 10px; height: 300px; border-radius: 5px; background-color: #3a3a58;"></div>
            <textarea id="chat-input" rows="4" placeholder="Type your message here..."></textarea>
            <button id="send-button" class="send-button">📨 Send</button>
            <br><br>
            <input type="file" id="file-input" accept=".txt,.py,.md">
        </div>

        <script>
        {% raw %}
            document.addEventListener('DOMContentLoaded', function() {
                const logPanel = document.getElementById('log-panel');
                const modelSelect = document.getElementById('model-select');
                const maxTokensInput = document.getElementById('max-tokens');
                const increaseButton = document.getElementById('increase-tokens');
                const decreaseButton = document.getElementById('decrease-tokens');
                const sendButton = document.getElementById('send-button');
                const chatInput = document.getElementById('chat-input');
                const chatOutput = document.getElementById('chat-output');
                const fileInput = document.getElementById('file-input');
                const tabsDiv = document.getElementById('tabs');
                const runCodeButton = document.getElementById('run-code');
                const terminalOutput = document.getElementById('terminal-output');

                // Increase Max Tokens
                increaseButton.addEventListener('click', function() {
                    let value = parseInt(maxTokensInput.value);
                    if (!isNaN(value)) {
                        maxTokensInput.value = value + 100;
                    } else {
                        log('Max Tokens must be an integer.', 'error');
                    }
                });

                // Decrease Max Tokens
                decreaseButton.addEventListener('click', function() {
                    let value = parseInt(maxTokensInput.value);
                    if (!isNaN(value)) {
                        let newValue = value - 100;
                        if (newValue < 0) newValue = 0;
                        maxTokensInput.value = newValue;
                    } else {
                        log('Max Tokens must be an integer.', 'error');
                    }
                });

                // Send Message
                sendButton.addEventListener('click', function() {
                    let message = chatInput.value.trim();
                    if (message === '') return;

                    appendChat('User', message);
                    chatInput.value = '';

                    fetch('/send_message', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            model: modelSelect.value,
                            max_tokens: parseInt(maxTokensInput.value),
                            messages: getAllSystemMessages(),
                            user_message: message
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.error) {
                            log(data.error, 'error');
                        } else {
                            appendChat('Assistant', data.reply);
                            // Extract code blocks and add as tabs without using regex
                            let codeBlocks = extractCodeBlocks(data.reply);
                            codeBlocks.forEach((code, index) => {
                                addTab(`Assistant Code ${index+1}`, code);
                                log(`Added code from assistant: Assistant Code ${index+1}`, 'success');
                            });
                        }
                    })
                    .catch(error => {
                        log(error.toString(), 'error');
                    });
                });

                // File Upload
                fileInput.addEventListener('change', function() {
                    let file = fileInput.files[0];
                    if (!file) return;

                    let reader = new FileReader();
                    reader.onload = function(e) {
                        let content = e.target.result;
                        addTab(file.name, content);
                        log(`Loaded file: ${file.name}`, 'success');
                        // Optionally, you can send this for embedding
                    };
                    reader.onerror = function(e) {
                        log('Error loading file.', 'error');
                    };
                    reader.readAsText(file);
                    fileInput.value = '';
                });

                // Run Code
                runCodeButton.addEventListener('click', function() {
                    let activeTab = getActiveTab();
                    if (!activeTab) {
                        terminalOutput.innerHTML += `<p class="error">No code to run.</p>`;
                        return;
                    }

                    let code = activeTab.content;
                    fetch('/run_code', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ code: code })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.error) {
                            terminalOutput.innerHTML += `<pre class="error">${escapeHtml(data.error)}</pre>`;
                        } else {
                            if (data.stdout) {
                                terminalOutput.innerHTML += `<pre>${escapeHtml(data.stdout)}</pre>`;
                            }
                            if (data.stderr) {
                                terminalOutput.innerHTML += `<pre class="error">${escapeHtml(data.stderr)}</pre>`;
                            }
                            log(`Executed code from tab: ${activeTab.title}`, 'success');
                        }
                    })
                    .catch(error => {
                        terminalOutput.innerHTML += `<pre class="error">${escapeHtml(error.toString())}</pre>`;
                        log(error.toString(), 'error');
                    });
                });

                // Helper Functions
                function log(message, type) {
                    let p = document.createElement('p');
                    if (type === 'error') {
                        p.classList.add('error');
                    } else if (type === 'success') {
                        p.classList.add('success');
                    }
                    p.textContent = message;
                    logPanel.appendChild(p);
                    logPanel.scrollTop = logPanel.scrollHeight;
                }

                function appendChat(role, message) {
                    let div = document.createElement('div');
                    div.innerHTML = `<strong>${role}:</strong> ${escapeHtml(message)}`;
                    chatOutput.appendChild(div);
                    chatOutput.scrollTop = chatOutput.scrollHeight;
                }

                function addTab(title, content) {
                    let tabDiv = document.createElement('div');
                    tabDiv.classList.add('tab');
                    tabDiv.innerHTML = `<h3>${escapeHtml(title)}</h3><pre>${escapeHtml(content)}</pre>`;
                    tabDiv.content = content;
                    tabsDiv.appendChild(tabDiv);
                }

                function getActiveTab() {
                    let tabs = document.querySelectorAll('.tab');
                    if (tabs.length === 0) return null;
                    return tabs[tabs.length - 1]; // Return the latest tab as active
                }

                function getAllSystemMessages() {
                    // Retrieve system messages for context
                    return [{"role": "system", "content": "You are a helpful assistant."}];
                }

                function extractCodeBlocks(text) {
                    let codes = [];
                    let parts = text.split('```');
                    for (let i = 1; i < parts.length; i += 2) {
                        codes.push(parts[i]);
                    }
                    return codes;
                }

                function escapeHtml(text) {
                    const map = {
                        '&': '&amp;',
                        '<': '&lt;',
                        '>': '&gt;',
                        '"': '&quot;',
                        "'": '&#039;'
                    };
                    let escaped = '';
                    for (let char of text) {
                        escaped += map[char] || char;
                    }
                    return escaped;
                }
            {% endraw %}
            </script>
    </body>
    </html>
    """, model_options=get_available_models())

@app.route('/send_message', methods=['POST'])
def send_message_route():
    data = request.get_json()
    model = data.get('model', 'gpt-4o-mini')
    max_tokens = data.get('max_tokens', 1000)
    user_message = data.get('user_message', '')
    system_messages = data.get('messages', [{"role": "system", "content": "You are a helpful assistant."}])

    if not user_message:
        return jsonify({'error': 'User message is empty.'}), 400

    messages = system_messages + [{"role": "user", "content": user_message}]

    try:
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            max_tokens=max_tokens
        )
        assistant_reply = response.choices[0].message.content.strip()
        return jsonify({'reply': assistant_reply})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/run_code', methods=['POST'])
def run_code_route():
    data = request.get_json()
    code = data.get('code', '')

    if not code:
        return jsonify({'error': 'No code provided.'}), 400

    try:
        process = subprocess.Popen(
            [sys.executable, '-c', code],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        stdout, stderr = process.communicate()
        return jsonify({'stdout': stdout, 'stderr': stderr})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# ============================
# Embedding Route
# ============================

@app.route('/embed', methods=['POST'])
def embed_route():
    data = request.get_json()
    texts = data.get('texts', [])

    if not texts:
        return jsonify({'error': 'No texts provided for embedding.'}), 400

    try:
        embeddings = [get_embedding(text) for text in texts]
        # Example: Save embeddings to CSV
        df = pd.DataFrame({
            'text': texts,
            'embedding': embeddings
        })
        output_path = 'output/embedded_texts.csv'
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        df.to_csv(output_path, index=False)
        return jsonify({'embeddings': embeddings, 'message': f'Embeddings saved to {output_path}.'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

# ============================
# Run the App
# ============================

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5010, debug=True)