Skip to content

AI Integration

Rumen Damyanov edited this page Sep 22, 2025 · 1 revision

AI Integration Guide

This guide covers everything you need to know about integrating AI providers with the PHP-SEO package for automated SEO content generation.

Overview

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

Quick Start

Basic AI Setup

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]);

Environment Variables Setup

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

OpenAI Integration

Setup

  1. Get API Key: Sign up at OpenAI Platform
  2. 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,
        ],
    ],
]);

Available Models

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

Example Usage

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',
]);

Anthropic (Claude) Integration

Setup

  1. Get API Key: Sign up at Anthropic Console
  2. 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,
        ],
    ],
]);

Available Models

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

Example Usage

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',
]);

Google AI (Gemini) Integration

Setup

  1. Get API Key: Create project at Google AI Studio
  2. 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,
        ],
    ],
]);

Available Models

Model Use Case Features
gemini-pro Text generation Fast, cost-effective
gemini-pro-vision Text + Image analysis Multimodal capabilities

Example Usage

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',
]);

Ollama (Local Models) Integration

Setup

  1. Install Ollama: Download from Ollama website
  2. 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
  1. Configure: Set up local integration
$config = new SeoConfig([
    'providers' => [
        'ollama' => [
            'model' => 'llama2',
            'base_url' => 'http://localhost:11434',
            'timeout' => 60,  // Local models may be slower
        ],
    ],
]);

Available Models

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

Example Usage

use Rumenx\PhpSeo\Providers\OllamaProvider;

$provider = new OllamaProvider($config);

// Local generation, no API costs
$title = $provider->generateTitle($analysis, [
    'max_length' => 60,
    'temperature' => 0.7,
]);

Multi-Provider Strategy

Fallback Chain

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',
        ],
    ],
]);

Provider Selection Logic

// 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,
]);

AI Prompts Customization

Custom Prompts

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.',
        ],
    ],
]);

Prompt Variables

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

Performance Optimization

Caching AI Responses

$config = new SeoConfig([
    'cache' => [
        'enabled' => true,
        'ttl' => 86400,  // Cache for 24 hours
        'driver' => 'redis',
    ],
    'ai' => [
        'cache_responses' => true,
        'cache_key_strategy' => 'content_hash',
    ],
]);

Rate Limiting

$config = new SeoConfig([
    'ai' => [
        'rate_limiting' => [
            'enabled' => true,
            'requests_per_minute' => 10,
            'burst_limit' => 5,
        ],
    ],
]);

Batch Processing

// 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
}

Cost Management

Monitoring API Usage

$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,
    ],
]);

Cost-Effective Strategies

  1. Use Caching: Cache AI responses to avoid duplicate requests
  2. Choose Right Models: Use cheaper models for simple tasks
  3. Batch Requests: Combine multiple requests when possible
  4. Set Limits: Configure budget limits and rate limiting
  5. Monitor Usage: Track API costs and usage patterns

Model Cost Comparison

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
Google gemini-pro $0.0005
Ollama Any model Free (local)

Error Handling

Common Issues and Solutions

API Key Issues

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]);
}

Rate Limiting

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);
}

Network Issues

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]);
    }
}

Best Practices

Security

  1. Secure API Keys: Never commit API keys to version control
  2. Environment Variables: Use environment variables for sensitive data
  3. Access Control: Limit AI access to authorized users only
  4. Audit Logs: Keep logs of AI usage for security monitoring

Quality Control

  1. Review Generated Content: Always review AI-generated content
  2. A/B Testing: Test AI vs manual content performance
  3. Feedback Loop: Use performance data to improve prompts
  4. Human Oversight: Maintain human oversight for critical content

Performance

  1. Monitor Response Times: Track AI provider response times
  2. Set Appropriate Timeouts: Configure timeouts based on use case
  3. Use Caching: Cache responses to reduce API calls
  4. Optimize Prompts: Shorter, clearer prompts = better performance

Troubleshooting

Debug Mode

Enable debug mode to see detailed AI interactions:

$config = new SeoConfig([
    'logging' => [
        'enabled' => true,
        'level' => 'debug',
        'log_ai_requests' => true,
    ],
]);

Testing AI Integration

// 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";
}

Common Debugging Steps

  1. Check API Keys: Verify API keys are correct and have sufficient credits
  2. Test Connectivity: Ensure network connectivity to AI providers
  3. Review Logs: Check application logs for error messages
  4. Validate Configuration: Ensure configuration is properly formatted
  5. Test with Simple Content: Start with basic content to isolate issues

Next Steps

Clone this wiki locally