-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathContent_Classification.php
More file actions
586 lines (521 loc) · 19.1 KB
/
Content_Classification.php
File metadata and controls
586 lines (521 loc) · 19.1 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
<?php
/**
* Content classification WordPress Ability implementation.
*
* @package WordPress\AI
*/
declare( strict_types=1 );
namespace WordPress\AI\Abilities\Content_Classification;
use WP_Error;
use WP_Post;
use WP_Post_Type;
use WordPress\AI\Abstracts\Abstract_Ability;
use WordPress\AI\Experiments\Content_Classification\Content_Classification as Content_Classification_Experiment;
use function WordPress\AI\get_post_context;
use function WordPress\AI\get_preferred_models_for_text_generation;
use function WordPress\AI\normalize_content;
/**
* Content classification WordPress Ability.
*
* Generates taxonomy term suggestions based on post content analysis.
*
* @since 0.7.0
*/
class Content_Classification extends Abstract_Ability {
/**
* Returns the input schema of the ability.
*
* @since 0.7.0
*
* @return array<string, mixed> The input schema of the ability.
*/
protected function input_schema(): array {
return array(
'type' => 'object',
'properties' => array(
'content' => array(
'type' => 'string',
'description' => esc_html__( 'Content to generate taxonomy suggestions for.', 'ai' ),
),
'post_id' => array(
'type' => 'integer',
'description' => esc_html__( 'Content from this post will be used to generate taxonomy suggestions. This overrides the content parameter if both are provided.', 'ai' ),
),
'taxonomy' => array(
'type' => 'string',
'default' => 'post_tag',
'description' => esc_html__( 'The taxonomy to generate suggestions for (e.g., post_tag, category).', 'ai' ),
),
'strategy' => array(
'type' => 'string',
'default' => Content_Classification_Experiment::STRATEGY_EXISTING_ONLY,
'description' => esc_html__( 'The suggestion strategy: existing_only or allow_new.', 'ai' ),
),
'max_suggestions' => array(
'type' => 'integer',
'minimum' => 1,
'maximum' => 10,
'default' => Content_Classification_Experiment::DEFAULT_MAX_SUGGESTIONS,
'description' => esc_html__( 'Maximum number of suggestions to generate.', 'ai' ),
),
),
);
}
/**
* Returns the output schema of the ability.
*
* @since 0.7.0
*
* @return array<string, mixed> The output schema of the ability.
*/
protected function output_schema(): array {
return array(
'type' => 'object',
'properties' => array(
'suggestions' => array(
'type' => 'array',
'description' => esc_html__( 'Generated taxonomy term suggestions.', 'ai' ),
'items' => array(
'type' => 'object',
'properties' => array(
'term' => array(
'type' => 'string',
'description' => esc_html__( 'The suggested term name.', 'ai' ),
),
'confidence' => array(
'type' => 'number',
'description' => esc_html__( 'Confidence score between 0 and 1.', 'ai' ),
),
'is_new' => array(
'type' => 'boolean',
'description' => esc_html__( 'Whether this is a new term or an existing one.', 'ai' ),
),
'parent' => array(
'type' => 'string',
'description' => esc_html__( 'Parent term name for hierarchical taxonomies.', 'ai' ),
),
),
),
),
),
);
}
/**
* Executes the ability with the given input arguments.
*
* @since 0.7.0
*
* @param mixed $input The input arguments to the ability.
* @return array{suggestions: array<array{term: string, confidence: float, is_new: bool, parent?: string}>}|\WP_Error The result of the ability execution, or a WP_Error on failure.
*/
protected function execute_callback( $input ) {
// Default arguments.
$args = wp_parse_args(
$input,
array(
'content' => null,
'post_id' => null,
'taxonomy' => 'post_tag',
'strategy' => Content_Classification_Experiment::STRATEGY_EXISTING_ONLY,
'max_suggestions' => (int) Content_Classification_Experiment::DEFAULT_MAX_SUGGESTIONS,
),
);
// Validate taxonomy.
if ( ! taxonomy_exists( $args['taxonomy'] ) ) {
return new WP_Error(
'invalid_taxonomy',
/* translators: %s: Taxonomy name. */
sprintf( esc_html__( 'Taxonomy "%s" does not exist.', 'ai' ), sanitize_key( $args['taxonomy'] ) )
);
}
$assigned_terms = array();
// If a post ID is provided, ensure the post exists before using its content.
if ( $args['post_id'] ) {
$post = get_post( (int) $args['post_id'] );
if ( ! $post instanceof WP_Post ) {
return new WP_Error(
'post_not_found',
/* translators: %d: Post ID. */
sprintf( esc_html__( 'Post with ID %d not found.', 'ai' ), absint( $args['post_id'] ) )
);
}
// Get the post context.
$context = get_post_context( (int) $args['post_id'] );
// Default to the passed in content if it exists.
if ( $args['content'] ) {
$context['content'] = normalize_content( $args['content'] );
}
// Get terms already assigned to this post for the taxonomy.
$assigned = wp_get_object_terms( (int) $args['post_id'], $args['taxonomy'], array( 'fields' => 'names' ) );
if ( ! is_wp_error( $assigned ) ) {
$assigned_terms = (array) $assigned;
}
} else {
$context = array(
'content' => normalize_content( $args['content'] ?? '' ),
);
}
// If we have no content, return an error.
if ( empty( $context['content'] ) ) {
return new WP_Error(
'content_not_provided',
esc_html__( 'Content is required to generate taxonomy suggestions.', 'ai' )
);
}
// Generate the suggestions.
$result = $this->generate_suggestions(
$context,
$args['taxonomy'],
$args['strategy'],
(int) $args['max_suggestions'],
$assigned_terms
);
// If we have an error, return it.
if ( is_wp_error( $result ) ) {
return $result;
}
// If we have no results, return an error.
if ( empty( $result ) ) {
return new WP_Error(
'no_results',
esc_html__( 'No taxonomy suggestions were generated.', 'ai' )
);
}
return array(
'suggestions' => $result,
);
}
/**
* Returns the permission callback of the ability.
*
* @since 0.7.0
*
* @param mixed $args The input arguments to the ability.
* @return bool|\WP_Error True if the user has permission, WP_Error otherwise.
*/
protected function permission_callback( $args ) {
$post_id = isset( $args['post_id'] ) ? absint( $args['post_id'] ) : null;
if ( $post_id ) {
$post = get_post( $post_id );
// Ensure the post exists.
if ( ! $post instanceof WP_Post ) {
return new WP_Error(
'post_not_found',
/* translators: %d: Post ID. */
sprintf( esc_html__( 'Post with ID %d not found.', 'ai' ), $post_id )
);
}
// Ensure the user has permission to edit this particular post.
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return new WP_Error(
'insufficient_capabilities',
esc_html__( 'You do not have permission to generate taxonomy suggestions for this post.', 'ai' )
);
}
$post_type_obj = get_post_type_object( $post->post_type );
if ( ! $post_type_obj instanceof WP_Post_Type || empty( $post_type_obj->show_in_rest ) ) {
return false;
}
} elseif ( ! current_user_can( 'edit_posts' ) ) {
// Ensure the user has permission to edit posts in general.
return new WP_Error(
'insufficient_capabilities',
esc_html__( 'You do not have permission to generate taxonomy suggestions.', 'ai' )
);
}
return true;
}
/**
* Returns the meta of the ability.
*
* @since 0.7.0
*
* @return array<string, mixed> The meta of the ability.
*/
protected function meta(): array {
return array(
'show_in_rest' => true,
);
}
/**
* Generates taxonomy term suggestions from the given content.
*
* The LLM generates suggestions based purely on content analysis
* and the currently assigned terms. Post-processing then matches
* suggestions against existing terms and applies the strategy.
*
* @since 0.7.0
*
* @param string|array<string, string> $context The context to generate suggestions from.
* @param string $taxonomy The taxonomy to suggest terms for.
* @param string $strategy The suggestion strategy.
* @param int $max_suggestions The maximum number of suggestions.
* @param array<string> $assigned_terms Terms already assigned to the post.
* @return array<array{term: string, confidence: float, is_new: bool, parent?: string}>|\WP_Error The generated suggestions, or a WP_Error if there was an error.
*/
protected function generate_suggestions( $context, string $taxonomy, string $strategy, int $max_suggestions, array $assigned_terms = array() ) {
// Convert the context to a string if it's an array.
if ( is_array( $context ) ) {
$context = implode(
"\n",
array_map(
static function ( $key, $value ) {
return sprintf(
'%s: %s',
ucwords( str_replace( '_', ' ', $key ) ),
$value
);
},
array_keys( $context ),
$context
)
);
}
// When using existing_only strategy, send the top terms to the LLM
// so it can select from actual terms rather than guessing.
$available_terms = array();
if ( Content_Classification_Experiment::STRATEGY_EXISTING_ONLY === $strategy ) {
$available_terms = $this->get_top_terms( $taxonomy );
}
// Piece together the various prompt parts.
$prompt_parts = array();
$prompt_parts[] = '<taxonomy>' . $taxonomy . '</taxonomy>';
$prompt_parts[] = '<content>' . $context . '</content>';
// If we have currently assigned terms, add them to the prompt to avoid redundant suggestions.
if ( ! empty( $assigned_terms ) ) {
$prompt_parts[] = '<assigned-terms>' . implode( ', ', $assigned_terms ) . '</assigned-terms>';
}
// If we're using the existing_only strategy, add the top 100 terms to the prompt.
if ( ! empty( $available_terms ) ) {
$prompt_parts[] = '<available-terms>' . implode( ', ', $available_terms ) . '</available-terms>';
}
$prompt = implode( "\n", $prompt_parts );
/**
* Filters the prompt string before it is sent to the AI model for taxonomy suggestion generation.
*
* Allows developers to modify, augment, or replace the prompt that the AI analyzes
* when generating taxonomy term suggestions.
*
* @since 0.7.0
*
* @param string $prompt The prompt string to be sent to the AI model.
* @param string|array<string, string> $context The context to generate suggestions from.
* @param string $taxonomy The taxonomy slug being suggested for (e.g., 'post_tag', 'category').
* @param array<string> $assigned_terms Terms already assigned to the post.
* @param array<string> $available_terms Available terms to suggest from.
*/
$prompt = (string) apply_filters( 'wpai_content_classification_prompt', $prompt, $context, $taxonomy, $assigned_terms, $available_terms );
$prompt_builder = $this->get_prompt_builder( $prompt );
if ( is_wp_error( $prompt_builder ) ) {
return $prompt_builder;
}
// Generate the suggestions using the AI client with structured output.
$result = $prompt_builder->generate_text();
if ( is_wp_error( $result ) ) {
return $result;
}
// Parse, match against existing terms, filter, and limit.
$suggestions = $this->parse_suggestions( $result, $strategy, $assigned_terms, $taxonomy, $max_suggestions );
if ( is_wp_error( $suggestions ) ) {
return $suggestions;
}
/**
* Filters the parsed taxonomy suggestions before they are returned to the client.
*
* Allows developers to modify, reorder, add, or remove suggestions after the AI
* has generated them and they have been parsed into structured data.
*
* Each suggestion is an associative array with the keys:
* - 'term' (string) The suggested term name.
* - 'confidence' (float) Confidence score between 0 and 1.
* - 'is_new' (bool) Whether the term is new or already exists on the site.
* - 'parent' (string) Optional. Parent term name for hierarchical taxonomies.
*
* @since 0.7.0
*
* @param array<array{term: string, confidence: float, is_new: bool, parent?: string}> $suggestions The parsed suggestions.
* @param string $taxonomy The taxonomy slug (e.g., 'post_tag', 'category').
* @param string $strategy The suggestion strategy ('existing_only' or 'allow_new').
*/
return (array) apply_filters( 'wpai_content_classification_suggestions', $suggestions, $taxonomy, $strategy );
}
/**
* Get the prompt builder for generating taxonomy term suggestions.
*
* @since 0.7.0
*
* @param string $prompt The prompt to use for generating taxonomy term suggestions.
* @return \WP_AI_Client_Prompt_Builder|\WP_Error The prompt builder, or a WP_Error on failure.
*/
private function get_prompt_builder( string $prompt ) {
$prompt_builder = wp_ai_client_prompt( $prompt )
->using_system_instruction( $this->get_system_instruction() )
->using_temperature( 0.5 )
->using_model_preference( ...get_preferred_models_for_text_generation() )
->as_json_response( $this->suggestions_schema() );
return $this->ensure_text_generation_supported(
$prompt_builder,
esc_html__( 'Term generation failed. Please ensure you have a connected provider that supports text generation.', 'ai' )
);
}
/**
* Returns the JSON schema for structured output from the AI model.
*
* @since 0.7.0
*
* @return array<string, mixed> The JSON schema for structured output.
*/
protected function suggestions_schema(): array {
return array(
'type' => 'object',
'properties' => array(
'suggestions' => array(
'type' => 'array',
'items' => array(
'type' => 'object',
'properties' => array(
'term' => array( 'type' => 'string' ),
'confidence' => array( 'type' => 'number' ),
),
'required' => array( 'term', 'confidence' ),
'additionalProperties' => false,
),
),
),
'required' => array( 'suggestions' ),
'additionalProperties' => false,
);
}
/**
* Parses the AI response into structured suggestions.
*
* Matches LLM suggestions against existing terms (case-insensitive),
* filters out assigned terms, applies the strategy, sorts by confidence,
* and limits to the requested number of suggestions.
*
* @since 0.7.0
*
* @param string $response The raw AI response.
* @param string $strategy The suggestion strategy ('existing_only' or 'allow_new').
* @param array<string> $assigned_terms Terms already assigned to the post.
* @param string $taxonomy The taxonomy to suggest terms for.
* @param int $max_suggestions The maximum number of suggestions to return.
* @return array<array{term: string, confidence: float, is_new: bool, parent?: string}>|\WP_Error Parsed suggestions or error.
*/
private function parse_suggestions( string $response, string $strategy, array $assigned_terms, string $taxonomy, int $max_suggestions ) {
$decoded = json_decode( $response, true );
if ( ! is_array( $decoded ) || ! isset( $decoded['suggestions'] ) || ! is_array( $decoded['suggestions'] ) ) {
return new WP_Error(
'invalid_response',
esc_html__( 'Could not parse AI response as valid suggestions.', 'ai' )
);
}
// Only fetch existing terms when we need them for post-processing (existing_only strategy).
$existing_terms = Content_Classification_Experiment::STRATEGY_EXISTING_ONLY === $strategy
? $this->get_existing_terms( $taxonomy )
: array();
// Build a lowercase → original name lookup for existing terms.
// We don't use slugs here because the LLM may generate terms that don't match the taxonomy slug.
if ( ! empty( $existing_terms ) ) {
$existing_terms = array_combine( array_map( 'strtolower', $existing_terms ), $existing_terms );
}
// Build a lowercase set of assigned terms for filtering.
$assigned_terms = array_map( 'strtolower', $assigned_terms );
$suggestions = array();
foreach ( $decoded['suggestions'] as $item ) {
if ( ! is_array( $item ) || empty( $item['term'] ) ) {
continue;
}
$term = sanitize_text_field( trim( $item['term'] ) );
$term_lower = strtolower( $term );
$is_new = ! isset( $existing_terms[ $term_lower ] );
$confidence = isset( $item['confidence'] ) ? (float) $item['confidence'] : 0.5;
// Skip terms already assigned to the post.
// The agent should avoid suggesting these, but just in case we'll check here as well.
if ( in_array( $term_lower, $assigned_terms, true ) ) {
continue;
}
// For existing_only strategy, skip terms that don't exist.
if ( Content_Classification_Experiment::STRATEGY_EXISTING_ONLY === $strategy && $is_new ) {
continue;
}
// Use the original capitalized name for existing terms.
if ( ! $is_new ) {
$term = $existing_terms[ $term_lower ];
}
$suggestion = array(
'term' => $term,
'confidence' => max( 0.0, min( 1.0, $confidence ) ),
'is_new' => $is_new,
);
// Only preserve parent for hierarchical taxonomies, and strip it
// when the AI returns the taxonomy slug itself as the parent.
if (
! empty( $item['parent'] )
&& is_taxonomy_hierarchical( $taxonomy )
&& strtolower( trim( $item['parent'] ) ) !== strtolower( $taxonomy )
) {
$suggestion['parent'] = sanitize_text_field( trim( $item['parent'] ) );
}
$suggestions[] = $suggestion;
}
// Sort by confidence descending.
usort(
$suggestions,
static function ( $a, $b ) {
return $b['confidence'] <=> $a['confidence'];
}
);
// Limit to max suggestions.
return array_slice( $suggestions, 0, $max_suggestions );
}
/**
* Gets existing terms for a taxonomy.
*
* @since 0.7.0
*
* @param string $taxonomy The taxonomy to get terms for.
* @return array<string> List of existing term names.
*/
private function get_existing_terms( string $taxonomy ): array {
$terms = get_terms(
array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'fields' => 'names',
)
);
if ( is_wp_error( $terms ) ) {
return array();
}
return (array) $terms;
}
/**
* Gets the top terms for a taxonomy, ordered by usage count.
*
* Used to provide the LLM with a set of existing terms to select from
* when using the existing_only strategy, improving match quality.
*
* @since 0.7.0
*
* @param string $taxonomy The taxonomy to get terms for.
* @param int $limit Maximum number of terms to return.
* @return array<string> List of term names ordered by count descending.
*/
private function get_top_terms( string $taxonomy, int $limit = 100 ): array {
$terms = get_terms(
array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'fields' => 'names',
'orderby' => 'count',
'order' => 'DESC',
'number' => $limit,
)
);
if ( is_wp_error( $terms ) ) {
return array();
}
return (array) $terms;
}
}