Tutorial: Getting Started with AI (Artificial Intelligence) in Drupal CMS
Prerequisites
- Basic understanding of Artificial Intelligence (AI)
- Drupal CMS site (preferably running locally using DDEV for this tutorial)
- AI Assistant recipe installed in Drupal CMS (or basic knowledge of installing Drupal modules)
What You'll Learn
- Understanding the core functionalities and ecosystem of Drupal AI modules.
- Ability to install and configure AI assistant and related modules securely.
- Proficiency in leveraging AI for basic Drupal site building tasks (content types, fields, taxonomies).
- Skill in integrating AI capabilities into CKEditor for content generation, modification, and translation.
- Knowledge of using AI Automators for automated field-level content generation.
- Capacity to design and implement complex, event-driven AI workflows using the ECA module.
- Debugging skills for AI interactions using the logging module and understanding potential issues like rate limiting and hallucination.
In this tutorial, you will explore the exciting world of integrating Artificial Intelligence (AI) with the Drupal Content Management System (CMS). This article provides a comprehensive guide to understanding, installing, and leveraging Drupal's AI modules to enhance your site-building and content creation workflows. We will cover core AI functionalities, secure setup practices, and practical applications for generating content and automating tasks. This tutorial assumes a basic understanding of AI, a working Drupal CMS site (preferably local with DDEV), and familiarity with installing Drupal modules.
Table of Contents
- Introduction to Drupal AI Suite and Module Overview
- Module Installation and Initial Setup
- Site Building with AI Assistant: Content Types and Fields
- Advanced AI Features: API Explorer and CKEditor Integration
- AI Automator: Automating Content Generation
- Event-Condition-Action (ECA) Module Integration
Step 1: Introduction to Drupal AI Suite and Module Overview
This tutorial focuses on using the Drupal AI suite of modules within Drupal CMS.
To begin, you will install the AI assistant recipe. This offers many features right away, including a chatbot and an AI agent. The installation process is straightforward:
- Navigate to the 'Extend' section in your Drupal CMS.
- Click on 'Recommend'.
- Select 'AI Assistant' from the list of recommended modules.
Before diving deeper, it's beneficial to understand a bit about the Drupal AI module. You can find comprehensive information on the module's dedicated page: drupal.org/project/ai. When reviewing modules, it's always a good practice to check their statistics, as they can indicate usability and adoption. For example, a consistent upward trend in usage stats often signifies a healthy and actively maintained module.
The Drupal AI module has a core component and several submodules. These submodules provide specific integrations and functionalities:
- Search: For integrating AI capabilities into search functions.
- Chatbot: Powers the conversational AI features.
- CKEditor: Integrates AI directly into the CKEditor WYSIWYG.
- Logging: Helps track and debug AI interactions.
- Translation: Facilitates AI-powered content translation.
- Validation: Aids in validating AI outputs.
- Automators: Enables automated AI tasks.
In addition to these submodules, there are separate provider modules that allow Drupal AI to connect with various external AI services. These include:
- OpenAI
- Anthropic
- Grock
- Google Gemini
- Eleven Labs (for audio-related tasks)
- Azure
- AWS Bedrock
- Hugging Face
While there are also vector database providers for advanced search functionalities, these will not be covered in this tutorial. The ecosystem of these submodules is continuously evolving, with new additions and changes happening frequently.
To get started with any of these AI integrations, the most crucial first step is to obtain an API key from your chosen AI service provider. This tutorial will focus on OpenAI, so you'll need to create an OpenAI API key. Note that you may need to provide credit card information to acquire one.
For those who wish to follow along without setting up a local development environment or managing API keys directly, Drupal Forge offers a convenient solution. You can spin up a Drupal CMS AI demo site with pre-configured settings and a limited API token allowance ($1 token usage limit) that lasts for an hour.
Here's how to spin up a demo site on Drupal Forge:
- Go to
drupalforge.org. - Locate and click on the 'Drupal AI' option.
- Complete the simple math verification.
- Click the button to deploy the site.
Once deployed, you will be able to access the site. The default login credentials for the demo site are admin for both the username and password. Upon logging in, you'll immediately see the AI chatbot on the right-hand side of the page. You can interact with it, for example, by typing "Hello," to confirm it's working. This setup eliminates the need for local DDEV installations or manual API key configuration for initial testing.
In a standard Drupal CMS installation (like one running locally with DDEV), the necessary modules are usually included. However, if you are installing them manually, remember to download the correct version of the Drupal AI module and, critically, a corresponding provider module (e.g., for OpenAI).
After installing the AI Assistant module, you will be prompted to enter your API key. Once entered, Drupal AI handles the rest of the setup. You might also encounter a cookie consent pop-up. To ensure full functionality, click on 'Manage privacy settings' and enable all options. Test the chatbot again by saying "Hello" to confirm it's fully operational.
It's helpful to understand the backend configuration, even with the convenience of recipes, as this knowledge is crucial for troubleshooting.
To access AI-related configurations:
- Go to 'Configuration'.
- Click on 'AI'.
Here, you'll find several settings:
- Default settings: Allows you to set specific providers for different operations (e.g., image generation, speech-to-speech). You can use various providers (OpenAI, Anthropic, Azure, etc.) simultaneously and assign them to different tasks or define a default model.
- AI Agent settings: Configures AI agents. More details on this will be discussed later, but it's a deep topic that could warrant its own session.
- AI Assistant settings: Configures your chatbot and determines which AI agents it utilizes.
- Image Alt Text settings: Manages AI-generated alt text for images.
- Provider settings: This is where you enter and manage your API keys for different service providers. After installing a provider module, an option will appear here. You must add your key and then select it.
Drupal AI wisely leverages the Key module for managing API keys. This is important because it prevents direct storage of sensitive API keys in the database, which is a significant security risk (e.g., through leaked database dumps). The Key module allows keys to be stored as configuration, but more securely, as environment variables on your server. When editing a key, the system will warn you about visibility, which is especially useful during live demonstrations. You can add new keys and specify their storage method: file, configuration, or environment variable. Environment variables are ideal for injecting secrets directly onto servers and facilitate key rotation.
Once your API key is set up, remember to go back to the provider configuration and select the newly added key for use. This is a common step that is sometimes overlooked.
Let's begin site building with the AI agent. The chatbot displayed on the site is implemented as a block. If you inspect the block layout (specifically in the Gin theme for backend-only access), you'll find the "AI Agent" block.
The AI assistant's behavior can be managed through the 'AI Assistant' configuration. This section contains detailed instructions for the assistant and allows you to select its AI provider. Crucially, you can enable specific AI agents that the assistant can utilize. For example, out-of-the-box, there are "Content type agent," "Field agent," and "Taxonomy agent."
Under 'AI Agent settings,' you can configure these individual agents. For instance, clicking on a "Content type agent" reveals options like 'max loops' (though a full deep dive into agent configuration is beyond this tutorial). Importantly, for each AI agent, you can define specific instructions and select tools that enable it to perform actions like editing, creating, and retrieving information about content types.
Before proceeding with more advanced tasks, it's highly recommended to install the AI logging module. This module is invaluable for debugging and understanding how the AI processes requests.
- Go to 'Extend'.
- Search for 'logging' and install the 'AI logging' module.
- Navigate to its settings and enable 'Automatically log requests and responses' to log everything.
Note: As of this recording, there's a known core issue related to the "navigation title component" that can cause a fatal error with the logging page. A patch may be required to resolve this.
With logging enabled, let's try some basic interactions with the chatbot:
- "Can you list out all the content types?": The AI will process this and ask for confirmation ("Yes, proceed"). It will then contact its agents and list the available content types. You can review the interaction, including the prompt, provider, and response, in the AI log. This logging is critical for debugging, especially when context might not be passed correctly, as AI can "hallucinate" or make up information if it lacks sufficient context.
Now, let's build something:
- "Can you create a content type called project?": Confirm with "Yes, proceed." The AI will create the content type. You can verify this by going to 'Structure' > 'Content types'.
- "Can you create a field called project description? It should be a formatted long text field.": Again, confirm. The AI will create the field.
During these operations, especially complex ones like field creation, observe the AI log. You'll notice a significant amount of data, including context and tokens, being passed in the prompt. For instance, creating a field might involve nearly 8,000 tokens. Be aware that sending large prompts or frequent requests can lead to rate limiting from AI providers like OpenAI, especially on lower API tiers. Tiers often upgrade after a certain spending threshold, granting higher request rates.
Let's continue building:
- "Please create a task content type.": Confirm.
- "On the task content type, create a task description, a formatted long text field, and create a project field, which is an entity reference field back to the project content type.": This prompt is more complex, asking for multiple actions on a new content type, including an entity reference. The AI will often confirm and then execute the request. Verify the new fields and the entity reference on the 'Task' content type.
- "Can you add the following description to the task content type: 'a content type for managing tasks'?": The AI will confirm and update the description.
Next, we'll create a taxonomy vocabulary:
- "Can you create a taxonomy vocabulary called project status with the following terms: to do, in progress, and completed?": The AI will create the vocabulary and its terms.
- "Can you add an entity reference field on the project content type referencing the project status vocab?": This creates a reference field, allowing project nodes to link to project status terms.
- "On the project status field on the project content type, can you change the widget to a select widget and reorder the widgets so it's above the project description?": This demonstrates the AI's ability to modify existing field settings, including the widget type and order.
As seen from the extensive logging, the AI performs a lot of background operations to fulfill these requests. The AI API Explorer module (drupal.org/project/ai_api_explorer) is another useful tool for testing and understanding AI interactions.
To install it:
- Go to 'Extend'.
- Search for 'AI' and install 'AI API Explorer'.
Once installed, navigate to Configuration > AI > AI API Explorer.
Key features of the AI API Explorer:
- Chat Generation Explorer: Functions like a simplified ChatGPT interface. You can type prompts, stream responses, and switch between different AI models. It also shows the raw code necessary to programmatically run these prompts in Drupal, which is useful for developers.
- Tool Explorer: Allows you to test specific AI tools, such as
List bundlesorGet all content types. Some tools might not use AI and simply retrieve information. You can run predefined prompts to see their output.
Additionally, with the AI API Explorer, you'll find a new 'Test' button on individual AI agent settings pages. This allows you to quickly test specific actions of an agent, like listing content entities filtered by type (e.g., 'node' or 'task').
Now, let's integrate AI with CKEditor. This allows AI functionalities directly within your content editing interface.
- Go to 'Extend'.
- Search for 'AI' and install the 'AI CK Editor integration' module.
To configure CKEditor for AI integration:
- Go to 'Configuration' > 'Text formats and editors'.
- Select the text format you wish to configure (e.g., 'Basic HTML').
- Drag the 'AI CKEditor' button to your active toolbar.
- Optionally, add the 'AI Balloon menu' button. This creates a contextual AI menu that appears when you select text, providing quick access to AI tools.
- Click on the 'AI Tools' tab. Here, you can enable specific AI features for CKEditor.
- Generate with AI: Allows AI to generate content. You'll need to input a prompt here (e.g., "Make it easy to read").
- Modify: Allows AI to modify existing content.
- Summarize: Enables AI to summarize selected text. You can often adjust the tone.
- Translate: Integrates AI translation.
- Fix: Allows AI to correct spelling, grammar, or reformat content.
Let's test these CKEditor features:
- Create a new page.
- In the CKEditor body field, type a prompt (e.g., "How to use views in Drupal 11").
- Click the 'Generate with AI' button.
- Provide a detailed request (e.g., "Can you write a 500-word blog post on using views in Drupal 11? Be as detailed as possible.").
- The AI will generate the content, indicated by a "AI writer" status. Once finished, click 'Save changes to editor'.
To use the AI Balloon menu, select a portion of the generated text. A pop-up will appear allowing you to:
- Modify: E.g., instructing it to "Make it longer."
- Fix spelling: Highlight text with errors and select 'Fix spelling'.
- Summarize: Select a long passage and choose 'Summarize'.
For the translation feature, additional configuration is required:
- Go back to 'Configuration' > 'Text formats and editors' and locate your configured text format.
- In the 'AI Tools' section, enable 'Translate'.
- The translation feature requires a vocabulary to list available languages. Use the chatbot to create this:
- "Can you create a vocab language?"
- "Can you add a few common languages as terms?" (This will automatically add terms like English, French, etc.)
- "Also add in Croatian." (You can add specific languages.)
- Once the vocabulary is created, return to the CKEditor settings.
- Under 'Translate', you can now select the 'Language' vocabulary.
- You can enable 'Autocreate' to allow the AI to add new language terms as needed, and 'Use term description for translation context' for more nuanced translations.
- Save the configuration.
Now, in the CKEditor, select text and choose 'Translate'. You can select the target language (e.g., French, German, Croatian) and see the translation appear. If a translation fails, check the AI logs for "Unexpected error" messages. This might happen due to rate limiting or other API issues.
CKEditor integration offers advanced options for managing context. For instance, you can configure the history context length for the chatbot in the AI Assistant settings to control how much past conversation the AI considers.
Finally, let's explore AI Automators. This module allows you to automate AI-driven tasks on fields in your content types.
- Go to 'Extend'.
- Search for 'AI' and install the 'AI Automator' module.
Example: Automatically generate a social summary for basic pages.
-
Use the chatbot to create a new field on the 'Basic Page' content type:
- "Can you create a field on the basic page content type called social summary? It should be a formatted long text field."
- "Can you move the social summary widget above the content widget?" (This might place it above 'description' instead of 'content', but it still works.)
-
Now, configure the automator on the 'Social summary' field:
- Go to 'Structure' > 'Content types' > 'Basic page' > 'Manage fields'.
- Click on the 'Social summary' field.
- Scroll down and enable 'AI automator'.
- Select 'LLM text' (for formatted long text fields).
- Choose 'Base mode' for 'Import mode'. This allows you to use another field's content as context.
- For 'Base field', select 'Content'. This means the AI will use the content from the body field as its input.
- Enter your prompt. For example: "Can you please generate a social media summary of the following text: [field:content]? Use lots of emojis." The
[field:content]token is crucial here; it injects the content from the body field into the prompt. Without this, the AI might "hallucinate." - Set 'Edit when' to 'Edit when changed' or 'Edit always' if desired.
- For 'Execution mode', choose 'Direct' for immediate execution (or 'Cued' if you want it to run via cron).
- Save the field.
To test the automator:
- Go to a 'Basic page' node and ensure the 'Social summary' field is empty.
- Add content to the body field.
- Save the node.
You'll notice a slight delay during save, indicating the automator is running. Upon successful save, the 'Social summary' field should be populated with AI-generated content, complete with emojis. If you save the node again without clearing the 'Social summary' field, it will save instantly because the automator only triggers if the field is empty or changed.
Reviewing the AI logs for these automated actions is vital. You can see the exact prompt that was sent, including the [field:content] injection. This helps verify that context is being passed correctly and prevents hallucinations.
A powerful application of AI Automators is creating custom CKEditor actions. This allows you to define reusable AI-powered tasks that can be triggered directly from the editor's toolbar or balloon menu.
Here's how to create a "Call to Action" automator for CKEditor:
- Go to 'Configuration' > 'AI' > 'Automators' > 'Automator Chain settings'.
- Click 'Add automator chain' and name it 'Call to Action'.
- Edit the new automator chain. It is a fieldable entity.
- Click 'Manage fields'.
- Add a new field of type 'Text (formatted, long)' and name it 'Input'. This field must be required for it to appear as an option in CKEditor settings. This 'Input' field will receive the selected text from CKEditor.
- Add another field of type 'Text (formatted, long)' and name it 'Output'.
- For the 'Output' field, enable AI automator and select 'LLM text'.
- Set 'Import mode' to 'Base mode' and 'Base field' to 'Input' (the field you just created). This ensures the AI uses the 'Input' field's content as its context.
- Enter your prompt for the AI. For example: "Convert the following text into a viral, professional social media post, using emojis. Input text: [field:input]. Requirements: Wrap response in a blockquote tag. Ivan." The
[field:input]token will insert the text selected in CKEditor. - In 'Advanced settings' for the 'Output' field, set 'Execution mode' to 'Direct'. This is essential for CKEditor integration.
- Save the field.
Now, configure this automator in CKEditor:
- Go to 'Configuration' > 'Text formats and editors', and select your text format.
- Go to 'AI Tools'. A new 'AI Automators' section will appear.
- Enable the 'Call to Action' automator.
- For 'Input', select your 'Input' field. Make sure the checkbox below it, indicating a required selection, is checked.
- For 'Output', select your 'Output' field.
- Set the 'Write mode'. For a blockquote, 'Append' is suitable to place it after existing content, or 'Prepend' for placing it before.
- Save the configuration.
To test the custom CKEditor action:
- Go to a page with CKEditor.
- Select some text within the editor.
- From the 'AI' dropdown or balloon menu, choose 'Call to Action'.
- The selected text will automatically populate the automator's input. Click 'Generate'.
- The AI will process the request and generate the content as specified in your prompt (e.g., a viral social media post in a blockquote).
- Click 'Save changes to editor' to insert the generated content.
This method allows editors to trigger complex AI tasks with a single click, automating common needs like content reformatting or generating social media snippets.
Finally, we'll look at replicating similar automation using ECA (Event-Condition-Action). ECA is a robust workflow tool. While AI Automators are often easier for field-level automation, ECA offers broader workflow capabilities.
- Go to 'Extend'.
- Search for 'ECA' and install the 'AI ECA Integration' module. (ECA itself is often included in Drupal CMS distributions, but the AI integration module needs to be added.)
Example: Automate social summary generation for basic pages using ECA.
-
First, disable or remove the AI Automator previously configured on the 'Social summary' field to avoid conflicts.
-
Go to 'Configuration' > 'Workflow' > 'ECA' and click 'Add new model'.
-
Name it 'Generate social summary' and save.
-
In the ECA model editor, click the '+' button to add an 'Event'
- Select 'Content' > 'Pre-save entity'. This event triggers before a content entity is saved or updated.
- For 'Entity Type', select 'Content'.
- For 'Bundle', select 'Basic Page'. This restricts the workflow to basic pages.
-
Add a 'Condition' to the 'Pre-save entity' event:
- Select 'Content' > 'Field value is empty'.
- Negate the condition (set to 'Yes') to ensure the action only runs if the field is empty.
- For 'Field Name', enter
field_social_summary.
-
Add an 'Action' to the condition:
- Select 'Content' > 'Get field value'.
- For 'Entity', ensure it's the 'Content' entity from the event.
- For 'Field Name', enter
field_content(the body field). - For 'Token Name', enter
page_content. This stores the body content in a reusable token.
-
Add another 'Action':
- Select 'AI Automation' > 'Generate Chat (LLM)'.
- For 'Input Token', enter
[page_content]. This passes the body content to the AI. - For 'Result Token', enter
ai_list. This token will hold the AI's generated response. - For 'Prompt', enter: "Please generate a summary of the following text: [page_content]." (Ensure consistent token usage without extra brackets in the prompt itself if using the "without brackets" option.)
-
Add another 'Action':
- Select 'Content' > 'Set field value'.
- For 'Field Name', enter
field_social_summary. - For 'Field Value', enter
[ai_list](the token holding the AI's response).
-
(Optional but recommended for debugging) Add a 'Status Message' action after setting the field value:
- For 'Message', enter: "Generated: [ai_list]". This will display a message on save, confirming the generation.
-
Save the ECA model.
To test the ECA workflow:
- Go to a 'Basic page' node.
- Clear the 'Social summary' field.
- Modify the body content.
- Save the node. You'll see the status message confirming generation, and the 'Social summary' field will be populated. If you save again without clearing the field, the ECA condition will prevent regeneration.
ECA is powerful but can be complex. While AI Automators are simpler for direct field automation, ECA offers the flexibility to build more intricate workflows based on various events and conditions within Drupal.
In summary, the Drupal AI module suite, particularly with AI Assistant, offers powerful tools for integrating AI into content management:
- AI Assistant: Provides out-of-the-box chatbot and agent functionality for quick setup.
- CKEditor Integration: Embeds AI directly into the content editing experience for generation, translation, summarization, and correction.
- AI Automators: Automates AI tasks on specific content fields, useful for generating summaries, alt text, or other structured content.
- ECA Integration: Enables complex, event-driven AI workflows within Drupal, offering advanced automation logic.
Remember that managing prompts across different modules (Automators, ECA, CKEditor) can become a challenge in large sites, suggesting a potential need for a centralized prompt management system in the future. Despite this, the current AI capabilities within Drupal significantly enhance the content editing workflow.
Step 2: Module Installation and Initial Setup
Module Installation and Initial Setup
To begin using the AI capabilities within Drupal CMS, you must first install the necessary module and configure fundamental settings. This section guides you through installing the AI Assistant module, setting up your API key, adjusting privacy settings, and performing an initial functionality test.
1. Install the AI Assistant Module
The AI Assistant module provides a comprehensive suite of AI tools straight out of the box, including a chatbot and an AI agent, allowing you to start building immediately.
- Navigate to the administrative interface of your Drupal CMS site.
- In the navigation menu, select Extend.
- Click on Recommend.
- Locate and select the AI assistant module.
- Click the Install button to begin the installation process.
The installation should be swift. After installation, you will need to configure the module with an API key.
2. Configure Your API Key
An API key is essential for the AI module to function, as it connects your Drupal site to the AI provider. This tutorial focuses on OpenAI, so ensure you have an OpenAI API key. While this process is demonstrated securelyオフ-screen, the general steps involve navigating to the module's settings and entering your key.
- After installing the AI Assistant module, you will be prompted to enter your API key.
- It is crucial to enter your API key securely. While entering, it is advised to block the key from view on-screen.
- Enter your API key into the designated field.
- Click Continue to validate and save the setup.
The system will then validate the API key, and if successful, the setup is complete.
3. Adjust Privacy Settings and Enable Cookies
Drupal CMS utilizes cookies for various functionalities, and proper privacy settings are necessary to ensure the AI chat features work correctly.
- Upon successful API key setup, you might notice a cookie consent pop-up in the bottom right corner of your screen. This is part of Drupal CMS's privacy features.
- Click on Manage privacy setting.
- Within the privacy settings, ensure that all cookies are enabled. You may need to toggle all options on to allow full functionality.
- After enabling all cookies, the cookie consent pop-up should disappear, confirming that all necessary settings are active.
4. Initial Testing of the AI Assistant Chatbot
To confirm that the AI Assistant is functioning as expected, perform a simple test by sending a basic message to the chatbot.
- You should now see the AI Assistant chatbot interface, typically located in the bottom right of your screen.
- In the chatbot's input field, type
Hello. - Press Enter or click the send button to send the message.
The chatbot should respond with a greeting, confirming that it is operational. This ensures that the core AI functionality is correctly set up.
Step 3: Site Building with AI Assistant: Content Types and Fields
Site Building with AI Assistant: Content Types and Fields
This section will guide you through using the AI assistant to perform basic site-building tasks, specifically creating content types and fields within Drupal.
First, ensure your AI assistant is accessible. On your Drupal CMS site, look for the chatbot; it's typically loaded as a block. If you're on the backend, it will be in the Gin theme. For example, if you go to Structure > Block layout, select the Gin theme, and search for "AI agent," you'll find it usually placed in a sidebar. This AI assistant is managed through Configuration > AI > AI assistant. Here, you can define its instructions and select which AI provider and agents it uses (e.g., Content Type agent, Field agent, Taxonomy agent).
Understanding AI Agents and Logging
Before we start building, it's helpful to understand the underlying mechanisms and how to monitor them. When you interact with the AI assistant, it uses various "tools" (e.g., createContentType, editContentType, getFieldInfo). These tools are configured within the AI agents (e.g., Configuration > AI > AI agent settings). While the AI Assistant recipe makes site building much easier, understanding these agents helps with debugging if anything goes wrong.
To monitor AI assistant actions, install the AI Logging module. Search for "logging" under Extend and install it. After installation, go to Configuration > AI > AI Logging and ensure Automatically log requests and responses is enabled to log everything. This is crucial for debugging, especially to check if content or context is being properly passed to the AI, as AI can "hallucinate" or make things up if the context is missing.
Creating Content Types and Fields
Let's begin by building some site components using the AI assistant.
-
List Existing Content Types:
In the AI assistant chat, type:
Can you list out all the content types?
The assistant will think, ask for confirmation (Yes, proceed), and then list the existing content types. Currently, you should only see "Basic page" and "Article" by default. -
Create a 'Project' Content Type:
In the AI assistant chat, type:
Can you create a content type called project?
The assistant will again ask for confirmation (Yes, proceed). It will then go ahead and create the content type. You can verify this by navigating toStructure > Content typesin the Drupal admin interface. -
Add a Formatted Long Text Field to 'Project':
Next, let's add a description field. In the AI assistant chat, type:
Can you create a field called project description? It should be a formatted long text field.
Confirm withYes, proceed. The AI assistant will process the request.- Important Note on AI Rate Limiting: Be aware that making numerous requests quickly, especially when building out complex structures, can lead to API rate limiting, depending on your AI service plan (e.g., OpenAI). If you exceed your request limits, you might experience issues or delays. Certain tiers with OpenAI, for instance, provide higher rates once you spend over a certain amount ($50 in API tokens). This is why you might experience occasional delays or failures; the system might be waiting to send the next request due to rate limits.
You can verify the field creation by navigating to
Structure > Content types, clicking onManage fieldsfor the "Project" content type. -
Create a 'Task' Content Type and Linked Fields:
Now, let's create another content type and link it to the "Project" content type.-
Create the 'Task' Content Type:
In the AI assistant chat, type:
Please create a task content type.
Confirm withYes, proceed. -
Add 'Task Description' and 'Project' Entity Reference Fields:
In the AI assistant chat, type:
On the task content type, create a task description formatted long text field and create a project field, which is an entity reference field back to the Project content type.The assistant will process this request. You might notice it sometimes proceeds without confirmation, while other times it explicitly asks. This process can take a moment, which might increase your stress level if you're watching it in real-time.
You can verify these fields by going to
Structure > Content types, thenManage fieldsfor the "Task" content type.
-
-
Refine 'Task' Content Type Description:
We can also ask the AI to update existing content type settings. To add a description to the "Task" content type, in the AI assistant chat, type:
Can you add the following description to the Task content type? a content type for managing tasks.
It will likely ask for confirmation. Confirm withYes, proceed.
To verify, go toStructure > Content types, click onEditfor the "Task" content type. You will see the description updated. -
Add Test Content (Nodes) to Verify Functional Linkages:
To see the entity reference at work, create some test content:-
Create a 'Project' node:
Go toContent > Add content > Project.
Enter a title, such as "Test Project".
Save the node. -
Create a 'Task' node:
Go toContent > Add content > Task.
Enter a title, such as "Test Task".
For the "Project" field, you should be able to select the "Test Project" you just created. This verifies the functional linkage between the "Task" and "Project" content types.
Save the node.
-
Step 4: Advanced AI Features: API Explorer and CKEditor Integration
Advanced AI Features: API Explorer and CKEditor Integration
This section will guide you through using the AI API Explorer for testing and integrating AI functionalities directly into CKEditor.
AI API Explorer: A Testing Tool
The AI API Explorer module is an excellent tool for testing the AI capabilities within your Drupal environment.
-
Install the Module:
- Navigate to
Extend. - Search for "AI".
- Find and install the "AI API Explorer" module.
- Navigate to
-
Access the Explorer:
- Once installed, go to
Configuration>AI>AI API Explorer.
- Once installed, go to
-
Utilize the Chat Generation Explorer:
- The
Chat Generation Explorerwithin the AI API Explorer functions much like a standalone chat application (e.g., ChatGPT). - You can directly input questions or prompts (e.g., "Hello").
- You have options to stream responses and switch between different AI models.
- This is a valuable tool for verifying that your AI setup is working correctly.
- You can also view the raw code generated, which is useful if you intend to programmatically run these prompts within your own Drupal code since Drupal AI abstracts these functionalities into services. You can copy this code and integrate it into your custom modules.
- The
-
Explore Other Tools:
- The
Tool Explorerallows you to test specific AI tools, such asList Bundles, which lists all bundles without involving AI. - You can run specific prompts, such as "Get all content types," to see the returned data.
- The
-
Integration with Assistant Settings:
- When the AI API Explorer is enabled, a test button appears within the assistant settings.
- You can use this button to test specific functionalities, like listing content entities. For example, by typing "node," it will list all node content. You can also filter by content type (e.g., "task") or limit the number of results.
Integrating AI Functionality into CKEditor
Integrating AI directly into CKEditor enhances the content creation and editing experience by providing AI tools at your fingertips.
-
Install the CKEditor Integration Module:
- Go to
Extend. - Search for "AI".
- Install the "AI CKEditor integration" module.
- Go to
-
Configure Text Formats and Editors:
- Navigate to
Configuration>Content authoring>Text formats and editors. - Select the text format you wish to configure (e.g., "Basic HTML," "Full HTML" or "Restricted HTML").
- Navigate to
-
Add AI Buttons to the Toolbar:
- Drag and drop two specific buttons into your active toolbar:
AI CK Editor: This button provides access to various AI tools.AI Balloon Menu: This feature displays a hovering menu with AI options when text is selected. It's particularly useful for quick access to tools for selected content.
- Drag and drop two specific buttons into your active toolbar:
-
Configure AI Tools:
- Click on the
AI Toolsbutton within the CKEditor configuration. - Enable the desired AI options by checking their respective boxes:
- Generate with AI: Use this to create new content from scratch. You'll need to enter placeholder text in the "Prompt" field (e.g., "Make it easy to read"), even if you don't intend to use it directly, due to a known minor bug.
- Modify: Allows you to alter selected text (e.g., "Make it longer").
- Summarize: Condenses selected text.
- Translate: Translates selected text. This requires additional configuration (see "Enabling and Configuring Translation" below).
- Fix: Corrects spelling and can clean up HTML from pasted content.
- (Optional) Tone: Adjusts the tone of the content.
- (Optional) Reformat HTML: Useful for standardizing or fixing malformed HTML, especially common when content is copied and pasted from external sources.
- Click on the
Demonstration of CKEditor AI Features
Let's walk through some practical examples of using AI within CKEditor.
-
Generating Content with AI:
- Create a new content page (e.g.,
Content>Add content>Basic page). - In the CKEditor body field, click the
AI CK Editorbutton. - Select
Generate with AI. - Enter a detailed prompt, such as: "Can you write a 500-word blog post on using views in Drupal 11. Be as detailed as possible."
- Click
Generate. - The AI will stream the content into the editor.
- Click
Save changes to editoronce generation is complete. - Save or publish your node.
- Create a new content page (e.g.,
-
Using the AI Balloon Menu:
- Select a block of text within your CKEditor content.
- The
AI Balloon Menuwill appear as a hovering popup. - Make it Longer (Modify): Click on
Modifyand thenMake it longer. The AI will expand the selected text. - Fix Spelling: Intentionally introduce spelling mistakes in your text (e.g., "speling mistakes"). Select the misspelled text. In the AI Balloon Menu, click
Fix spelling. The AI will correct the errors. - Summarize: Select a longer passage of text. In the AI Balloon Menu, click
Summarize. The AI will condense the selected content.
-
Enabling and Configuring Translation (CKEditor):
- To use the
Translatefeature, you need to create a vocabulary for languages. - Create Language Vocabulary:
- Go to your chatbot (AI Assistant in the lower right).
- Prompt: "Can you create a vocab language?" (Ensure the vocabulary is created successfully).
- Prompt: "Can you add a few common languages as terms?" (This will add general languages).
- (Optional) Add specific languages: "Also add in Croatian."
- Configure Translate Option in CKEditor:
- Go to
Configuration>Content authoring>Text formats and editors(the same place you configured other AI tools). - Click
AI Tools. - Enable the
Translateoption. - In the
Translatesettings, select the language vocabulary you just created. - You can enable
Auto createto allow the AI to add languages as needed. - You can also specify
Use term description for translation contextif you want to provide more information to the AI during translation. - Save the configuration.
- Go to
- Using Translation:
- Go back to a content page in CKEditor.
- Select the text you want to translate.
- In the AI Balloon Menu or by clicking the
AI CK Editorbutton, selectTranslate. - Choose your target language (e.g., French, German, or Croatian).
- Click
Translate. The AI will provide the translated text.
- To use the
Managing Context with AI
When working with AI, especially within a content management system like Drupal, context management is crucial. If your content is already within Drupal, managing the context for AI interactions should be relatively straightforward. This is because the AI can leverage the existing structure and content within your site. For example, if you have rich content directly in your Drupal fields, the AI can draw upon that for operations like summarization or modification.
The Fix feature is particularly useful for cleaning up HTML that might be problematic, especially when content is copy-pasted from external sources. It helps ensure that your content remains well-formatted and consistent.
Step 5: AI Automator: Automating Content Generation
AI Automator: Automating Content Generation
This section focuses on automating content generation using the 'AI Automator' module. The primary goal is to automatically generate a social summary for a field on the 'Basic Page' content type.
Installation and Setup of AI Automator
- Install the 'AI Automator' module:
- Navigate to Extend.
- Search for "AI".
- Select the "Automators" module and click Install.
Adding a 'Social Summary' Field to 'Basic Page'
The 'social summary' field will be a formatted long text field that automatically populates with an AI-generated summary of the content.
- Create the 'Social Summary' field:
- Open the chatbot.
- Proroll the prompt: "Can you create a field on the Basic Page content type called social summary. It should be a formatted long text field."
- Confirm by typing "proceed" when prompted.
- Move the 'Social Summary' widget:
- Once the field is created, use the chatbot to move its widget: "Can you move the social summary widget above the content widget?"
- Confirm by typing "proceed" when prompted.
- While the AI assistant might place it above the description field rather than explicitly the content field, this is acceptable for the demonstration.
Configuring the 'Social Summary' Field with AI Automator
Now, you will configure the newly created 'social summary' field to use the AI Automator.
- Edit the 'Social Summary' field:
- Go to the
Basic Pagecontent type. - Locate and click on the 'social summary' field to edit its settings.
- Go to the
- Enable AI Automator:
- Scroll down to the "AI Automator" section.
- Check "Enable AI Automator".
- For the automator type, select "LLM text".
- Note: The distinction between 'text' and 'text simple' automator types is based on the field format. 'Text simple' is for plain text fields, while 'text' is for formatted long text fields, as is the case with our 'social summary' field.
- Configure Prompt Context:
- For the 'Import mode', select "Base mode".
- For the 'Prompt context', select "Base field".
- From the 'Base field' dropdown, choose "Content" (representing the main body field of the page). This ensures the AI uses the basic page's primary content as input for the summary.
- Craft the AI Prompt:
- In the 'Prompt' text area, input the following:
Can you please generate a social media summary of the following text? [text] and use lots of emojis. - Crucial Point: It is vital to use the
[text]token to pass the content of the 'Base field' (which is the 'content' field in this case) to the AI. Failure to pass the correct content token will lead to AI "hallucinations" or an inability to assist, as the AI will lack the necessary context.
- In the 'Prompt' text area, input the following:
- Configure Automator Options:
- Edit when changed: Check this option. This setting ensures the automator triggers and updates the social summary whenever the content field is modified and saved.
- Execution type:
- "Direct" will run the automator immediately upon save.
- "Cued" will add the task to a cron queue, meaning it will be processed when cron runs.
- For this demonstration, leave it as "Direct".
- You can set a weight if you have multiple automators, but for this setup, leave default.
- Save the configuration: Click Save.
Demonstration of AI Automator in Action
- Create a new 'Basic Page' node:
- Navigate to Content > Add content > Basic Page.
- Provide a title for the page.
- Enter some text into the main 'Content' field.
- Ensure the 'Social summary' field is empty before saving.
- Observe automatic summary generation:
- Click Save.
- You should notice a brief delay (a second or two) before the page reloads. This indicates the automator is processing the request. If the page reloads instantly, it signifies the automator did not trigger.
- Once the page reloads, scroll down to the 'Social summary' field. You should see the automatically generated social media summary, complete with emojis, derived from the content you entered.
Debugging and Illustrating AI Hallucination
The logging module (installed in a previous step) is invaluable for debugging and understanding how the AI automator processes requests.
- Review the Generated Prompt in Logging:
- Go to Configuration > AI > Logging.
- Locate the most recent log entry related to the social summary generation.
- Click View on the log entry.
- Examine the "Prompt" section to confirm that the
[text]token correctly passed the content from your 'Basic Page' to the AI. This is a critical step to ensure the AI receives the proper context.
- Illustrate AI Hallucination (by omitting the content token):
- Go back to the 'Social summary' field configuration (for the Basic Page content type).
- In the 'AI Prompt' text area, remove the
[text]token, leaving only: "Can you please generate a social media summary of the following text? and use lots of emojis." - Save the changes.
- Go back to your 'Basic Page' node.
- Delete the content from the 'Social summary' field (if any).
- Click Save.
- This time, the AI will likely respond with "I'm sorry, I can't assist you with that request." or generate irrelevant content because it lacks the necessary context. This demonstrates the critical importance of correctly passing the content token.
- Re-add the
[text]token to the prompt and save the configuration to restore the automator's functionality.
Step 6: Event-Condition-Action (ECA) Module Integration
Event-Condition-Action (ECA) Module Integration
The ECA (Event-Condition-Action) module is described as a very powerful successor to Drupal 7's Rules module. It empowers you to create custom workflows for a wide range of tasks, such as user validation, automated password resets, or changing content statuses. While ECA is incredibly flexible for complex, multi-step operations, AI Automators are generally simpler for direct, field-level automation. ECA comes out-of-the-box with Drupal CMS, but requires the 'AI ECA integration' module for AI functionalities.
Let's demonstrate how to re-implement the social summary generation using ECA instead of the AI Automator. This will illustrate a potential use case for ECA, though for this specific scenario, AI Automators are generally simpler to set up.
1. Remove Previous AI Automator Configuration
First, remove the existing AI Automator configuration for the 'social summary' field to avoid conflicts and ensure ECA handles the generation. Navigate to the field settings and disable the AI Automator option that was previously enabled for the 'Social Summary' field.
2. Create a New ECA Workflow
Navigate to Workflow > ECA and create a new workflow by clicking Add new model. Name this new model "Generate social summary."
3. Add an "Event" Node
Click on the workflow canvas and drag an "Event" node onto it. In the configuration sidebar:
a. Select the Pre-save entity template.
b. Set the type to "Basic Page" (or your desired content type).
This configures the ECA workflow to trigger before a 'Basic Page' entity is saved or updated.
4. Add a "Condition" Node
Drag a "Condition" node onto the canvas and connect it to the "Event" node from the previous step. Configure this condition as follows:
a. Select the "Field value is empty" condition.
b. Enter the field name as "field_social_summary". This ensures the summary is only generated if the social summary field is currently empty, preventing regeneration when content already exists.
5. Add a "Get Field Value" Action
Drag an "Action" node, connect it to the "Condition" node, and configure it to retrieve the content from the main body field of the page:
a. Select the "Get field value" action (ensure it's under ECA Content, not ECA Form).
b. For "Field name", enter "field_content" (this assumes your main content field is named field_content).
c. For "Token name," assign its value to a custom token named "page_content." This token will hold the content of the main body field, making it reusable later in the workflow.
6. Add a "Generate Chat" Action (AI Integration)
Drag another "Action" node, connect it to the "Get Field Value" action, and configure it for AI generation:
a. Select the "Generate chat" action template.
b. For "Input Token", specify "page_content" (the token created in the previous step).
c. Define the AI prompt. The prompt for this example will be: "Please generate a list summary of the following text: [text token]".
d. Crucially, ensure the token usage is correct. For the [text token] part in the prompt, you should use the actual token name without the brackets, like this: "page_content". The full prompt would look like: "Please generate a list summary of the following text: page_content".
e. The results of this chat action will be assigned to a token named "AI list".
7. Add a "Set Field Value" Action
Drag a final "Action" node, connect it to the "Generate Chat" action, and configure it to set the social summary field:
a. Select the "Set field value" action (again, ensure it's under ECA Content, not ECA Form).
b. For "Field name", enter "field_social_summary".
c. For "Field value", use the AI-generated token: "[AI list]". Make sure this token is wrapped in brackets.
8. Add a "Status Message" Action (for Debugging)
For debugging and user feedback, add another "Action" node connected parallel to the "Set Field Value" action (or after it):
a. Select the "Status message" action.
b. In the message field, enter "Generated [AI list]" (using the token with brackets). This message will appear on the screen after the page is saved, confirming that the summary was generated and displaying its content.
9. Review and Save the ECA Workflow
Confirm the logic:
-
The workflow triggers on 'Pre-save' for a 'Basic Page'.
-
It checks if 'field_social_summary' is empty.
-
If empty, it retrieves the content from 'field_content' and assigns it to a token called 'page_content'.
-
It passes 'page_content' to the AI for chat generation, which then returns content to the 'AI list' token.
-
Finally, it sets the 'field_social_summary' from the content of the 'AI list' token.
Save the ECA workflow.
10. Test the ECA Workflow
a. Create a new 'Basic Page' or edit an existing one. Ensure the 'Social Summary' field is empty.
b. Add some content to the main body field.
c. Save the page. You should observe a slight delay as the AI processes the request. A status message "Generated [AI list content]" will appear, and the 'Social Summary' field will be populated with the AI-generated content.
d. To confirm the "empty field" condition works, save the page again without emptying the 'Social Summary' field. You will notice no delay, and the status message will not appear, indicating that the ECA workflow did not re-trigger because the condition was not met.
The importance of status messages for user feedback when content is generated asynchronously cannot be overstated. It keeps the editor informed about what's happening behind the scenes.
Key Concepts
- Artificial Intelligence (AI) basics within Drupal context
- Drupal AI module suite (core, submodules, providers)
- API Key management and security best practices
- AI Logging and its role in debugging AI interactions
- Content types, fields, and taxonomies (Drupal concepts)
- AI Rate Limiting (external concept, applied to AI services)
- AI Hallucination (AI concept)
- CKEditor integration and plugin configuration
- Context management in AI prompts
- AI Automator (Direct vs. Cued execution)
- ECA (Event-Condition-Action) module and its workflow components (Events, Conditions, Actions, Tokens)
- Environment variables for secure configuration
Conclusion
This tutorial article guided you through the entire process of getting started with AI in Drupal. You learned about the Drupal AI module suite, successfully installed and configured key modules, and applied AI to site-building tasks like creating content types and fields. We explored advanced features such as CKEditor integration for content generation and utilized AI Automators for automated content. Finally, you gained an understanding of building complex AI workflows using the ECA module.