-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathGrok.php
More file actions
870 lines (762 loc) · 27.8 KB
/
Grok.php
File metadata and controls
870 lines (762 loc) · 27.8 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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
<?php
/**
* xAI Grok integration
*/
namespace Classifai\Providers\XAI;
use Classifai\Features\ContentResizing;
use Classifai\Features\DescriptiveTextGenerator;
use Classifai\Features\ExcerptGeneration;
use Classifai\Features\TitleGeneration;
use Classifai\Providers\OpenAI\Tokenizer;
use Classifai\Providers\Provider;
use Classifai\Normalizer;
use WP_Error;
use function Classifai\get_default_prompt;
use function Classifai\sanitize_number_of_responses_field;
use function Classifai\get_modified_image_source_url;
use function Classifai\get_largest_size_and_dimensions_image_url;
use function Classifai\get_temperature;
class Grok extends Provider {
/**
* Provider ID
*
* @var string
*/
const ID = 'xai_grok';
/**
* xAI Grok URL
*
* @var string
*/
protected $completions_url = 'https://api.x.ai/v1/chat/completions';
/**
* xAI Models URL
*
* @var string
*/
protected $models_url = 'https://api.x.ai/v1/language-models';
/**
* xAI Grok default model
*
* @var string
*/
protected $default_model = 'grok-2-1212';
/**
* xAI Grok default vision model
*
* @var string
*/
protected $default_vision_model = 'grok-2-vision-1212';
/**
* Maximum number of tokens our model supports
*
* @var int
*/
protected $max_tokens = 131072;
/**
* xAI Grok constructor.
*
* @param \Classifai\Features\Feature $feature_instance The feature instance.
*/
public function __construct( $feature_instance = null ) {
$this->feature_instance = $feature_instance;
}
/**
* Get the model name.
*
* @return string
*/
public function get_model(): string {
$settings = $this->feature_instance->get_settings();
$model = ! empty( $settings[ static::ID ]['model'] ) ? $settings[ static::ID ]['model'] : $this->default_model;
/**
* Filter the model name.
*
* Useful if you want to use a different model, like
* grok-beta
*
* @since 3.3.0
* @hook classifai_xai_grok_model
*
* @param string $model The default model to use.
*
* @return string The model to use.
*/
return apply_filters( 'classifai_xai_grok_model', $model );
}
/**
* Get the vision model (model for images).
*
* @return string
*/
public function get_vision_model(): string {
$settings = $this->feature_instance->get_settings();
$model = ! empty( $settings[ static::ID ]['model'] ) ? $settings[ static::ID ]['model'] : $this->default_vision_model;
/**
* Filter the vision model name (The model with image and text capabilities).
*
* Useful if you want to use a different model, like
* grok-vision-beta
*
* @since 3.3.0
* @hook classifai_xai_grok_vision_model
*
* @param string $model The default model to use.
*
* @return string The model to use.
*/
return apply_filters( 'classifai_xai_grok_vision_model', $model );
}
/**
* Returns the default settings for this provider.
*
* @return array
*/
public function get_default_provider_settings(): array {
$common_settings = [
'api_key' => '',
'authenticated' => false,
'model' => $this->default_model,
'models' => [],
];
/**
* Default values for feature specific settings.
*/
switch ( $this->feature_instance::ID ) {
case ContentResizing::ID:
case TitleGeneration::ID:
$common_settings['number_of_suggestions'] = 1;
break;
case DescriptiveTextGenerator::ID:
$common_settings['model'] = $this->default_vision_model;
$common_settings['prompt'] = [
[
'title' => esc_html__( 'ClassifAI default', 'classifai' ),
'prompt' => $this->feature_instance->prompt,
'original' => 1,
'default' => 1,
],
];
break;
}
return $common_settings;
}
/**
* Sanitize the settings for this provider.
*
* @param array $new_settings The settings array.
* @return array
*/
public function sanitize_settings( array $new_settings ): array {
$settings = $this->feature_instance->get_settings();
$api_key_settings = $this->sanitize_api_key_settings( $new_settings, $settings );
$model = ! empty( $new_settings[ static::ID ]['model'] ) ? sanitize_text_field( $new_settings[ static::ID ]['model'] ) : $this->default_model;
if ( DescriptiveTextGenerator::ID === $this->feature_instance::ID ) {
$model = ! empty( $new_settings[ static::ID ]['model'] ) ? sanitize_text_field( $new_settings[ static::ID ]['model'] ) : $this->default_vision_model;
}
$new_settings[ static::ID ]['api_key'] = $api_key_settings[ static::ID ]['api_key'];
$new_settings[ static::ID ]['authenticated'] = $api_key_settings[ static::ID ]['authenticated'];
$new_settings[ static::ID ]['model'] = $model;
$new_settings[ static::ID ]['models'] = $api_key_settings[ static::ID ]['models'];
switch ( $this->feature_instance::ID ) {
case ContentResizing::ID:
case TitleGeneration::ID:
$new_settings[ static::ID ]['number_of_suggestions'] = sanitize_number_of_responses_field( 'number_of_suggestions', $new_settings[ static::ID ], $settings[ static::ID ] );
break;
}
return $new_settings;
}
/**
* Sanitize the API key, showing an error message if needed.
*
* @param array $new_settings Incoming settings, if any.
* @param array $settings Current settings, if any.
* @return array
*/
public function sanitize_api_key_settings( array $new_settings = [], array $settings = [] ): array {
$models = $this->get_models( $new_settings[ static::ID ]['api_key'] ?? '' );
$new_settings[ static::ID ]['authenticated'] = $settings[ static::ID ]['authenticated'];
$new_settings[ static::ID ]['models'] = $settings[ static::ID ]['models'] ?? [];
if ( is_wp_error( $models ) ) {
$new_settings[ static::ID ]['authenticated'] = false;
$error_message = $models->get_error_message();
// For response code 429, credentials are valid but rate limit is reached.
if ( 429 === (int) $models->get_error_code() ) {
$new_settings[ static::ID ]['authenticated'] = true;
}
add_settings_error(
'api_key',
'classifai-auth',
$error_message,
'error'
);
} else {
$new_settings[ static::ID ]['authenticated'] = true;
switch ( $this->feature_instance::ID ) {
case ContentResizing::ID:
case TitleGeneration::ID:
case ExcerptGeneration::ID:
$text_models = array_filter( $models, fn( $model ) => in_array( 'text', $model['input_modalities'], true ) );
$formatted_models = array();
foreach ( $text_models as $model ) {
$formatted_models[ $model['id'] ] = $model['id'];
}
$new_settings[ static::ID ]['models'] = $formatted_models;
break;
case DescriptiveTextGenerator::ID:
$image_models = array_filter( $models, fn( $model ) => in_array( 'image', $model['input_modalities'], true ) );
$formatted_models = array();
foreach ( $image_models as $model ) {
$formatted_models[ $model['id'] ] = $model['id'];
}
$new_settings[ static::ID ]['models'] = $formatted_models;
break;
}
}
$new_settings[ static::ID ]['api_key'] = sanitize_text_field( $new_settings[ static::ID ]['api_key'] ?? $settings[ static::ID ]['api_key'] );
return $new_settings;
}
/**
* Authenticate our credentials.
*
* @param string $api_key Api Key.
* @return array|WP_Error
*/
protected function get_models( string $api_key = '' ) {
// Check that we have credentials before hitting the API.
if ( empty( $api_key ) ) {
return new WP_Error( 'auth', esc_html__( 'Please enter your xAI API key.', 'classifai' ) );
}
// Make request to ensure credentials work.
$request = new APIRequest( $api_key );
$response = $request->get( $this->models_url );
if ( is_wp_error( $response ) ) {
return $response;
}
$models = $response['models'] ?? [];
/**
* Filter the models returned by the xAI Grok API.
*
* @since 3.6.0
* @hook classifai_xai_grok_models
*
* @param {array} $models The models.
*
* @return {array} The models.
*/
return apply_filters( 'classifai_xai_grok_models', $models );
}
/**
* Common entry point for all REST endpoints for this provider.
*
* @param int $post_id The Post ID we're processing.
* @param string $route_to_call The route we are processing.
* @param array $args Optional arguments to pass to the route.
* @return string|WP_Error
*/
public function rest_endpoint_callback( $post_id = 0, string $route_to_call = '', array $args = [] ) {
if ( ! $post_id || ! get_post( $post_id ) ) {
return new WP_Error( 'post_id_required', esc_html__( 'A valid ID is required.', 'classifai' ) );
}
$route_to_call = strtolower( $route_to_call );
$return = '';
// Handle all of our routes.
switch ( $route_to_call ) {
case 'descriptive_text':
$return = $this->generate_descriptive_text( $post_id, $args );
break;
case 'excerpt':
$return = $this->generate_excerpt( $post_id, $args );
break;
case 'title':
$return = $this->generate_titles( $post_id, $args );
break;
case 'resize_content':
$return = $this->resize_content( $post_id, $args );
break;
}
return $return;
}
/**
* Generate descriptive text of an image.
*
* @param int $post_id The attachment ID we're processing.
* @param array $args Optional arguments.
* @return string|WP_Error
*/
public function generate_descriptive_text( int $post_id = 0, array $args = [] ) {
// Check to be sure the attachment exists and is an image.
if ( ! wp_attachment_is_image( $post_id ) ) {
return new WP_Error( 'invalid', esc_html__( 'This attachment can\'t be processed.', 'classifai' ) );
}
$metadata = wp_get_attachment_metadata( $post_id );
if ( ! $metadata || ! is_array( $metadata ) ) {
return new WP_Error( 'invalid', esc_html__( 'No valid metadata found.', 'classifai' ) );
}
$image_url = get_modified_image_source_url( $post_id );
if ( empty( $image_url ) || ! filter_var( $image_url, FILTER_VALIDATE_URL ) ) {
if ( isset( $metadata['sizes'] ) && is_array( $metadata['sizes'] ) ) {
$image_url = get_largest_size_and_dimensions_image_url(
get_attached_file( $post_id ),
wp_get_attachment_url( $post_id ),
$metadata,
[ 28, 16000 ],
[ 28, 16000 ],
10 * MB_IN_BYTES
);
} else {
$image_url = wp_get_attachment_url( $post_id );
}
}
if ( empty( $image_url ) ) {
return new WP_Error( 'error', esc_html__( 'Valid image size not found. Make sure the image is bigger than 512x512px.', 'classifai' ) );
}
$feature = new DescriptiveTextGenerator();
$settings = $feature->get_settings();
// These checks (and the one above) happen in the REST permission_callback,
// but we run them again here in case this method is called directly.
if ( empty( $settings ) || ( isset( $settings[ static::ID ]['authenticated'] ) && false === $settings[ static::ID ]['authenticated'] ) || ( ! $feature->is_feature_enabled() && ( ! defined( 'WP_CLI' ) || ! WP_CLI ) ) ) {
return new WP_Error( 'not_enabled', esc_html__( 'Descriptive text generation is disabled or xAI authentication failed. Please check your settings.', 'classifai' ) );
}
$request = new APIRequest( $settings[ static::ID ]['api_key'] ?? '', $feature->get_option_name() );
/**
* Filter the prompt we will send to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_descriptive_text_prompt
*
* @param string $prompt Prompt we are sending to xAI Grok.
* @param int $post_id ID of attachment we are describing.
*
* @return string Prompt.
*/
$prompt = apply_filters( 'classifai_xai_grok_descriptive_text_prompt', get_default_prompt( $settings[ static::ID ]['prompt'] ?? [] ) ?? $feature->prompt, $post_id );
/**
* Filter the request body before sending to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_descriptive_text_request_body
*
* @param array $body Request body that will be sent to xAI Grok.
* @param int $post_id ID of attachment we are describing.
*
* @return array Request body.
*/
$body = apply_filters(
'classifai_xai_grok_descriptive_text_request_body',
[
'model' => $this->get_vision_model(),
'messages' => [
[
'role' => 'system',
'content' => $prompt,
],
[
'role' => 'user',
'content' => [
[
'type' => 'image_url',
'image_url' => [
'url' => $image_url,
'detail' => 'auto',
],
],
],
],
],
'temperature' => 0.2,
'max_tokens' => 300,
],
$post_id
);
// Make our API request.
$response = $request->post(
$this->completions_url,
[
'body' => wp_json_encode( $body ),
]
);
// Extract out the text response, if it exists.
if ( ! is_wp_error( $response ) && ! empty( $response['choices'] ) ) {
foreach ( $response['choices'] as $choice ) {
if ( isset( $choice['message'], $choice['message']['content'] ) ) {
$response = sanitize_text_field( trim( $choice['message']['content'], ' "\'' ) );
}
}
}
return $response;
}
/**
* Generate an excerpt using Grok.
*
* @param int $post_id The Post ID we're processing
* @param array $args Arguments passed in.
* @return string|WP_Error
*/
public function generate_excerpt( int $post_id = 0, array $args = [] ) {
if ( ! $post_id || ! get_post( $post_id ) ) {
return new WP_Error( 'post_id_required', esc_html__( 'A valid post ID is required to generate an excerpt.', 'classifai' ) );
}
$feature = new ExcerptGeneration();
$settings = $feature->get_settings();
$args = wp_parse_args(
array_filter( $args ),
[
'content' => '',
'title' => get_the_title( $post_id ),
'author' => '',
]
);
$post_type = get_post_type( $post_id );
// These checks (and the one above) happen in the REST permission_callback,
// but we run them again here in case this method is called directly.
if ( empty( $settings ) || ( isset( $settings[ static::ID ]['authenticated'] ) && false === $settings[ static::ID ]['authenticated'] ) || ( ! $feature->is_feature_enabled() && ( ! defined( 'WP_CLI' ) || ! WP_CLI ) ) ) {
return new WP_Error( 'not_enabled', esc_html__( 'Excerpt generation is disabled or xAI authentication failed. Please check your settings.', 'classifai' ) );
}
$excerpt_length = absint( $settings['length'] ?? 55 );
$request = new APIRequest( $settings[ static::ID ]['api_key'] ?? '', $feature->get_option_name() );
// Overwrite the prompt if we are generating an excerpt for a product.
if ( 'product' === $post_type ) {
$excerpt_prompt = $feature->woo_prompt;
} else {
$excerpt_prompt = esc_textarea( get_default_prompt( $settings['generate_excerpt_prompt'] ) ?? $feature->prompt );
}
// Replace our variables in the prompt.
$prompt_search = array( '{{WORDS}}', '{{TITLE}}', '{{AUTHOR}}' );
$prompt_replace = array( $excerpt_length, $args['title'], $args['author'] );
$prompt = str_replace( $prompt_search, $prompt_replace, $excerpt_prompt );
/**
* Filter the prompt we will send to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_excerpt_prompt
*
* @param string $prompt Prompt we are sending to xAI Grok. Gets added before post content.
* @param int $post_id ID of post we are summarizing.
* @param int $excerpt_length Length of final excerpt.
*
* @return string Prompt.
*/
$prompt = apply_filters( 'classifai_xai_grok_excerpt_prompt', $prompt, $post_id, $excerpt_length );
// Check if we are generating an excerpt for a product.
if ( 'product' === $post_type && function_exists( 'wc_get_product' ) && \wc_get_product( $post_id ) ) {
$args['content'] = $this->get_product_content( $post_id );
}
// Get the filtered content for request.
$message_content = $this->get_content( $post_id, $excerpt_length, false, $args['content'] );
/**
* Filter the request body before sending to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_excerpt_request_body
*
* @param array $body Request body that will be sent to xAI Grok.
* @param int $post_id ID of post we are summarizing.
*
* @return array Request body.
*/
$body = apply_filters(
'classifai_xai_grok_excerpt_request_body',
[
'model' => $this->get_model(),
'messages' => $this->get_request_messages( $post_id, $prompt, $message_content ),
'stream' => false,
'temperature' => 0.9,
],
$post_id
);
// Make our API request.
$response = $request->post(
$this->completions_url,
[
'body' => wp_json_encode( $body ),
]
);
set_transient( 'classifai_xai_grok_excerpt_generation_latest_response', $response, DAY_IN_SECONDS * 30 );
// Extract out the text response, if it exists.
if ( ! is_wp_error( $response ) && ! empty( $response['choices'] ) ) {
foreach ( $response['choices'] as $choice ) {
if ( isset( $choice['message'], $choice['message']['content'] ) ) {
$response = sanitize_text_field( trim( $choice['message']['content'], ' "\'' ) );
}
}
}
return $response;
}
/**
* Generate titles using xAI Grok.
*
* @param int $post_id The Post Id we're processing
* @param array $args Arguments passed in.
* @return string|WP_Error
*/
public function generate_titles( int $post_id = 0, array $args = [] ) {
if ( ! $post_id || ! get_post( $post_id ) ) {
return new WP_Error( 'post_id_required', esc_html__( 'Post ID is required to generate titles.', 'classifai' ) );
}
$feature = new TitleGeneration();
$settings = $feature->get_settings();
$args = wp_parse_args(
array_filter( $args ),
[
'num' => $settings[ static::ID ]['number_of_suggestions'] ?? 1,
'content' => '',
]
);
$post_type = get_post_type( $post_id );
// These checks happen in the REST permission_callback,
// but we run them again here in case this method is called directly.
if ( empty( $settings ) || ( isset( $settings[ static::ID ]['authenticated'] ) && false === $settings[ static::ID ]['authenticated'] ) || ! $feature->is_feature_enabled() ) {
return new WP_Error( 'not_enabled', esc_html__( 'Title generation is disabled or xAI authentication failed. Please check your settings.', 'classifai' ) );
}
$request = new APIRequest( $settings[ static::ID ]['api_key'] ?? '', $feature->get_option_name() );
// Overwrite the prompt if we are generating titles for a product.
if ( 'product' === $post_type ) {
$prompt = $feature->woo_prompt;
} else {
$prompt = esc_textarea( get_default_prompt( $settings['generate_title_prompt'] ) ?? $feature->prompt );
}
/**
* Filter the prompt we will send to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_title_prompt
*
* @param string $prompt Prompt we are sending to xAI Grok. Gets added before post content.
* @param int $post_id ID of post we are summarizing.
* @param array $args Arguments passed to endpoint.
*
* @return string Prompt.
*/
$prompt = apply_filters( 'classifai_xai_grok_title_prompt', $prompt, $post_id, $args );
// Check if we are generating titles for a product.
if ( 'product' === $post_type && function_exists( 'wc_get_product' ) && \wc_get_product( $post_id ) ) {
$args['content'] = $this->get_product_content( $post_id );
}
// Get the filtered content for request.
$message_content = $this->get_content( $post_id, absint( $args['num'] ) * 15, false, $args['content'] );
/**
* Filter the request body before sending to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_title_request_body
*
* @param array $body Request body that will be sent to xAI Grok.
* @param int $post_id ID of post we are summarizing.
*
* @return array Request body.
*/
$body = apply_filters(
'classifai_xai_grok_title_request_body',
[
'model' => $this->get_model(),
'messages' => $this->get_request_messages( $post_id, $prompt, $message_content ),
'temperature' => get_temperature( 0.9, absint( $args['num'] ) ),
'stream' => false,
'n' => absint( $args['num'] ),
],
$post_id
);
// Make our API request.
$response = $request->post(
$this->completions_url,
[
'body' => wp_json_encode( $body ),
]
);
set_transient( 'classifai_xai_grok_title_generation_latest_response', $response, DAY_IN_SECONDS * 30 );
if ( is_wp_error( $response ) ) {
return $response;
}
if ( empty( $response['choices'] ) ) {
return new WP_Error( 'no_choices', esc_html__( 'No choices were returned from xAI.', 'classifai' ) );
}
// Extract out the text response.
$return = [];
foreach ( $response['choices'] as $choice ) {
if ( isset( $choice['message'], $choice['message']['content'] ) ) {
$return[] = sanitize_text_field( trim( $choice['message']['content'], ' "\'' ) );
}
}
return $return;
}
/**
* Resizes content.
*
* @param int $post_id The Post Id we're processing
* @param array $args Arguments passed in.
* @return string|WP_Error
*/
public function resize_content( int $post_id, array $args = array() ) {
if ( ! $post_id || ! get_post( $post_id ) ) {
return new WP_Error( 'post_id_required', esc_html__( 'Post ID is required to resize content.', 'classifai' ) );
}
$feature = new ContentResizing();
$settings = $feature->get_settings();
$args = wp_parse_args(
array_filter( $args ),
[
'num' => $settings[ static::ID ]['number_of_suggestions'] ?? 1,
]
);
$request = new APIRequest( $settings[ static::ID ]['api_key'] ?? '', $feature->get_option_name() );
if ( 'shrink' === $args['resize_type'] ) {
$prompt = esc_textarea( get_default_prompt( $settings['condense_text_prompt'] ) ?? $feature->condense_prompt );
} else {
$prompt = esc_textarea( get_default_prompt( $settings['expand_text_prompt'] ) ?? $feature->expand_prompt );
}
/**
* Filter the resize prompt we will send to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_' . $args['resize_type'] . '_content_prompt
*
* @param string $prompt Resize prompt we are sending to xAI Grok. Gets added as a system prompt.
* @param int $post_id ID of post.
* @param array $args Arguments passed to endpoint.
*
* @return string Prompt.
*/
$prompt = apply_filters( 'classifai_xai_grok_' . $args['resize_type'] . '_content_prompt', $prompt, $post_id, $args );
/**
* Filter the resize request body before sending to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_resize_content_request_body
*
* @param array $body Request body that will be sent to xAI Grok.
* @param int $post_id ID of post.
*
* @return array Request body.
*/
$body = apply_filters(
'classifai_xai_grok_resize_content_request_body',
[
'model' => $this->get_model(),
'messages' => [
[
'role' => 'system',
'content' => 'You will be provided with content delimited by triple quotes. ' . $prompt,
],
[
'role' => 'user',
'content' => '"""' . esc_html( $args['content'] ) . '"""',
],
],
'temperature' => get_temperature( 0.9, absint( $args['num'] ) ),
'stream' => false,
'n' => absint( $args['num'] ),
],
$post_id
);
// Make our API request.
$response = $request->post(
$this->completions_url,
[
'body' => wp_json_encode( $body ),
]
);
set_transient( 'classifai_xai_grok_content_resizing_latest_response', $response, DAY_IN_SECONDS * 30 );
if ( is_wp_error( $response ) ) {
return $response;
}
if ( empty( $response['choices'] ) ) {
return new WP_Error( 'no_choices', esc_html__( 'No choices were returned from xAI.', 'classifai' ) );
}
// Extract out the text response.
$return = [];
foreach ( $response['choices'] as $choice ) {
if ( isset( $choice['message'], $choice['message']['content'] ) ) {
// xAI Grok often adds quotes to strings, so remove those as well as extra spaces.
$return[] = sanitize_text_field( trim( $choice['message']['content'], ' "\'' ) );
}
}
return $return;
}
/**
* Get our content, trimming if needed.
*
* @param int $post_id Post ID to get content from.
* @param int $return_length Word length of returned content.
* @param bool $use_title Whether to use the title or not.
* @param string $post_content The post content.
* @return string
*/
public function get_content( int $post_id = 0, int $return_length = 0, bool $use_title = true, string $post_content = '' ): string {
$tokenizer = new Tokenizer( $this->max_tokens );
$normalizer = new Normalizer();
/**
* We first determine how many tokens, roughly, our returned content will require.
* This is determined by the number of words we expect to be returned and how
* many tokens are in an average word.
*/
$return_tokens = $tokenizer->tokens_in_words( $return_length );
/**
* We then subtract those tokens from the max number of tokens xAI Grok allows
* in a single request, as well as subtracting out the number of tokens in our
* prompt (~50). xAI Grok counts both the tokens in the request and in
* the response towards the max.
*/
$max_content_tokens = $this->max_tokens - $return_tokens - 50;
if ( empty( $post_content ) ) {
$post = get_post( $post_id );
$post_content = apply_filters( 'the_content', $post->post_content );
}
$post_content = preg_replace( '#\[.+\](.+)\[/.+\]#', '$1', $post_content );
// Then trim our content, if needed, to stay under the max.
if ( $use_title ) {
$content = $tokenizer->trim_content(
$normalizer->normalize( $post_id, $post_content ),
(int) $max_content_tokens
);
} else {
$content = $tokenizer->trim_content(
$normalizer->normalize_content( $post_content, '', $post_id ),
(int) $max_content_tokens
);
}
/**
* Filter content that will get sent to xAI Grok.
*
* @since 3.3.0
* @hook classifai_xai_grok_content
*
* @param string $content Content that will be sent to xAI Grok.
* @param int $post_id ID of post we are summarizing.
*
* @return string Content.
*/
return apply_filters( 'classifai_xai_grok_content', $content, $post_id );
}
/**
* Returns the debug information for the provider settings.
*
* @return array
*/
public function get_debug_information(): array {
$settings = $this->feature_instance->get_settings();
$provider_settings = $settings[ static::ID ];
$debug_info = [];
$debug_info[ __( 'Model', 'classifai' ) ] = $this->get_model();
if ( $this->feature_instance instanceof TitleGeneration ) {
$debug_info[ __( 'No. of titles', 'classifai' ) ] = $provider_settings['number_of_suggestions'] ?? 1;
$debug_info[ __( 'Generate title prompt', 'classifai' ) ] = wp_json_encode( $settings['generate_title_prompt'] ?? [] );
$debug_info[ __( 'Latest response', 'classifai' ) ] = $this->get_formatted_latest_response( get_transient( 'classifai_xai_grok_title_generation_latest_response' ) );
} elseif ( $this->feature_instance instanceof ExcerptGeneration ) {
$debug_info[ __( 'Excerpt length', 'classifai' ) ] = $settings['length'] ?? 55;
$debug_info[ __( 'Generate excerpt prompt', 'classifai' ) ] = wp_json_encode( $settings['generate_excerpt_prompt'] ?? [] );
$debug_info[ __( 'Latest response', 'classifai' ) ] = $this->get_formatted_latest_response( get_transient( 'classifai_xai_grok_excerpt_generation_latest_response' ) );
} elseif ( $this->feature_instance instanceof ContentResizing ) {
$debug_info[ __( 'No. of suggestions', 'classifai' ) ] = $provider_settings['number_of_suggestions'] ?? 1;
$debug_info[ __( 'Expand text prompt', 'classifai' ) ] = wp_json_encode( $settings['expand_text_prompt'] ?? [] );
$debug_info[ __( 'Condense text prompt', 'classifai' ) ] = wp_json_encode( $settings['condense_text_prompt'] ?? [] );
$debug_info[ __( 'Latest response', 'classifai' ) ] = $this->get_formatted_latest_response( get_transient( 'classifai_xai_grok_content_resizing_latest_response' ) );
}
return apply_filters(
'classifai_' . self::ID . '_debug_information',
$debug_info,
$settings,
$this->feature_instance
);
}
}