WP Manifestindependent plugin directory
manifest / ai / snn-ai-api-system

SNN AI API System

A comprehensive WordPress plugin for AI integration supporting multiple providers with powerful data injection capabilities.

by Sinan Isler · github.com/sinanisler/snn-ai-api-system · website

0stars
0forks

Install

No release zip yet. The repository archive installs, but the folder name will carry the branch suffix and updates will not flow:

wp plugin install https://github.com/sinanisler/snn-ai-api-system/archive/refs/heads/main.zip

Readme

SNN AI API System

AI Integration for WordPress: Multi-Provider Support with Contextual Data Intelligence

The SNN AI API System is a robust WordPress plugin engineered to integrate leading Artificial Intelligence models directly into your website environment. This plugin provides a streamlined interface for connecting to providers like OpenAI, OpenRouter, and Anthropic, allowing WordPress users and developers to leverage advanced AI capabilities without extensive custom coding. A core feature is its data injection system, which dynamically pulls WordPress content and inserts it into AI prompts, enabling contextual and relevant AI interactions for various applications such as content generation, intelligent chatbots, and data analysis.

This plugin is designed for performance, security, and extensibility, offering a solid foundation for AI-powered features within any WordPress site. It serves as a practical demonstration of integrating complex AI APIs with a content management system, emphasizing efficient data handling and a modular architecture.


Features

The SNN AI API System offers key features for effective AI integration:

  • Multi-Provider Connectivity: Connects to OpenAI, OpenRouter, and Anthropic APIs, with a design that supports additional custom providers.
  • Contextual Data Injection: Dynamically feeds WordPress data (e.g., posts, users, terms, custom fields) into AI prompts, enhancing response relevance.
  • REST API Integration: Provides a complete set of REST API endpoints for AI operations, facilitating integration with custom applications, themes, and plugins.
  • Intuitive Admin Interface: Features a user-friendly backend for managing AI provider settings, data templates, and monitoring usage.
  • Integrated Security: Includes input validation, rate limiting, WordPress capability-based access control, API key encryption, and nonce verification.
  • Performance Optimization: Utilizes caching for AI responses and template data, with optimized database interactions for efficient operation.
  • Comprehensive Usage Tracking: Logs detailed AI usage data, including request counts, token consumption, estimated costs, and response times for analytical purposes.
  • Extensible Architecture: Built with a clean, object-oriented PHP design, offering numerous hooks and filters for deep customization and developer flexibility.

Installation

System Requirements

Verify your environment meets these minimum requirements:

  • WordPress: Version 5.0 or higher.
  • PHP: Version 7.4 or higher.
  • MySQL: Version 5.6 or higher.
  • Memory: Minimum 256MB PHP memory limit.
  • PHP Extensions: cURL and OpenSSL extensions must be enabled.

Download & Upload

Choose one of the following methods:

Via FTP/SFTP:

  1. Download the plugin .zip file from the GitHub Repository.
  2. Extract the snn-ai-api-system.zip file.
  3. Upload the extracted snn-ai-api-system directory to your WordPress installation's /wp-content/plugins/ folder.

Via WordPress Admin:

  1. Navigate to your WordPress Admin Dashboard.
  2. Go to Plugins > Add New.
  3. Click the Upload Plugin button.
  4. Choose the snn-ai-api-system.zip file and click Install Now.

Activation

After uploading:

  1. In your WordPress Admin, go to Plugins.
  2. Find "SNN AI API System" and click Activate.

Upon activation, the plugin automatically sets up the following database tables:

  • wp_snn_ai_providers
  • wp_snn_ai_sessions
  • wp_snn_ai_templates
  • wp_snn_ai_logs
  • wp_snn_ai_cache
  • wp_snn_ai_usage

Initial Configuration

Configure your AI provider API keys:

  1. In your WordPress admin menu, go to SNN AI > Providers.
  2. For OpenAI: Obtain your API key from https://platform.openai.com/. Enter it and optionally your Organization ID.
  3. For OpenRouter: Obtain your API key from https://openrouter.ai/. Enter it.
  4. For Anthropic: Obtain your API key from https://console.anthropic.com/. Enter it.
  5. Test Connection for each provider to ensure correct setup.

Configuration via wp-config.php

For enhanced security and environment management, define API keys and other settings in your wp-config.php file.

Example wp-config.php entries:

// --- AI Provider API Keys ---

// OpenAI Configuration
define('SNN_AI_OPENAI_API_KEY', 'sk-your-openai-api-key-here');
define('SNN_AI_OPENAI_ORGANIZATION', 'your-openai-org-id'); // Optional

// OpenRouter Configuration
define('SNN_AI_OPENROUTER_API_KEY', 'sk-or-your-openrouter-key-here');

