Skip to content

Commit 15ac3c2

Browse files
Copilotswissspidy
andauthored
Add wp ai is-supported command (#13)
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: Pascal Birchler <pascalb@google.com>
1 parent 27cf619 commit 15ac3c2

4 files changed

Lines changed: 197 additions & 17 deletions

File tree

‎composer.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
"ai",
3232
"ai check",
3333
"ai generate",
34+
"ai is-supported",
3435
"ai status",
3536
"connectors",
3637
"connectors get",

‎features/generate.feature‎

Lines changed: 92 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ Feature: Generate AI content
77
<?php
88
99
use WordPress\AiClient\AiClient;
10+
use WordPress\AiClient\Files\DTO\File;
11+
use WordPress\AiClient\Files\Enums\FileTypeEnum;
12+
use WordPress\AiClient\Files\Enums\MediaOrientationEnum;
1013
use WordPress\AiClient\Messages\DTO\MessagePart;
1114
use WordPress\AiClient\Messages\DTO\ModelMessage;
1215
use WordPress\AiClient\Messages\Enums\ModalityEnum;
@@ -17,6 +20,7 @@ Feature: Generate AI content
1720
use WordPress\AiClient\Providers\Enums\ProviderTypeEnum;
1821
use WordPress\AiClient\Providers\Models\Contracts\ModelInterface;
1922
use WordPress\AiClient\Providers\Models\TextGeneration\Contracts\TextGenerationModelInterface;
23+
use WordPress\AiClient\Providers\Models\ImageGeneration\Contracts\ImageGenerationModelInterface;
2024
use WordPress\AiClient\Providers\Models\DTO\ModelConfig;
2125
use WordPress\AiClient\Providers\Models\DTO\ModelMetadata;
2226
use WordPress\AiClient\Providers\Models\DTO\SupportedOption;
@@ -26,13 +30,12 @@ Feature: Generate AI content
2630
use WordPress\AiClient\Results\DTO\GenerativeAiResult;
2731
use WordPress\AiClient\Results\DTO\TokenUsage;
2832
use WordPress\AiClient\Results\Enums\FinishReasonEnum;
29-
use WordPress\AI_Client\API_Credentials\API_Credentials_Manager;
3033
3134
if ( ! interface_exists( 'WordPress\AiClient\Providers\Models\Contracts\ModelInterface' ) ) {
3235
return;
3336
}
3437
35-
class WP_CLI_Mock_Model implements ModelInterface, TextGenerationModelInterface {
38+
class WP_CLI_Mock_Model implements ModelInterface, TextGenerationModelInterface, ImageGenerationModelInterface {
3639
private $id;
3740
private $config;
3841
@@ -52,19 +55,28 @@ Feature: Generate AI content
5255
],
5356
// Supported options.
5457
[
55-
new SupportedOption(
56-
OptionEnum::inputModalities(),
57-
[
58-
[ModalityEnum::text()]
59-
]
60-
),
58+
new SupportedOption(OptionEnum::candidateCount()),
59+
new SupportedOption(OptionEnum::outputMimeType(), ['image/png']),
60+
new SupportedOption(OptionEnum::outputFileType(), [FileTypeEnum::inline()]),
61+
new SupportedOption(OptionEnum::inputModalities(), [[ModalityEnum::text()]]),
6162
new SupportedOption(
6263
OptionEnum::outputModalities(),
6364
[
6465
[ModalityEnum::text()],
66+
[ModalityEnum::image()],
6567
[ModalityEnum::text(), ModalityEnum::image()],
6668
]
6769
),
70+
new SupportedOption(OptionEnum::candidateCount()),
71+
new SupportedOption(OptionEnum::outputMimeType(), ['image/png']),
72+
new SupportedOption(OptionEnum::outputFileType(), [FileTypeEnum::inline(), FileTypeEnum::remote()]),
73+
new SupportedOption(OptionEnum::outputMediaOrientation(), [
74+
MediaOrientationEnum::square(),
75+
MediaOrientationEnum::landscape(),
76+
MediaOrientationEnum::portrait(),
77+
]),
78+
new SupportedOption(OptionEnum::outputMediaAspectRatio(), ['1:1', '7:4', '4:7']),
79+
new SupportedOption(OptionEnum::customOptions()),
6880
]
6981
);
7082
}
@@ -85,14 +97,14 @@ Feature: Generate AI content
8597
// throw new RuntimeException('No candidates were generated');
8698
8799
$modelMessage = new ModelMessage([
88-
new MessagePart('Generated content')
100+
new MessagePart('This is mock-generated text')
89101
]);
90102
$candidate = new Candidate(
91103
$modelMessage,
92104
FinishReasonEnum::stop(),
93105
42
94106
);
95-
$tokenUsage = new TokenUsage(10, 42, 52);
107+
$tokenUsage = new TokenUsage( 10, 42, 52 );
96108
return new GenerativeAiResult(
97109
'result_123',
98110
[ $candidate ],
@@ -106,6 +118,35 @@ Feature: Generate AI content
106118
public function streamGenerateTextResult(array $prompt): Generator {
107119
yield from [];
108120
}
121+
122+
public function generateImageResult(array $prompt): GenerativeAiResult {
123+
// throw new RuntimeException('No candidates were generated');
124+
125+
$modelMessage = new ModelMessage( [
126+
new MessagePart(
127+
// A base64-encoded 1x1 black PNG.
128+
new File(
129+
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=',
130+
'image/png'
131+
)
132+
)
133+
] );
134+
$candidate = new Candidate(
135+
$modelMessage,
136+
FinishReasonEnum::stop(),
137+
42
138+
);
139+
$tokenUsage = new TokenUsage(10, 42, 52);
140+
return new GenerativeAiResult(
141+
'result_123',
142+
[ $candidate ],
143+
$tokenUsage,
144+
$this->providerMetadata(),
145+
$this->metadata(),
146+
[ 'provider' => 'wp-cli-mock-provider' ]
147+
);
148+
}
149+
109150
}
110151
111152
class WP_CLI_Mock_Provider implements ProviderInterface {
@@ -144,12 +185,10 @@ Feature: Generate AI content
144185
}
145186
}
146187
147-
WP_CLI::add_hook(
148-
'ai_client_init',
188+
WP_CLI::add_wp_hook(
189+
'init',
149190
static function () {
150191
AiClient::defaultRegistry()->registerProvider( WP_CLI_Mock_Provider::class );
151-
152-
( new API_Credentials_Manager() )->initialize();
153192
}
154193
);
155194
"""
@@ -196,3 +235,42 @@ Feature: Generate AI content
196235
"""
197236
Top-k must be a positive integer
198237
"""
238+
239+
@require-wp-7.0
240+
Scenario: Generate fails when AI is disabled
241+
Given a wp-content/mu-plugins/disable-ai.php file:
242+
"""
243+
<?php
244+
add_filter( 'wp_supports_ai', '__return_false' );
245+
"""
246+
247+
When I try `wp ai generate text "Test prompt"`
248+
Then the return code should be 1
249+
And STDERR should contain:
250+
"""
251+
AI features are not supported in this environment.
252+
"""
253+
254+
@require-wp-7.0
255+
Scenario: Generates text using mock provider
256+
When I run `wp ai status`
257+
Then STDOUT should be a table containing rows:
258+
| capability | supported |
259+
| Text Generation | Yes |
260+
| Image Generation | Yes |
261+
262+
@require-wp-7.0
263+
Scenario: Generates text using mock provider
264+
When I run `wp ai generate text "Test prompt"`
265+
Then STDOUT should be:
266+
"""
267+
This is mock-generated text
268+
"""
269+
270+
@require-wp-7.0
271+
Scenario: Generates image using mock provider
272+
When I run `wp ai generate image "Test prompt"`
273+
Then STDOUT should be:
274+
"""
275+
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=
276+
"""

‎features/is-supported.feature‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Feature: Check if AI features are supported
2+
3+
Background:
4+
Given a WP install
5+
6+
@less-than-wp-7.0
7+
Scenario: Command not available on WP < 7.0
8+
When I try `wp ai is-supported`
9+
Then the return code should be 1
10+
11+
@require-wp-7.0
12+
Scenario: AI is supported by default
13+
When I run `wp ai is-supported`
14+
Then the return code should be 0
15+
16+
@require-wp-7.0
17+
Scenario: AI is not supported when disabled via filter
18+
Given a wp-content/mu-plugins/disable-ai.php file:
19+
"""
20+
<?php
21+
add_filter( 'wp_supports_ai', '__return_false' );
22+
"""
23+
24+
When I try `wp ai is-supported`
25+
Then the return code should be 1

‎src/AI_Command.php‎

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace WP_CLI\AI;
44

55
use WP_CLI;
6+
use WP_CLI\Utils;
67
use WP_CLI_Command;
78
use WordPress\AiClient\Results\DTO\TokenUsage;
89

@@ -118,10 +119,19 @@ class AI_Command extends WP_CLI_Command {
118119
public function generate( $args, $assoc_args ) {
119120
list( $type, $prompt ) = $args;
120121

122+
// @phpstan-ignore function.notFound
123+
if ( ! wp_supports_ai() ) {
124+
WP_CLI::error( 'AI features are not supported in this environment.' );
125+
}
126+
121127
try {
122128
// @phpstan-ignore function.notFound
123129
$builder = wp_ai_client_prompt( $prompt );
124130

131+
if ( is_wp_error( $builder ) ) {
132+
WP_CLI::error( $builder->get_error_message() );
133+
}
134+
125135
if ( isset( $assoc_args['provider'] ) ) {
126136
$builder = $builder->using_provider( $assoc_args['provider'] );
127137
}
@@ -185,6 +195,32 @@ public function generate( $args, $assoc_args ) {
185195
}
186196
}
187197

198+
/**
199+
* Checks whether AI features are supported in the current environment.
200+
*
201+
* Exits with code 0 if AI features are supported, or code 1 if they are not.
202+
*
203+
* ## EXAMPLES
204+
*
205+
* # Check if AI is supported
206+
* $ wp ai is-supported
207+
* Success: AI features are supported.
208+
*
209+
* @subcommand is-supported
210+
*
211+
* @param string[] $args Positional arguments. Unused.
212+
* @param string[] $assoc_args Associative arguments. Unused.
213+
* @return void
214+
*/
215+
public function is_supported( $args, $assoc_args ) {
216+
// @phpstan-ignore function.notFound
217+
if ( wp_supports_ai() ) {
218+
WP_CLI::halt( 0 );
219+
} else {
220+
WP_CLI::halt( 1 );
221+
}
222+
}
223+
188224
/**
189225
* Checks if a prompt is supported for generation.
190226
*
@@ -217,10 +253,19 @@ public function check( $args, $assoc_args ) {
217253
list( $prompt ) = $args;
218254
$type = $assoc_args['type'] ?? 'text';
219255

256+
// @phpstan-ignore function.notFound
257+
if ( ! wp_supports_ai() ) {
258+
WP_CLI::error( 'AI features are not supported in this environment.' );
259+
}
260+
220261
try {
221262
// @phpstan-ignore function.notFound
222263
$builder = wp_ai_client_prompt( $prompt );
223264

265+
if ( is_wp_error( $builder ) ) {
266+
WP_CLI::error( $builder->get_error_message() );
267+
}
268+
224269
if ( 'text' === $type ) {
225270
$supported = $builder->is_supported_for_text_generation();
226271
if ( $supported ) {
@@ -267,7 +312,7 @@ public function check( $args, $assoc_args ) {
267312
* # Check AI status
268313
* $ wp ai status
269314
* +------------------+-----------+
270-
* | Capability | Supported |
315+
* | capability | supported |
271316
* +------------------+-----------+
272317
* | Text Generation | Yes |
273318
* | Image Generation | No |
@@ -282,6 +327,10 @@ public function status( $args, $assoc_args ) {
282327
// @phpstan-ignore function.notFound
283328
$builder = wp_ai_client_prompt();
284329

330+
if ( is_wp_error( $builder ) ) {
331+
WP_CLI::error( $builder->get_error_message() );
332+
}
333+
285334
// Check each capability
286335
$capabilities = array(
287336
array(
@@ -292,6 +341,26 @@ public function status( $args, $assoc_args ) {
292341
'capability' => 'Image Generation',
293342
'supported' => $builder->is_supported_for_image_generation() ? 'Yes' : 'No',
294343
),
344+
array(
345+
'capability' => 'Text to Speech Generation',
346+
'supported' => $builder->is_supported_for_text_to_speech_conversion() ? 'Yes' : 'No',
347+
),
348+
array(
349+
'capability' => 'Video Generation',
350+
'supported' => $builder->is_supported_for_video_generation() ? 'Yes' : 'No',
351+
),
352+
array(
353+
'capability' => 'Speech Generation',
354+
'supported' => $builder->is_supported_for_speech_generation() ? 'Yes' : 'No',
355+
),
356+
array(
357+
'capability' => 'Music Generation',
358+
'supported' => $builder->is_supported_for_music_generation() ? 'Yes' : 'No',
359+
),
360+
array(
361+
'capability' => 'Embedding Generation',
362+
'supported' => $builder->is_supported_for_embedding_generation() ? 'Yes' : 'No',
363+
),
295364
);
296365

297366
$format = $assoc_args['format'] ?? 'table';
@@ -321,6 +390,10 @@ private function generate_text( $builder, $assoc_args ) {
321390
// @phpstan-ignore class.notFound
322391
$text = $builder->generate_text_result();
323392

393+
if ( is_wp_error( $text ) ) {
394+
WP_CLI::error( $text );
395+
}
396+
324397
if ( 'json' === $format ) {
325398
$json = json_encode( array( 'text' => $text->toText() ) );
326399
if ( false === $json ) {
@@ -380,6 +453,10 @@ private function generate_image( $builder, $assoc_args ) {
380453
// @phpstan-ignore class.notFound
381454
$image_file = $builder->generate_image();
382455

456+
if ( is_wp_error( $image_file ) ) {
457+
WP_CLI::error( $image_file );
458+
}
459+
383460
if ( isset( $assoc_args['destination-file'] ) ) {
384461
$output_path = $assoc_args['destination-file'];
385462
$output_path = realpath( dirname( $output_path ) ) . DIRECTORY_SEPARATOR . basename( $output_path );
@@ -406,7 +483,7 @@ private function generate_image( $builder, $assoc_args ) {
406483
}
407484

408485
WP_CLI::success( 'Image saved to ' . $output_path );
409-
} elseif ( $assoc_args['stdout'] ) {
486+
} elseif ( Utils\get_flag_value( $assoc_args, 'stdout', false ) ) {
410487
$data_uri = $image_file->getDataUri();
411488

412489
$data_parts = $data_uri ? explode( ',', $data_uri, 2 ) : [];
@@ -424,7 +501,6 @@ private function generate_image( $builder, $assoc_args ) {
424501

425502
WP_CLI::log( $image_data );
426503
} else {
427-
WP_CLI::success( 'Image generated:' );
428504
WP_CLI::line( (string) $image_file->getDataUri() );
429505
}
430506
}

0 commit comments

Comments
 (0)