Files
wevads-platform/scripts/api_hamid-brain.php
2026-02-26 04:53:11 +01:00

517 lines
22 KiB
PHP
Executable File

<?php
/**
* WEVAL MIND BRAIN - Central AI Intelligence
* 11 Providers: Cerebras, Groq, DeepSeek, Gemini, Claude, Hyperbolic, Mistral, Cohere, SambaNova, Ollama
*/
header('Content-Type: application/json');
$pdo = new PDO("pgsql:host=localhost;dbname=adx_system", "admin", "admin123", [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec("
CREATE TABLE IF NOT EXISTS admin.hamid_providers (
id SERIAL PRIMARY KEY,
name VARCHAR(100) UNIQUE,
api_url TEXT,
api_key TEXT,
model VARCHAR(255),
priority INTEGER DEFAULT 5,
is_active BOOLEAN DEFAULT true,
requests_today INTEGER DEFAULT 0,
avg_response_time FLOAT DEFAULT 0,
success_rate FLOAT DEFAULT 100,
last_used TIMESTAMP
);
CREATE TABLE IF NOT EXISTS admin.hamid_conversations (
id SERIAL PRIMARY KEY,
session_id VARCHAR(100),
role VARCHAR(20),
content TEXT,
provider_used VARCHAR(100),
tokens_used INTEGER,
response_time FLOAT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS admin.hamid_knowledge (
id SERIAL PRIMARY KEY,
category VARCHAR(100),
topic VARCHAR(255),
content TEXT,
source VARCHAR(255),
confidence FLOAT DEFAULT 0.8,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(category, topic)
);
CREATE TABLE IF NOT EXISTS admin.hamid_tasks (
id SERIAL PRIMARY KEY,
task_type VARCHAR(100),
input_data TEXT,
output_data TEXT,
status VARCHAR(50) DEFAULT 'pending',
provider_used VARCHAR(100),
execution_time FLOAT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP
);
");
class HamidBrain {
private $pdo;
private $providers = [];
public function __construct($pdo) {
$this->pdo = $pdo;
$this->initProviders();
$this->loadKnowledge();
}
private function initProviders() {
$defaultProviders = [
['Cerebras', 'https://api.cerebras.ai/v1/chat/completions', '', 'llama3.1-70b', 1],
['Groq', 'https://api.groq.com/openai/v1/chat/completions', '', 'llama-3.1-70b-versatile', 2],
['DeepSeek', 'https://api.deepseek.com/v1/chat/completions', '', 'deepseek-chat', 3],
['Gemini', 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent', '', 'gemini-pro', 4],
['Claude', 'https://api.anthropic.com/v1/messages', '', 'claude-3-haiku-20240307', 5],
['Hyperbolic', 'https://api.hyperbolic.xyz/v1/chat/completions', '', 'meta-llama/Llama-3.2-3B-Instruct', 6],
['Mistral', 'https://api.mistral.ai/v1/chat/completions', '', 'mistral-small-latest', 7],
['Cohere', 'https://api.cohere.ai/v1/chat', '', 'command-r', 8],
['SambaNova', 'https://api.sambanova.ai/v1/chat/completions', '', 'Meta-Llama-3.1-8B-Instruct', 9],
['Ollama', 'http://localhost:11434/api/chat', '', 'llama3', 10],
['OpenAI', 'https://api.openai.com/v1/chat/completions', '', 'gpt-3.5-turbo', 11]
];
foreach ($defaultProviders as $p) {
$this->pdo->prepare("INSERT INTO admin.hamid_providers (name, api_url, api_key, model, priority) VALUES (?, ?, ?, ?, ?) ON CONFLICT (name) DO NOTHING")
->execute($p);
}
$this->providers = $this->pdo->query("SELECT * FROM admin.hamid_providers WHERE is_active = true ORDER BY priority ASC")->fetchAll(PDO::FETCH_ASSOC);
}
private function loadKnowledge() {
$knowledge = [
// Email Deliverability
['deliverability', 'spam_filters', 'Major spam filters: Cloudmark (Videotron, GMX), Google AI (Gmail), SmartScreen (Outlook), Vade Secure (Orange, SFR, LaPoste), SpamAssassin (Free)', 'internal'],
['deliverability', 'warmup_rules', 'IP warmup: Start 50/day, increase 20% daily. Domain warmup: 14-45 days depending on ISP. Never exceed 15000/server/day', 'internal'],
['deliverability', 'inbox_factors', 'Inbox factors: Authentication (SPF/DKIM/DMARC), Engagement, Content quality, Sender reputation, List hygiene', 'internal'],
// ISP Specifics
['isp', 'gmail', 'Gmail: Google AI filter, 45-day warmup, engagement-first sending, max 500/hour initially, requires List-Unsubscribe', 'internal'],
['isp', 'outlook', 'Outlook: SmartScreen filter, SCL score must be <1, 30-day warmup, List-Unsubscribe-Post required', 'internal'],
['isp', 'videotron', 'Videotron: Cloudmark filter, 21-day warmup, 2000/hour max, personal tone works best', 'internal'],
['isp', 'yahoo', 'Yahoo: Strong DKIM required, 30-day warmup, avoid URL shorteners, 800/hour max', 'internal'],
// Send Methods
['methods', 'pmta_direct', 'PMTA Direct: Best for high volume, requires dedicated IPs, full control over headers, 15000/server/day', 'internal'],
['methods', 'o365_relay', 'Office 365 Relay: Good reputation, limited to 10000/day/mailbox, requires connector setup', 'internal'],
['methods', 'gsuite_relay', 'GSuite Relay: Trusted sender, requires IP whitelisting, 2000/user/day limit', 'internal'],
// Campaign Optimization
['optimization', 'segmentation', 'Segment by engagement: Hot (7 days), Warm (30 days), Cold (90+ days). Send to hot first to build reputation', 'internal'],
['optimization', 'timing', 'Best send times: B2B 9-11am, 2-4pm. B2C 10am-12pm, 7-9pm. Avoid weekends for business', 'internal'],
['optimization', 'content', 'Avoid spam triggers: free, click here, act now, winner, urgent. Use personalization. Keep subjects <60 chars', 'internal'],
// Infrastructure
['infrastructure', 'huawei_t6', 'Huawei T6: 2 vCPUs, 4GB RAM, 300Mbps, pay-per-use, all ports open, best regions: af-south-1, eu-west-0', 'internal'],
['infrastructure', 'pmta_config', 'PMTA optimal: max-smtp-out 20, pattern-lifetime 1h, backoff-max-msg-rate for throttling', 'internal']
];
foreach ($knowledge as $k) {
$this->pdo->prepare("INSERT INTO admin.hamid_knowledge (category, topic, content, source) VALUES (?, ?, ?, ?) ON CONFLICT (category, topic) DO UPDATE SET content = ?, last_updated = NOW()")
->execute([$k[0], $k[1], $k[2], $k[3], $k[2]]);
}
}
// ============================================
// AI PROVIDER CALLS
// ============================================
public function ask($question, $context = [], $preferredProvider = null) {
$startTime = microtime(true);
// Enhance question with knowledge
$enhancedPrompt = $this->enhanceWithKnowledge($question);
// Try providers in order
$providers = $preferredProvider
? array_merge(
array_filter($this->providers, fn($p) => $p['name'] == $preferredProvider),
array_filter($this->providers, fn($p) => $p['name'] != $preferredProvider)
)
: $this->providers;
foreach ($providers as $provider) {
$response = $this->callProvider($provider, $enhancedPrompt, $context);
if ($response['success']) {
$elapsed = microtime(true) - $startTime;
// Log conversation
$this->logConversation($question, $response['content'], $provider['name'], $elapsed);
// Update provider stats
$this->updateProviderStats($provider['name'], true, $elapsed);
return [
'success' => true,
'response' => $response['content'],
'provider' => $provider['name'],
'time' => round($elapsed, 2)
];
}
$this->updateProviderStats($provider['name'], false, 0);
}
return ['success' => false, 'error' => 'All providers failed'];
}
private function callProvider($provider, $prompt, $context = []) {
$name = $provider['name'];
$url = $provider['api_url'];
$key = $provider['api_key'];
$model = $provider['model'];
$systemPrompt = "You are WEVAL MIND, an expert AI assistant for email marketing and deliverability. You help with campaign optimization, ISP-specific strategies, content generation, and infrastructure management. Be concise and actionable.";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, true);
switch ($name) {
case 'Claude':
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'x-api-key: ' . $key,
'anthropic-version: 2023-06-01'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => $model,
'max_tokens' => 1024,
'system' => $systemPrompt,
'messages' => [['role' => 'user', 'content' => $prompt]]
]));
break;
case 'Gemini':
$url .= '?key=' . $key;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'contents' => [['parts' => [['text' => $systemPrompt . "\n\n" . $prompt]]]]
]));
break;
case 'Cohere':
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $key
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => $model,
'message' => $prompt,
'preamble' => $systemPrompt
]));
break;
case 'Ollama':
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => $model,
'messages' => [
['role' => 'system', 'content' => $systemPrompt],
['role' => 'user', 'content' => $prompt]
],
'stream' => false
]));
break;
default: // OpenAI-compatible (Groq, Cerebras, DeepSeek, Mistral, Hyperbolic, SambaNova, OpenAI)
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $key
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'model' => $model,
'messages' => [
['role' => 'system', 'content' => $systemPrompt],
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => 1024,
'temperature' => 0.7
]));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 300 && $response) {
$data = json_decode($response, true);
$content = $this->extractContent($name, $data);
if ($content) {
return ['success' => true, 'content' => $content];
}
}
return ['success' => false];
}
private function extractContent($provider, $data) {
switch ($provider) {
case 'Claude':
return $data['content'][0]['text'] ?? null;
case 'Gemini':
return $data['candidates'][0]['content']['parts'][0]['text'] ?? null;
case 'Cohere':
return $data['text'] ?? null;
case 'Ollama':
return $data['message']['content'] ?? null;
default:
return $data['choices'][0]['message']['content'] ?? null;
}
}
private function enhanceWithKnowledge($question) {
$questionLower = strtolower($question);
$relevantKnowledge = [];
// Find relevant knowledge
$keywords = ['gmail', 'outlook', 'yahoo', 'videotron', 'warmup', 'pmta', 'deliverability', 'spam', 'inbox', 'huawei', 'campaign'];
foreach ($keywords as $kw) {
if (strpos($questionLower, $kw) !== false) {
$knowledge = $this->pdo->query("SELECT content FROM admin.hamid_knowledge WHERE topic LIKE '%$kw%' OR content LIKE '%$kw%' LIMIT 2")->fetchAll(PDO::FETCH_COLUMN);
$relevantKnowledge = array_merge($relevantKnowledge, $knowledge);
}
}
if (!empty($relevantKnowledge)) {
return "Context:\n" . implode("\n", array_unique($relevantKnowledge)) . "\n\nQuestion: " . $question;
}
return $question;
}
private function logConversation($question, $response, $provider, $time) {
$sessionId = session_id() ?: uniqid();
$this->pdo->prepare("INSERT INTO admin.hamid_conversations (session_id, role, content, provider_used, response_time) VALUES (?, 'user', ?, ?, ?)")
->execute([$sessionId, $question, $provider, $time]);
$this->pdo->prepare("INSERT INTO admin.hamid_conversations (session_id, role, content, provider_used, response_time) VALUES (?, 'assistant', ?, ?, ?)")
->execute([$sessionId, $response, $provider, $time]);
}
private function updateProviderStats($name, $success, $time) {
if ($success) {
$this->pdo->exec("UPDATE admin.hamid_providers SET requests_today = requests_today + 1, avg_response_time = (avg_response_time + $time) / 2, last_used = NOW() WHERE name = '$name'");
} else {
$this->pdo->exec("UPDATE admin.hamid_providers SET success_rate = success_rate * 0.95 WHERE name = '$name'");
}
}
// ============================================
// SPECIALIZED TASKS
// ============================================
public function generateSubject($offer, $sponsor, $isp) {
$prompt = "Generate 5 email subject lines for:
Offer: $offer
Sponsor: $sponsor
Target ISP: $isp
Requirements:
- Avoid spam triggers for $isp
- Under 50 characters
- Personal and engaging
- No ALL CAPS or excessive punctuation
Return only the 5 subject lines, numbered 1-5.";
return $this->ask($prompt);
}
public function generateFromName($offer, $style = 'professional') {
$prompt = "Generate 5 sender names for email marketing:
Offer type: $offer
Style: $style
Requirements:
- Look trustworthy
- Match the offer type
- Mix of male and female names
Return only the 5 names, numbered 1-5.";
return $this->ask($prompt);
}
public function optimizeContent($content, $isp) {
$prompt = "Analyze and optimize this email content for $isp inbox delivery:
$content
Provide:
1. Spam trigger analysis
2. Specific issues found
3. Optimized version
4. Score (0-100)";
return $this->ask($prompt);
}
public function planCampaign($params) {
$prompt = "Plan an email campaign with:
- Target ISP: {$params['isp']}
- Volume: {$params['volume']}
- Offer: {$params['offer']}
- Budget: {$params['budget']}
Provide:
1. Recommended send method
2. Server requirements (Huawei T6 specs)
3. Warmup strategy if needed
4. Segmentation approach
5. Optimal send times
6. Risk assessment";
return $this->ask($prompt);
}
public function analyzeDeliverability($data) {
$prompt = "Analyze these email campaign results:
- Sent: {$data['sent']}
- Delivered: {$data['delivered']}
- Opens: {$data['opens']}
- Clicks: {$data['clicks']}
- Bounces: {$data['bounces']}
- Spam complaints: {$data['complaints']}
- ISP: {$data['isp']}
Provide:
1. Performance assessment
2. Key issues identified
3. Specific recommendations
4. Priority actions";
return $this->ask($prompt);
}
public function executeTask($taskType, $input) {
$this->pdo->prepare("INSERT INTO admin.hamid_tasks (task_type, input_data, status) VALUES (?, ?, 'processing')")
->execute([$taskType, json_encode($input)]);
$taskId = $this->pdo->lastInsertId();
$start = microtime(true);
switch ($taskType) {
case 'generate_subject':
$result = $this->generateSubject($input['offer'] ?? '', $input['sponsor'] ?? '', $input['isp'] ?? 'Gmail');
break;
case 'generate_from':
$result = $this->generateFromName($input['offer'] ?? '', $input['style'] ?? 'professional');
break;
case 'optimize_content':
$result = $this->optimizeContent($input['content'] ?? '', $input['isp'] ?? 'Gmail');
break;
case 'plan_campaign':
$result = $this->planCampaign($input);
break;
case 'analyze':
$result = $this->analyzeDeliverability($input);
break;
default:
$result = $this->ask($input['question'] ?? '');
}
$elapsed = microtime(true) - $start;
$this->pdo->prepare("UPDATE admin.hamid_tasks SET output_data = ?, status = 'completed', provider_used = ?, execution_time = ?, completed_at = NOW() WHERE id = ?")
->execute([json_encode($result), $result['provider'] ?? 'unknown', $elapsed, $taskId]);
return array_merge($result, ['task_id' => $taskId]);
}
// ============================================
// KNOWLEDGE MANAGEMENT
// ============================================
public function addKnowledge($category, $topic, $content, $source = 'user') {
$this->pdo->prepare("INSERT INTO admin.hamid_knowledge (category, topic, content, source) VALUES (?, ?, ?, ?) ON CONFLICT (category, topic) DO UPDATE SET content = ?, last_updated = NOW()")
->execute([$category, $topic, $content, $source, $content]);
return ['success' => true];
}
public function searchKnowledge($query) {
$results = $this->pdo->query("SELECT * FROM admin.hamid_knowledge WHERE content ILIKE '%$query%' OR topic ILIKE '%$query%' ORDER BY confidence DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
return ['results' => $results];
}
public function getStats() {
return [
'providers' => $this->pdo->query("SELECT name, is_active, requests_today, avg_response_time, success_rate FROM admin.hamid_providers ORDER BY priority")->fetchAll(PDO::FETCH_ASSOC),
'knowledge_count' => $this->pdo->query("SELECT COUNT(*) FROM admin.hamid_knowledge")->fetchColumn(),
'conversations_today' => $this->pdo->query("SELECT COUNT(*) FROM admin.hamid_conversations WHERE DATE(created_at) = CURRENT_DATE")->fetchColumn(),
'tasks_completed' => $this->pdo->query("SELECT COUNT(*) FROM admin.hamid_tasks WHERE status = 'completed'")->fetchColumn()
];
}
}
$hamid = new HamidBrain($pdo);
$action = $_POST['action'] ?? $_GET['action'] ?? '';
switch ($action) {
case 'ask':
echo json_encode($hamid->ask($_POST['question'] ?? $_GET['question'], [], $_POST['provider'] ?? null));
break;
case 'task':
echo json_encode($hamid->executeTask($_POST['task_type'], $_POST));
break;
case 'generate_subject':
echo json_encode($hamid->generateSubject($_POST['offer'], $_POST['sponsor'] ?? '', $_POST['isp'] ?? 'Gmail'));
break;
case 'generate_from':
echo json_encode($hamid->generateFromName($_POST['offer'], $_POST['style'] ?? 'professional'));
break;
case 'optimize':
echo json_encode($hamid->optimizeContent($_POST['content'], $_POST['isp'] ?? 'Gmail'));
break;
case 'plan':
echo json_encode($hamid->planCampaign($_POST));
break;
case 'analyze':
echo json_encode($hamid->analyzeDeliverability($_POST));
break;
case 'add_knowledge':
echo json_encode($hamid->addKnowledge($_POST['category'], $_POST['topic'], $_POST['content'], $_POST['source'] ?? 'user'));
break;
case 'search':
echo json_encode($hamid->searchKnowledge($_GET['query']));
break;
case 'providers':
echo json_encode(['providers' => $pdo->query("SELECT * FROM admin.hamid_providers ORDER BY priority")->fetchAll(PDO::FETCH_ASSOC)]);
break;
case 'set_key':
$pdo->prepare("UPDATE admin.hamid_providers SET api_key = ? WHERE name = ?")->execute([$_POST['api_key'], $_POST['provider']]);
echo json_encode(['success' => true]);
break;
case 'knowledge':
echo json_encode(['knowledge' => $pdo->query("SELECT * FROM admin.hamid_knowledge ORDER BY category, topic")->fetchAll(PDO::FETCH_ASSOC)]);
break;
case 'stats':
echo json_encode($hamid->getStats());
break;
default:
echo json_encode([
'name' => 'WEVAL MIND Brain',
'version' => '2.0',
'providers' => 11,
'actions' => ['ask','task','generate_subject','generate_from','optimize','plan','analyze','add_knowledge','search','providers','set_key','knowledge','stats']
]);
}