// Anthropic Configuration
define('SNN_AI_ANTHROPIC_API_KEY', 'sk-ant-your-anthropic-key-here');

// --- Plugin Settings ---

// Enable/disable caching
define('SNN_AI_CACHE_ENABLED', true);

// Cache duration in seconds (default: 1800 = 30 minutes)
define('SNN_AI_CACHE_DURATION', 1800);

// Rate limiting settings
define('SNN_AI_RATE_LIMIT', 100); // Requests per period
define('SNN_AI_RATE_LIMIT_PERIOD', 3600); // Period in seconds (1 hour)

// Logging settings
define('SNN_AI_LOG_LEVEL', 'info'); // debug, info, warning, error
define('SNN_AI_LOG_RETENTION_DAYS', 30); // Keep logs for 30 days

// Security settings
define('SNN_AI_ENCRYPT_API_KEYS', true); // Encrypt API keys in database
define('SNN_AI_ENABLE_NONCE_VERIFICATION', true); // Enable CSRF protection

// Performance settings
define('SNN_AI_MAX_TOKENS', 4000); // Maximum tokens per request
define('SNN_AI_REQUEST_TIMEOUT', 60); // Request timeout in seconds
define('SNN_AI_MEMORY_LIMIT', '256M'); // Memory limit for AI operations

// Debug settings (only enable during development)
define('SNN_AI_DEBUG_MODE', false);
define('SNN_AI_DEBUG_LOG_REQUESTS', false);
define('SNN_AI_DEBUG_LOG_RESPONSES', false);

// --- Advanced Settings ---

// Custom endpoint URLs (optional)
define('SNN_AI_OPENAI_ENDPOINT', 'https://api.openai.com/v1');
define('SNN_AI_OPENROUTER_ENDPOINT', 'https://openrouter.ai/api/v1');
define('SNN_AI_ANTHROPIC_ENDPOINT', 'https://api.anthropic.com/v1');

// Provider-specific settings
define('SNN_AI_OPENAI_DEFAULT_MODEL', 'gpt-3.5-turbo');
define('SNN_AI_OPENROUTER_DEFAULT_MODEL', 'anthropic/claude-3-haiku');
define('SNN_AI_ANTHROPIC_DEFAULT_MODEL', 'claude-3-sonnet-20240229');

// Data injection settings
define('SNN_AI_TEMPLATE_CACHE_ENABLED', true);
define('SNN_AI_TEMPLATE_CACHE_DURATION', 900); // 15 minutes

// WordPress integration settings
define('SNN_AI_ADMIN_CAPABILITY', 'manage_options'); // Required capability for admin access
define('SNN_AI_API_CAPABILITY', 'edit_posts'); // Required capability for API access
define('SNN_AI_CHAT_CAPABILITY', 'edit_posts'); // Required capability for chat interface

You can also use environment variables for keys:

// In wp-config.php, assuming environment variables are set externally:
define('SNN_AI_OPENAI_API_KEY', getenv('SNN_AI_OPENAI_API_KEY'));
define('SNN_AI_OPENROUTER_API_KEY', getenv('SNN_AI_OPENROUTER_API_KEY'));
define('SNN_AI_ANTHROPIC_API_KEY', getenv('SNN_AI_ANTHROPIC_API_KEY'));

Quick Start

Start utilizing AI functions directly in your code or via the admin interface.

Basic PHP Usage

The plugin provides global helper functions for common AI operations:

// Example: Simple chat request
$response = snn_ai_chat([
    'provider' => 'openai',
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!']
    ]
]);

if (is_wp_error($response)) {
    error_log('AI Chat Error: ' . $response->get_error_message());
} else {
    echo 'AI says: ' . $response['content'];
}

// Example: Text completion
$response = snn_ai_complete([
    'provider' => 'anthropic',
    'model' => 'claude-3-sonnet-20240229',
    'prompt' => 'Write a short paragraph about the benefits of AI in content creation.',
    'max_tokens' => 200
]);

if (is_wp_error($response)) {
    error_log('AI Completion Error: ' . $response->get_error_message());
} else {
    echo 'AI completion: ' . $response['text'];
}

// Example: Generate embeddings
$response = snn_ai_embed('This is a sample text for embedding.', [
    'provider' => 'openai',
    'model' => 'text-embedding-3-small'
]);

if (is_wp_error($response)) {
    error_log('AI Embeddings Error: ' . $response->get_error_message());
} else {
    echo 'Embedding vector size: ' . count($response['embedding']);
}

// Example: Generate an image
$response = snn_ai_generate_image([
    'provider' => 'openai',
    'model' => 'dall-e-3',
    'prompt' => 'A serene digital painting of a Japanese garden with cherry blossoms.',
    'size' => '1024x1024'
]);

