Skip to content

feat: Product image enhancement with AI #2775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

shohag121
Copy link
Member

@shohag121 shohag121 commented Jun 30, 2025

All Submissions:

  • My code follow the WordPress' coding standards
  • My code satisfies feature requirements
  • My code is tested
  • My code passes the PHPCS tests
  • My code has proper inline documentation
  • I've included related pull request(s) (optional)
  • I've included developer documentation (optional)
  • I've added proper labels to this pull request

Changes proposed in this Pull Request:

Related Pull Request(s)

Closes

How to test the changes in this Pull Request:

  • Steps or issue link

Changelog entry

No changelog is needed.

Before Changes

Describe the issue before changes with screenshots(s).

After Changes

Describe the issue after changes with screenshot(s).

Feature Video (optional)

Link of detailed video if this PR is for a feature.

PR Self Review Checklist:

  • Code is not following code style guidelines
  • Bad naming: make sure you would understand your code if you read it a few months from now.
  • KISS: Keep it simple, Sweetie (not stupid!).
  • DRY: Don't Repeat Yourself.
  • Code that is not readable: too many nested 'if's are a bad sign.
  • Performance issues
  • Complicated constructions that need refactoring or comments: code should almost always be self-explanatory.
  • Grammar errors.

FOR PR REVIEWER ONLY:

As a reviewer, your feedback should be focused on the idea, not the person. Seek to understand, be respectful, and focus on constructive dialog.

As a contributor, your responsibility is to learn from suggestions and iterate your pull request should it be needed based on feedback. Seek to collaborate and produce the best possible contribution to the greater whole.

  • Correct — Does the change do what it’s supposed to? ie: code 100% fulfilling the requirements?
  • Secure — Would a nefarious party find some way to exploit this change? ie: everything is sanitized/escaped appropriately for any SQL or XSS injection possibilities?
  • Readable — Will your future self be able to understand this change months down the road?
  • Elegant — Does the change fit aesthetically within the overall style and architecture?

Summary by CodeRabbit

  • New Features

    • Introduced support for multiple AI providers and models, including new Gemini and OpenAI variants.
    • Enhanced AI settings to dynamically display all available providers and models.
    • Added interfaces and structures for text and image generation, enabling future expansion.
  • Improvements

    • Streamlined AI provider and model management for better flexibility and scalability.
    • Improved error handling and configuration for AI requests.
  • Bug Fixes

    • Fixed issues with AI settings not reflecting all available providers or models.
  • Refactor

    • Refactored and modularized AI service codebase for easier maintenance and extensibility.

@shohag121 shohag121 self-assigned this Jun 30, 2025
@shohag121 shohag121 added Needs: Testing This requires further testing Needs: Dev Review It requires a developer review and approval labels Jun 30, 2025
Copy link
Contributor

coderabbitai bot commented Jun 30, 2025

Walkthrough

This update introduces a modular AI provider and model architecture, refactors service registration, and adds interfaces for AI models, providers, and generation types (text, image). It restructures settings and request handling to support multiple AI engines and models, and lays the foundation for image generation features alongside text generation.

Changes

Files/Group Change Summary
includes/DependencyManagement/Providers/IntelligenceServiceProvider.php Refactored to register multiple AI providers/models via loop; added new service classes and use statements.
includes/Intelligence/Admin/Settings.php Refactored AI settings rendering to dynamically support multiple providers/models; added "AI Product Info Generator".
includes/Intelligence/Manager.php Enhanced to support multiple generation types (text, image, video); added provider/model management methods.
includes/Intelligence/REST/AIRequestController.php Refactored request handling to use provider/model system; removed EngineFactory.
includes/Intelligence/Services/AIImageGenerationInterface.php Added interface for image generation models.
includes/Intelligence/Services/AIModelInterface.php Added interface for AI models with metadata and capability checks.
includes/Intelligence/Services/AIProviderInterface.php Added interface for AI providers with metadata and model management.
includes/Intelligence/Services/AITextGenerationInterface.php Added interface for text generation models.
includes/Intelligence/Services/Model.php Added abstract base class for AI models, with support type logic and request handling.
includes/Intelligence/Services/Provider.php Added abstract base class for AI providers, with model management and hook integration.
includes/Intelligence/Services/Providers/Gemini.php, .../OpenAI.php Added Gemini and OpenAI provider classes with metadata methods.
includes/Intelligence/Services/Models/GeminiTwoDotFiveFlash.php, ... (all new model classes) Added new model classes for Gemini and OpenAI variants, each with metadata methods.
includes/Intelligence/Services/Models/GeminiTwoDotFiveFlashLite.php Refactored and renamed from GeminiResponseService; implements new interfaces and extends Model.
includes/Intelligence/Services/Models/OpenAIGPTThreeDotFiveTurbo.php Refactored and renamed from ChatgptResponseService; implements new interfaces and extends Model.
includes/Intelligence/Services/AIServiceInterface.php, .../BaseAIService.php, .../EngineFactory.php Deleted legacy AI service interface, base class, and engine factory.

