bluefly/llm

Core LLM functionality and integration for the platform

Installs: 105

Dependents: 5

Suggesters: 1

Security: 0

Type:drupal-module

0.1.0 2025-07-27 17:46 UTC

This package is auto-updated.

Last update: 2025-08-04 12:28:40 UTC


README

This Drupal module provides core AI/LLM integration functionality for the LLM Platform ecosystem. It offers enterprise-grade security auditing, government compliance features, multi-provider AI support, and comprehensive usage tracking while maintaining Drupal best practices and extensibility.

Architecture

graph TB
    subgraph "Drupal Core"
        ROUTING[Routing System]
        ENTITY[Entity API]
        SERVICES[Service Container]
        EVENTS[Event System]
    end
    
    subgraph "LLM Module Core"
        MANAGER[LLM Platform Manager]
        CHAT[AI Chat Service]
        TRACKER[Usage Tracker]
        AUDITOR[Security Auditor]
    end
    
    subgraph "Plugin Systems"
        WORKFLOW[Workflow Plugins]
        SECURITY[Security Plugins]
        CALC[Cost Calculator Plugins]
    end
    
    subgraph "External Integration"
        AI[Drupal AI Module]
        GROUP[Group Module]
        DOMAIN[Domain Module]
        ECA[ECA Module]
    end
    
    ROUTING --> MANAGER
    ENTITY --> TRACKER
    SERVICES --> CHAT
    EVENTS --> AUDITOR
    
    MANAGER --> WORKFLOW
    AUDITOR --> SECURITY
    TRACKER --> CALC
    
    CHAT --> AI
    MANAGER --> GROUP
    MANAGER --> DOMAIN
    WORKFLOW --> ECA

Installation

Prerequisites

  • Drupal 10.2+ or Drupal 11.x
  • PHP 8.3+
  • Composer
  • Drupal AI module (drupal/ai)

Setup

# Install via Composer
composer require drupal/llm

# Enable the module
drush en llm -y

# Run database updates
drush updatedb

# Clear caches
drush cr

Configuration

Initial Configuration

  1. Configure AI Providers:

    • Navigate to /admin/config/ai/llm/providers
    • Add API keys for your providers
    • Test connectivity
  2. Security Settings:

    • Visit /admin/llm/security
    • Configure security policies
    • Run initial security audit
  3. Usage Tracking:

    • Configure at /admin/config/ai/llm/usage
    • Set cost limits
    • Enable analytics

Environment Configuration

// settings.php
$config['llm.settings']['providers'] = [
  'openai' => [
    'api_key' => getenv('OPENAI_API_KEY'),
    'default_model' => 'gpt-4',
  ],
  'ollama' => [
    'base_url' => 'http://localhost:11434',
    'default_model' => 'llama3.2',
  ],
];

$config['llm.settings']['security'] = [
  'audit_frequency' => 'daily',
  'compliance_standards' => ['owasp', 'fedramp'],
];

$config['llm.settings']['debug'] = FALSE;

Usage

Basic AI Operations

// Get AI chat service
$chatService = \Drupal::service('llm.ai_chat');

// Send a message
$response = $chatService->sendMessage('Explain quantum computing', [
  'provider' => 'openai',
  'model' => 'gpt-4',
  'temperature' => 0.7,
  'max_tokens' => 500,
]);

// Process response
$content = $response['content'];
$usage = $response['usage'];

Security Auditing

// Get security auditor
$auditor = \Drupal::service('llm.security.owasp_auditor');

// Run comprehensive audit
$results = $auditor->performSecurityAudit(['all']);

// Run specific checks
$results = $auditor->performSecurityAudit([
  'broken_access_control',
  'cryptographic_failures',
  'injection',
]);

// Get critical findings
$critical = array_filter($results['findings'], function($finding) {
  return $finding['severity'] === 'critical';
});

Usage Tracking

// Track AI usage
$tracker = \Drupal::service('llm.usage_tracker');

$tracker->trackUsage([
  'provider' => 'openai',
  'model' => 'gpt-4',
  'tokens_input' => 150,
  'tokens_output' => 200,
  'operation' => 'chat',
  'cost' => 0.015,
]);

// Get usage statistics
$stats = $tracker->getUsageStatistics($account->id());

Features

AI Provider Integration

  • Multi-Provider Support: OpenAI, Anthropic, Ollama, and more
  • Provider Failover: Automatic fallback on errors
  • Model Management: Configure and switch models
  • Streaming Support: Real-time response streaming
  • Cost Optimization: Smart provider selection

Security & Compliance

  • OWASP Auditing: Full OWASP Top 10 security checks
  • Government Standards: FedRAMP, FISMA, HIPAA compliance
  • Audit Logging: Comprehensive security audit trails
  • Access Control: Fine-grained permissions
  • Data Encryption: At-rest and in-transit encryption

Usage Analytics

  • Token Tracking: Input/output token monitoring
  • Cost Calculation: Real-time cost tracking
  • Usage Limits: Per-user and per-organization limits
  • Billing Integration: Export for billing systems
  • Analytics Dashboard: Visual usage insights

Multi-Tenancy

  • Organization Support: Via Group module integration
  • Domain Isolation: Via Domain module integration
  • Tenant Configuration: Per-tenant AI settings
  • Usage Segregation: Separate usage tracking
  • Security Isolation: Tenant-specific security policies

