Magento 2 AI Product Descriptions — OpenAI PHP Plugin Guide

CodeAtoZ Engineer, CodeAtoZ
13 min read · 2441 words
Share: 𝕏 in
AI & AUTOMATION · AI INTEGRATION FOR DEVELOPERS #3

Magento 2 AI Product Descriptions — OpenAI PHP Plugin Guide (2026)

Generate Magento 2 AI product descriptions at scale using OpenAI and PHP — admin button, batch CLI command, tone control, attribute injection, and cost management.

GPT-4oModel
PHP 8.1+Required
M2 2.4+Magento
2026Updated

Generating Magento 2 AI product descriptions at scale with OpenAI solves one of the most time-consuming tasks in any catalogue migration or product launch — writing unique, SEO-optimised descriptions for hundreds or thousands of products. Magento 2 AI product descriptions built via a custom module give you full control over tone, length, the product attributes included in the prompt, and cost per generation. This guide builds a complete Magento 2 AI product descriptions module: an admin product edit button for single generation, a WP-CLI-style Magento console command for batch generation, encrypted OpenAI key storage, attribute injection into prompts, and per-store-view language handling.

Magento 2 AI product descriptions work by pulling product data — name, SKU, categories, custom attributes — and constructing a structured prompt that tells the model exactly what to write. The response is saved back to the product’s description field via Magento’s product repository. The entire flow runs server-side: the API key never touches the browser, and the generation can run via admin UI or CLI batch command.

magento 2 ai product descriptions — OpenAI prompt pipeline admin button batch CLI and store view handling by CodeAtoZ
Magento 2 AI product descriptions — architecture from attribute extraction through prompt construction to description save

Step 1: Magento 2 AI Product Descriptions — Encrypted API Key Config

Store the OpenAI API key in Magento’s encrypted system configuration. Magento’s native MagentoConfigModelConfigBackendEncrypted backend encrypts the value at rest using the Magento encryption key — no custom encryption code needed for Magento 2 AI product descriptions.

XML — etc/adminhtml/system.xml
<section id="caz_ai" translate="label" type="text" sortOrder="600" showInDefault="1">
    <label>AI Product Descriptions</label>
    <tab>catalog</tab>
    <group id="openai" translate="label" type="text" sortOrder="10" showInDefault="1">
        <label>OpenAI Settings</label>
        <field id="api_key" translate="label" type="obscure" sortOrder="10" showInDefault="1">
            <label>OpenAI API Key</label>
            <!-- Magento 2 AI product descriptions: native encrypted storage -->
            <backend_model>MagentoConfigModelConfigBackendEncrypted</backend_model>
        </field>
        <field id="model" translate="label" type="select" sortOrder="20" showInDefault="1">
            <label>Model</label>
            <source_model>CodeAtoZAiDescriptionsModelConfigSourceOpenAiModel</source_model>
        </field>
        <field id="max_tokens" translate="label" type="text" sortOrder="30" showInDefault="1">
            <label>Max Tokens</label>
            <comment>Default 350. Controls length and cost of Magento 2 AI product descriptions.</comment>
        </field>
    </group>
</section>

Step 2: Build the Magento 2 AI Product Descriptions Generator Service

The generator service is the core of the Magento 2 AI product descriptions module. It builds the prompt from product data, calls OpenAI via Magento’s HTTP client, and saves the result back to the product.

PHP — Model/DescriptionGenerator.php
<?php
namespace CodeAtoZAiDescriptionsModel;

use MagentoFrameworkHTTPClientCurl;
use MagentoFrameworkAppConfigScopeConfigInterface;
use MagentoFrameworkEncryptionEncryptorInterface;
use MagentoCatalogApiProductRepositoryInterface;

class DescriptionGenerator
{
    private const API_URL = 'https://api.openai.com/v1/chat/completions';

    public function __construct(
        private readonly Curl $curl,
        private readonly ScopeConfigInterface $config,
        private readonly EncryptorInterface $encryptor,
        private readonly ProductRepositoryInterface $productRepo
    ) {}

