Drupal AI Module: KI-Integration in Drupal 11 und Drupal 10
Drupal AI Module: KI-Integration in Drupal 11 und Drupal 10
Das Drupal AI Module (drupal.org/project/ai) revolutioniert die Content-Verwaltung durch nahtlose Integration von künstlicher Intelligenz. Dieser Guide zeigt Ihnen, wie Sie AI-Funktionen in Ihre Drupal-Website einbinden.
Was ist das Drupal AI Module?
Das AI Module ist ein Framework, das verschiedene AI-Provider (OpenAI, Anthropic Claude, Google PaLM, Azure OpenAI) in Drupal integriert und standardisierte APIs für AI-Funktionen bereitstellt.
Hauptfunktionen
- Content Generation: Automatische Texterstellung
- Text Transformation: Zusammenfassungen, Übersetzungen, Umschreibungen
- Image Generation: DALL-E, Stable Diffusion Integration
- Embeddings: Vektorisierung für semantische Suche
- Chatbots: Conversational AI für Benutzerinteraktion
- Moderation: Automatische Content-Prüfung
- SEO Optimization: AI-generierte Meta-Descriptions
Installation & Setup
Systemanforderungen
Drupal: 10.2+ oder 11.x
PHP: 8.1+
Composer: 2.x
Extensions: php-curl, php-json
Installation via Composer
# AI Module installieren
composer require drupal/ai
# Abhängige Module
composer require drupal/key
composer require drupal/encrypt
# AI Module aktivieren
drush en ai -y
drush en ai_content -y
drush en ai_automator -y
Provider-Module installieren
# OpenAI Provider
composer require drupal/ai_openai
drush en ai_openai -y
# Anthropic Claude Provider
composer require drupal/ai_anthropic
drush en ai_anthropic -y
# Ollama (Self-hosted)
composer require drupal/ai_ollama
drush en ai_ollama -y
OpenAI Configuration
1. API Key Setup
Über Key Module (empfohlen):
# Key Module konfigurieren
drush en key -y
# Navigate to: /admin/config/system/keys/add
Key erstellen:
Key name: openai_api_key
Key type: Authentication
Key provider: Configuration
Key value: sk-proj-xxxxxxxxxxxxx
2. AI Provider konfigurieren
Navigation: /admin/config/ai/providers
OpenAI Provider Setup:
Provider: OpenAI
API Key: [Key: openai_api_key]
Model: gpt-4o-mini
Temperature: 0.7
Max Tokens: 2000
Organization: [optional]
3. Modelle konfigurieren
Verfügbare OpenAI Modelle:
| Modell | Verwendung | Kosten/1M Tokens |
|---|---|---|
| gpt-4o | Komplexe Aufgaben | $5.00 input |
| gpt-4o-mini | Standard Tasks | $0.15 input |
| gpt-3.5-turbo | Einfache Tasks | $0.50 input |
| text-embedding-3-small | Embeddings | $0.02 |
| dall-e-3 | Bildgenerierung | $0.040/image |
Praktische Anwendungsfälle
1. Automatische Content-Zusammenfassungen
Configuration: /admin/config/ai/automator
Trigger: Node save
Content Type: Article
Field: body
Action: Generate summary
Target Field: field_summary
Prompt: "Erstelle eine prägnante Zusammenfassung in 2-3 Sätzen"
Custom Code Beispiel:
<?php
use Drupal\ai\AiProviderPluginManager;
function mymodule_node_presave($node) {
if ($node->bundle() == 'article' && $node->get('field_summary')->isEmpty()) {
$ai_provider = \Drupal::service('ai.provider');
$body = $node->get('body')->value;
$prompt = "Erstelle eine SEO-optimierte Zusammenfassung des folgenden Texts:\n\n" . $body;
$response = $ai_provider->chat([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'max_tokens' => 150,
]);
$summary = $response->getNormalized();
$node->set('field_summary', $summary);
}
}
2. AI-gestützte Meta-Description Generierung
<?php
/**
* Implements hook_entity_presave().
*/
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() === 'node') {
$ai_service = \Drupal::service('ai.provider');
// Meta Description generieren
if ($entity->hasField('field_meta_description') &&
$entity->get('field_meta_description')->isEmpty()) {
$title = $entity->getTitle();
$body = strip_tags($entity->get('body')->value);
$prompt = <<<PROMPT
Erstelle eine SEO-optimierte Meta-Description für folgende Webseite:
Titel: {$title}
Inhalt: {$body}
Anforderungen:
- Maximal 155 Zeichen
- Enthält relevante Keywords
- Call-to-Action
- Deutsch
PROMPT;
$response = $ai_service->chat([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'system', 'content' => 'Du bist ein SEO-Experte.'],
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.7,
]);
$meta_desc = $response->getNormalized();
$entity->set('field_meta_description', $meta_desc);
}
}
}
3. Content Translation mit AI
<?php
/**
* AI-gestützte Übersetzung.
*/
function translate_content_with_ai($text, $target_language) {
$ai_provider = \Drupal::service('ai.provider');
$prompt = "Übersetze den folgenden Text nach {$target_language}. " .
"Behalte den Ton und die Formatierung bei:\n\n{$text}";
$response = $ai_provider->chat([
'model' => 'gpt-4o',
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.3, // Niedriger für konsistente Übersetzungen
]);
return $response->getNormalized();
}
4. Chatbot Integration
Views Integration:
# views.view.ai_chatbot.yml
id: ai_chatbot
label: 'AI Chatbot'
module: views
display:
default:
display_plugin: block
display_title: 'AI Chat Widget'
id: default
Custom Chatbot Service:
<?php
namespace Drupal\mymodule\Service;
use Drupal\ai\AiProviderPluginManager;
class ChatbotService {
protected $aiProvider;
protected $conversationHistory = [];
public function __construct(AiProviderPluginManager $ai_provider) {
$this->aiProvider = $ai_provider;
}
public function chat($user_message, $session_id) {
// Conversation History laden
$this->loadConversation($session_id);
// User Message hinzufügen
$this->conversationHistory[] = [
'role' => 'user',
'content' => $user_message
];
// AI Response
$response = $this->aiProvider->chat([
'model' => 'gpt-4o-mini',
'messages' => array_merge(
[['role' => 'system', 'content' => $this->getSystemPrompt()]],
$this->conversationHistory
),
'temperature' => 0.8,
]);
$ai_message = $response->getNormalized();
// Response zur History hinzufügen
$this->conversationHistory[] = [
'role' => 'assistant',
'content' => $ai_message
];
// History speichern
$this->saveConversation($session_id);
return $ai_message;
}
protected function getSystemPrompt() {
return <<<PROMPT
Du bist ein hilfreicher Assistent für unsere Drupal-Website.
Du beantwortest Fragen zu unseren Produkten und Services.
Antworte freundlich, präzise und professionell auf Deutsch.
PROMPT;
}
}
Image Generation mit DALL-E
<?php
/**
* Bildgenerierung mit DALL-E.
*/
function generate_article_image($node) {
$ai_provider = \Drupal::service('ai.provider');
$title = $node->getTitle();
$summary = $node->get('field_summary')->value;
$prompt = "Professional photograph for article titled '{$title}'. " .
"Context: {$summary}. " .
"Style: Modern, clean, high-quality stock photo.";
$response = $ai_provider->generateImage([
'model' => 'dall-e-3',
'prompt' => $prompt,
'size' => '1792x1024',
'quality' => 'hd',
'n' => 1,
]);
// Image speichern
$image_url = $response->getImageUrl();
$file = system_retrieve_file($image_url, 'public://ai-images/', TRUE);
if ($file) {
$node->set('field_image', [
'target_id' => $file->id(),
'alt' => $title,
]);
$node->save();
}
}
Embeddings & Semantische Suche
<?php
/**
* Vektorisierung für semantische Suche.
*/
function create_content_embeddings($node) {
$ai_provider = \Drupal::service('ai.provider');
// Text für Embedding vorbereiten
$text = $node->getTitle() . ' ' .
strip_tags($node->get('body')->value);
// Embedding erstellen
$response = $ai_provider->embeddings([
'model' => 'text-embedding-3-small',
'input' => $text,
]);
$embedding = $response->getEmbedding();
// In custom table speichern
\Drupal::database()->merge('node_embeddings')
->key(['nid' => $node->id()])
->fields([
'embedding' => json_encode($embedding),
'updated' => time(),
])
->execute();
}
/**
* Semantische Suche durchführen.
*/
function semantic_search($query) {
$ai_provider = \Drupal::service('ai.provider');
// Query Embedding erstellen
$response = $ai_provider->embeddings([
'model' => 'text-embedding-3-small',
'input' => $query,
]);
$query_embedding = $response->getEmbedding();
// Cosine Similarity mit gespeicherten Embeddings
$results = \Drupal::database()->query("
SELECT nid, (embedding <=> :query_vector) as similarity
FROM node_embeddings
ORDER BY similarity
LIMIT 10
", [':query_vector' => json_encode($query_embedding)]);
return $results->fetchAll();
}
Content Moderation
<?php
/**
* AI-gestützte Content-Moderation.
*/
function moderate_comment($comment) {
$ai_provider = \Drupal::service('ai.provider');
$text = $comment->get('comment_body')->value;
$prompt = <<<PROMPT
Analysiere den folgenden Kommentar auf:
1. Spam
2. Beleidigungen
3. Unangemessenen Inhalt
4. Off-Topic
Kommentar: {$text}
Antworte im JSON-Format:
{
"is_appropriate": boolean,
"confidence": 0.0-1.0,
"reason": "string"
}
PROMPT;
$response = $ai_provider->chat([
'model' => 'gpt-4o-mini',
'messages' => [
['role' => 'user', 'content' => $prompt]
],
'temperature' => 0.2,
]);
$result = json_decode($response->getNormalized(), TRUE);
if (!$result['is_appropriate'] && $result['confidence'] > 0.8) {
$comment->setUnpublished();
$comment->save();
// Admin benachrichtigen
\Drupal::messenger()->addWarning(
t('Comment flagged by AI: @reason', ['@reason' => $result['reason']])
);
}
}
Performance & Caching
Response Caching
<?php
/**
* AI Responses cachen.
*/
function get_cached_ai_response($prompt, $cache_ttl = 86400) {
$cache_key = 'ai_response:' . md5($prompt);
// Cache prüfen
if ($cache = \Drupal::cache()->get($cache_key)) {
return $cache->data;
}
// AI Request
$ai_provider = \Drupal::service('ai.provider');
$response = $ai_provider->chat([
'model' => 'gpt-4o-mini',
'messages' => [['role' => 'user', 'content' => $prompt]],
]);
$result = $response->getNormalized();
// Cache speichern
\Drupal::cache()->set($cache_key, $result, time() + $cache_ttl);
return $result;
}
Rate Limiting
<?php
/**
* Rate Limiting für API Calls.
*/
function check_ai_rate_limit($user_id) {
$rate_limit_key = "ai_calls:{$user_id}:" . date('YmdH');
$current_count = \Drupal::state()->get($rate_limit_key, 0);
$max_calls_per_hour = 100;
if ($current_count >= $max_calls_per_hour) {
throw new \Exception('AI API rate limit exceeded');
}
\Drupal::state()->set($rate_limit_key, $current_count + 1);
}
Kosten-Optimierung
Best Practices für Cost Management
<?php
/**
* Token-Zählung vor Request.
*/
function estimate_tokens($text) {
// Grobe Schätzung: 1 Token ≈ 4 Zeichen
return ceil(strlen($text) / 4);
}
/**
* Smart Model Selection.
*/
function select_optimal_model($task_complexity, $text_length) {
$estimated_tokens = estimate_tokens($text_length);
if ($task_complexity === 'simple' && $estimated_tokens < 1000) {
return 'gpt-3.5-turbo'; // $0.50/1M tokens
}
if ($task_complexity === 'medium' && $estimated_tokens < 5000) {
return 'gpt-4o-mini'; // $0.15/1M tokens
}
return 'gpt-4o'; // $5.00/1M tokens
}
Monitoring & Logging
<?php
/**
* AI Usage Tracking.
*/
function log_ai_usage($model, $tokens_used, $cost) {
\Drupal::database()->insert('ai_usage_log')
->fields([
'timestamp' => time(),
'model' => $model,
'tokens_used' => $tokens_used,
'estimated_cost' => $cost,
'user_id' => \Drupal::currentUser()->id(),
])
->execute();
}
Häufige Probleme & Lösungen
Problem 1: “API Key nicht gefunden”
# Lösung: Key Module prüfen
drush config:get key.key.openai_api_key
# Oder manuell in settings.php:
$config['ai_openai.settings']['api_key'] = 'sk-proj-xxxxx';
Problem 2: “Rate Limit Exceeded”
<?php
// Exponential Backoff implementieren
function ai_request_with_retry($callable, $max_retries = 3) {
$attempt = 0;
while ($attempt < $max_retries) {
try {
return $callable();
}
catch (\Exception $e) {
if (strpos($e->getMessage(), 'rate limit') !== FALSE) {
$wait_time = pow(2, $attempt) * 1000000; // Microseconds
usleep($wait_time);
$attempt++;
}
else {
throw $e;
}
}
}
throw new \Exception('Max retries exceeded');
}
Sicherheit & Datenschutz
DSGVO-konforme AI-Nutzung
# Wichtige Überlegungen:
- Keine personenbezogenen Daten an externe AI-APIs senden
- Nutzer über AI-Nutzung informieren (Privacy Policy)
- Opt-out Möglichkeit anbieten
- Self-hosted AI (Ollama) für sensible Daten erwägen
Anonymisierung vor AI-Request:
<?php
function anonymize_before_ai($text) {
// E-Mails entfernen
$text = preg_replace('/[\w\.-]+@[\w\.-]+\.\w+/', '[EMAIL]', $text);
// Telefonnummern entfernen
$text = preg_replace('/\+?\d{10,}/', '[PHONE]', $text);
// Namen ersetzen (beispielhaft)
$text = preg_replace('/\b[A-Z][a-z]+ [A-Z][a-z]+\b/', '[NAME]', $text);
return $text;
}
Fazit
Das Drupal AI Module öffnet eine neue Dimension der Content-Automatisierung und Personalisierung. Von automatischer Content-Generierung über intelligente Chatbots bis hin zur semantischen Suche – die Möglichkeiten sind vielfältig.
Wichtig ist eine durchdachte Implementation mit Fokus auf Kosten-Optimierung, Datenschutz und Performance.
Weiterführende Ressourcen
Benötigen Sie Unterstützung bei der AI-Integration in Ihre Drupal-Website? Mit 20+ Jahren Drupal-Erfahrung helfe ich Ihnen gerne. Kontakt: mail@stevenschulz.net oder 04037420859
Häufig gestellte Fragen (FAQ)
Welche AI-Provider werden vom Drupal AI Module unterstützt?
Wie sichere ich meinen OpenAI API Key in Drupal?
Was sind Embeddings und wofür brauche ich sie?
Wie kann ich AI-Kosten in Drupal optimieren?
Ist das Drupal AI Module DSGVO-konform?
Das könnte Sie auch interessieren
AI Content-Generierung in Drupal: Automatische Texterstellung mit ChatGPT
Praktischer Guide zur automatischen Content-Generierung in Drupal mit dem AI Module und OpenAI: Blog-Posts, Produktbesch...
AI Chatbot in Drupal: ChatGPT Integration für Customer Support
Kompletter Guide zur Chatbot-Integration in Drupal mit dem AI Module: OpenAI ChatGPT, Claude, Conversational AI, RAG-Sys...
Drupal 11 Migration: Step-by-Step Guide für den Upgrade von Drupal 10
Kompletter Drupal 11 Migration Guide: PHP 8.3 Requirements, CKEditor 5 Updates, Deprecated Module ersetzen, Performance-...