PluginProbe
Plugin Check (PCP) / trunk
Plugin Check (PCP) vtrunk
2.1.0 trunk 0.1 0.2.0 0.2.1 0.2.2 0.2.3 1.0.0 1.0.1 1.0.2 1.1.0 1.2.0 1.3.0 1.3.1 1.4.0 1.5.0 1.6.0 1.7.0 1.8.0 1.9.0 2.0.0 ci-artifacts
plugin-check / includes / Traits / AI_Utils.php

AI_Utils.php in Plugin Check (PCP) trunk, at includes/Traits/AI_Utils.php

605 lines 16.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Trait WordPress\Plugin_Check\Traits\AI_Utils
4 *
5 * @package plugin-check
6 */
7
8 namespace WordPress\Plugin_Check\Traits;
9
10 use WordPress\AiClient\AiClient;
11 use WP_Error;
12
13 /**
14 * Trait for shared AI utilities (config, raw output, JSON formatting).
15 *
16 * @since 1.9.0
17 */
18 trait AI_Utils {
19
20 /**
21 * Checks AI prerequisites: feature flag, function availability, and version.
22 *
23 * @since 2.0.0
24 *
25 * @return true|WP_Error True if all prerequisites are met, WP_Error otherwise.
26 */
27 protected function check_ai_prerequisites() {
28
29 if ( function_exists( 'wp_supports_ai' ) && ! wp_supports_ai() ) {
30 return new WP_Error(
31 'ai_disabled',
32 __( 'The Plugin Check Namer feature requires AI support to be enabled on this site. Please enable AI functionality to use this feature.', 'plugin-check' )
33 );
34 }
35
36 if ( ! is_wp_version_compatible( '7.0' ) ) {
37 return new WP_Error(
38 'ai_client_not_available',
39 sprintf(
40 /* translators: %s: WordPress version. */
41 __( 'The Plugin Check Namer Tool requires WordPress version 7.0 or higher. You are running WordPress version %s.', 'plugin-check' ),
42 get_bloginfo( 'version' )
43 )
44 );
45 }
46
47 return true;
48 }
49
50 /**
51 * Checks that at least one AI connector is configured and active.
52 *
53 * @since 2.0.0
54 *
55 * @return true|WP_Error True if a connector is available, WP_Error otherwise.
56 */
57 protected function check_ai_connectors() {
58 if ( $this->has_no_active_ai_connectors() ) {
59 return new WP_Error(
60 'ai_not_configured',
61 __( 'AI connectors are not configured. Please connect and enable an AI provider in WordPress 7.0+ settings.', 'plugin-check' )
62 );
63 }
64
65 return true;
66 }
67
68 /**
69 * Gets AI configuration from core AI connectors.
70 *
71 * @since 1.9.0
72 *
73 * @param string $model_preference Selected model preference (optional).
74 * @return array|WP_Error AI config array or error.
75 */
76 protected function get_ai_config( $model_preference = '' ) {
77
78 $prerequisites = $this->check_ai_prerequisites();
79 if ( is_wp_error( $prerequisites ) ) {
80 return $prerequisites;
81 }
82
83 $connectors = $this->check_ai_connectors();
84 if ( is_wp_error( $connectors ) ) {
85 return $connectors;
86 }
87
88 if ( ! function_exists( 'wp_ai_client_prompt' ) ) {
89 return new WP_Error(
90 'ai_client_not_available',
91 sprintf(
92 /* translators: %s: WordPress version. */
93 __( 'The Plugin Check Namer Tool requires WordPress version 7.0 or newer. You are running WordPress version %s.', 'plugin-check' ),
94 get_bloginfo( 'version' )
95 )
96 );
97 }
98
99 $builder = wp_ai_client_prompt( 'Plugin Check AI availability test.' );
100 if ( is_wp_error( $builder ) ) {
101 return $builder;
102 }
103
104 $builder = $this->apply_model_preference( $builder, $model_preference );
105 if ( is_wp_error( $builder ) ) {
106 return $builder;
107 }
108
109 if ( method_exists( $builder, 'is_supported_for_text_generation' ) ) {
110 $supported = $builder->is_supported_for_text_generation();
111 if ( is_wp_error( $supported ) ) {
112 return $supported;
113 }
114 if ( ! $supported ) {
115 return new WP_Error(
116 'ai_not_configured',
117 __( 'AI connectors are not configured. Please connect an AI provider in WordPress 7.0+ settings.', 'plugin-check' )
118 );
119 }
120 }
121
122 return array(
123 'model_preference' => (string) $model_preference,
124 );
125 }
126
127 /**
128 * Applies a model preference to the prompt builder if supported.
129 *
130 * @since 2.0.0
131 *
132 * @param object $builder Prompt builder instance.
133 * @param string $model_preference Model preference.
134 * @return object|WP_Error Updated builder or WP_Error.
135 */
136 protected function apply_model_preference( $builder, $model_preference ) {
137 if ( empty( $model_preference ) ) {
138 return $builder;
139 }
140
141 $preference = $this->normalize_model_preference( $model_preference );
142
143 try {
144 $result = $builder->using_model_preference( $preference );
145 return $result ? $result : $builder;
146 } catch ( \Exception $e ) {
147 return new WP_Error(
148 'model_preference_error',
149 sprintf(
150 /* translators: %s: Exception message */
151 __( 'Failed to apply model preference: %s', 'plugin-check' ),
152 $e->getMessage()
153 )
154 );
155 }
156 }
157
158 /**
159 * Normalizes a model preference string into a supported preference format.
160 *
161 * @since 2.0.0
162 *
163 * @param string $model_preference Model preference string.
164 * @return string|array Normalized preference.
165 */
166 protected function normalize_model_preference( $model_preference ) {
167 $trimmed = trim( (string) $model_preference );
168 if ( '' === $trimmed ) {
169 return '';
170 }
171
172 foreach ( array( '::', '|', ':' ) as $separator ) {
173 if ( false !== strpos( $trimmed, $separator ) ) {
174 list( $provider, $model ) = array_map( 'trim', explode( $separator, $trimmed, 2 ) );
175 if ( '' !== $provider && '' !== $model ) {
176 return array( $provider, $model );
177 }
178 }
179 }
180
181 return $trimmed;
182 }
183
184 /**
185 * Gets raw output string from parsed result or analysis.
186 *
187 * @since 1.8.0
188 *
189 * @param array $parsed Parsed analysis.
190 * @param string|array $analysis Raw analysis.
191 * @return string Raw output.
192 */
193 protected function get_raw_output( $parsed, $analysis ) {
194 if ( ! empty( $parsed['raw'] ) ) {
195 return $parsed['raw'];
196 }
197
198 if ( is_array( $analysis ) && isset( $analysis['text'] ) ) {
199 return $analysis['text'];
200 }
201
202 if ( is_string( $analysis ) ) {
203 return $analysis;
204 }
205
206 return '';
207 }
208
209 /**
210 * Formats JSON output with proper indentation if the text is valid JSON.
211 *
212 * @since 1.8.0
213 *
214 * @param string $text Text that might be JSON.
215 * @return string Formatted JSON or original text.
216 */
217 protected function format_json_output( $text ) {
218 if ( empty( $text ) || ! is_string( $text ) ) {
219 return $text;
220 }
221
222 $trimmed = $this->remove_markdown_fences( trim( $text ) );
223
224 if ( ! $this->looks_like_json( $trimmed ) ) {
225 return $text;
226 }
227
228 $json_text = $this->extract_json_text( $trimmed );
229 $decoded = json_decode( $json_text, true );
230
231 if ( JSON_ERROR_NONE === json_last_error() && is_array( $decoded ) ) {
232 return wp_json_encode( $decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
233 }
234
235 return $text;
236 }
237
238 /**
239 * Removes markdown code fences from text.
240 *
241 * @since 1.8.0
242 *
243 * @param string $text Text with possible markdown fences.
244 * @return string Text without markdown fences.
245 */
246 protected function remove_markdown_fences( $text ) {
247 $text = preg_replace( '/^```(?:json)?\s*\n?/m', '', $text );
248 $text = preg_replace( '/\n?```\s*$/m', '', $text );
249 return trim( $text );
250 }
251
252 /**
253 * Checks if text looks like JSON.
254 *
255 * @since 1.8.0
256 *
257 * @param string $text Text to check.
258 * @return bool True if looks like JSON.
259 */
260 protected function looks_like_json( $text ) {
261 return ! empty( $text ) && ( '{' === $text[0] || '[' === $text[0] );
262 }
263
264 /**
265 * Extracts JSON text from mixed content.
266 *
267 * @since 1.8.0
268 *
269 * @param string $text Text containing JSON.
270 * @return string Extracted JSON text.
271 */
272 protected function extract_json_text( $text ) {
273 $bounds = $this->find_json_bounds( $text );
274
275 if ( -1 !== $bounds['start'] && -1 !== $bounds['end'] && $bounds['end'] > $bounds['start'] ) {
276 return substr( $text, $bounds['start'], $bounds['end'] - $bounds['start'] + 1 );
277 }
278
279 return $text;
280 }
281
282 /**
283 * Finds JSON boundaries in text.
284 *
285 * @since 1.8.0
286 *
287 * @param string $text Text to search.
288 * @return array Array with 'start' and 'end' positions.
289 */
290 protected function find_json_bounds( $text ) {
291 $first_brace = strpos( $text, '{' );
292 $first_bracket = strpos( $text, '[' );
293
294 if ( false !== $first_brace && ( false === $first_bracket || $first_brace < $first_bracket ) ) {
295 return array(
296 'start' => $first_brace,
297 'end' => strrpos( $text, '}' ),
298 );
299 }
300
301 if ( false !== $first_bracket ) {
302 return array(
303 'start' => $first_bracket,
304 'end' => strrpos( $text, ']' ),
305 );
306 }
307
308 return array(
309 'start' => -1,
310 'end' => -1,
311 );
312 }
313
314 /**
315 * Returns whether a model metadata object supports text for both input and output.
316 *
317 * Checks supported capabilities for text_generation, then inspects input/output
318 * modality options. Falls back to name-based inference when metadata is insufficient.
319 *
320 * @since 2.0.0
321 *
322 * @param object $model_meta Model metadata object.
323 * @return bool True when the model supports text input and text output.
324 */
325 protected function supports_text_io_from_metadata( $model_meta ) {
326 if ( ! is_object( $model_meta ) ) {
327 return false;
328 }
329
330 // If capabilities metadata is present, require text_generation capability.
331 if ( method_exists( $model_meta, 'getSupportedCapabilities' ) ) {
332 $supported = $model_meta->getSupportedCapabilities();
333 if ( is_array( $supported ) && ! $this->meta_has_text_generation_cap( $supported ) ) {
334 return false;
335 }
336 }
337
338 // Check input/output modality options for text support.
339 if ( method_exists( $model_meta, 'getSupportedOptions' ) ) {
340 $options = $model_meta->getSupportedOptions();
341 if ( is_array( $options ) ) {
342 $modality = $this->meta_get_modality_text_support( $options );
343 if ( null !== $modality['input'] || null !== $modality['output'] ) {
344 return (bool) $modality['input'] && (bool) $modality['output'];
345 }
346 }
347 }
348
349 return ! $this->meta_is_audio_model_by_name( $model_meta );
350 }
351
352 /**
353 * Returns whether a supported-values matrix contains a text modality.
354 *
355 * @since 2.0.0
356 *
357 * @param mixed $values Supported values from a SupportedOption (array of combinations).
358 * @return bool True when at least one item resolves to text.
359 */
360 protected function modality_values_include_text( $values ) {
361 if ( ! is_array( $values ) ) {
362 return false;
363 }
364
365 foreach ( $values as $combination ) {
366 if ( ! is_array( $combination ) ) {
367 continue;
368 }
369 foreach ( $combination as $modality ) {
370 $text = '';
371 if ( is_string( $modality ) ) {
372 $text = strtolower( $modality );
373 } elseif ( is_object( $modality ) && 'text' === strtolower( (string) $modality ) ) {
374 return true;
375 }
376 if ( 'text' === $text ) {
377 return true;
378 }
379 }
380 }
381
382 return false;
383 }
384
385 /**
386 * Returns whether a capabilities array contains text_generation.
387 *
388 * @since 2.0.0
389 *
390 * @param array $supported Capabilities from getSupportedCapabilities().
391 * @return bool
392 */
393 private function meta_has_text_generation_cap( array $supported ): bool {
394 foreach ( $supported as $cap ) {
395 if ( is_object( $cap ) && 'text_generation' === strtolower( (string) $cap ) ) {
396 return true;
397 }
398 if ( is_string( $cap ) && 'text_generation' === strtolower( $cap ) ) {
399 return true;
400 }
401 }
402 return false;
403 }
404
405 /**
406 * Returns input/output text-modality support derived from getSupportedOptions().
407 *
408 * @since 2.0.0
409 *
410 * @param array $options Options from getSupportedOptions().
411 * @return array
412 */
413 private function meta_get_modality_text_support( array $options ): array {
414 $input_has_text = null;
415 $output_has_text = null;
416
417 foreach ( $options as $option ) {
418 if ( ! is_object( $option ) || ! method_exists( $option, 'getName' ) ) {
419 continue;
420 }
421 $name = $option->getName();
422 $is_input = false;
423 $is_output = false;
424 if ( is_object( $name ) ) {
425 $raw = strtolower( (string) $name );
426 $is_input = 'input_modalities' === $raw;
427 $is_output = 'output_modalities' === $raw;
428 } elseif ( is_string( $name ) ) {
429 $raw = strtolower( $name );
430 $is_input = 'inputmodalities' === $raw || 'input_modalities' === $raw;
431 $is_output = 'outputmodalities' === $raw || 'output_modalities' === $raw;
432 }
433 if ( ( ! $is_input && ! $is_output ) || ! method_exists( $option, 'getSupportedValues' ) ) {
434 continue;
435 }
436 $has_text = $this->modality_values_include_text( $option->getSupportedValues() );
437 if ( $is_input ) {
438 $input_has_text = $has_text;
439 }
440 if ( $is_output ) {
441 $output_has_text = $has_text;
442 }
443 }
444
445 return array(
446 'input' => $input_has_text,
447 'output' => $output_has_text,
448 );
449 }
450
451 /**
452 * Returns true when model name suggests audio-only (transcription / TTS / realtime).
453 *
454 * @since 2.0.0
455 *
456 * @param object $model_meta Model metadata object.
457 * @return bool
458 */
459 private function meta_is_audio_model_by_name( $model_meta ): bool {
460 if ( ! method_exists( $model_meta, 'getId' ) ) {
461 return false;
462 }
463 $model = strtolower( (string) $model_meta->getId() );
464 return false !== strpos( $model, 'transcribe' )
465 || false !== strpos( $model, 'tts' )
466 || false !== strpos( $model, 'realtime' );
467 }
468
469 /**
470 * Returns models from active/configured providers using the official AI Client registry flow.
471 *
472 * @since 1.9.0
473 *
474 * @return array
475 */
476 protected function get_filtered_ai_models() {
477 if ( ! class_exists( AiClient::class ) ) {
478 return array();
479 }
480
481 $models = array();
482
483 try {
484 $registry = AiClient::defaultRegistry();
485
486 foreach ( $registry->getRegisteredProviderIds() as $provider_id ) {
487 if ( ! $registry->isProviderConfigured( $provider_id ) ) {
488 continue;
489 }
490
491 $class_name = $registry->getProviderClassName( $provider_id );
492 $provider_meta = $class_name::metadata();
493
494 foreach ( $class_name::modelMetadataDirectory()->listModelMetadata() as $model_meta ) {
495 if ( ! $this->supports_text_io_from_metadata( $model_meta ) ) {
496 continue;
497 }
498
499 $models[] = array(
500 'provider' => (string) $provider_id,
501 'provider_label' => (string) $provider_meta->getName(),
502 'id' => (string) $model_meta->getId(),
503 'label' => (string) $model_meta->getName(),
504 );
505 }
506 }
507 } catch ( \Throwable $e ) {
508 return array();
509 }
510
511 $models = apply_filters( 'plugin_check_ai_model_preferences', $models );
512 return is_array( $models ) ? $models : array();
513 }
514
515 /**
516 * Returns whether there are no active AI connectors.
517 *
518 * @since 1.9.0
519 *
520 * @return bool
521 */
522 protected function has_no_active_ai_connectors() {
523 $models = $this->get_filtered_ai_models();
524 return empty( $models );
525 }
526
527 /**
528 * Gets model preference from the current request.
529 *
530 * @since 1.9.0
531 *
532 * @return string Model preference.
533 */
534 protected function get_model_preference_from_request() {
535 $model_preference = isset( $_POST['model_preference'] ) ? sanitize_text_field( wp_unslash( $_POST['model_preference'] ) ) : '';
536 return trim( (string) $model_preference );
537 }
538
539 /**
540 * Gets available model preferences from AI connectors.
541 *
542 * @since 1.9.0
543 *
544 * @SuppressWarnings(PHPMD.NPathComplexity)
545 * @SuppressWarnings(PHPMD.CyclomaticComplexity)
546 *
547 * @return array Map of provider label => list of model options.
548 */
549 protected function get_available_model_preferences() {
550 $grouped = array();
551 $models = $this->get_filtered_ai_models();
552
553 if ( is_array( $models ) ) {
554 foreach ( $models as $key => $model ) {
555 if ( is_array( $model ) ) {
556 $provider = isset( $model['provider'] ) ? (string) $model['provider'] : '';
557 $provider_label = isset( $model['provider_label'] ) ? (string) $model['provider_label'] : '';
558 $id = isset( $model['id'] ) ? (string) $model['id'] : ( isset( $model['model'] ) ? (string) $model['model'] : '' );
559 $label = isset( $model['label'] ) ? (string) $model['label'] : '';
560
561 $value = '';
562 if ( '' !== $provider && '' !== $id ) {
563 $value = $provider . '::' . $id;
564 } elseif ( '' !== $id ) {
565 $value = $id;
566 }
567
568 if ( '' === $label ) {
569 $label = '' !== $provider ? $provider . ' / ' . $id : $id;
570 }
571
572 if ( '' !== $value ) {
573 $group_label = '' !== $provider_label ? $provider_label : ( '' !== $provider ? $provider : __( 'Other', 'plugin-check' ) );
574 if ( ! isset( $grouped[ $group_label ] ) ) {
575 $grouped[ $group_label ] = array();
576 }
577 $grouped[ $group_label ][] = array(
578 'value' => $value,
579 'label' => $label,
580 );
581 }
582
583 continue;
584 }
585
586 $model_id = is_string( $model ) ? $model : ( is_string( $key ) ? $key : '' );
587 if ( '' === $model_id ) {
588 continue;
589 }
590
591 $group_label = __( 'Other', 'plugin-check' );
592 if ( ! isset( $grouped[ $group_label ] ) ) {
593 $grouped[ $group_label ] = array();
594 }
595 $grouped[ $group_label ][] = array(
596 'value' => $model_id,
597 'label' => $model_id,
598 );
599 }
600 }
601
602 return $grouped;
603 }
604 }
605