Repository navigation
Expand file tree
/
Copy pathAI_Command.php
More file actions
605 lines (537 loc) · 18.7 KB
/
Copy pathAI_Command.php
File metadata and controls
605 lines (537 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
<?php
namespace WP_CLI\AI;
use WP_CLI;
use WP_CLI\Utils;
use WP_CLI_Command;
use WordPress\AiClient\Results\DTO\TokenUsage;
/**
* Interacts with the WordPress AI Client for text and image generation.
*
* ## EXAMPLES
*
* # Check AI capabilities status
* $ wp ai status
* +------------------+-----------+
* | Capability | Supported |
* +------------------+-----------+
* | Text Generation | Yes |
* | Image Generation | No |
* +------------------+-----------+
*
* # Generate text from a prompt
* $ wp ai generate text "Write a haiku about WordPress"
* Success: Generated text:
* Open source and free
* Empowering creators
* WordPress shines bright
*
* # Generate an image from a prompt
* $ wp ai generate image "A futuristic WordPress logo" --destination-file=logo.png
* Success: Image saved to logo.png
*
* # Check if a prompt is supported
* $ wp ai check "Summarize this text"
* Success: Text generation is supported for this prompt.
*
* @when after_wp_load
*/
class AI_Command extends WP_CLI_Command {
/**
* Generates AI content.
*
* ## OPTIONS
*
* <type>
* : Type of content to generate.
* ---
* options:
* - text
* - image
* ---
*
* <prompt>
* : The prompt to send to the AI.
*
* [--model=<models>]
* : Comma-separated list of models in order of preference. Format: "provider,model" (e.g., "openai,gpt-4" or "openai,gpt-4,anthropic,claude-3").
*
* [--provider=<provider>]
* : Specific AI provider to use (e.g., "openai", "anthropic", "google").
*
* [--temperature=<temperature>]
* : Temperature for generation, typically between 0.0 and 1.0. Lower is more deterministic.
*
* [--top-p=<top-p>]
* : Top-p (nucleus sampling) parameter. Value between 0.0 and 1.0.
*
* [--top-k=<top-k>]
* : Top-k sampling parameter. Positive integer.
*
* [--max-tokens=<tokens>]
* : Maximum number of tokens to generate.
*
* [--system-instruction=<instruction>]
* : System instruction to guide the AI's behavior.
*
* [--image=<image>]
* : An image to use as input for text or image generation. Can be a local file path, a URL, a data URI, or a WordPress attachment ID.
*
* [--destination-file=<file>]
* : For image generation, path to save the generated image.
*
* [--stdout]
* : Output the whole image using standard output (incompatible with --destination-file=)
*
* [--format=<format>]
* : Output format for text.
* ---
* default: text
* options:
* - text
* - json
* ---
*
* ## EXAMPLES
*
* # Generate text
* $ wp ai generate text "Explain WordPress in one sentence"
*
* # Generate text with specific settings
* $ wp ai generate text "List 3 WordPress features" --temperature=0.1 --max-tokens=100
*
* # Generate with top-p and top-k sampling
* $ wp ai generate text "Write a story" --top-p=0.9 --top-k=40
*
* # Generate with model preferences
* $ wp ai generate text "Write a haiku" --model=openai,gpt-4,anthropic,claude-3
*
* # Generate with system instruction
* $ wp ai generate text "Explain AI" --system-instruction="Explain as if to a 5-year-old"
*
* # Generate text from a prompt with an image
* $ wp ai generate text "Describe this image" --image=photo.jpg
*
* # Generate alt text for an attachment
* $ wp ai generate text "Generate alt text for this image" --image=42
*
* # Generate text with an image URL
* $ wp ai generate text "What is in this image?" --image=https://example.com/photo.jpg
*
* # Generate image
* $ wp ai generate image "A minimalist WordPress logo" --destination-file=wp-logo.png
*
* @param array{0: string, 1: string} $args Positional arguments.
* @param array{model: string, provider: string, temperature: float, 'top-p': float, 'top-k': int, 'max-tokens': int, 'system-instruction': string, image?: string, 'destination-file': string, stdout: bool, format: string} $assoc_args Associative arguments.
* @return void
*/
public function generate( $args, $assoc_args ) {
list( $type, $prompt ) = $args;
if ( ! wp_supports_ai() ) {
WP_CLI::error( 'AI features are not supported in this environment.' );
}
try {
$builder = wp_ai_client_prompt( $prompt );
if ( isset( $assoc_args['provider'] ) ) {
$builder = $builder->using_provider( $assoc_args['provider'] );
}
if ( isset( $assoc_args['model'] ) ) {
// Models should be in pairs: provider:model,provider:model,...
// Convert to array of [provider, model] pairs.
$model_preferences = explode( ',', $assoc_args['model'] );
foreach ( $model_preferences as $key => $value ) {
$value = explode( ':', $value );
$entries[ $key ] = $value;
if ( count( $value ) !== 2 ) {
WP_CLI::error( 'Model must be in format "provider:model" pairs (e.g., "openai:gpt-4" or "openai:gpt-4,anthropic:claude-3").' );
}
}
$builder = $builder->using_model_preference( ...$model_preferences );
}
if ( isset( $assoc_args['temperature'] ) ) {
$builder = $builder->using_temperature( (float) $assoc_args['temperature'] );
}
if ( isset( $assoc_args['top-p'] ) ) {
$top_p = (float) $assoc_args['top-p'];
if ( $top_p < 0.0 || $top_p > 1.0 ) {
WP_CLI::error( 'Top-p must be between 0.0 and 1.0.' );
}
$builder = $builder->using_top_p( $top_p );
}
if ( isset( $assoc_args['top-k'] ) ) {
$top_k = (int) $assoc_args['top-k'];
if ( $top_k <= 0 ) {
WP_CLI::error( 'Top-k must be a positive integer.' );
}
$builder = $builder->using_top_k( $top_k );
}
if ( isset( $assoc_args['max-tokens'] ) ) {
$max_tokens = (int) $assoc_args['max-tokens'];
if ( $max_tokens <= 0 ) {
WP_CLI::error( 'Max tokens must be a positive integer.' );
}
$builder = $builder->using_max_tokens( $max_tokens );
}
if ( isset( $assoc_args['system-instruction'] ) ) {
$builder = $builder->using_system_instruction( $assoc_args['system-instruction'] );
}
if ( 'text' === $type ) {
if ( isset( $assoc_args['image'] ) ) {
$builder = $this->with_image_input( $builder, $assoc_args['image'] );
}
$this->generate_text( $builder, $assoc_args );
} elseif ( 'image' === $type ) {
if ( isset( $assoc_args['image'] ) ) {
$builder = $this->with_image_input( $builder, $assoc_args['image'] );
}
$this->generate_image( $builder, $assoc_args );
}
} catch ( \Exception $e ) {
WP_CLI::error( 'AI generation failed: ' . $e->getMessage() );
}
}
/**
* Checks whether AI features are supported in the current environment.
*
* Exits with code 0 if AI features are supported, or code 1 if they are not.
*
* ## EXAMPLES
*
* # Check if AI is supported
* $ wp ai is-supported
* Success: AI features are supported.
*
* @subcommand is-supported
*
* @param string[] $args Positional arguments. Unused.
* @param string[] $assoc_args Associative arguments. Unused.
* @return void
*/
public function is_supported( $args, $assoc_args ) {
if ( wp_supports_ai() ) {
WP_CLI::halt( 0 );
} else {
WP_CLI::halt( 1 );
}
}
/**
* Checks if a prompt is supported for generation.
*
* ## OPTIONS
*
* <prompt>
* : The prompt to check.
*
* [--type=<type>]
* : Type to check.
* ---
* options:
* - text
* - image
* ---
*
* ## EXAMPLES
*
* # Check if text generation is supported
* $ wp ai check "Write a poem"
*
* # Check if image generation is supported
* $ wp ai check "A sunset" --type=image
*
* @param array{0: string} $args Positional arguments.
* @param array{type: string} $assoc_args Associative arguments.
* @return void
*/
public function check( $args, $assoc_args ) {
list( $prompt ) = $args;
$type = $assoc_args['type'] ?? 'text';
if ( ! wp_supports_ai() ) {
WP_CLI::error( 'AI features are not supported in this environment.' );
}
try {
$builder = wp_ai_client_prompt( $prompt );
if ( 'text' === $type ) {
$supported = $builder->is_supported_for_text_generation();
if ( $supported ) {
WP_CLI::success( 'Text generation is supported for this prompt.' );
} else {
WP_CLI::error( 'Text generation is not supported. Make sure AI provider credentials are configured.' );
}
} elseif ( 'image' === $type ) {
$supported = $builder->is_supported_for_image_generation();
if ( $supported ) {
WP_CLI::success( 'Image generation is supported for this prompt.' );
} else {
WP_CLI::error( 'Image generation is not supported. Make sure AI provider credentials are configured.' );
}
} else {
WP_CLI::error( 'Invalid type. Must be "text" or "image".' );
}
} catch ( \Exception $e ) {
WP_CLI::error( 'Check failed: ' . $e->getMessage() );
}
}
/**
* Checks which AI capabilities are currently supported.
*
* Checks the environment and credentials to determine which AI operations
* are available. Displays a table showing supported capabilities.
*
* ## OPTIONS
*
* [--format=<format>]
* : Render output in a particular format.
* ---
* default: table
* options:
* - table
* - csv
* - json
* - yaml
* ---
*
* ## EXAMPLES
*
* # Check AI status
* $ wp ai status
* +------------------+-----------+
* | capability | supported |
* +------------------+-----------+
* | Text Generation | Yes |
* | Image Generation | No |
* +------------------+-----------+
*
* @param string[] $args Positional arguments. Unused.
* @param array{format: string} $assoc_args Associative arguments.
* @return void
*/
public function status( $args, $assoc_args ) {
try {
$builder = wp_ai_client_prompt();
// Check each capability
$capabilities = array(
array(
'capability' => 'Text Generation',
'supported' => $builder->is_supported_for_text_generation() ? 'Yes' : 'No',
),
array(
'capability' => 'Image Generation',
'supported' => $builder->is_supported_for_image_generation() ? 'Yes' : 'No',
),
array(
'capability' => 'Text to Speech Generation',
'supported' => $builder->is_supported_for_text_to_speech_conversion() ? 'Yes' : 'No',
),
array(
'capability' => 'Video Generation',
'supported' => $builder->is_supported_for_video_generation() ? 'Yes' : 'No',
),
array(
'capability' => 'Speech Generation',
'supported' => $builder->is_supported_for_speech_generation() ? 'Yes' : 'No',
),
array(
'capability' => 'Music Generation',
'supported' => $builder->is_supported_for_music_generation() ? 'Yes' : 'No',
),
array(
'capability' => 'Embedding Generation',
'supported' => $builder->is_supported_for_embedding_generation() ? 'Yes' : 'No',
),
);
$format = $assoc_args['format'] ?? 'table';
WP_CLI\Utils\format_items( $format, $capabilities, array( 'capability', 'supported' ) );
} catch ( \Exception $e ) {
WP_CLI::error( 'Status check failed: ' . $e->getMessage() );
}
}
/**
* Generates text from the prompt builder.
*
* @param \WP_AI_Client_Prompt_Builder $builder The prompt builder.
* @param array{format: string} $assoc_args Associative arguments.
* @return void
*/
private function generate_text( $builder, $assoc_args ) {
$format = $assoc_args['format'] ?? 'text';
if ( ! $builder->is_supported_for_text_generation() ) {
WP_CLI::error( 'Text generation is not supported. Make sure AI provider credentials are configured.' );
}
$text = $builder->generate_text_result();
if ( is_wp_error( $text ) ) {
WP_CLI::error( $text );
}
if ( 'json' === $format ) {
$json = json_encode( array( 'text' => $text->toText() ) );
if ( false === $json ) {
WP_CLI::error( 'Failed to encode text as JSON: ' . json_last_error_msg() );
}
WP_CLI::line( $json );
} else {
WP_CLI::line( $text->toText() );
}
$token_usage = $text->getTokenUsage()->toArray();
WP_CLI::debug(
sprintf(
"Summary:\nModel used: %s (%s)\nToken usage:\nInput tokens: %s\nOutput tokens: %s\nTotal: %s\n",
$text->getModelMetadata()->getName(),
$text->getProviderMetadata()->getName(),
$token_usage[ TokenUsage::KEY_PROMPT_TOKENS ],
$token_usage[ TokenUsage::KEY_COMPLETION_TOKENS ],
$token_usage[ TokenUsage::KEY_TOTAL_TOKENS ]
),
'ai'
);
}
/**
* Generates an image from the prompt builder.
*
* @param \WP_AI_Client_Prompt_Builder $builder The prompt builder.
* @param array{'destination-file': string, stdout: bool} $assoc_args Associative arguments.
* @return void
*/
private function generate_image( $builder, $assoc_args ) {
if ( ! $builder->is_supported_for_image_generation() ) {
WP_CLI::error( 'Image generation is not supported. Make sure AI provider credentials are configured.' );
}
if ( ! empty( $assoc_args['stdout'] ) && ! empty( $assoc_args['dir'] ) ) {
WP_CLI::error( '--stdout and --destination-file cannot be used together.' );
}
if ( isset( $assoc_args['destination-file'] ) ) {
$output_path = $assoc_args['destination-file'];
$parent_dir = dirname( $output_path );
if ( ! is_dir( $parent_dir ) ) {
WP_CLI::error( 'Invalid output directory. Directory does not exist: ' . $parent_dir );
}
}
$image_file = $builder->generate_image();
if ( is_wp_error( $image_file ) ) {
WP_CLI::error( $image_file );
}
if ( isset( $assoc_args['destination-file'] ) ) {
$output_path = $assoc_args['destination-file'];
$output_path = realpath( dirname( $output_path ) ) . DIRECTORY_SEPARATOR . basename( $output_path );
$data_uri = $image_file->getDataUri();
$data_parts = $data_uri ? explode( ',', $data_uri, 2 ) : [];
if ( count( $data_parts ) !== 2 ) {
WP_CLI::error( 'Invalid image data received.' );
}
$base64_data = $data_parts[1];
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
$image_data = base64_decode( $base64_data, true );
if ( false === $image_data ) {
WP_CLI::error( 'Invalid base64 image data format.' );
}
// Save to file
$result = file_put_contents( $output_path, $image_data );
if ( false === $result ) {
WP_CLI::error( 'Failed to save image to ' . $output_path );
}
WP_CLI::success( 'Image saved to ' . $output_path );
} elseif ( Utils\get_flag_value( $assoc_args, 'stdout', false ) ) {
$data_uri = $image_file->getDataUri();
$data_parts = $data_uri ? explode( ',', $data_uri, 2 ) : [];
if ( count( $data_parts ) !== 2 ) {
WP_CLI::error( 'Invalid image data received.' );
}
$base64_data = $data_parts[1];
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
$image_data = base64_decode( $base64_data, true );
if ( false === $image_data ) {
WP_CLI::error( 'Invalid base64 image data format.' );
}
WP_CLI::log( $image_data );
} else {
WP_CLI::line( (string) $image_file->getDataUri() );
}
}
/**
* Adds image input to the prompt builder.
*
* Accepts a local file path, a URL (http/https), a data URI, or a WordPress attachment ID.
*
* @param \WP_AI_Client_Prompt_Builder $builder The prompt builder.
* @param string $image_input Local file path, URL, data URI, or attachment ID.
* @return \WP_AI_Client_Prompt_Builder The updated prompt builder.
*/
private function with_image_input( $builder, $image_input ) {
// Attachment ID (positive integer string).
if ( ctype_digit( $image_input ) && (int) $image_input > 0 ) {
return $this->with_attachment_input( $builder, (int) $image_input );
}
// Data URI or remote URL — pass directly to with_file().
if (
0 === strpos( $image_input, 'data:' ) ||
0 === strpos( $image_input, 'http://' ) ||
0 === strpos( $image_input, 'https://' )
) {
return $builder->with_file( $image_input );
}
// Local file path.
return $this->with_local_file_input( $builder, $image_input );
}
/**
* Adds a WordPress attachment as image input to the prompt builder.
*
* @param \WP_AI_Client_Prompt_Builder $builder The prompt builder.
* @param int $attachment_id The attachment ID.
* @return \WP_AI_Client_Prompt_Builder The updated prompt builder.
*/
private function with_attachment_input( $builder, $attachment_id ) {
$attachment = get_post( $attachment_id );
if ( ! $attachment ) {
WP_CLI::error( "Attachment with ID {$attachment_id} not found." );
}
if ( 'attachment' !== $attachment->post_type ) {
WP_CLI::error( "Post with ID {$attachment_id} is not an attachment." );
}
if ( ! wp_attachment_is_image( $attachment_id ) ) {
WP_CLI::error( "Attachment {$attachment_id} is not an image." );
}
$file_path = get_attached_file( $attachment_id );
if ( $file_path && file_exists( $file_path ) ) {
$mime_type = get_post_mime_type( $attachment_id );
if ( ! $mime_type ) {
WP_CLI::error( "Could not determine MIME type for attachment {$attachment_id}." );
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$contents = file_get_contents( $file_path );
if ( false === $contents ) {
WP_CLI::error( "Could not read image file for attachment {$attachment_id}." );
}
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
$data_uri = 'data:' . $mime_type . ';base64,' . base64_encode( $contents );
return $builder->with_file( $data_uri );
}
// Fall back to the attachment URL.
$image_src = wp_get_attachment_image_src( $attachment_id, 'full' );
if ( $image_src && ! empty( $image_src[0] ) ) {
return $builder->with_file( $image_src[0] );
}
WP_CLI::error( "Could not retrieve image for attachment {$attachment_id}." );
}
/**
* Adds a local image file as input to the prompt builder.
*
* @param \WP_AI_Client_Prompt_Builder $builder The prompt builder.
* @param string $file_path The local file path.
* @return \WP_AI_Client_Prompt_Builder The updated prompt builder.
*/
private function with_local_file_input( $builder, $file_path ) {
if ( ! file_exists( $file_path ) ) {
WP_CLI::error( "Image file not found: {$file_path}" );
}
$filetype = wp_check_filetype( $file_path );
$mime_type = $filetype['type'];
if ( ! $mime_type || 0 !== strpos( $mime_type, 'image/' ) ) {
WP_CLI::error( "File does not appear to be an image: {$file_path}" );
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$contents = file_get_contents( $file_path );
if ( false === $contents ) {
WP_CLI::error( "Could not read image file: {$file_path}" );
}
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
$data_uri = 'data:' . $mime_type . ';base64,' . base64_encode( $contents );
return $builder->with_file( $data_uri );
}
}