if (is_wp_error($response)) {
    error_log('AI Image Generation Error: ' . $response->get_error_message());
} else {
    echo 'Generated image URL: ' . $response['images'][0]['url'];
}

JavaScript Usage

The plugin exposes a global wp.snnAI object for front-end API interactions. This requires WordPress's wp-api-fetch and wp-nonce scripts to be enqueued.

// Example: Chat request
wp.snnAI.chat({
    provider: 'openrouter',
    model: 'anthropic/claude-3-haiku',
    messages: [
        {role: 'user', content: 'What is the capital of France?'}
    ]
}).then(response => {
    console.log('Chat Response:', response.content);
}).catch(error => {
    console.error('Chat API Error:', error.message);
});

// Example: Image generation
wp.snnAI.generateImage({
    provider: 'openai',
    model: 'dall-e-3',
    prompt: 'A minimalistic landscape with a single tree under a starry sky.',
    size: '1024x1024'
}).then(response => {
    console.log('Generated Image URLs:', response.images);
}).catch(error => {
    console.error('Image Generation API Error:', error.message);
});

Data Injection System

This system allows you to feed dynamic WordPress data into AI prompts, ensuring context-aware responses.

Creating Templates

Define data templates programmatically to specify what data to retrieve and how to format it for AI consumption.

$plugin = SNN_AI_API_System::get_instance();
$data_injector = $plugin->get_data_injector();

// Define a template to fetch recent WordPress posts
$template_id = $data_injector->create_template('Recent Blog Posts Context', [
    'description' => 'Retrieves the titles and excerpts of the 5 most recent published posts.',
    'query_config' => [
        'query_type' => 'posts', // Specifies the type of data to query (posts, terms, users, meta)
        'post_type' => 'post',
        'post_status' => 'publish',
        'posts_per_page' => 5,
        'orderby' => 'date',
        'order' => 'DESC'
    ],
    'dynamic_tags' => [ // Maps data fields to dynamic tags for use in template_content
        'post_title' => 'get_the_title',
        'post_excerpt' => 'get_the_excerpt',
        'post_date' => 'get_the_date("Y-m-d")',
        'post_author' => 'get_the_author'
    ],
    'template_content' => '
    Here are some recent blog posts from our website:
    {{#posts}}
    Title: {{post_title}}
    Author: {{post_author}}
    Date: {{post_date}}
    Excerpt: {{post_excerpt}}
    ---
    {{/posts}}
    '
]);

if ($template_id) {
    echo "Template 'Recent Blog Posts Context' created with ID: " . $template_id;
} else {
    echo "Failed to create template.";
}

Using Templates

Once a template exists, inject its content into your AI requests to provide context.

$plugin = SNN_AI_API_System::get_instance();
$data_injector = $plugin->get_data_injector();

// Assuming template ID 1 is 'Recent Blog Posts Context'
$injected_data = $data_injector->inject_data(1);

if (is_wp_error($injected_data)) {
    error_log('Data Injection Error: ' . $injected_data->get_error_message());
} else {
    // Use the generated content in a system or user message for AI
    $response = snn_ai_chat([
        'provider' => 'openai',
        'model' => 'gpt-4',
        'messages' => [
            ['role' => 'system', 'content' => $injected_data['content']],
            ['role' => 'user', 'content' => 'Summarize the provided blog posts in a concise manner, highlighting key topics.']
        ]
    ]);

    if (is_wp_error($response)) {
        error_log('AI Chat Error with context: ' . $response->get_error_message());
    } else {
        echo 'AI Summary with context: ' . $response['content'];
    }
}

API Endpoints

The SNN AI API System exposes REST API endpoints under the /wp-json/snn-ai/v1/ namespace. These endpoints are designed for integration with headless WordPress setups, custom front-ends, or other applications. All requests to these endpoints require proper WordPress authentication (e.g., nonce for logged-in users).

Chat Completion

Method: POST Path: /wp-json/snn-ai/v1/chat

Request Body Example:

{
    "provider": "openai",
    "model": "gpt-3.5-turbo",
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Tell me a joke."}
    ],
    "max_tokens": 150,
    "temperature": 0.7
}

Text Completion

Method: POST Path: /wp-json/snn-ai/v1/complete

Request Body Example:

{
    "provider": "anthropic",
    "model": "claude-3-sonnet-20240229",
    "prompt": "Once upon a time in a land far away, there was a young wizard who",
    "max_tokens": 100,
    "temperature": 0.9
}

Embeddings

Method: POST Path: /wp-json/snn-ai/v1/embed

Request Body Example:

{
    "provider": "openai",
    "model": "text-embedding-3-small",
    "text": "The quick brown fox jumps over the lazy dog."
}

Read the full README on GitHub →