-
Notifications
You must be signed in to change notification settings - Fork 215
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
base: develop
Are you sure you want to change the base?
Conversation
WalkthroughThis 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
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
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
Assessment against linked issues
Assessment against linked issues: Out-of-scope changes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
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.phpERROR: Referenced sniff "PHPCompatibilityWP" does not exist Run "phpcs --help" for usage information includes/Intelligence/Admin/Settings.phpERROR: Referenced sniff "PHPCompatibilityWP" does not exist Run "phpcs --help" for usage information includes/Intelligence/REST/AIRequestController.phpERROR: Referenced sniff "PHPCompatibilityWP" does not exist Run "phpcs --help" for usage information
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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:
- The
mixed
return type is quite broad - consider using a more specific type or union type to better define expected return values- No guidance on error handling - consider documenting expected exceptions or error return patterns
- 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:
- Consider the same type safety improvements (more specific return types)
- Add similar error handling documentation
- 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
: Adddeclare(strict_types=1);
and a file-level docblockAll 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 classesfinal
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 asfinal
to prevent unintended inheritanceSame rationale as the previous class.
-class OpenAIGPTFourOMini extends OpenAIGPTThreeDotFiveTurbo { +final class OpenAIGPTFourOMini extends OpenAIGPTThreeDotFiveTurbo {includes/Intelligence/Services/Models/OpenAIGPTFourTurbo.php (2)
1-3
: Adddeclare(strict_types=1);
& header docblock
5-6
: Preferfinal
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 docblockConsistent with other service classes.
<?php +declare(strict_types=1); + +/** + * Provider: OpenAI + * + * @package dokan-lite + */
30-32
: Default model choice – isgpt-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 togpt-4-turbo
(once verified) or exposing a setting in the UI.
34-36
: Hard-coded URL – add constant or configIf 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 unusedModel
import
use WeDevs\Dokan\Intelligence\Services\Model;
is never referenced, violating WPCSUnusedUse
rule.-use WeDevs\Dokan\Intelligence\Services\Model;
1-3
: Missingdeclare(strict_types=1);
and docblockSame recommendation as for the OpenAI models.
8-9
: Make the classfinal
Lightweight metadata container – inheritance not required.
-class GeminiTwoDotFiveFlash extends GeminiTwoDotFiveFlashLite implements AITextGenerationInterface { +final class GeminiTwoDotFiveFlash extends GeminiTwoDotFiveFlashLite implements AITextGenerationInterface {
10-30
: Mixed tabs and spacesLines 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 importThe
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 parameterThe 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 usingarray_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 IDincludes/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
📒 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 usersThe
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’
inincludes/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 (commonlygpt-4o
or dated suffixes such asgpt-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
: Validategpt-4o-mini
availabilityDouble-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 namegpt-4-turbo
OpenAI’s stable alias was historically
gpt-4-turbo-preview
; newer endpoints usegpt-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 modelThe 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 providersThe 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 versionI 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 updateget_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 architectureThe 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 registrationThe 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-LiteSetting
'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 scenariosIf 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 |
There was a problem hiding this comment.
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.”
- Add a
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."
|
||
public function get_api_key_url(): string { | ||
return 'https://aistudio.google.com/app/apikey'; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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.
$process_call = 'process_' . sanitize_key( $type ); | ||
$response = $model->{$process_call}( $prompt, $args ); |
There was a problem hiding this comment.
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.
$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; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
if ( gettype( $response ) === 'string' ) { | ||
$response = preg_replace( '/^"(.*)"$/', '$1', $response ); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
protected function is_valid_api_kay(): bool { | ||
if ( empty( $this->get_api_key() ) ) { | ||
return false; | ||
} | ||
return true; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
All Submissions:
Changes proposed in this Pull Request:
Related Pull Request(s)
Closes
How to test the changes in this Pull Request:
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:
FOR PR REVIEWER ONLY:
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Refactor