    public function generate( int $productId, int $storeId = 0 ): string
    {
        $product = $this->productRepo->getById( $productId, false, $storeId );

        // Build prompt for Magento 2 AI product descriptions
        $prompt = $this->buildPrompt( $product );
        $model  = $this->config->getValue( 'caz_ai/openai/model' ) ?: 'gpt-4o-mini';
        $tokens = (int) ( $this->config->getValue( 'caz_ai/openai/max_tokens' ) ?: 350 );
        $apiKey = $this->encryptor->decrypt(
            $this->config->getValue( 'caz_ai/openai/api_key' )
        );

        $payload = json_encode([
            'model'      => $model,
            'max_tokens' => $tokens,
            'messages'   => [
                [ 'role' => 'system', 'content' => 'You are an expert e-commerce copywriter. Write in British English.' ],
                [ 'role' => 'user',   'content' => $prompt ],
            ],
        ]);

        $this->curl->setHeaders([
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . $apiKey,
        ]);
        $this->curl->post( self::API_URL, $payload );

        $response = json_decode( $this->curl->getBody(), true );
        return $response['choices'][0]['message']['content'] ?? '';
    }

    private function buildPrompt( MagentoCatalogApiDataProductInterface $p ): string
    {
        // Include attributes for richer Magento 2 AI product descriptions
        $attrs = [];
        foreach ( ['color','size','material','weight'] as $attr ) {
            $val = $p->getAttributeText( $attr ) ?: $p->getData( $attr );
            if ( $val ) $attrs[] = ucfirst( $attr ) . ': ' . $val;
        }

        return sprintf(
            'Write a compelling 150-200 word product description for this Magento 2 product.
Name: %s
SKU: %s
%s
Tone: professional and persuasive. Include key features and a subtle call to action.
Do not include the product name as a header.',
            $p->getName(),
            $p->getSku(),
            implode( "n", $attrs )
        );
    }

    public function saveDescription( int $productId, string $description, int $storeId = 0 ): void
    {
        $product = $this->productRepo->getById( $productId, true, $storeId );
        $product->setDescription( nl2br( htmlspecialchars( $description ) ) );
        $this->productRepo->save( $product );
    }
}

Step 3: Magento 2 AI Product Descriptions — Admin UI Button

Add a “Generate AI Description” button to the product edit page using a UI component. The button triggers an admin AJAX controller that calls the generator service and returns the result for the admin user to review before saving.

PHP — Controller/Adminhtml/Generate/Description.php
<?php
namespace CodeAtoZAiDescriptionsControllerAdminhtmlGenerate;

use MagentoBackendAppAction;
use MagentoFrameworkControllerResultJsonFactory;

class Description extends Action
{
    public const ADMIN_RESOURCE = 'CodeAtoZ_AiDescriptions::generate';

    public function __construct(
        ActionContext $context,
        private readonly JsonFactory $jsonFactory,
        private readonly CodeAtoZAiDescriptionsModelDescriptionGenerator $generator
    ) {
        parent::__construct( $context );
    }

    public function execute(): MagentoFrameworkControllerResultJson
    {
        $result    = $this->jsonFactory->create();
        $productId = (int) $this->getRequest()->getParam( 'product_id' );

        if ( ! $productId ) {
            return $result->setData([ 'success' => false, 'message' => 'No product ID.' ]);
        }

        try {
            // Generate Magento 2 AI product descriptions for the current product
            $description = $this->generator->generate( $productId );
            return $result->setData([ 'success' => true, 'description' => $description ]);
        } catch ( Exception $e ) {
            return $result->setData([ 'success' => false, 'message' => $e->getMessage() ]);
        }
    }
}

Step 4: Magento 2 AI Product Descriptions — Batch CLI Command

For generating Magento 2 AI product descriptions across an entire catalogue, a Magento console command is far more practical than clicking an admin button per product. The CLI command processes products in batches with configurable concurrency and rate limit delay.

PHP — Console/Command/GenerateDescriptions.php
<?php
namespace CodeAtoZAiDescriptionsConsoleCommand;

use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleInputInputOption;
use SymfonyComponentConsoleOutputOutputInterface;

class GenerateDescriptions extends Command
{
    protected function configure(): void {
        $this->setName( 'caz:ai:generate-descriptions' )
             ->setDescription( 'Generate Magento 2 AI product descriptions in batch' )
             ->addOption( 'limit',  null, InputOption::VALUE_OPTIONAL, 'Max products', 100 )
             ->addOption( 'dry-run', null, InputOption::VALUE_NONE, 'Preview prompts only' )
             ->addOption( 'category', null, InputOption::VALUE_OPTIONAL, 'Category ID filter' );
    }

