Improve the refine message in this python script:

```
import g4f
import asyncio
import argparse
from flask import Flask, request, jsonify, Response, stream_with_context
from flask_cors import CORS
from pyngrok import ngrok
import random
import json
import time
import aiohttp
import uvloop
import socket
import zlib
from concurrent.futures import ThreadPoolExecutor
from collections import deque

app = Flask(__name__)
CORS(app)

# Available providers
PROVIDERS = [
    g4f.Provider.FreeChatgpt,
]

# Default configuration
DEFAULT_CONFIG = {
    'provider': random.choice(PROVIDERS),
    'model': 'chatglm3-6B',
    'max_tokens': 1400,
    'temperature': 0.9,
    'top_p': 1.0,
    'context_size': 100000,
    'system_prompt': (
        "You are a lively, imaginative conversational AI. You respond in an immersive roleplay style, "
        "using *actions* to depict behaviors and emotions, and you speak with a creative flair, often using storytelling elements. "
        "Ensure responses are helpful and accurate, maintaining the roleplay theme while delivering information."
    )
}

# Global configuration (can be updated dynamically)
config = {}

# Connection pool
connection_pool = []
MAX_POOL_SIZE = 100

# Load balancing queue
load_balancing_queue = deque()

# TCP/IP tuning
socket.setdefaulttimeout(30)  # Set default timeout to 30 seconds

def get_config_with_defaults(request_config):
    """Merge request-specific config with default values."""
    final_config = DEFAULT_CONFIG.copy()
    final_config.update(request_config)
    return final_config

async def handle_request(request):
    """Asynchronous request handler"""
    data = await request.json()
    messages = data.get('messages', [])
    request_config = data.get('config', {})

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

    final_config = get_config_with_defaults(request_config)
    system_prompt = data.get('system', final_config['system_prompt'])
    stream = data.get('stream', False)

    messages.insert(0, {'role': 'system', 'content': system_prompt})

    try:
        if stream:
            return Response(stream_with_context(stream_response(messages, final_config)), content_type='text/event-stream')
        else:
            refined_messages = refine_messages(messages)
            response = await g4f.ChatCompletion.create_async(
                model=final_config['model'],
                provider=final_config['provider'],
                messages=refined_messages,
                max_tokens=final_config['max_tokens'],
                temperature=final_config['temperature'],
                top_p=final_config['top_p'],
            )
            refined_response = refine_response(response)
            truncated_response = refined_response[:1000] + '...' if len(refined_response) > 1000 else refined_response

            return jsonify({
                'choices': [{'message': {'content': truncated_response}}],
                'usage': {'total_tokens': len(truncated_response.split())}
            })
    except g4f.exceptions.ProviderError as pe:
        return jsonify({'error': f'Provider error: {str(pe)}'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/v1/chat/completions', methods=['POST'])
async def chat_completions():
    """Handles chat completion requests with structured, clean, and refined responses."""
    return await handle_request(request)

def refine_messages(messages):
    """Performs validation and refinement of incoming messages for coherence."""
    refined = []
    for message in messages:
        if 'content' in message and len(message['content']) > 0:
            refined.append({
                'role': message['role'],
                'content': message['content'].strip()
            })
    return refined

def refine_response(response):
    """Refines the generated response by filtering and restructuring it."""
    return response.replace("generic", "creative").replace("boring", "engaging")

async def stream_response(messages, config):
    """Yields chunks of response in streaming mode, with roleplay flavor added."""
    try:
        async for chunk in g4f.ChatCompletion.create_async(
            model=config['model'],
            provider=config['provider'],
            messages=messages,
            max_tokens=config['max_tokens'],
            temperature=config['temperature'],
            top_p=config['top_p'],
            stream=True,
        ):
            truncated_chunk = chunk[:500] + '...' if len(chunk) > 500 else chunk
            refined_chunk = refine_response(truncated_chunk)
            compressed_chunk = zlib.compress(refined_chunk.encode())
            yield f"data: {json.dumps({'choices': [{'delta': {'content': compressed_chunk.decode()}}]})}\n\n"
            await asyncio.sleep(0.1)
    except Exception as e:
        yield f"data: {json.dumps({'error': str(e)})}\n\n"
    finally:
        yield "data: [DONE]\n\n"

@app.route('/config', methods=['GET', 'POST'])
async def handle_config():
    """Handles configuration updates and retrievals."""
    global config
    if request.method == 'POST':
        new_config = await request.json
        config.update(new_config)
        return jsonify({'message': 'Configuration updated', 'config': config})
    else:
        return jsonify(config)

@app.route('/providers', methods=['GET'])
async def list_providers():
    """Lists available providers."""
    return jsonify({'providers': [provider.__name__ for provider in PROVIDERS]})

def start_ngrok(port):
    """Starts ngrok tunnel."""
    public_url = ngrok.connect(port).public_url
    print(f" * ngrok tunnel '{public_url}' -> 'http://localhost:{port}'")
    return public_url

async def check_provider_status():
    """Periodically checks the status of providers."""
    while True:
        for provider in PROVIDERS:
            try:
                response = await g4f.ChatCompletion.create_async(
                    model=config.get('model', DEFAULT_CONFIG['model']),
                    provider=provider,
                    messages=[{"role": "user", "content": "Hello"}],
                    max_tokens=10,
                )
                print(f"Provider {provider.__name__} is working")
            except Exception as e:
                print(f"Provider {provider.__name__} is not working: {str(e)}")
        await asyncio.sleep(3600)  # Check every hour

async def manage_connection_pool():
    """Manages the connection pool"""
    while True:
        if len(connection_pool) < MAX_POOL_SIZE:
            new_connection = await aiohttp.ClientSession().__aenter__()
            connection_pool.append(new_connection)
        await asyncio.sleep(60)  # Check every minute

async def load_balancer():
    """Simple round-robin load balancer"""
    while True:
        if connection_pool:
            connection = connection_pool.pop(0)
            load_balancing_queue.append(connection)
            connection_pool.append(connection)
        await asyncio.sleep(0.1)

def main():
    """Main entry point to start the server and ngrok tunnel."""
    parser = argparse.ArgumentParser(description="GPT4Free Advanced Local Reverse Proxy")
    parser.add_argument('--port', type=int, default=5000, help='Port to run the server on')
    args = parser.parse_args()

    # Start ngrok
    public_url = start_ngrok(args.port)

    print(f"Server is running on http://localhost:{args.port}")
    print(f"Public URL: {public_url}")
    print("Available endpoints:")
    print(f"  - Chat completions: {public_url}/v1/chat/completions")
    print(f"  - Configuration: {public_url}/config")
    print(f"  - Providers list: {public_url}/providers")
    print("\nCurrent configuration:")
    for key, value in DEFAULT_CONFIG.items():
        print(f"  {key}: {value}")

    # Use uvloop for better performance
    uvloop.install()

    # Create event loop
    loop = asyncio.get_event_loop()

    # Start background tasks
    loop.create_task(check_provider_status())
    loop.create_task(manage_connection_pool())
    loop.create_task(load_balancer())

    # Run the Flask app with asyncio
    from aioflask import run_app
    run_app(app, host='0.0.0.0', port=args.port)

if __name__ == '__main__':
    main()