Workflow Automation

  • ECA Integration: Event-driven AI workflows
  • Custom Workflows: Plugin-based workflow system
  • Batch Processing: Async job processing
  • Queue Management: Reliable task execution
  • Error Handling: Automatic retry logic

API Reference

REST Endpoints

# Get OpenAPI specification
GET /api/llm/v1/openapi.json

# Chat completion
POST /api/llm/v1/chat
Content-Type: application/json
X-CSRF-Token: {token}

{
  "message": "Hello",
  "provider": "openai",
  "model": "gpt-4"
}

# List providers
GET /api/llm/v1/providers

# Get usage statistics
GET /api/llm/v1/usage/{user_id}

Drush Commands

# Platform management
drush llm:status                    # Platform status
drush llm:providers                 # List providers
drush llm:test-provider {provider}  # Test connectivity

# Security
drush llm:security:audit           # Run audit
drush llm:security:last-audit      # Last results
drush llm:security:audit-history   # Audit history

# Usage
drush llm:usage:stats              # Statistics
drush llm:usage:export             # Export data
drush llm:usage:reset {user}       # Reset usage

Services

// Core services
llm.platform_manager      # Central coordinator
llm.ai_chat              # Chat operations
llm.usage_tracker        # Usage tracking
llm.cost_calculator      # Cost calculation
llm.security.owasp_auditor # Security auditing

Integration

With Drupal AI Module

// The module automatically integrates with Drupal AI
$provider = \Drupal::service('ai.provider')->getProvider('openai');
$chatService->setProvider($provider);

With Group Module

// Multi-tenant support
$group = Group::load($group_id);
$chatService->setContext(['group' => $group]);

With ECA Module

# ECA model for AI workflow
events:
  - plugin: content_entity:insert
    entity_type: node
actions:
  - plugin: llm:generate_summary
    configuration:
      field: field_summary

Security

Security Auditing

  • Automated Scans: Scheduled security audits
  • OWASP Compliance: Full OWASP Top 10 coverage
  • Vulnerability Detection: SQL injection, XSS, CSRF
  • Access Control: Permission-based security
  • Audit Logging: All security events logged

Data Protection

  • Encryption: Field-level encryption support
  • PII Detection: Automatic PII filtering
  • Data Retention: Configurable retention policies
  • GDPR Compliance: Right to erasure support
  • Audit Trail: Complete data access logging

API Security

  • Authentication: Drupal session + CSRF tokens
  • Rate Limiting: Configurable rate limits
  • Input Validation: Strict input sanitization
  • Output Filtering: XSS protection
  • SSL/TLS: HTTPS enforcement

API-First TDD Development Workflow

This module follows the LLM Platform's API-first, test-driven development approach using TDDAI.

Development Commands

# Comprehensive Drupal module analysis (includes UI/UX assessment)
cd web/modules/custom/llm
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js drupal audit . --comprehensive \
  --analyze-ui-components \
  --check-entity-definitions \
  --review-views-displays \
  --assess-admin-interfaces \
  --identify-missing-frontend \
  --create-ux-improvement-plan

# Alternative: Use analyze command with Drupal-specific prompts
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js analyze . --context drupal-contrib \
  --prompts "ui-components,entity-configs,views-displays,admin-forms,frontend-gaps,ux-plan"

# Start TDD cycle for this module
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js tdd cycle --context drupal-module

# Write failing tests first (RED)
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js test-gen --module llm
../../../vendor/bin/phpunit tests/src/Unit/

# Implement minimal code (GREEN)
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js generate service <ServiceName> --module llm --tdd

# Refactor and optimize (REFACTOR)
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js improve fix --all --module llm

# Full contrib-ready assessment (all quality gates)
node /Users/flux423/Sites/LLM/common_npm/tddai/dist/cli.js drupal ultra-strict . \
  --contrib-ready \
  --ui-analysis \
  --performance-check \
  --accessibility-audit

# Standards and quality checks
../../../vendor/bin/phpcs --standard=Drupal,DrupalPractice src/
../../../vendor/bin/phpstan analyse src/

API Standards

  • ✅ REST API endpoints with OpenAPI 3.1 specification
  • ✅ GraphQL schema extensions where applicable
  • ✅ 95% test coverage requirement
  • ✅ Drupal 10/11 best practices compliance
  • ✅ Service-based architecture with dependency injection

See main project README for complete workflow documentation.

Contributing

Development Setup

# Clone the module
git clone https://gitlab.bluefly.io/llm/drupal-modules/llm.git
cd llm

# Install dependencies
composer install

# Run tests
./vendor/bin/phpunit

Coding Standards

# Check standards
phpcs --standard=Drupal,DrupalPractice .

# Fix violations
phpcbf --standard=Drupal,DrupalPractice .

# Use TDDAI for analysis
tddai drupal:check module ./llm

Testing

# Run all tests
phpunit

# Run specific test groups
phpunit --group llm
phpunit --group llm_security

# Run with coverage
phpunit --coverage-html coverage

Plugin Development

Create custom plugins in src/Plugin/:

  • Workflow plugins in Workflow/
  • Security plugins in SecurityAuditor/
  • Cost calculator plugins in CostCalculator/

License

This module is part of the LLM Platform ecosystem and is licensed under GPL-2.0+.

For more information about the LLM Platform, visit the main documentation.