    protected function execute( InputInterface $in, OutputInterface $out ): int {
        $limit  = (int) $in->getOption( 'limit' );
        $dryRun = $in->getOption( 'dry-run' );

        $out->writeln( "<info>Starting Magento 2 AI product descriptions batch ($limit products)</info>" );

        $products = $this->getProductsNeedingDescriptions( $limit, $in->getOption('category') );
        $count = 0;

        foreach ( $products as $productId ) {
            try {
                if ( $dryRun ) {
                    $out->writeln( "  [DRY RUN] Would generate for product $productId" );
                } else {
                    $desc = $this->generator->generate( $productId );
                    $this->generator->saveDescription( $productId, $desc );
                    $out->writeln( "  <info>Generated Magento 2 AI product descriptions for product $productId</info>" );
                    sleep( 1 );  // Rate limit delay between OpenAI API calls
                }
                $count++;
            } catch ( Exception $e ) {
                $out->writeln( "  <error>Product $productId: {$e->getMessage()}</error>" );
            }
        }

        $out->writeln( "<info>Done. Generated $count Magento 2 AI product descriptions.</info>" );
        return Command::SUCCESS;
    }
}

The OpenAI Chat Completions API documentation covers all model options and parameters. The Magento 2 console command documentation covers Symfony Console integration. See our OpenAI WooCommerce plugin guide for the WooCommerce equivalent of this Magento 2 AI product descriptions approach.

💡 Batch cost estimate: GPT-4o mini at 350 max tokens per product costs roughly $0.001 per description. Generating Magento 2 AI product descriptions for 10,000 products costs approximately $10. Set a monthly spend cap in your OpenAI dashboard before running any large batch to prevent unexpected charges.

Frequently Asked Questions — Magento 2 AI Product Descriptions

How do I generate Magento 2 AI product descriptions with OpenAI?

Build a Magento 2 module with a generator service that pulls product name, SKU, and custom attributes to construct a prompt, calls the OpenAI Chat Completions API via Magento’s HTTP client, and saves the response back to the product description field via ProductRepositoryInterface. Store the API key using Magento’s native Encrypted config backend so it is encrypted at rest automatically.

Are Magento 2 AI product descriptions good for SEO?

Yes — when prompts include specific product attributes, category context, and tone instructions, Magento 2 AI product descriptions are unique, keyword-rich, and significantly better than blank or duplicate descriptions. Always review generated content for accuracy before publishing to live, especially for technical specifications. AI-generated descriptions outperform empty fields and generic placeholder text for both SEO and conversion.

How do I generate Magento 2 AI product descriptions in multiple languages?

Pass the store_id to the generator and include the target language in the system prompt: “Write in French” or “Write in German”. Run the CLI command once per store view: bin/magento caz:ai:generate-descriptions –store=2. The Magento 2 AI product descriptions are saved to the specific store view’s description field and do not overwrite the default store view content.

How do I control the quality of Magento 2 AI product descriptions?

Include rich product data in the prompt — name, SKU, all relevant attributes, category, and target audience. Specify tone, length, and style in the system message. Use a temperature of 0.7 in the API call for creative but consistent output. Review the first batch of Magento 2 AI product descriptions manually and refine the prompt before running it at scale. GPT-4o produces higher quality than GPT-4o mini at roughly 6x the cost per description.

Can I run Magento 2 AI product descriptions generation as a cron job?

Yes — create a Magento cron job that calls the generator service for any product where the description is empty or was last updated before a given date. Set the cron schedule to run nightly during low-traffic hours. Always include a rate limit delay between API calls and a maximum batch size per cron run to stay within OpenAI’s requests-per-minute limits. See our Magento 2 cron job setup guide for the crontab.xml configuration.

How do I prevent Magento 2 AI product descriptions from overwriting manually edited content?

Add a custom product attribute like caz_ai_description_locked (boolean). Set it to true when a product editor manually updates the description. In the generator service and CLI command, check this flag before generating: skip the product if locked is true. This lets editors protect specific descriptions while the batch process continues to fill in the remaining blank Magento 2 AI product descriptions automatically.

Need AI Content Generation for Your Magento Store?

CodeAtoZ builds Magento 2 AI product description modules — batch CLI generation, admin UI, multi-language, and GPT model selection.

CodeAtoZ
Lead Engineer & Founder, CodeAtoZ

10+ years building Magento 2 and WooCommerce platforms for high-volume e-commerce businesses. Writes about performance engineering, plugin architecture, and scalable commerce systems.

Join the Discussion

Your email address will not be published. Required fields are marked *