Sequence Diagram(s)

sequenceDiagram
    participant Admin as Admin UI
    participant Settings as Settings
    participant Manager as Manager
    participant Provider as AIProvider
    participant Model as AIModel

    Admin->>Settings: render_ai_settings()
    Settings->>Manager: get_text_supported_providers()
    Manager->>Provider: get_models()
    Provider->>Model: get_id(), get_title(), get_description()
    Settings-->>Admin: Render dynamic provider/model fields
Loading
sequenceDiagram
    participant REST as REST API
    participant Manager as Manager
    participant Provider as AIProvider
    participant Model as AIModel

    REST->>Manager: get_provider(provider_id)
    Manager->>Provider: get_model(model_id)
    REST->>Model: process_text(prompt, args)
    Model->>Model: request(prompt, args)
    Model-->>REST: AI response
Loading

Assessment against linked issues

Objective Addressed Explanation
Admin Setting: Add "AI Product Info Generator" section and dynamic AI provider/model settings (1-12) (#4473)
Vendor End: Enable "Enhance" button and flow for image enhancement, prompt merging, and API connection (#4473) Only backend/provider/model infrastructure and admin settings are present; vendor UI and image flow missing.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
None found

Possibly related PRs

  • Dokan AI #2555: Refactored and introduced the initial structure for IntelligenceServiceProvider, upon which this PR directly builds.

Suggested labels

PM Dependency, Bump Version

Suggested reviewers

  • mrabbani

Poem

A rabbit hops through code so bright,
With models, providers, all in sight.
Gemini and OpenAI now join the show,
Settings dynamic, engines in tow.
From text to image, new features bloom—
This fluffy coder cheers: more AI soon!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 phpcs (3.7.2)
includes/DependencyManagement/Providers/IntelligenceServiceProvider.php

ERROR: Referenced sniff "PHPCompatibilityWP" does not exist

Run "phpcs --help" for usage information

includes/Intelligence/Admin/Settings.php

ERROR: Referenced sniff "PHPCompatibilityWP" does not exist

Run "phpcs --help" for usage information

includes/Intelligence/REST/AIRequestController.php

ERROR: Referenced sniff "PHPCompatibilityWP" does not exist

Run "phpcs --help" for usage information

  • 17 others
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🔭 Outside diff range comments (3)
includes/Intelligence/Services/Models/OpenAIGPTThreeDotFiveTurbo.php (1)

108-133: Make the system prompt configurable instead of hardcoding e-commerce specific instructions.

The hardcoded system prompt is overly specific to e-commerce product descriptions and limits the model's flexibility for other use cases. Consider making it configurable through settings or accepting it as a parameter.

Apply this diff to make the system prompt configurable:

         if ( isset( $args['json_format'] ) ) {
+            $default_system_prompt = 'You are an AI assistant. Always return the response in strict JSON format without any markdown or special characters.';
+            $system_prompt = apply_filters( 'dokan_ai_openai_system_prompt', $default_system_prompt, $prompt, $args );
+            
             array_unshift(
                 $messages, [
                     'role' => 'system',
-                    'content' => 'You are an AI assistant specializing in WooCommerce and e-commerce product.
-                    Your task is to generate SEO-optimized content that helps increase sales and search rankings.
-                    Always return the response in strict JSON format without any markdown or special characters.
-                    Format the response as follows:
-                    {
-                      "title": "<Compelling product title optimized for SEO>",
-                      "short_description": "<A concise, keyword-rich summary (minimum 80-150 words) that attracts buyers and improves search engine visibility>",
-                      "long_description": "<A detailed, engaging product long description including features, benefits, use cases, and persuasive copywriting techniques>"
-                    }
-
-                    Guidelines:
-                    — Output language should be the same as the input language strictly matching the prompt.
-                    — Using <p></p> tags for paragraphs instead of newlines.
-                    — Do not use Markdown formatting (** or `#` or `>` characters).
-                    — Do not include backticks (```json or ```) or any non-JSON syntax.
-                    — Do not add extra commentary or explanations—only return the JSON object.
-                    — Ensure readability with short sentences, bullet points, and clear formatting.
-                    — Highlight key features (if need), unique selling points, and benefits.
-                    — Output should be a valid JSON object with the keys: title, short_description, long_description.',
+                    'content' => $system_prompt,
                 ],
             );
         }
includes/Intelligence/Services/Models/GeminiTwoDotFiveFlashLite.php (2)

69-93: Extract duplicated system prompt to a shared location.

The hardcoded system prompt for JSON format is duplicated across multiple model implementations (OpenAI and Gemini). This violates the DRY principle and makes maintenance difficult.

Consider creating a shared trait or helper class for common AI prompts:

// In a new file: includes/Intelligence/Services/Traits/AIPromptsTrait.php
trait AIPromptsTrait {
    protected function getProductDescriptionSystemPrompt(): string {
        return apply_filters( 'dokan_ai_product_description_system_prompt', 
            'You are an AI assistant specializing in WooCommerce and e-commerce product...'
        );
    }
}

Then use it in your model classes:

+use WeDevs\Dokan\Intelligence\Services\Traits\AIPromptsTrait;
+
 class GeminiTwoDotFiveFlashLite extends Model implements AITextGenerationInterface {
+    use AIPromptsTrait;
+    
     // ... other code ...
     
     protected function get_payload( string $prompt, array $args = [] ): array {
         if ( isset( $args['json_format'] ) ) {
-            $pre_prompt = 'You are an AI assistant specializing in WooCommerce and e-commerce product...';
+            $pre_prompt = $this->getProductDescriptionSystemPrompt();
             $prompt = $pre_prompt . PHP_EOL . $prompt;
         }

135-137: Remove unnecessary quote stripping logic.

Similar to the OpenAI model, this quote stripping logic could corrupt valid JSON strings that legitimately contain quotes.

Apply this diff:

-        // if response type of string
-        if ( gettype( $response ) === 'string' ) {
-            $response = preg_replace( '/^"(.*)"$/', '$1', $response );
-        }
🧹 Nitpick comments (19)
includes/Intelligence/Services/AIImageGenerationInterface.php (1)

5-15: Consider improving type safety and error handling guidance.

The interface design is clean, but there are opportunities for improvement:

  1. The mixed return type is quite broad - consider using a more specific type or union type to better define expected return values
  2. No guidance on error handling - consider documenting expected exceptions or error return patterns
  3. The $prompt parameter lacks validation constraints (e.g., non-empty string requirements)

Consider this more specific approach:

interface AIImageGenerationInterface {
    /**
     * Process the image prompt and return the generated image.
     *
     * @param string $prompt The input prompt for the AI model (must not be empty).
     * @param array $args Optional additional data.
-    * @return mixed The generated image from the AI model.
+    * @return array|string The generated image data (URL, base64, or structured response).
+    * @throws \InvalidArgumentException When prompt is empty or invalid.
+    * @throws \RuntimeException When image generation fails.
     */
-   public function process_image( string $prompt, array $args = [] );
+   public function process_image( string $prompt, array $args = [] ): array|string;
}
includes/Intelligence/Services/AITextGenerationInterface.php (1)

5-15: Apply consistent improvements with AIImageGenerationInterface.

This interface has identical design considerations as AIImageGenerationInterface. For consistency:

  1. Consider the same type safety improvements (more specific return types)
  2. Add similar error handling documentation
  3. Include parameter validation guidance

Additionally, given the structural similarity between text and image generation interfaces, consider whether a base interface would be beneficial:

+interface AIGenerationInterface {
+    /**
+     * Process the prompt and return the generated content.
+     *
+     * @param string $prompt The input prompt for the AI model.
+     * @param array $args Optional additional data.
+     * @return mixed The generated content from the AI model.
+     */
+    public function process( string $prompt, array $args = [] );
+}
+
-interface AITextGenerationInterface {
+interface AITextGenerationInterface extends AIGenerationInterface {
    /**
     * Process the text prompt and return the generated response.
     */
-   public function process_text( string $prompt, array $args = [] );
+   public function process_text( string $prompt, array $args = [] ): string;
}
includes/Intelligence/Services/Models/OpenAIChatGPTFourO.php (2)

1-3: Add declare(strict_types=1); and a file-level docblock

All new model files omit strict_types. Enabling strict typing avoids silent coercions and aligns with modern PHP best practices.
Likewise, a short docblock (author, purpose) helps future maintainers.

 <?php
+declare(strict_types=1);
+
+/**
+ * Model: OpenAI ChatGPT-4o
+ *
+ * @package dokan-lite
+ */

5-12: Consider making lightweight metadata classes final

These classes only provide constants; subclassing them brings no benefit and can introduce accidental overrides. Marking them final signals intent and allows small opcache optimisations.

-class OpenAIChatGPTFourO extends OpenAIGPTThreeDotFiveTurbo {
+final class OpenAIChatGPTFourO extends OpenAIGPTThreeDotFiveTurbo {
includes/Intelligence/Services/Models/OpenAIGPTFourOMini.php (2)

1-3: Apply strict types & docblock (same as other model files)


5-6: Mark as final to prevent unintended inheritance

Same rationale as the previous class.

-class OpenAIGPTFourOMini extends OpenAIGPTThreeDotFiveTurbo {
+final class OpenAIGPTFourOMini extends OpenAIGPTThreeDotFiveTurbo {
includes/Intelligence/Services/Models/OpenAIGPTFourTurbo.php (2)

1-3: Add declare(strict_types=1); & header docblock


5-6: Prefer final keyword for constant-only classes

-class OpenAIGPTFourTurbo extends OpenAIGPTThreeDotFiveTurbo {
+final class OpenAIGPTFourTurbo extends OpenAIGPTThreeDotFiveTurbo {
includes/Intelligence/Services/Providers/OpenAI.php (3)

1-3: Enable strict types & add file docblock

Consistent with other service classes.

 <?php
+declare(strict_types=1);
+
+/**
+ * Provider: OpenAI
+ *
+ * @package dokan-lite
+ */

30-32: Default model choice – is gpt-3.5-turbo still intended?

With several GPT-4* variants bundled, shipping the 3.5 model as default may surprise users expecting the newest capabilities.
Consider elevating the default to gpt-4-turbo (once verified) or exposing a setting in the UI.


34-36: Hard-coded URL – add constant or config

If the OpenAI dashboard URL ever changes, having it duplicated in code is brittle.
Suggest extracting to a class constant or configuration option.

-    public function get_api_key_url(): string {
-        return 'https://platform.openai.com/api-keys';
-    }
+    public function get_api_key_url(): string {
+        return self::API_KEY_URL;
+    }
+
+    private const API_KEY_URL = 'https://platform.openai.com/api-keys';
includes/Intelligence/Services/Models/GeminiTwoDotFiveFlash.php (4)

5-6: Remove unused Model import

use WeDevs\Dokan\Intelligence\Services\Model; is never referenced, violating WPCS UnusedUse rule.

-use WeDevs\Dokan\Intelligence\Services\Model;

1-3: Missing declare(strict_types=1); and docblock

Same recommendation as for the OpenAI models.


8-9: Make the class final

Lightweight metadata container – inheritance not required.

-class GeminiTwoDotFiveFlash extends GeminiTwoDotFiveFlashLite implements AITextGenerationInterface {
+final class GeminiTwoDotFiveFlash extends GeminiTwoDotFiveFlashLite implements AITextGenerationInterface {

10-30: Mixed tabs and spaces

Lines 10-30 use tabs, earlier lines use spaces. This will be flagged by PHPCS Generic.WhiteSpace.DisallowTabIndent. Convert to spaces for consistency.

includes/Intelligence/Services/Models/GeminiTwoDotFivePro.php (1)

6-6: Remove unused import

The Model class is imported but not used in this file.

-use WeDevs\Dokan\Intelligence\Services\Model;
includes/Intelligence/Services/AIProviderInterface.php (1)

69-69: Fix documentation to match the generic parameter

The comment mentions "text models" but the method accepts any model type as a parameter.

-     * @return bool True if text models are supported, false otherwise.
+     * @return bool True if models of the specified type are supported, false otherwise.
includes/Intelligence/Services/Provider.php (1)

52-53: Clean up commented code.

Remove the commented array_find code since it's not available in older PHP versions and the current implementation using array_filter works correctly.

-        // $model = array_find( $models, fn( $model, $key ) => $model->get_id() === $model_id );
-        // Using array_filter to find the model by ID
+        // Using array_filter to find the model by ID
includes/Intelligence/Manager.php (1)

149-166: Consider adding PHPDoc for the switch cases.

The get_type_prefix method would benefit from documenting why certain types have prefixes while text doesn't.

     /**
      * Get the type prefix for the given generation type.
      *
+     * Text generation uses no prefix for backward compatibility,
+     * while other types use prefixes to namespace their settings.
+     *
      * @param string $type The type of generation (e.g., 'text', 'image', 'video').
      *
      * @return string The prefix for the type.
      */
     public function get_type_prefix( string $type ): string {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97b88e3 and f981eb6.

📒 Files selected for processing (23)
  • includes/DependencyManagement/Providers/IntelligenceServiceProvider.php (2 hunks)
  • includes/Intelligence/Admin/Settings.php (2 hunks)
  • includes/Intelligence/Manager.php (2 hunks)
  • includes/Intelligence/REST/AIRequestController.php (2 hunks)
  • includes/Intelligence/Services/AIImageGenerationInterface.php (1 hunks)
  • includes/Intelligence/Services/AIModelInterface.php (1 hunks)
  • includes/Intelligence/Services/AIProviderInterface.php (1 hunks)
  • includes/Intelligence/Services/AIServiceInterface.php (0 hunks)
  • includes/Intelligence/Services/AITextGenerationInterface.php (1 hunks)
  • includes/Intelligence/Services/BaseAIService.php (0 hunks)
  • includes/Intelligence/Services/EngineFactory.php (0 hunks)
  • includes/Intelligence/Services/Model.php (1 hunks)
  • includes/Intelligence/Services/Models/GeminiTwoDotFiveFlash.php (1 hunks)
  • includes/Intelligence/Services/Models/GeminiTwoDotFiveFlashLite.php (3 hunks)
  • includes/Intelligence/Services/Models/GeminiTwoDotFivePro.php (1 hunks)
  • includes/Intelligence/Services/Models/OpenAIChatGPTFourO.php (1 hunks)
  • includes/Intelligence/Services/Models/OpenAIGPTFourO.php (1 hunks)
  • includes/Intelligence/Services/Models/OpenAIGPTFourOMini.php (1 hunks)
  • includes/Intelligence/Services/Models/OpenAIGPTFourTurbo.php (1 hunks)
  • includes/Intelligence/Services/Models/OpenAIGPTThreeDotFiveTurbo.php (2 hunks)
  • includes/Intelligence/Services/Provider.php (1 hunks)
  • includes/Intelligence/Services/Providers/Gemini.php (1 hunks)
  • includes/Intelligence/Services/Providers/OpenAI.php (1 hunks)
💤 Files with no reviewable changes (3)
  • includes/Intelligence/Services/EngineFactory.php
  • includes/Intelligence/Services/AIServiceInterface.php
  • includes/Intelligence/Services/BaseAIService.php
🧰 Additional context used
🧬 Code Graph Analysis (2)
includes/Intelligence/Services/AIProviderInterface.php (4)
includes/Intelligence/Services/AIModelInterface.php (3)
  • get_id (20-20)
  • get_title (27-27)
  • get_description (34-34)
includes/Intelligence/Services/Providers/OpenAI.php (4)
  • get_id (12-14)
  • get_title (19-21)
  • get_description (26-28)
  • get_api_key_url (34-36)
includes/Intelligence/Services/Providers/Gemini.php (4)
  • get_id (12-14)
  • get_title (19-21)
  • get_description (26-28)
  • get_api_key_url (35-37)
includes/Intelligence/Services/Provider.php (8)
  • get_id (25-25)
  • get_title (30-30)
  • get_description (35-35)
  • get_api_key_url (37-37)
  • get_models (42-44)
  • get_model (49-63)
  • get_default_model (68-72)
  • has_model (79-90)
includes/Intelligence/Services/Models/OpenAIGPTFourOMini.php (2)
includes/Intelligence/Services/Models/OpenAIGPTThreeDotFiveTurbo.php (4)
  • OpenAIGPTThreeDotFiveTurbo (8-140)
  • get_id (15-17)
  • get_title (22-24)
  • get_description (29-31)
includes/Intelligence/Services/Model.php (3)
  • get_id (57-57)
  • get_title (64-64)
  • get_description (71-71)
🪛 PHPMD (2.15.0)
includes/Intelligence/REST/AIRequestController.php

94-94: Avoid using static access to class '\WeDevs\Dokan\Intelligence\Utils\PromptUtils' in method 'handle_request'. (Clean Code Rules)

(StaticAccess)

⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: e2e tests (2, 3)
  • GitHub Check: e2e tests (3, 3)
  • GitHub Check: e2e tests (1, 3)
  • GitHub Check: api tests (1, 1)
🔇 Additional comments (20)
includes/Intelligence/Services/Models/OpenAIGPTFourO.php (1)

5-27: LGTM! Clean model implementation.

The class correctly extends the base OpenAI model and properly overrides the metadata methods. The use of WordPress localization functions is appropriate, and the model ID follows OpenAI's naming convention.

includes/Intelligence/Services/AIModelInterface.php (1)

14-49: Excellent interface design with comprehensive model contract.

This interface provides a well-thought-out contract for AI models with:

  • Clear metadata methods for model identification and description
  • Flexible supports() method for checking generation type capabilities
  • Proper documentation with package and version information
  • Clean method signatures with appropriate return types

The design supports the modular architecture goals effectively.

includes/Intelligence/Admin/Settings.php (5)

45-45: Excellent refactoring to dynamic provider management.

The move from hardcoded providers to dynamic retrieval using the Manager is a great improvement that supports the new modular architecture.


48-54: Good addition of AI Product Info subsection.

The new subsection provides clear organization for AI product generation features, aligning with the PR objectives for product image enhancement.


69-101: Clean dynamic field generation implementation.

The dynamic generation of API key and model selection fields is well-implemented:

  • Proper use of provider metadata
  • Correct conditional field display logic
  • Good use of modern PHP arrow functions

103-103: Good practice adding filter hook for extensibility.

The addition of the dokan_ai_settings_fields filter allows for further customization of AI settings, which is excellent for extensibility.


59-67: Default engine change is safe for existing users

The default => 'openai' value is only used when no prior setting exists—any installation that has already selected “chatgpt” will continue using that stored value. We only see one hardcoded return of ‘chatgpt-4o-latest’ in includes/Intelligence/Services/Models/OpenAIChatGPTFourO.php, which pertains to the model ID and does not affect the provider default. No migration strategy is required.

includes/Intelligence/Services/Models/OpenAIChatGPTFourO.php (1)

5-12: Confirm model identifier accuracy

chatgpt-4o-latest is not an official model ID in OpenAI’s public docs (commonly gpt-4o or dated suffixes such as gpt-4o-2024-05-13).
If the back-end passes this literal string to the API, requests will fail with “model_not_found”.

Please verify against the current OpenAI reference and adjust accordingly.

includes/Intelligence/Services/Models/OpenAIGPTFourOMini.php (1)

10-12: Validate gpt-4o-mini availability

Double-check that gpt-4o-mini is accepted by the OpenAI endpoint; at time of writing it is still in limited beta.
If the ID is wrong, downstream 404/400 errors will occur.
Run an integration smoke test or feature flag the model until it is generally available.

includes/Intelligence/Services/Models/OpenAIGPTFourTurbo.php (1)

10-12: Re-check the model name gpt-4-turbo

OpenAI’s stable alias was historically gpt-4-turbo-preview; newer endpoints use gpt-4o variants. Please confirm the exact string to avoid runtime failures.

includes/Intelligence/Services/Models/GeminiTwoDotFivePro.php (1)

8-30: LGTM! Clean implementation of the Gemini 2.5 Pro model

The class properly extends the base model and provides appropriate metadata through well-structured methods with proper localization.

includes/Intelligence/Services/AIProviderInterface.php (1)

14-72: Well-designed interface for AI providers

The interface provides a clean contract with comprehensive methods for provider metadata, model management, and type checking. The structure promotes extensibility and follows interface segregation principles.

includes/Intelligence/Services/Providers/Gemini.php (1)

30-32: Confirm the correct default Gemini model version

I didn’t find any local model implementations for a 2.5-series Gemini ID—only get_default_model_id() returns 'gemini-2.0-flash'. Please verify which Gemini version should be the default and:

  • If you intend to switch to a 2.5 model, add or import the corresponding model classes in includes/Intelligence/Services/Models/ and update get_default_model_id().
  • Otherwise, keep the default as 'gemini-2.0-flash', since no 2.5 models are present locally.
includes/Intelligence/REST/AIRequestController.php (1)

78-96: Well-structured refactoring to use the new provider/model architecture

The implementation properly resolves providers and models based on configuration, with appropriate error handling for misconfiguration scenarios. The dynamic type support makes the system extensible.

includes/DependencyManagement/Providers/IntelligenceServiceProvider.php (1)

43-48: Clean refactoring of service registration

The loop-based registration approach reduces code duplication and makes it easier to add new services in the future. Good application of DRY principle.

includes/Intelligence/Services/Models/OpenAIGPTThreeDotFiveTurbo.php (1)

12-39: LGTM! Well-structured metadata methods.

The metadata methods are properly implemented with appropriate return values and follow the interface contract.

includes/Intelligence/Services/Provider.php (1)

42-137: Well-structured provider implementation with good extensibility.

The provider class provides a solid foundation with:

  • Proper use of filters for extensibility
  • Clean separation of concerns
  • Efficient model filtering and retrieval methods
  • Proper hook registration pattern
includes/Intelligence/Services/Models/GeminiTwoDotFiveFlashLite.php (1)

113-115: Confirm thinkingConfig Behavior for Gemini 2.5 Flash-Lite

Setting

'thinkingConfig' => [
    'thinkingBudget' => 0,
],

turns off the model’s internal “thinking” phase for Gemini 2.5 Flash-Lite, yielding faster, lower-cost responses at the expense of deeper reasoning.

• File: includes/Intelligence/Services/Models/GeminiTwoDotFiveFlashLite.php (lines 113–115)
• Effect: disables all “thinking” tokens for this model
• Intended use case: simple or latency-sensitive scenarios

If you require more thorough reasoning, consider increasing thinkingBudget (e.g., 512 or 1024). Otherwise, no changes are needed.

includes/Intelligence/Services/Model.php (1)

1-206: Well-architected base model class.

The abstract Model class provides an excellent foundation with:

  • Clear separation of abstract and concrete methods
  • Proper constants for generation types
  • Comprehensive error handling
  • Good use of WordPress filters for extensibility

The only issue is the typo mentioned in the previous comment.

includes/Intelligence/Manager.php (1)

1-167: Excellent Manager implementation with clear separation of concerns.

The Manager class effectively handles:

  • Multi-type AI engine management
  • Provider discovery and filtering
  • Type-specific configuration
  • Extensibility through WordPress filters

Great architectural design that supports the new AI provider system.

* It includes methods to retrieve provider details, models, and check model types.
*
* @package WeDevs\Dokan\Intelligence\Services
* @since DOKAN_SINCE
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Replace DOKAN_SINCE placeholder with actual version

The @since tag contains a placeholder that needs to be replaced with the actual version number.


🏁 Script executed:

#!/bin/bash
# Search for other occurrences of DOKAN_SINCE to understand the versioning pattern
rg "DOKAN_SINCE" --type php -A 2 -B 2

Length of output: 3962


Here’s the interface’s top 200 lines so we can confirm the doc inconsistency around the type parameter:


🏁 Script executed:

#!/bin/bash
sed -n '1,200p' includes/Intelligence/Services/AIProviderInterface.php

Length of output: 1938


Replace DOKAN_SINCE placeholder with actual version and correct has_model PHPDoc

  • In includes/Intelligence/Services/AIProviderInterface.php, update the file-level @since DOKAN_SINCE to your current release (e.g. @since 3.7.0).
  • In the has_model() docblock:
    • Add a @param string $type description.
    • Change the @return description from “True if text models are supported” to “True if models of the specified type are supported.”

Suggested diff:

--- a/includes/Intelligence/Services/AIProviderInterface.php
+++ b/includes/Intelligence/Services/AIProviderInterface.php
@@
- * @since DOKAN_SINCE
+ * @since 3.x.x
@@
-    /**
-     * Check if the provider supports type-based models.
-     *
-     * @return bool True if text models are supported, false otherwise.
-     */
+    /**
+     * Check if the provider supports models of a given type.
+     *
+     * @param string $type The model type to check support for.
+     * @return bool True if models of the specified type are supported, false otherwise.
+     */
🤖 Prompt for AI Agents
In includes/Intelligence/Services/AIProviderInterface.php at line 12, replace
the placeholder @since DOKAN_SINCE with the actual release version, for example
@since 3.7.0. Also, locate the has_model() method's PHPDoc and add a @param
string $type description, then update the @return description to "True if models
of the specified type are supported" instead of the current "True if text models
are supported."

Comment on lines +34 to +37

public function get_api_key_url(): string {
return 'https://aistudio.google.com/app/apikey';
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix indentation to use tabs consistently

Line 35 uses spaces instead of tabs, which is inconsistent with the rest of the file.

-
-
-    public function get_api_key_url(): string {
+
+	public function get_api_key_url(): string {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public function get_api_key_url(): string {
return 'https://aistudio.google.com/app/apikey';
}
public function get_api_key_url(): string {
return 'https://aistudio.google.com/app/apikey';
}
🤖 Prompt for AI Agents
In includes/Intelligence/Services/Providers/Gemini.php around lines 34 to 37,
the indentation on line 35 uses spaces instead of tabs, causing inconsistency
with the rest of the file. Replace the spaces at the beginning of line 35 with
tabs to match the file's indentation style.

Comment on lines +95 to +96
$process_call = 'process_' . sanitize_key( $type );
$response = $model->{$process_call}( $prompt, $args );
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Validate dynamic method exists before calling

The dynamic method call could throw a fatal error if the method doesn't exist on the model. Consider adding validation.

 $process_call = 'process_' . sanitize_key( $type );
+if ( ! method_exists( $model, $process_call ) ) {
+    throw new Exception(
+        sprintf( esc_html__( 'Model does not support %s generation.', 'dokan-lite' ), $type ),
+        400
+    );
+}
 $response     = $model->{$process_call}( $prompt, $args );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$process_call = 'process_' . sanitize_key( $type );
$response = $model->{$process_call}( $prompt, $args );
$process_call = 'process_' . sanitize_key( $type );
if ( ! method_exists( $model, $process_call ) ) {
throw new Exception(
sprintf( esc_html__( 'Model does not support %s generation.', 'dokan-lite' ), $type ),
400
);
}
$response = $model->{$process_call}( $prompt, $args );
🤖 Prompt for AI Agents
In includes/Intelligence/REST/AIRequestController.php around lines 95 to 96, the
code dynamically calls a method on the model without checking if it exists,
which can cause a fatal error. Before calling the method, use method_exists or
is_callable to verify that the method named by $process_call exists on the
$model object. If the method does not exist, handle the situation gracefully,
such as returning an error response or throwing an exception, to prevent runtime
errors.

use WeDevs\Dokan\Intelligence\Services\Models\OpenAIChatGPTFourO;
use WeDevs\Dokan\Intelligence\Services\Models\OpenAIGPTFourO;
use WeDevs\Dokan\Intelligence\Services\Models\OpenAIGPTFourOMini;
use WeDevs\Dokan\Intelligence\Services\Models\OpenAIGPTThreeDotFiveTurbo;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

OpenAIGPTFourTurbo is imported but not registered

The OpenAIGPTFourTurbo class is imported but not included in the $services array. Either remove the import or add it to the services array.

Either remove the unused import:

-use WeDevs\Dokan\Intelligence\Services\Models\OpenAIGPTFourTurbo;

Or add it to the services array:

 OpenAIGPTThreeDotFiveTurbo::class,
+OpenAIGPTFourTurbo::class,
 OpenAIGPTFourOMini::class,

Also applies to: 25-38

🤖 Prompt for AI Agents
In includes/DependencyManagement/Providers/IntelligenceServiceProvider.php
around lines 15 and 25 to 38, the OpenAIGPTFourTurbo class is imported but not
registered in the $services array. To fix this, either remove the unused import
statement for OpenAIGPTFourTurbo or add the OpenAIGPTFourTurbo class to the
$services array to ensure it is properly registered and used.

Comment on lines +81 to +83
if ( gettype( $response ) === 'string' ) {
$response = preg_replace( '/^"(.*)"$/', '$1', $response );
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Remove unnecessary quote stripping that could corrupt valid data.

The regex pattern /^"(.*)"$/ strips quotes from the beginning and end of strings, which could corrupt valid JSON strings that legitimately contain quotes. OpenAI's API returns properly formatted JSON, so this manipulation is unnecessary and potentially harmful.

Apply this diff to remove the problematic quote stripping:

-        // if response type of string
-        if ( gettype( $response ) === 'string' ) {
-            $response = preg_replace( '/^"(.*)"$/', '$1', $response );
-        }
+        // Response is already in the correct format from OpenAI API

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In includes/Intelligence/Services/Models/OpenAIGPTThreeDotFiveTurbo.php around
lines 81 to 83, remove the conditional block that checks if $response is a
string and strips quotes using preg_replace. This quote stripping is unnecessary
and can corrupt valid JSON data returned by OpenAI's API. Simply delete these
lines to avoid altering the response string.

Comment on lines +160 to +165
protected function is_valid_api_kay(): bool {
if ( empty( $this->get_api_key() ) ) {
return false;
}
return true;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix typo in method name: is_valid_api_kay should be is_valid_api_key.

There's a typo in the method name that makes the code less professional and could cause confusion.

Apply this diff:

-    protected function is_valid_api_kay(): bool {
+    protected function is_valid_api_key(): bool {
         if ( empty( $this->get_api_key() ) ) {
             return false;
         }
         return true;
     }

     // ... other code ...

     protected function request( string $prompt, array $args = [] ): array {
-        if ( ! $this->is_valid_api_kay() ) {
+        if ( ! $this->is_valid_api_key() ) {
             throw new Exception( esc_html__( 'API key is not configured', 'dokan-lite' ) );
         }

Also applies to: 177-177

🤖 Prompt for AI Agents
In includes/Intelligence/Services/Model.php at lines 160-165 and line 177,
rename the method is_valid_api_kay to is_valid_api_key to fix the typo. Update
all references to this method accordingly to maintain consistency and avoid
confusion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs: Dev Review It requires a developer review and approval Needs: Testing This requires further testing
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant