-
-
Notifications
You must be signed in to change notification settings - Fork 1
AI Integration
Rumen Damyanov edited this page Sep 22, 2025
·
1 revision
This guide covers everything you need to know about integrating AI providers with the PHP-SEO package for automated SEO content generation.
The PHP-SEO package supports multiple AI providers for generating SEO-optimized content:
- OpenAI (GPT models) - Most popular, great quality
- Anthropic (Claude models) - High quality, good for longer content
- Google AI (Gemini models) - Fast and cost-effective
- Ollama (Local models) - Privacy-focused, no API costs
use Rumenx\PhpSeo\Config\SeoConfig;
use Rumenx\PhpSeo\SeoManager;
// Configure with AI enabled
$config = new SeoConfig([
'ai' => [
'enabled' => true,
'provider' => 'openai',
'fallback_enabled' => true,
],
'providers' => [
'openai' => [
'api_key' => 'your-openai-api-key',
'model' => 'gpt-3.5-turbo',
],
],
]);
$seoManager = new SeoManager($config);
// AI will automatically be used for generation
$analysis = $seoManager->analyze($content);
$title = $seoManager->generateTitle($analysis, ['use_ai' => true]);Create a .env file with your API keys:
# OpenAI
OPENAI_API_KEY=sk-your-openai-api-key-here
# Anthropic
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key-here
# Google AI
GOOGLE_API_KEY=your-google-ai-api-key
# SEO Configuration
SEO_AI_ENABLED=true
SEO_AI_PROVIDER=openai- Get API Key: Sign up at OpenAI Platform
- Configure: Set up your OpenAI configuration
$config = new SeoConfig([
'ai' => [
'enabled' => true,
'provider' => 'openai',
],
'providers' => [
'openai' => [
'api_key' => $_ENV['OPENAI_API_KEY'],
'model' => 'gpt-3.5-turbo', // or 'gpt-4', 'gpt-4-turbo'
'base_url' => 'https://api.openai.com/v1',
'timeout' => 30,
],
],
]);| Model | Use Case | Cost | Speed |
|---|---|---|---|
gpt-3.5-turbo |
General use, cost-effective | Low | Fast |
gpt-4 |
High quality, complex content | High | Slow |
gpt-4-turbo |
Balance of quality and speed | Medium | Medium |
use Rumenx\PhpSeo\Providers\OpenAiProvider;
$provider = new OpenAiProvider($config);
// Generate title
$title = $provider->generateTitle($analysis, [
'max_length' => 60,
'style' => 'engaging',
]);
// Generate description
$description = $provider->generateDescription($analysis, [
'max_length' => 160,
'include_keywords' => true,
]);
// Generate keywords
$keywords = $provider->generateKeywords($analysis, [
'max_keywords' => 10,
'focus' => 'long-tail',
]);- Get API Key: Sign up at Anthropic Console
- Configure: Set up Claude integration
$config = new SeoConfig([
'providers' => [
'anthropic' => [
'api_key' => $_ENV['ANTHROPIC_API_KEY'],
'model' => 'claude-3-sonnet-20240229',
'base_url' => 'https://api.anthropic.com/v1',
'timeout' => 30,
],
],
]);| Model | Use Case | Context Window |
|---|---|---|
claude-3-haiku-20240307 |
Fast, simple tasks | 200K tokens |
claude-3-sonnet-20240229 |
Balanced performance | 200K tokens |
claude-3-opus-20240229 |
Complex, high-quality tasks | 200K tokens |
use Rumenx\PhpSeo\Providers\AnthropicProvider;
$provider = new AnthropicProvider($config);
// Claude is excellent for longer, more detailed descriptions
$description = $provider->generateDescription($analysis, [
'max_length' => 160,
'style' => 'conversational',
'target_audience' => 'professionals',
]);- Get API Key: Create project at Google AI Studio
- Configure: Set up Gemini integration
$config = new SeoConfig([
'providers' => [
'google' => [
'api_key' => $_ENV['GOOGLE_API_KEY'],
'model' => 'gemini-pro',
'base_url' => 'https://generativelanguage.googleapis.com/v1',
'timeout' => 30,
],
],
]);| Model | Use Case | Features |
|---|---|---|
gemini-pro |
Text generation | Fast, cost-effective |
gemini-pro-vision |
Text + Image analysis | Multimodal capabilities |
use Rumenx\PhpSeo\Providers\GoogleProvider;
$provider = new GoogleProvider($config);
// Gemini is fast and cost-effective for bulk operations
$title = $provider->generateTitle($analysis, [
'max_length' => 60,
'optimization_focus' => 'click-through-rate',
]);- Install Ollama: Download from Ollama website
- Pull Models: Download models locally
# Install Ollama
curl -fsSL https://ollama.ai/install.sh | sh
# Pull models
ollama pull llama2
ollama pull codellama
ollama pull mistral- Configure: Set up local integration
$config = new SeoConfig([
'providers' => [
'ollama' => [
'model' => 'llama2',
'base_url' => 'http://localhost:11434',
'timeout' => 60, // Local models may be slower
],
],
]);| Model | Size | Use Case |
|---|---|---|
llama2 |
3.8GB | General purpose |
llama2:13b |
7.3GB | Better quality |
mistral |
4.1GB | Fast, efficient |
codellama |
3.8GB | Code-focused content |
use Rumenx\PhpSeo\Providers\OllamaProvider;
$provider = new OllamaProvider($config);
// Local generation, no API costs
$title = $provider->generateTitle($analysis, [
'max_length' => 60,
'temperature' => 0.7,
]);Configure multiple providers with automatic fallback:
$config = new SeoConfig([
'ai' => [
'enabled' => true,
'provider' => 'openai',
'fallback_providers' => ['anthropic', 'google', 'manual'],
'fallback_enabled' => true,
],
'providers' => [
'openai' => [
'api_key' => $_ENV['OPENAI_API_KEY'],
'model' => 'gpt-3.5-turbo',
],
'anthropic' => [
'api_key' => $_ENV['ANTHROPIC_API_KEY'],
'model' => 'claude-3-sonnet-20240229',
],
'google' => [
'api_key' => $_ENV['GOOGLE_API_KEY'],
'model' => 'gemini-pro',
],
],
]);// Automatic provider selection based on content type
$analysis = $seoManager->analyze($content);
if ($analysis['word_count'] > 1000) {
// Use Claude for longer content
$provider = 'anthropic';
} elseif ($analysis['content_type'] === 'product') {
// Use GPT for product descriptions
$provider = 'openai';
} else {
// Use Gemini for general content (cost-effective)
$provider = 'google';
}
$title = $seoManager->generateTitle($analysis, [
'provider' => $provider,
]);Customize AI prompts for better results:
$config = new SeoConfig([
'ai' => [
'prompts' => [
'title' => 'Generate an SEO-optimized title for this {content_type}. Keep it under {max_length} characters and make it compelling for {target_audience}.',
'description' => 'Create a meta description that summarizes this content in {max_length} characters. Focus on benefits and include a call-to-action.',
'keywords' => 'Extract {max_keywords} relevant keywords from this content, focusing on search intent and user queries.',
],
],
]);Available variables for prompt customization:
-
{content_type}- Type of content (article, product, page) -
{max_length}- Maximum length constraint -
{target_audience}- Target audience -
{brand_voice}- Brand voice/tone -
{industry}- Industry/niche -
{keywords}- Existing keywords -
{competitors}- Competitor analysis
$config = new SeoConfig([
'cache' => [
'enabled' => true,
'ttl' => 86400, // Cache for 24 hours
'driver' => 'redis',
],
'ai' => [
'cache_responses' => true,
'cache_key_strategy' => 'content_hash',
],
]);$config = new SeoConfig([
'ai' => [
'rate_limiting' => [
'enabled' => true,
'requests_per_minute' => 10,
'burst_limit' => 5,
],
],
]);// Process multiple items efficiently
$contents = [
'content1' => '<h1>Title 1</h1><p>Content...</p>',
'content2' => '<h1>Title 2</h1><p>Content...</p>',
];
$results = [];
foreach ($contents as $key => $content) {
$analysis = $seoManager->analyze($content);
$results[$key] = [
'title' => $seoManager->generateTitle($analysis),
'description' => $seoManager->generateDescription($analysis),
];
// Add small delay to respect rate limits
usleep(100000); // 0.1 seconds
}$config = new SeoConfig([
'ai' => [
'cost_tracking' => true,
'budget_limits' => [
'daily' => 10.00, // $10 per day
'monthly' => 200.00, // $200 per month
],
],
'logging' => [
'enabled' => true,
'log_ai_requests' => true,
],
]);- Use Caching: Cache AI responses to avoid duplicate requests
- Choose Right Models: Use cheaper models for simple tasks
- Batch Requests: Combine multiple requests when possible
- Set Limits: Configure budget limits and rate limiting
- Monitor Usage: Track API costs and usage patterns
| Provider | Model | Cost per 1K tokens |
|---|---|---|
| OpenAI | gpt-3.5-turbo | $0.001 |
| OpenAI | gpt-4-turbo | $0.01 |
| Anthropic | claude-3-haiku | $0.0025 |
| Anthropic | claude-3-sonnet | $0.003 |
| gemini-pro | $0.0005 | |
| Ollama | Any model | Free (local) |
try {
$title = $seoManager->generateTitle($analysis);
} catch (AuthenticationException $e) {
// Invalid API key
error_log('AI provider authentication failed: ' . $e->getMessage());
// Fall back to manual generation
$title = $seoManager->generateTitle($analysis, ['use_ai' => false]);
}try {
$title = $seoManager->generateTitle($analysis);
} catch (RateLimitException $e) {
// Rate limit exceeded
error_log('Rate limit exceeded, retrying in 60 seconds');
sleep(60);
$title = $seoManager->generateTitle($analysis);
}try {
$title = $seoManager->generateTitle($analysis);
} catch (NetworkException $e) {
// Network connectivity issues
error_log('Network error: ' . $e->getMessage());
if ($config->get('ai.fallback_enabled')) {
$title = $seoManager->generateTitle($analysis, ['use_ai' => false]);
}
}- Secure API Keys: Never commit API keys to version control
- Environment Variables: Use environment variables for sensitive data
- Access Control: Limit AI access to authorized users only
- Audit Logs: Keep logs of AI usage for security monitoring
- Review Generated Content: Always review AI-generated content
- A/B Testing: Test AI vs manual content performance
- Feedback Loop: Use performance data to improve prompts
- Human Oversight: Maintain human oversight for critical content
- Monitor Response Times: Track AI provider response times
- Set Appropriate Timeouts: Configure timeouts based on use case
- Use Caching: Cache responses to reduce API calls
- Optimize Prompts: Shorter, clearer prompts = better performance
Enable debug mode to see detailed AI interactions:
$config = new SeoConfig([
'logging' => [
'enabled' => true,
'level' => 'debug',
'log_ai_requests' => true,
],
]);// Test AI provider connectivity
$provider = new OpenAiProvider($config);
if ($provider->isConfigured()) {
try {
$response = $provider->generateTitle($testAnalysis);
echo "AI provider working correctly: " . $response;
} catch (Exception $e) {
echo "AI provider error: " . $e->getMessage();
}
} else {
echo "AI provider not configured correctly";
}- Check API Keys: Verify API keys are correct and have sufficient credits
- Test Connectivity: Ensure network connectivity to AI providers
- Review Logs: Check application logs for error messages
- Validate Configuration: Ensure configuration is properly formatted
- Test with Simple Content: Start with basic content to isolate issues
- Configuration Guide - Detailed configuration options
- Basic Examples - Try AI integration in practice
- Performance Optimization - Optimize AI usage
- Troubleshooting - Solve common issues