The long-form content is easy to control in Drupal, which includes articles, documentation pages, blog posts, and so on. Writing summaries on each work may be time consuming.
Here we are going to use the API of OpenAI to automatically create short summaries whenever a node (content item) is saved in Drupal 11.
- Create a custom Drupal module
- Hook into the node save process
- Generate summaries with AI using PHP
- Save the results back to the node
This fits perfectly into our AI + PHP CMS Framework series, where we bring practical AI tools into real CMS frameworks like WordPress, Joomla, and Drupal etc.
Prerequisites
- Drupal 11
- PHP 8.1 or higher
- Composer
- cURL enabled
- An OpenAI API key
Step 1: Create a Custom Module
Create a new module called ai_summary.
/modules/custom/ai_summary/Inside that folder, create two files:
- ai_summary.info.yml
- ai_summary.module
ai_summary.info.yml
Add the below code in the info.yml file.
name: AI Summary type: module description: Automatically generate summaries for Drupal nodes using OpenAI API. core_version_requirement: ^11 package: Custom version: 1.0.0
ai_summary.module
This is where the logic lives.
To run our code just before a node is saved we will use hook_entity_presave of Drupal.
use Drupal\node\Entity\Node;
use Drupal\Core\Entity\EntityInterface;
/**
* Implements hook_entity_presave().
*/
function ai_summary_entity_presave(EntityInterface $entity) {
if ($entity->getEntityTypeId() !== 'node') {
return;
}
// Only summarize articles (you can change this as needed)
if ($entity->bundle() !== 'article') {
return;
}
$body = $entity->get('body')->value ?? '';
if (empty($body)) {
return;
}
// Generate AI summary
$summary = ai_summary_generate_summary($body);
if ($summary) {
// Save it in the summary field
$entity->get('body')->summary = $summary;
}
}
/**
* Generate summary using OpenAI API.
*/
function ai_summary_generate_summary($text) {
$api_key = 'YOUR_OPENAI_API_KEY';
$endpoint = 'https://api.openai.com/v1/chat/completions';
$payload = [
"model" => "gpt-4o-mini",
"messages" => [
["role" => "system", "content" => "Summarize the following text in 2-3 sentences. Keep it concise and human-readable."],
["role" => "user", "content" => $text]
],
"temperature" => 0.7
];
$ch = curl_init($endpoint);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer {$api_key}"
],
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 15
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
return trim($data['choices'][0]['message']['content'] ?? '');
}
This functionality performs three primary functions:
- Identifies article saving in Drupal.
- Sends the content to OpenAI to be summarized.
- The summary is stored in the body summary field of the article.
Step 2: Enable the Module
- Place the new module folder directly in /modules/custom/.
- In Drupal Admin panel, go to: Extend → Install new module (or Enable module).
- Check AI Summary and turn it on.
Step 3: Test the AI Summary
- Select Content -> Add content -> Article.
- Enter the long paragraph in the body field.
- Save the article.
- On reloading the page, open it one more time — the summary field will be already filled automatically.
Example:
Input Body:
Artificial Intelligence has been changing how developers build and deploy applications...
Generated Summary:
AI is reshaping software development by automating repetitive tasks and improving decision-making through data-driven insights.
Step 4: Extend It Further
The following are some of the ideas that can be used to improve the module:
- Add settings: Add a form to enable the user to add the API key and the select the type of model.
- Queue processing: Queue processing Use the drugndrup queue API to process the existing content in batches.
- Custom field storage: Store summaries in object now: field_ai_summary.
- Views integration: Show or hide articles in terms of length of summary or its presence.
Security & Performance Tips
- Never hardcode your API key but keep it in the configuration or in the.env file of Drupal.
- Shorten long text in order to send (OpenAI token limit = cost).
- Gracefully manage API timeouts.
- Watchdoging errors to log API.
Next, we will dive into the Symfony, and we will create an AI-Powered Semantic Search System that uses text embeddings to discover the content in a smarter way.
0 comments:
Post a Comment