Verify API Key: Ensure your API key is correctly set in your environment variables
Copy
// Check if API key is setif (empty(getenv('OPENAI_API_KEY'))) {echo "API key is not set in environment variables\n";}
Check API Key Format: Some providers require specific formats for API keys
Copy
// OpenAI keys typically start with 'sk-'if (!str_starts_with(getenv('OPENAI_API_KEY'), 'sk-')) {echo "OpenAI API key format is incorrect\n";}// Anthropic keys typically start with 'sk-ant-'if (!str_starts_with(getenv('ANTHROPIC_API_KEY'), 'sk-ant-')) {echo "Anthropic API key format is incorrect\n";}
Test Keys Directly: Use a simple script to test your API keys
Copy
<?phpuse Cognesy\Polyglot\Inference\Inference;use Cognesy\Polyglot\Inference\LLMProvider;use Cognesy\Http\Exceptions\HttpRequestException;function testApiKey(string $preset): bool { try { $llm = (new LLMFactory)->fromPreset($preset); $inference = new Inference($llm); $inference->with( messages: 'Test message', options: ['max_tokens' => 5] )->get(); echo "Connection using '$connection' is working correctly\n"; return true; } catch (HttpRequestException $e) { echo "Error with connection '$connection': " . $e->getMessage() . "\n"; return false; }}// Test major providerstestApiKey('openai');testApiKey('anthropic');testApiKey('mistral');?>
Environment Variables: Ensure your environment variables are being loaded correctly
Copy
<?php// If using dotenv$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);$dotenv->load();$dotenv->required(['OPENAI_API_KEY'])->notEmpty();?>