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
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
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 = {}
# LangChain setup
llm = OpenAI(temperature=0.9)
conversation = ConversationChain(
llm=llm,
memory=ConversationBufferMemory(),
prompt=PromptTemplate(
input_variables=["history", "input"],
template="{history}\nHuman: {input}\nAI:"
)
)
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
@app.route('/v1/chat/completions', methods=['POST'])
def chat_completions():
"""Handles chat completion requests with structured, clean, and refined responses."""
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)
system_prompt = data.get('system', final_config['system_prompt'])
stream = data.get('stream', False)
# Prepend system message to maintain the roleplay theme
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:
# First refinement - checking the incoming request for consistency
refined_messages = refine_messages(messages)
# Use LangChain for response generation
user_input = refined_messages[-1]['content']
response = conversation.predict(input=user_input)
# Double refinement - polishing the response content
refined_response = refine_response(response)
# Truncate the response if it exceeds length
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 refine_messages(messages):
"""Performs validation and refinement of incoming messages for coherence."""
refined = []
for message in messages:
# Simple validation and trimming for potential malformed input
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."""
# In this case, let's assume response refinement could involve filtering certain phrases
return response.replace("generic", "creative").replace("boring", "engaging")
def stream_response(messages, config):
"""Yields chunks of response in streaming mode, with roleplay flavor added."""
try:
user_input = messages[-1]['content']
response = conversation.predict(input=user_input)
# Simulate streaming by splitting the response into chunks
chunks = [response[i:i+10] for i in range(0, len(response), 10)]
for chunk in chunks:
# Refine chunk and maintain immersive flow with structured responses
refined_chunk = refine_response(chunk)
yield f"data: {json.dumps({'choices': [{'delta': {'content': refined_chunk}}]})}\n\n"
time.sleep(0.1) # Simulate streaming delay with a lively pause
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():
"""Handles configuration updates and retrievals."""
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():
"""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
def main():
"""Main entry point to start the server and ngrok tunnel."""
parser = argparse.ArgumentParser(description="GPT4Free Advanced Local Reverse Proxy with LangChain")
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}")
# Start the provider status checking task
asyncio.get_event_loop().create_task(check_provider_status())
app.run(port=args.port, threaded=True)
if __name__ == '__main__':
main()
# proxy.py
import os
import sys
import importlib.util
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
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
from stable_baselines3 import PPO
from multiprocessing import Process, Manager
from threading import Thread
# Initialize Flask app
app = Flask(__name__)
CORS(app)
# Load configurations
CONFIG_PATH = 'config/config.json'
with open(CONFIG_PATH, 'r') as f:
DEFAULT_CONFIG = json.load(f)
# Dynamically load custom reward function
reward_function_path = os.path.join('config', 'reward_functions', DEFAULT_CONFIG['reward_function'])
spec = importlib.util.spec_from_file_location("custom_reward", reward_function_path)
custom_reward = importlib.util.module_from_spec(spec)
spec.loader.exec_module(custom_reward)
# Available providers
PROVIDERS = [
getattr(g4f.Provider, DEFAULT_CONFIG['provider']),
]
# Global configuration (can be updated dynamically)
config = DEFAULT_CONFIG.copy()
# LangChain setup
llm = OpenAI(temperature=config['temperature'])
conversation = ConversationChain(
llm=llm,
memory=ConversationBufferMemory(),
prompt=PromptTemplate(
input_variables=["history", "input"],
template="{history}\nHuman: {input}\nAI:"
)
)
# Manager for shared state
manager = Manager()
training_data = manager.list()
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
@app.route('/v1/chat/completions', methods=['POST'])
def chat_completions():
"""Handles chat completion requests with structured, clean, and refined responses."""
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)
system_prompt = data.get('system', final_config['system_prompt'])
stream = data.get('stream', False)
# Prepend system message to maintain the roleplay theme
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:
# First refinement - checking the incoming request for consistency
refined_messages = refine_messages(messages)
# Use LangChain for response generation
user_input = refined_messages[-1]['content']
response = conversation.predict(input=user_input)
# Double refinement - polishing the response content
refined_response = refine_response(response)
# Truncate the response if it exceeds length
truncated_response = refined_response[:1000] + '...' if len(refined_response) > 1000 else refined_response
# Collect metrics for reward calculation
metrics = evaluate_metrics(truncated_response)
# Append interaction to training data
training_data.append({
'input': user_input,
'response': truncated_response,
'metrics': metrics
})
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 refine_messages(messages):
"""Performs validation and refinement of incoming messages for coherence."""
refined = []
for message in messages:
# Simple validation and trimming for potential malformed input
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."""
# In this case, let's assume response refinement could involve filtering certain phrases
return response.replace("generic", "creative").replace("boring", "engaging")
def evaluate_metrics(response):
"""
Evaluates metrics based on the response.
This is a placeholder for actual metric evaluation logic.
"""
metrics = {
'coherence': random.uniform(0.8, 1.0), # Simulated coherence score
'creativity': random.uniform(0.5, 1.0) # Simulated creativity score
}
return metrics
def stream_response(messages, config):
"""Yields chunks of response in streaming mode, with roleplay flavor added."""
try:
user_input = messages[-1]['content']
response = conversation.predict(input=user_input)
# Simulate streaming by splitting the response into chunks
chunks = [response[i:i+10] for i in range(0, len(response), 10)]
for chunk in chunks:
# Refine chunk and maintain immersive flow with structured responses
refined_chunk = refine_response(chunk)
yield f"data: {json.dumps({'choices': [{'delta': {'content': refined_chunk}}]})}\n\n"
time.sleep(0.1) # Simulate streaming delay with a lively pause
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():
"""Handles configuration updates and retrievals."""
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():
"""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
def ppo_training_loop(training_data, config):
"""PPO training loop."""
ppo_config = config.get('ppo_config', {})
# Placeholder environment: implement a custom Gym environment for conversational AI
# For demonstration, we'll use a dummy environment
from stable_baselines3.common.envs import DummyEnv
env = DummyEnv()
model = PPO('MlpPolicy', env, **ppo_config)
while True:
if len(training_data) >= ppo_config.get('n_steps', 2048):
# Prepare training data
observations = [data['input'] for data in training_data]
actions = [data['response'] for data in training_data]
rewards = [custom_reward.calculate_reward(data['response'], data['metrics']) for data in training_data]
# Reset training data
training_data[:] = []
# Integrate rewards into the environment
env.update_rewards(observations, actions, rewards)
# Train the model
model.learn(total_timesteps=ppo_config.get('n_steps', 2048))
# Save the model
model.save('models/ppo_conversational_model')
time.sleep(60) # Check every minute
def es_training_loop(training_data, config):
"""Evolutionary Strategies training loop."""
es_config = config.get('es_config', {})
# Placeholder for ES implementation: implement or integrate an ES library
# For demonstration, this is a simplified version
population_size = es_config.get('population_size', 50)
sigma = es_config.get('sigma', 0.1)
learning_rate = es_config.get('learning_rate', 0.03)
num_generations = es_config.get('num_generations', 100)
# Initialize a dummy model parameters
model_params = [random.uniform(-1, 1) for _ in range(10)]
for generation in range(num_generations):
population = []
rewards = []
# Generate population
for _ in range(population_size):
perturbation = [p + random.gauss(0, sigma) for p in model_params]
population.append(perturbation)
# Evaluate fitness
for individual in population:
# Placeholder evaluation: higher sum means better
fitness = sum(individual)
rewards.append(fitness)
# Normalize rewards
mean = sum(rewards) / len(rewards)
std = (sum((x - mean) ** 2 for x in rewards) / len(rewards)) ** 0.5
normalized_rewards = [(r - mean) / std for r in rewards]
# Update model parameters
for i in range(len(model_params)):
gradient = sum(normalized_rewards[j] * population[j][i] for j in range(population_size))
model_params[i] += learning_rate * gradient / (population_size * sigma)
print(f"Generation {generation + 1}/{num_generations} completed.")
# Optionally, add a stopping condition or save intermediate models
def start_training_processes(training_data, config):
"""Starts training processes for PPO and ES."""
ppo_process = Process(target=ppo_training_loop, args=(training_data, config))
es_process = Process(target=es_training_loop, args=(training_data, config))
ppo_process.start()
es_process.start()
return [ppo_process, es_process]
def main():
"""Main entry point to start the server, ngrok tunnel, and training processes."""
parser = argparse.ArgumentParser(description="GPT4Free Advanced Local Reverse Proxy with LangChain and RL Training")
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}")
# Start the provider status checking task
asyncio.ensure_future(check_provider_status())
# Start training processes
training_processes = start_training_processes(training_data, config)
# Start Flask app
app.run(port=args.port, threaded=True)
# Ensure all training processes are terminated on exit
for process in training_processes:
process.join()
if __name__ == '__main__':
main()