Skip to main content

As AI becomes integral to web experiences, Drupal 10 developers are increasingly looking to create custom modules that harness the power of AI. Whether it’s content generation, intelligent tagging, or real-time suggestions, integrating AI into your module can supercharge your site's functionality.

This tutorial will walk you through creating a basic AI-powered custom module in Drupal 10 that connects to the OpenAI API and allows content editors to generate AI-written content from the node edit form.


🧱 Prerequisites

Before starting, ensure you have:

  • Drupal 10 installed and running

  • Composer available

  • An OpenAI API key (you can get one from https://platform.openai.com)

  • Basic PHP and Drupal module development knowledge


📁 Step 1: Create the Module Structure

In your /modules/custom directory, create a new folder:

bash
/modules/custom/ai_writer

Inside this folder, create these files:

  • ai_writer.info.yml

  • ai_writer.routing.yml

  • ai_writer.module

  • src/Form/AIContentForm.php


ai_writer.info.yml

name: 'AI Writer' type: module description: 'Provides AI content generation via OpenAI.' core_version_requirement: ^10 package: Custom dependencies:
  - node
 
 

ai_writer.routing.yml

yaml
 
ai_writer.form:
  path: '/admin/ai-writer'
  defaults:
    _form: '\Drupal\ai_writer\Form\AIContentForm'
    _title: 'AI Content Generator'
  requirements:
    _permission: 'access content' 

ai_writer.module

This file can remain empty or include basic hooks if needed. For now:

<?php
/**
 * @file
 * AI Writer module.
 */


 
🧠 Step 2: Create the Form with OpenAI Integration

Create the form that interacts with the OpenAI API:

src/Form/AIContentForm.php

php
<?php

namespace Drupal\ai_writer\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use GuzzleHttp\Client;

class AIContentForm extends FormBase {

  public function getFormId() {
    return 'ai_content_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['prompt'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Enter a prompt for the AI'),
      '#required' => TRUE,
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Generate Content'),
    ];

    if ($content = $form_state->get('generated_content')) {
      $form['output'] = [
        '#type' => 'textarea',
        '#title' => $this->t('Generated Content'),
        '#default_value' => $content,
        '#attributes' => ['readonly' => 'readonly'],
      ];
    }

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $prompt = $form_state->getValue('prompt');
    $api_key = 'YOUR_OPENAI_API_KEY';

    $client = new Client();
    try {
      $response = $client->post('https://api.openai.com/v1/completions', [
        'headers' => [
          'Authorization' => 'Bearer ' . $api_key,
          'Content-Type' => 'application/json',
        ],
        'json' => [
          'model' => 'text-davinci-003',
          'prompt' => $prompt,
          'max_tokens' => 150,
        ],
      ]);

      $data = json_decode($response->getBody(), true);
      $generated_text = $data['choices'][0]['text'] ?? 'No output';

      $form_state->set('generated_content', trim($generated_text));
      $form_state->setRebuild();
    } catch (\Exception $e) {
      \Drupal::logger('ai_writer')->error($e->getMessage());
      $form_state->set('generated_content', 'Error: ' . $e->getMessage());
      $form_state->setRebuild();
    }
  }
}

Note: Replace 'YOUR_OPENAI_API_KEY' with your real API key.


📦 Step 3: Install the Module and Use It

  1. Clear cache:

    bash
    drush cr
  2. Enable the module:

    bash
    drush en ai_writer
  3. Visit /admin/ai-writer to use your form.

You can now input any prompt, and the AI will return generated text.


🧪 Optional: Add AI to Node Editor

You can go further by:

  • Hooking into hook_form_FORM_ID_alter() to add the AI text area to node forms.

  • Adding CKEditor buttons for inline AI generation.

  • Saving the generated text as part of a field on the node.


🔐 Security & Best Practices

  • Store your API key securely using Drupal's config system.

  • Rate limit or restrict who can access the AI features.

  • Validate API responses to prevent misuse or bad output.


🧠 Final Thoughts

Building a custom AI-powered module in Drupal 10 opens up exciting possibilities—from automating workflows to enhancing editorial creativity. With tools like OpenAI, you can extend Drupal far beyond traditional CMS boundaries.

Tags