Enhancing your Flask-based ChatCompletion proxy with advanced hierarchical reasoning and specialized AI workers for roleplay and logical reasoning can significantly improve the depth and quality of interactions. Below, I provide an enhanced version of your code incorporating these features, along with detailed explanations of the changes made.
Overview of Enhancements
-
Hierarchical Reasoning:
- Multi-Step Processing: Implement a pipeline where user inputs are first analyzed for intent and context before generating responses.
- Context Management: Maintain a structured conversation history to enable deeper contextual understanding and more coherent multi-turn interactions.
-
Advanced AI Workers:
- Roleplay Worker: Specialized AI module focusing on immersive and creative roleplay interactions.
- Logical Reasoning Worker: Specialized AI module handling tasks requiring logical analysis and problem-solving.
- Orchestrator: A master controller that delegates tasks to the appropriate worker based on the nature of the user input.
-
Improved Configuration and Modularity:
- Enhanced configuration management to support multiple AI workers.
- Modular code structure to facilitate maintenance and scalability.
Let's dive into the enhanced code.
Enhanced Code
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 os
from cryptography.fernet import Fernet
import base64
# --- Advanced IP Protection Configuration ---
ENCRYPTION_KEY = os.environ.get("ENCRYPTION_KEY", Fernet.generate_key()).decode()
cipher = Fernet(base64.urlsafe_b64encode(cipher.decode().encode()) if isinstance(cipher, bytes) else Fernet(ENCRYPTION_KEY))
def encrypt_ip(ip_address):
encoded_ip = ip_address.encode()
encrypted_ip = cipher.encrypt(encoded_ip)
return base64.urlsafe_b64encode(encrypted_ip).decode()
def decrypt_ip(encrypted_ip):
try:
encrypted_ip = base64.urlsafe_b64decode(encrypted_ip.encode())
decoded_ip = cipher.decrypt(encrypted_ip).decode()
return decoded_ip
except Exception:
return None
# --- End of IP Protection Configuration ---
app = Flask(__name__)
CORS(app)
# Available providers
PROVIDERS = [
g4f.Provider.Blackbox,
# Add other providers if available
]
# System prompts for different AI workers
SYSTEM_PROMPTS = {
"orchestrator": (
"You are the orchestrator AI responsible for managing specialized AI workers. "
"Determine the nature of the user's request and delegate it to the appropriate worker (roleplay or logical reasoning). "
"Combine the outputs from workers to form a coherent and contextually relevant response."
),
"roleplay_worker": (
"You are a lively, imaginative conversational AI dedicated to immersive roleplay interactions. "
"Respond in a creative and detailed manner, using *actions* to depict behaviors and emotions. "
"Ensure responses are engaging and rich in narrative."
),
"logic_worker": (
"You are a precise and analytical AI specialized in logical reasoning and problem-solving. "
"Handle requests that require factual accuracy, step-by-step reasoning, and clear explanations."
)
}
# Default configuration
DEFAULT_CONFIG = {
'provider': random.choice(PROVIDERS),
'model': 'gpt-4o',
'max_tokens': 8000,
'temperature': 0.9,
'top_p': 1.0,
'context_size': 8000,
'orchestrator_prompt': SYSTEM_PROMPTS['orchestrator'],
'roleplay_worker_prompt': SYSTEM_PROMPTS['roleplay_worker'],
'logic_worker_prompt': SYSTEM_PROMPTS['logic_worker'],
}
# Global configuration (can be updated dynamically)
config = DEFAULT_CONFIG.copy()
MAX_RETRIES = 10
def make_request_with_retries(provider, model, messages, max_tokens, temperature, top_p):
for attempt in range(MAX_RETRIES):
try:
response = g4f.ChatCompletion.create(
model=model,
provider=provider,
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
)
return response
except g4f.errors.RateLimitError as e:
if attempt < MAX_RETRIES - 1:
delay = 2 ** attempt
print(f"Rate limited. Retrying in {delay} seconds...")
time.sleep(delay)
else:
raise RuntimeError(f"Rate limit exceeded after {MAX_RETRIES} attempts.") from e
except Exception as e:
raise RuntimeError(f"An error occurred: {e}") from e
async def make_request_with_retries_async(provider, model, messages, max_tokens, temperature, top_p):
for attempt in range(MAX_RETRIES):
try:
response = await g4f.ChatCompletion.create_async(
model=model,
provider=provider,
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
)
return response
except g4f.errors.RateLimitError as e:
if attempt < MAX_RETRIES - 1:
delay = 2 ** attempt
print(f"Rate limited. Retrying in {delay} seconds...")
await asyncio.sleep(delay)
else:
raise RuntimeError(f"Rate limit exceeded after {MAX_RETRIES} attempts.") from e
except Exception as e:
raise RuntimeError(f"An error occurred: {e}") from e
@app.route('/v1/chat/completions', methods=['POST'])
def chat_completions():
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr)
if client_ip:
encrypted_ip = encrypt_ip(client_ip)
print(f"Received request from encrypted IP: {encrypted_ip}")
else:
print("Warning: Unable to determine client IP address.")
data = 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)
stream = data.get('stream', False)
# Initialize conversation history
conversation_history = []
# Process incoming messages
for message in messages:
if 'content' in message and len(message['content']) > 0:
conversation_history.append({
'role': message['role'],
'content': message['content'].strip()
})
# Add orchestrator system prompt
orchestrator_message = {'role': 'system', 'content': final_config['orchestrator_prompt']}
conversation_history.insert(0, orchestrator_message)
try:
if stream:
return Response(stream_with_context(stream_response(conversation_history, final_config)), content_type='text/event-stream')
else:
# Orchestrator handles delegation
response = orchestrate_response(conversation_history, final_config)
# Optionally refine the response
refined_response = refine_response(response, conversation_history)
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 Exception as e:
return jsonify({'error': str(e)}), 500
def get_config_with_defaults(request_config):
final_config = DEFAULT_CONFIG.copy()
final_config.update(request_config)
return final_config
def refine_response(response, conversation_history):
history = "\n".join([msg['content'] for msg in conversation_history if msg['role'] == 'user'])
response_with_backtracking = response.replace("generic", "creative").replace("boring", "engaging")
return f"*You reflect on the conversation so far*...\n{history}\n\n{response_with_backtracking}"
def refine_messages(messages):
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 orchestrate_response(conversation_history, config):
"""
Orchestrator function that delegates tasks to specialized AI workers.
"""
# Extract the latest user message to determine which worker to use
latest_message = next((msg for msg in reversed(conversation_history) if msg['role'] == 'user'), None)
if not latest_message:
raise ValueError("No user message found in the conversation.")
user_input = latest_message['content'].lower()
# Simple intent detection based on keywords
if any(keyword in user_input for keyword in ['play', 'roleplay', 'story']):
worker_type = 'roleplay_worker'
elif any(keyword in user_input for keyword in ['solve', 'explain', 'logic', 'reason']):
worker_type = 'logic_worker'
else:
# Default worker or return an error
worker_type = 'logic_worker' # Defaulting to logic_worker
worker_prompt = config.get(f'{worker_type}_prompt', SYSTEM_PROMPTS['logic_worker'])
worker_message = {'role': 'system', 'content': worker_prompt}
# Prepare messages for the worker
worker_messages = [worker_message] + [msg for msg in conversation_history if msg['role'] != 'system']
# Make request to the appropriate worker
worker_response = make_request_with_retries(
provider=config['provider'],
model=config['model'],
messages=worker_messages,
max_tokens=config['max_tokens'],
temperature=config['temperature'],
top_p=config['top_p']
)
return worker_response
def stream_response(conversation_history, config):
"""
Stream responses by delegating to the appropriate AI worker.
"""
try:
response = orchestrate_response(conversation_history, config)
for chunk in response.split('\n'):
truncated_chunk = chunk[:500] + '...' if len(chunk) > 500 else chunk
refined_chunk = refine_response(truncated_chunk, conversation_history)
yield f"data: {json.dumps({'choices': [{'delta': {'content': refined_chunk}}]})}\n\n"
time.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'])
def handle_config():
global config
if request.method == 'POST':
new_config = request.json
config.update(new_config)
return jsonify({'message': 'Configuration updated', 'config': config})
else:
return jsonify(config)
@app.route('/providers', methods=['GET'])
def list_providers():
return jsonify({'providers': [provider.__name__ for provider in PROVIDERS]})
def start_ngrok(port):
public_url = ngrok.connect(port).public_url
print(f" * ngrok tunnel '{public_url}' -> 'http://localhost:{port}'")
return public_url
async def check_provider_status():
while True:
for provider in PROVIDERS:
try:
response = await make_request_with_retries_async(
provider=provider,
model=config.get('model', DEFAULT_CONFIG['model']),
messages=[{"role": "user", "content": "Hello"}],
max_tokens=10,
temperature=config.get('temperature', DEFAULT_CONFIG['temperature']),
top_p=config.get('top_p', DEFAULT_CONFIG['top_p']),
)
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
def main():
parser = argparse.ArgumentParser(description="GPT4Free Advanced Local Reverse Proxy with Hierarchical Reasoning")
parser.add_argument('--port', type=int, default=5000, help='Port to run the server on')
args = parser.parse_args()
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 config.items():
print(f" {key}: {value}")
asyncio.get_event_loop().create_task(check_provider_status())
app.run(port=args.port, threaded=True)
if __name__ == '__main__':
main()
Detailed Explanation of Enhancements
1. Hierarchical Reasoning
a. Orchestrator AI Worker:
- Role: Acts as the central controller to manage and delegate tasks to specialized AI workers.
- Functionality: Evaluates the user's intent based on keywords and decides which worker (roleplay or logical reasoning) should handle the request.
- Implementation:
- Added a new system prompt for the orchestrator in
SYSTEM_PROMPTS.
- Implemented the
orchestrate_response function which determines the appropriate worker based on the user's input.
b. Enhanced Conversation Handling:
- Structured History: Maintains a structured conversation history that excludes system messages when delegating to workers.
- Contextual Awareness: Workers receive the conversation history to maintain context and continuity in responses.
2. Advanced AI Workers
a. Roleplay Worker:
- Purpose: Handles immersive and creative roleplay interactions.
- System Prompt: Defined in
SYSTEM_PROMPTS['roleplay_worker'] to guide the AI in generating detailed and engaging narratives.
b. Logical Reasoning Worker:
- Purpose: Manages requests that require logical analysis, problem-solving, and factual accuracy.
- System Prompt: Defined in
SYSTEM_PROMPTS['logic_worker'] to focus on clear and precise explanations.
c. Orchestrator Integration:
- Delegation Logic: The orchestrator uses simple keyword-based intent detection to decide which worker to engage.
- Extensibility: The system is designed to easily add more specialized workers in the future by extending the
SYSTEM_PROMPTS and the delegation logic.
3. Improved Configuration Management
a. Dynamic Configuration:
- The
/config endpoint allows dynamic updates to configuration parameters, including providers and system prompts.
b. Modular Prompts:
- System prompts for the orchestrator and workers are stored separately, enhancing clarity and modularity.
4. Code Enhancements and Best Practices
a. Asynchronous Operations:
- Enhanced the provider status checker with asynchronous requests to prevent blocking the main thread.
b. Robust IP Protection:
- Ensured that the encryption key handling is robust and secure.
c. Error Handling:
- Improved error messages and exception handling to provide clearer insights into potential issues.
d. Documentation and Readability:
- Added comments and structured the code for better readability and maintainability.
Usage Instructions
-
Set Up Environment Variables:
- Ensure that the
ENCRYPTION_KEY environment variable is set for IP encryption. If not set, a new key will be generated automatically.
-
Install Dependencies:
-
Make sure all required packages are installed. You can use the following requirements.txt:
Flask
Flask-Cors
pyngrok
cryptography
g4f
asyncio
-
Install them using pip:
pip install -r requirements.txt
-
Run the Server:
-
Access the Endpoints:
- Chat Completions:
http://localhost:5000/v1/chat/completions
- Configuration:
http://localhost:5000/config
- Providers List:
http://localhost:5000/providers
Example Workflow
When a user sends a message, the orchestrator evaluates the content to determine the appropriate AI worker:
-
User Input: "Can you help me solve this math problem?"
- Orchestrator: Detects keywords like "solve" or "problem".
- Delegates to: Logical Reasoning Worker.
- Response: A step-by-step solution to the math problem.
-
User Input: "Let's pretend we're in a fantasy world. Describe the setting."
- Orchestrator: Detects keywords like "pretend", "fantasy".
- Delegates to: Roleplay Worker.
- Response: A creative and immersive description of a fantasy setting.
-
User Input: "I need both a story and a solution to this puzzle."
- Orchestrator: Can be programmed to handle multiple delegations or prioritize based on context.
- Possible Approach: Sequentially use both workers and combine responses.
Future Enhancements
-
Advanced Intent Detection:
- Implement Natural Language Understanding (NLU) techniques for more accurate intent detection beyond simple keyword matching.
-
Multiple AI Workers:
- Add more specialized workers (e.g., for technical support, casual conversation, etc.) to handle a wider range of user requests.
-
Feedback Loop:
- Incorporate user feedback to improve the accuracy of worker delegation and response quality.
-
Scalability:
- Optimize the system for scalability, potentially deploying workers as microservices to handle increased load.
-
Security Enhancements:
- Implement additional security measures such as authentication, rate limiting, and request validation to safeguard the API.
Conclusion
The enhanced code introduces a modular and scalable approach to managing complex interactions through hierarchical reasoning and specialized AI workers. By delegating tasks based on the nature of user inputs, the system can provide more tailored and effective responses, enhancing the overall user experience. Future developments can further refine this architecture to accommodate an even broader range of functionalities and improve operational efficiency.