Certainly! Enhancing the refine_messages and refine_response functions can significantly improve the robustness, security, and quality of interactions within your application. Below are the improved versions of these functions along with detailed explanations of the changes:
1. Improved refine_messages Function
Original Function:
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
Issues Identified:
- Validation: Lack of validation for the
role field.
- Security: Potential for malicious content if not sanitized.
- Robustness: Does not handle unexpected data types or missing fields gracefully.
- Consistency: Assumes all messages are dictionaries with specific keys.
Improved Function:
import html
import re
def refine_messages(messages):
"""
Validates and cleans incoming messages to ensure they are well-formed and secure.
Args:
messages (list): A list of message dictionaries.
Returns:
list: A list of refined and validated message dictionaries.
Raises:
ValueError: If message structure is invalid.
"""
VALID_ROLES = {'system', 'user', 'assistant'}
refined = []
for idx, message in enumerate(messages):
if not isinstance(message, dict):
raise ValueError(f"Message at index {idx} is not a dictionary.")
role = message.get('role')
content = message.get('content', '').strip()
# Validate role
if role not in VALID_ROLES:
raise ValueError(f"Invalid role '{role}' in message at index {idx}. Must be one of {VALID_ROLES}.")
# Validate content
if not content:
raise ValueError(f"Empty content in message at index {idx}.")
# Sanitize content to prevent injection attacks
sanitized_content = sanitize_text(content)
refined.append({
'role': role,
'content': sanitized_content
})
return refined
def sanitize_text(text):
"""
Sanitizes text by escaping HTML characters and removing potentially harmful patterns.
Args:
text (str): The text to sanitize.
Returns:
str: Sanitized text.
"""
# Escape HTML to prevent injection
sanitized = html.escape(text)
# Remove any script tags or harmful regex patterns
sanitized = re.sub(r'<\/?script[^>]*>', '', sanitized, flags=re.IGNORECASE)
# Optionally, enforce maximum length
MAX_LENGTH = 2000
if len(sanitized) > MAX_LENGTH:
sanitized = sanitized[:MAX_LENGTH] + '...'
return sanitized
Enhancements Explained:
-
Role Validation:
- Purpose: Ensures that each message has a valid
role. Only accepts predefined roles such as 'system', 'user', and 'assistant'.
- Implementation: Checks if the
role is within the VALID_ROLES set. Raises an error if not.
-
Content Validation and Sanitization:
- Purpose: Prevents processing of empty messages and sanitizes content to mitigate security risks like script injections.
- Implementation:
- Strips whitespace and checks for non-empty content.
- Uses the
sanitize_text helper function to escape HTML characters and remove any <script> tags or other malicious patterns.
- Enforces a maximum content length to avoid excessively long messages.
-
Error Handling:
- Purpose: Provides clear error messages when invalid data is encountered, facilitating easier debugging and safer operations.
- Implementation: Raises
ValueError with descriptive messages when validation fails.
-
Type Checking:
- Purpose: Ensures that each message is a dictionary, preventing unexpected errors during processing.
- Implementation: Uses
isinstance to verify message types.
2. Improved refine_response Function
Original Function:
def refine_response(response):
"""Refines the generated response by filtering and restructuring it."""
return response.replace("generic", "creative").replace("boring", "engaging")
Issues Identified:
- Hardcoded Replacements: Limited to specific words, making it less flexible.
- Case Sensitivity: Replacements are case-sensitive, potentially missing variations.
- Lack of Context Awareness: Doesn't account for context where replacements might not be appropriate.
- Security: Potential for introducing content inconsistencies or unwanted characters.
Improved Function:
import re
def refine_response(response):
"""
Refines the generated response by performing intelligent substitutions and ensuring content quality.
Args:
response (str): The raw response generated by the AI model.
Returns:
str: The refined and sanitized response.
"""
if not isinstance(response, str):
raise ValueError("Response must be a string.")
# Define patterns and replacements
replacements = {
r'\bgeneric\b': 'creative',
r'\bboring\b': 'engaging',
# Add more patterns and replacements as needed
}
refined = response
for pattern, replacement in replacements.items():
refined = re.sub(pattern, replacement, refined, flags=re.IGNORECASE)
# Additional refinements can be added here
refined = sanitize_response(refined)
return refined
def sanitize_response(text):
"""
Sanitizes the response to ensure it meets quality and security standards.
Args:
text (str): The text to sanitize.
Returns:
str: Sanitized text.
"""
# Remove unwanted characters or patterns
# Example: Remove any non-printable characters
sanitized = ''.join(char for char in text if char.isprintable())
# Optionally, enforce maximum length
MAX_LENGTH = 1000
if len(sanitized) > MAX_LENGTH:
sanitized = sanitized[:MAX_LENGTH].rstrip() + '...'
return sanitized
Enhancements Explained:
-
Intelligent Pattern Matching:
- Purpose: Allows for more flexible and comprehensive text replacements using regular expressions.
- Implementation: Uses word boundaries (
\b) in regex patterns to ensure only whole words are replaced, avoiding partial matches (e.g., replacing "boring" in "exploring" is prevented).
-
Case-Insensitive Replacements:
- Purpose: Ensures that replacements occur regardless of the case (e.g., "Generic" or "GENERIC").
- Implementation: Adds
flags=re.IGNORECASE to the re.sub function.
-
Extensibility:
- Purpose: Makes it easier to add more patterns and replacements without modifying the core logic.
- Implementation: Stores patterns and replacements in a dictionary (
replacements) which can be expanded as needed.
-
Response Sanitization:
- Purpose: Ensures that the final response is clean, free from unwanted characters, and within acceptable length limits.
- Implementation:
- Removes non-printable characters to prevent potential issues in downstream applications.
- Enforces a maximum length, truncating long responses and appending an ellipsis for readability.
-
Type Checking and Error Handling:
- Purpose: Validates input types to prevent unexpected errors.
- Implementation: Raises a
ValueError if the input response is not a string.
-
Security Considerations:
- Purpose: Prevents the introduction of malicious or unintended content through the response.
- Implementation: Sanitizes the response by removing non-printable characters and enforcing content length.
3. Additional Recommendations
While refining messages and responses is crucial, consider implementing the following additional improvements to enhance the overall system:
a. Rate Limiting and Throttling
- Purpose: Prevent abuse by limiting the number of requests a user can make within a specific timeframe.
- Implementation: Utilize Flask extensions like
flask-limiter to enforce rate limits.
b. Enhanced Logging
- Purpose: Maintain detailed logs for monitoring, debugging, and auditing purposes.
- Implementation: Configure Python’s
logging module to capture relevant events, errors, and usage statistics.
c. Comprehensive Error Handling
- Purpose: Provide more granular and user-friendly error messages.
- Implementation: Define custom exception handlers in Flask to manage different error scenarios gracefully.
d. Input Validation Using Schemas
- Purpose: Ensure that incoming data adheres to the expected structure and types.
- Implementation: Use libraries like
marshmallow or pydantic to define schemas and validate request payloads automatically.
e. Security Enhancements
- Purpose: Protect the application from common web vulnerabilities.
- Implementation:
- CORS Configuration: Fine-tune CORS settings to restrict allowed origins.
- Content Security Policy (CSP): Implement CSP headers to mitigate cross-site scripting (XSS) attacks.
- HTTPS Enforcement: Ensure all communications are over HTTPS, especially when exposing endpoints through ngrok.
f. Performance Optimizations
- Purpose: Improve application responsiveness and handle higher loads efficiently.
- Implementation:
- Asynchronous Processing: Ensure all I/O-bound operations are handled asynchronously.
- Caching: Implement caching strategies for frequently accessed data.
- Resource Management: Monitor and optimize the usage of threads, connections, and other resources.
4. Updated Script with Improved Refinement Functions
Below is the updated script incorporating the improved refine_messages and refine_response functions:
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
import html
import re
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
def sanitize_text(text):
"""
Sanitizes text by escaping HTML characters and removing potentially harmful patterns.
Args:
text (str): The text to sanitize.
Returns:
str: Sanitized text.
"""
# Escape HTML to prevent injection
sanitized = html.escape(text)
# Remove any script tags or harmful regex patterns
sanitized = re.sub(r'<\/?script[^>]*>', '', sanitized, flags=re.IGNORECASE)
# Optionally, enforce maximum length
MAX_LENGTH = 2000
if len(sanitized) > MAX_LENGTH:
sanitized = sanitized[:MAX_LENGTH] + '...'
return sanitized
def refine_messages(messages):
"""
Validates and cleans incoming messages to ensure they are well-formed and secure.
Args:
messages (list): A list of message dictionaries.
Returns:
list: A list of refined and validated message dictionaries.
Raises:
ValueError: If message structure is invalid.
"""
VALID_ROLES = {'system', 'user', 'assistant'}
refined = []
for idx, message in enumerate(messages):
if not isinstance(message, dict):
raise ValueError(f"Message at index {idx} is not a dictionary.")
role = message.get('role')
content = message.get('content', '').strip()
# Validate role
if role not in VALID_ROLES:
raise ValueError(f"Invalid role '{role}' in message at index {idx}. Must be one of {VALID_ROLES}.")
# Validate content
if not content:
raise ValueError(f"Empty content in message at index {idx}.")
# Sanitize content to prevent injection attacks
sanitized_content = sanitize_text(content)
refined.append({
'role': role,
'content': sanitized_content
})
return refined
def refine_response(response):
"""
Refines the generated response by performing intelligent substitutions and ensuring content quality.
Args:
response (str): The raw response generated by the AI model.
Returns:
str: The refined and sanitized response.
"""
if not isinstance(response, str):
raise ValueError("Response must be a string.")
# Define patterns and replacements
replacements = {
r'\bgeneric\b': 'creative',
r'\bboring\b': 'engaging',
# Add more patterns and replacements as needed
}
refined = response
for pattern, replacement in replacements.items():
refined = re.sub(pattern, replacement, refined, flags=re.IGNORECASE)
# Additional refinements can be added here
refined = sanitize_response(refined)
return refined
def sanitize_response(text):
"""
Sanitizes the response to ensure it meets quality and security standards.
Args:
text (str): The text to sanitize.
Returns:
str: Sanitized text.
"""
# Remove unwanted characters or patterns
# Example: Remove any non-printable characters
sanitized = ''.join(char for char in text if char.isprintable())
# Optionally, enforce maximum length
MAX_LENGTH = 1000
if len(sanitized) > MAX_LENGTH:
sanitized = sanitized[:MAX_LENGTH].rstrip() + '...'
return sanitized
async def handle_request(request):
"""Asynchronous request handler"""
try:
data = await request.json
except Exception:
return jsonify({'error': 'Invalid JSON format.'}), 400
messages = data.get('messages', [])
request_config = data.get('config', {})
if not messages:
return jsonify({'error': 'No messages provided.'}), 400
try:
refined_messages = refine_messages(messages)
except ValueError as ve:
return jsonify({'error': str(ve)}), 400
final_config = get_config_with_defaults(request_config)
system_prompt = data.get('system', final_config['system_prompt'])
stream = data.get('stream', False)
refined_messages.insert(0, {'role': 'system', 'content': system_prompt})
try:
if stream:
return Response(stream_with_context(stream_response(refined_messages, final_config)), content_type='text/event-stream')
else:
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)
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,
):
refined_chunk = refine_response(chunk)
# Compress using base64 to ensure data integrity in JSON
compressed_chunk = zlib.compress(refined_chunk.encode()).decode('latin1')
yield f"data: {json.dumps({'choices': [{'delta': {'content': compressed_chunk}}]})}\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':
try:
new_config = await request.json
# Optional: Validate new_config here
config.update(new_config)
return jsonify({'message': 'Configuration updated.', 'config': config})
except Exception:
return jsonify({'error': 'Invalid JSON format.'}), 400
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 run_flask_app(app, port):
"""Runs the Flask app using aioflask's run_app."""
from aioflask import run_app
run_app(app, host='0.0.0.0', port=port)
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
run_flask_app(app, port=args.port)
if __name__ == '__main__':
main()
5. Summary of Improvements
- Robust Validation: Ensures that both incoming messages and generated responses adhere to expected formats and content rules.
- Security Enhancements: Sanitizes inputs and outputs to prevent injection attacks and other security vulnerabilities.
- Error Handling: Provides clear and descriptive error messages, improving the debuggability and reliability of the application.
- Extensibility: Structures the refinement functions to allow easy addition of new patterns and rules.
- Performance Optimization: Maintains efficient resource management and leverages asynchronous processing for better scalability.
By implementing these enhancements, your application will be more secure, reliable, and maintainable, providing a better experience for both developers and end-users.