🔍 OpenAI API Diagnostic Tool";
echo "";
function makeTestRequest($delaySeconds = 0) {
if ($delaySeconds > 0) {
sleep($delaySeconds);
}
$messages = [
[
'role' => 'user',
'content' => 'Say "Hello" only.'
]
];
$data = [
'model' => 'gpt-4',
'messages' => $messages,
'max_tokens' => 10,
'temperature' => 0.1
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => GPT_API_ENDPOINT,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . OPENAI_API_KEY
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_HEADER => true,
CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
// Separate headers and body
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
return [
'http_code' => $httpCode,
'headers' => $headers,
'body' => $body,
'curl_error' => $curlError,
'timestamp' => time()
];
}
try {
echo "
1. API Key Validation
";
if (empty(OPENAI_API_KEY)) {
echo "❌ OpenAI API key is not configured
";
exit;
}
$keyLength = strlen(OPENAI_API_KEY);
$keyPrefix = substr(OPENAI_API_KEY, 0, 7);
echo "📊 API Key Length: $keyLength characters
";
echo "📊 API Key Prefix: $keyPrefix...
";
if ($keyPrefix !== 'sk-proj') {
echo "⚠️ API key doesn't start with 'sk-proj' - this might be an older key format
";
}
echo "2. Initial API Test
";
echo "🔍 Making initial test request...
";
$testResult = makeTestRequest();
echo "📊 HTTP Status Code: {$testResult['http_code']}
";
if ($testResult['curl_error']) {
echo "❌ CURL Error: {$testResult['curl_error']}
";
exit;
}
// Parse response
$responseData = json_decode($testResult['body'], true);
if ($testResult['http_code'] === 200) {
echo "✅ API key is valid and working!
";
echo "✅ Response: " . ($responseData['choices'][0]['message']['content'] ?? 'No content') . "
";
} elseif ($testResult['http_code'] === 429) {
echo "❌ Rate limit exceeded (HTTP 429)
";
if (isset($responseData['error'])) {
echo "Error details: " . json_encode($responseData['error'], JSON_PRETTY_PRINT) . "
";
// Check for specific rate limit information
if (isset($responseData['error']['message'])) {
$message = $responseData['error']['message'];
echo "📊 Rate limit message: $message
";
// Extract rate limit info if available
if (preg_match('/(\d+)\s*requests?\s*per\s*(\w+)/i', $message, $matches)) {
echo "⚠️ Detected rate limit: {$matches[1]} requests per {$matches[2]}
";
}
}
}
// Check headers for rate limit info
if (preg_match('/x-ratelimit-limit-requests:\s*(\d+)/i', $testResult['headers'], $matches)) {
echo "📊 Rate limit from headers: {$matches[1]} requests
";
}
if (preg_match('/x-ratelimit-remaining-requests:\s*(\d+)/i', $testResult['headers'], $matches)) {
echo "📊 Remaining requests: {$matches[1]}
";
}
if (preg_match('/x-ratelimit-reset-requests:\s*(.+)/i', $testResult['headers'], $matches)) {
echo "📊 Rate limit resets at: {$matches[1]}
";
}
} elseif ($testResult['http_code'] === 401) {
echo "❌ Authentication failed (HTTP 401) - Invalid API key
";
exit;
} elseif ($testResult['http_code'] === 403) {
echo "❌ Forbidden (HTTP 403) - API key lacks permissions
";
exit;
} else {
echo "❌ Unexpected HTTP status: {$testResult['http_code']}
";
echo "Response: " . htmlspecialchars($testResult['body']) . "
";
}
echo "3. Rate Limit Recovery Test
";
if ($testResult['http_code'] === 429) {
echo "🔍 Testing recovery strategies...
";
$waitTimes = [60, 120, 300]; // 1 minute, 2 minutes, 5 minutes
foreach ($waitTimes as $waitTime) {
echo "⏳ Waiting $waitTime seconds before retry...
";
flush();
$retryResult = makeTestRequest($waitTime);
echo "📊 After $waitTime seconds wait: HTTP {$retryResult['http_code']}
";
if ($retryResult['http_code'] === 200) {
echo "✅ Recovery successful after $waitTime seconds!
";
break;
} elseif ($retryResult['http_code'] !== 429) {
echo "⚠️ Different error after wait: HTTP {$retryResult['http_code']}
";
break;
}
}
}
echo "4. Recommended Solutions
";
if ($testResult['http_code'] === 429) {
echo "
🔧 Rate Limit Solutions:
- Wait for Natural Recovery:
- Stop all OptimAIze processes for 1-2 hours
- OpenAI rate limits usually reset automatically
- Your account may be in temporary penalty mode
- Use Conservative Settings:
- Reduce to 1-2 requests per minute initially
- Gradually increase as limits reset
- Use longer delays between requests
- Check Your OpenAI Plan:
- Free tier: Very limited requests
- Pay-as-you-go: Higher limits but still restricted
- Consider upgrading to a higher tier
- Implement Smart Batching:
- Process only a few combinations at a time
- Use longer delays between batches
- Implement exponential backoff
";
echo "
📝 Immediate Action Plan:
- Stop all current OptimAIze processes
- Wait 2-3 hours for rate limits to reset
- Use the conservative processor I'll provide below
- Monitor the process closely
- Gradually increase speed as stability improves
";
} elseif ($testResult['http_code'] === 200) {
echo "
✅ API is Working - Deployment Ready:
- Your API key is valid and working
- You can proceed with the enhanced OptimAIze system
- Start with moderate settings and increase gradually
- Monitor the logs for any rate limit warnings
";
}
echo "5. Current System Status
";
echo "";
echo "Timestamp: " . date('Y-m-d H:i:s') . "\n";
echo "API Key Status: " . ($testResult['http_code'] === 200 ? 'Working' : 'Issues Detected') . "\n";
echo "Rate Limit Status: " . ($testResult['http_code'] === 429 ? 'Exceeded' : 'OK') . "\n";
echo "Recommended Action: " . ($testResult['http_code'] === 429 ? 'Wait and use conservative settings' : 'Proceed with enhanced system') . "\n";
echo "
";
} catch (Exception $e) {
echo "❌ Diagnostic failed: " . htmlspecialchars($e->getMessage()) . "
";
}
?>