-
Notifications
You must be signed in to change notification settings - Fork 7
/
class-gwiz-gf-openai.php
1623 lines (1399 loc) · 51.7 KB
/
class-gwiz-gf-openai.php
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @package gravityforms-openai
* @copyright Copyright (c) 2022, Gravity Wiz, LLC
* @author Gravity Wiz <[email protected]>
* @license GPLv2
* @link https://github.com/gravitywiz/gravityforms-openai
*/
defined( 'ABSPATH' ) || die();
GFForms::include_feed_addon_framework();
/*
* @todo Make notes configurable
* @todo Make saving to meta configurable
*/
class GWiz_GF_OpenAI extends GFFeedAddOn {
/**
* @var array The default settings to pass to OpenAI
*/
public $default_settings = array(
'chat/completions' => array(
'max_tokens' => 1000,
'temperature' => 1,
'top_p' => 1,
'frequency_penalty' => 0,
'presence_penalty' => 0,
'timeout' => 15,
),
'moderations' => array(
'timeout' => 5,
),
);
/**
* @var GWiz_GF_OpenAI\Dependencies\Inc2734\WP_GitHub_Plugin_Updater\Bootstrap The updater instance.
*/
public $updater;
/**
* @var null|GWiz_GF_OpenAI
*/
private static $instance = null;
protected $_version = GWIZ_GF_OPENAI_VERSION;
protected $_path = 'gravityforms-openai/gravityforms-openai.php';
protected $_full_path = __FILE__;
protected $_slug = 'gravityforms-openai';
protected $_title = 'Gravity Forms OpenAI';
protected $_short_title = 'OpenAI (Free)';
/**
* Defines the capabilities needed for the Add-On.
*
* @var array $_capabilities The capabilities needed for the Add-On
*/
protected $_capabilities = array(
'gravityforms-openai',
'gravityforms-openai_uninstall',
'gravityforms-openai_results',
'gravityforms-openai_settings',
'gravityforms-openai_form_settings',
);
/**
* Defines the capability needed to access the Add-On settings page.
*
* @var string $_capabilities_settings_page The capability needed to access the Add-On settings page.
*/
protected $_capabilities_settings_page = 'gravityforms-openai_settings';
/**
* Defines the capability needed to access the Add-On form settings page.
*
* @var string $_capabilities_form_settings The capability needed to access the Add-On form settings page.
*/
protected $_capabilities_form_settings = 'gravityforms-openai_form_settings';
/**
* Defines the capability needed to uninstall the Add-On.
*
* @var string $_capabilities_uninstall The capability needed to uninstall the Add-On.
*/
protected $_capabilities_uninstall = 'gravityforms-openai_uninstall';
/**
* Disable async feed processing for now as it can prevent results mapped to fields from working in notifications.
*
* @var bool
*/
protected $_async_feed_processing = false;
/**
* Allow re-ordering of feeds.
*
* @var bool
*/
protected $_supports_feed_ordering = true;
public static function get_instance() {
if ( self::$instance === null ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Give the form settings and plugin settings panels a nice shiny icon.
*/
public function get_menu_icon() {
return $this->get_base_url() . '/icon.svg';
}
/**
* Defines the minimum requirements for the add-on.
*
* @return array
*/
public function minimum_requirements() {
return array(
'gravityforms' => array(
'version' => '2.5',
),
'wordpress' => array(
'version' => '4.8',
),
);
}
/**
* Load dependencies and initialize auto-updater
*/
public function pre_init() {
parent::pre_init();
$this->setup_autoload();
$this->init_auto_updater();
add_filter( 'gform_export_form', array( $this, 'export_feeds_with_form' ) );
add_action( 'gform_forms_post_import', array( $this, 'import_feeds_with_form' ) );
add_action( 'admin_footer', array( $this, 'add_warning_css' ) );
}
/**
* @credit https://github.com/google/site-kit-wp
*/
public function setup_autoload() {
$class_map = array_merge(
include plugin_dir_path( __FILE__ ) . 'third-party/vendor/composer/autoload_classmap.php'
);
spl_autoload_register(
function ( $class ) use ( $class_map ) {
if ( isset( $class_map[ $class ] ) && substr( $class, 0, 27 ) === 'GWiz_GF_OpenAI\\Dependencies' ) {
require_once $class_map[ $class ];
}
},
true,
true
);
}
/**
* Initialize the auto-updater.
*/
public function init_auto_updater() {
// Initialize GitHub auto-updater
add_filter(
'inc2734_github_plugin_updater_plugins_api_gravitywiz/gravityforms-openai',
array( $this, 'filter_auto_updater_response' ), 10, 2
);
$this->updater = new GWiz_GF_OpenAI\Dependencies\Inc2734\WP_GitHub_Plugin_Updater\Bootstrap(
plugin_basename( plugin_dir_path( __FILE__ ) . 'gravityforms-openai.php' ),
'gravitywiz',
'gravityforms-openai',
array(
'description_url' => 'https://raw.githubusercontent.com/gravitywiz/gravityforms-openai/master/readme.md',
'changelog_url' => 'https://raw.githubusercontent.com/gravitywiz/gravityforms-openai/master/changelog.txt',
'icons' => array(
'svg' => 'https://raw.githubusercontent.com/gravitywiz/gravityforms-openai/master/icon.svg',
),
'banners' => array(
'low' => 'https://gravitywiz.com/wp-content/uploads/2022/12/gfoai-by-dalle-1.png',
),
'requires_php' => '5.6.0',
)
);
}
/**
* Filter the GitHub auto-updater response to remove sections we don't need and update various fields.
*
* @param stdClass $obj
* @param stdClass $response
*
* @return stdClass
*/
public function filter_auto_updater_response( $obj, $response ) {
$remove_sections = array(
'installation',
'faq',
'screenshots',
'reviews',
'other_notes',
);
foreach ( $remove_sections as $section ) {
if ( isset( $obj->sections[ $section ] ) ) {
unset( $obj->sections[ $section ] );
}
}
if ( isset( $obj->active_installs ) ) {
unset( $obj->active_installs );
}
$obj->homepage = 'https://gravitywiz.com/gravity-forms-openai/';
$obj->author = '<a href="https://gravitywiz.com/" target="_blank">Gravity Wiz</a>';
$parsedown = new GWiz_GF_OpenAI\Dependencies\Parsedown();
$changelog = trim( $obj->sections['changelog'] );
// Remove the "Changelog" h1.
$changelog = preg_replace( '/^# Changelog/m', '', $changelog );
// Remove the tab before the list item so it's not treated as code.
$changelog = preg_replace( '/^\t- /m', '- ', $changelog );
// Convert h2 to h4 to avoid weird styles that add a lot of whitespace.
$changelog = preg_replace( '/^## /m', '#### ', $changelog );
$obj->sections['changelog'] = $parsedown->text( $changelog );
return $obj;
}
/**
* Initialize the add-on. Similar to construct, but done later.
*
* @return void
*/
public function init() {
parent::init();
load_plugin_textdomain( $this->_slug, false, basename( dirname( __file__ ) ) . '/languages/' );
// Filters/actions
add_filter( 'gform_tooltips', array( $this, 'tooltips' ) );
add_filter( 'gform_validation', array( $this, 'moderations_endpoint_validation' ) );
add_filter( 'gform_validation_message', array( $this, 'modify_validation_message' ), 15, 2 );
add_filter( 'gform_entry_is_spam', array( $this, 'moderations_endpoint_spam' ), 10, 3 );
add_filter( 'gform_pre_replace_merge_tags', array( $this, 'replace_merge_tags' ), 10, 7 );
}
/**
* Defines the available models.
*/
public function get_openai_models() {
$models = array(
'chat/completions' => array(
'gpt-4o' => array(
'description' => __( 'OpenAI\'s fastest and most affordable flagship model. Context length: 128k. <a href="https://platform.openai.com/docs/models/gpt-4o" target="_blank">More Details</a>', 'gravityforms-openai' ),
),
'gpt-4-turbo' => array(
'description' => __( 'OpenAI\'s previous high-intelligence model. Context length: 128k. <a href="https://platform.openai.com/docs/models/gpt-4-turbo-and-gpt-4" target="_blank">More Details</a>', 'gravityforms-openai' ),
),
'gpt-4o-mini' => array(
'description' => __( 'OpenAI\'s most cost-efficient small model. Context length: 128k. <a href="https://platform.openai.com/docs/models/gpt-4o-mini" target="_blank">More Details</a>', 'gravityforms-openai' ),
),
'gpt-3.5-turbo' => array(
'description' => __( 'Inexpensive model for simple tasks. Context length: 16k. <a href="https://platform.openai.com/docs/models/gpt-3-5-turbo" target="_blank">More Details</a>', 'gravityforms-openai' ),
),
),
'moderations' => array(
'text-moderation-stable' => array(
'type' => 'Moderation',
),
'text-moderation-latest' => array(
'type' => 'Moderation',
),
),
);
return apply_filters( 'gf_openai_models', $models );
}
/**
* Gets models owned by the user or organization.
*/
public function get_user_models() {
$url = 'https://api.openai.com/v1/models';
$cache_key = sha1( $url );
$transient = 'gform_openai_cache_' . $cache_key;
if ( get_transient( $transient ) ) {
return get_transient( $transient );
}
$response = wp_remote_get( $url, array(
'headers' => $this->get_headers(),
'timeout' => 5,
) );
$models = array();
if ( ! is_wp_error( $response ) ) {
try {
$response = wp_remote_retrieve_body( $response );
$response = json_decode( $response, true );
if ( is_array( rgar( $response, 'data' ) ) ) {
// Filter results to only models owned by the user/org.
foreach ( $response['data'] as $model ) {
if ( strpos( $model['owned_by'], 'user-' ) === 0 || strpos( $model['owned_by'], 'org-' ) === 0 ) {
$models[ $model['id'] ] = array_merge(
$model,
array(
'user_model' => true,
)
);
}
}
}
} catch ( Exception $e ) {
// Do nothing, $models is already an empty array.
}
}
// Cache for 5 minutes.
set_transient( $transient, $models, 5 * MINUTE_IN_SECONDS );
return $models;
}
/**
* Defines the settings for the plugin's global settings such as API key. Accessible via Forms » Settings
*
* @return array[]
*/
public function plugin_settings_fields() {
return array(
array(
'title' => $this->_title,
'fields' => array(
array(
'name' => 'secret_key',
'tooltip' => __( 'Enter your OpenAI secret key.', 'gravityforms-openai' ),
'description' => '<a href="https://beta.openai.com/account/api-keys" target="_blank">'
. __( 'Manage API keys' ) . '</a><br />'
. sprintf(
// translators: placeholder is a <code> element
__( 'Example: %s', 'gravityforms-openai' ),
'<code>sk-5q6D85X27xr1e1bNEUuLGQp6a0OANXvFxyIo1WnuUbsNb21Z</code>'
),
'label' => 'Secret Key',
'type' => 'text',
'input_type' => 'password',
'class' => 'medium',
'required' => true,
),
array(
'name' => 'organization',
'tooltip' => __( 'Enter your OpenAI organization if you belong to multiple.', 'gravityforms-openai' ),
'description' => '<a href="https://beta.openai.com/account/org-settings" target="_blank">'
. __( 'Organization Settings' ) . '</a><br />'
. sprintf(
// translators: placeholder is a <code> element
__( 'Example: %s', 'gravityforms-openai' ),
'<code>org-st6H4JIzknQvU9MoNqRWxPst</code>'
),
'label' => 'Organization',
'type' => 'text',
'class' => 'medium',
'required' => false,
),
),
),
);
}
/**
* @return array
*/
public function feed_list_columns() {
return array(
'feed_name' => __( 'Name', 'gravityforms-openai' ),
'endpoint' => __( 'OpenAI Endpoint', 'gravityforms-openai' ),
);
}
/**
* Registers tooltips with Gravity Forms. Needed for some things like radio choices.
*
* @param $tooltips array Existing tooltips.
*
* @return array
*/
public function tooltips( $tooltips ) {
foreach ( $this->get_openai_models() as $endpoint => $models ) {
foreach ( $models as $model => $model_info ) {
if ( ! rgar( $model_info, 'description' ) ) {
continue;
}
$tooltips[ 'openai_model_' . $model ] = $model_info['description'];
}
}
$tooltips['openai_endpoint_chat_completions'] = __( 'Given a single message, the model will return a model-generated message as an output.', 'gravityforms-openai' );
$tooltips['openai_endpoint_moderations'] = __( 'Given a input text, outputs if the model classifies it as violating OpenAI\'s content policy.', 'gravityforms-openai' );
return $tooltips;
}
/**
* Convert our array of models to choices that a radio settings field can use.
*
* @param $endpoint string The endpoint we're getting models for.
*
* @return array
*/
public function get_openai_model_choices( $endpoint ) {
$choices = array();
$models = rgar( $this->get_openai_models(), $endpoint );
// Add user models to completions models.
if ( $endpoint === 'completions' ) {
$models = array_merge( $models, $this->get_user_models() );
}
if ( ! $models ) {
return array();
}
foreach ( $models as $model => $model_info ) {
$choices[] = array(
'label' => $model . ( rgar( $model_info, 'waitlist' ) ? ' (' . __( 'Requires Waitlist', 'gravityforms-openai' ) . ')' : '' ),
'value' => $model,
'tooltip' => ! rgar( $model_info, 'user_model' ) ? 'openai_model_' . $model : null,
);
}
return $choices;
}
public function can_duplicate_feed( $feed_id ) {
return true;
}
public function feed_settings_fields() {
return array(
array(
'title' => 'General Settings',
'fields' => array(
array(
'label' => __( 'Name', 'gp-limit-submissions' ),
'type' => 'text',
'name' => 'feed_name',
'default_value' => $this->get_default_feed_name(),
'class' => 'medium',
'tooltip' => __( 'Enter a name for this OpenAI feed. Only displayed on administrative screens.', 'gravityforms-openai' ),
'required' => true,
),
array(
'name' => 'endpoint',
'tooltip' => 'Select the OpenAI Endpoint to use.',
'label' => __( 'OpenAI Endpoint', 'gravityforms-openai' ),
'type' => 'radio',
'choices' => array(
array(
'value' => 'chat/completions',
'label' => __( 'Chat Completions', 'gravityforms-openai' ),
'tooltip' => 'openai_endpoint_chat_completions',
),
array(
'value' => 'moderations',
'label' => __( 'Moderations', 'gravityforms-openai' ),
'tooltip' => 'openai_endpoint_moderations',
),
),
'default_value' => 'completions',
),
),
),
array(
'title' => 'Chat Completions',
'fields' => array(
array(
'name' => 'chat_completions_model',
'tooltip' => 'Select the OpenAI model to use.',
'label' => __( 'OpenAI Model', 'gravityforms-openai' ),
'type' => 'radio',
'choices' => $this->get_openai_model_choices( 'chat/completions' ),
'required' => true,
),
array(
'name' => 'chat_completions_message',
'tooltip' => 'Enter the message to send to OpenAI.',
'label' => 'Message',
'type' => 'textarea',
'class' => 'medium merge-tag-support mt-position-right',
'required' => true,
),
$this->feed_setting_enable_merge_tag( 'chat/completions' ),
$this->feed_setting_map_result_to_field( 'chat/completions' ),
),
'dependency' => array(
'live' => true,
'fields' => array(
array(
'field' => 'endpoint',
'values' => array( 'chat/completions' ),
),
),
),
),
array(
'title' => 'Moderations',
'fields' => array(
array(
'name' => 'moderations_model',
'tooltip' => 'Select the OpenAI model to use.',
'label' => __( 'OpenAI Model', 'gravityforms-openai' ),
'type' => 'radio',
'choices' => $this->get_openai_model_choices( 'moderations' ),
'required' => true,
),
array(
'name' => 'moderations_input',
'tooltip' => 'Enter the input to send to OpenAI for moderation.',
'label' => 'Input',
'default_value' => '{all_fields}',
'type' => 'textarea',
'class' => 'medium merge-tag-support mt-position-right',
'required' => true,
),
array(
'name' => 'moderations_behavior',
'tooltip' => 'What to do if moderations says the content policy is violated.',
'label' => 'Behavior',
'type' => 'select',
'choices' => array(
array(
'label' => __( 'Do nothing' ),
'value' => '',
),
array(
'label' => __( 'Mark entry as spam' ),
'value' => 'spam',
),
array(
'label' => __( 'Prevent submission by showing validation error' ),
'value' => 'validation_error',
),
),
'required' => false,
'fields' => array(
array(
'name' => 'moderations_validation_message',
'tooltip' => __( 'The validation message to display if the content policy is violated.', 'gravityforms-openai' ),
'label' => 'Validation Message',
'type' => 'text',
'placeholder' => $this->get_default_moderations_validation_message(),
'dependency' => array(
'live' => true,
'fields' => array(
array(
'field' => 'moderations_behavior',
'values' => array( 'validation_error' ),
),
),
),
),
),
),
),
'dependency' => array(
'live' => true,
'fields' => array(
array(
'field' => 'endpoint',
'values' => array( 'moderations' ),
),
),
),
),
//Conditional Logic
array(
'title' => esc_html__( 'Conditional Logic', 'gravityforms-openai' ),
'fields' => array(
array(
'label' => '',
'name' => 'conditional_logic',
'type' => 'feed_condition',
),
),
),
array(
'title' => 'Advanced Settings: Chat Completions',
'id' => 'advanced_settings_chat_completions',
'fields' => array(
$this->feed_advanced_setting_timeout( 'chat/completions' ),
$this->feed_advanced_setting_max_tokens( 'chat/completions' ),
$this->feed_advanced_setting_temperature( 'chat/completions' ),
$this->feed_advanced_setting_top_p( 'chat/completions' ),
$this->feed_advanced_setting_frequency_penalty( 'chat/completions' ),
$this->feed_advanced_setting_presence_penalty( 'chat/completions' ),
),
'collapsible' => true,
'is_collapsed' => ! isset( $_POST['gform_settings_section_collapsed_advanced_settings_chat_completions'] ),
'dependency' => array(
'live' => true,
'fields' => array(
array(
'field' => 'endpoint',
'values' => array( 'chat/completions' ),
),
),
),
),
array(
'title' => 'Advanced Settings: Moderations',
'id' => 'advanced_settings_moderations',
'fields' => array(
$this->feed_advanced_setting_timeout( 'moderations' ),
),
'collapsible' => true,
'is_collapsed' => ! isset( $_POST['gform_settings_section_collapsed_advanced_settings_moderations'] ),
'dependency' => array(
'live' => true,
'fields' => array(
array(
'field' => 'endpoint',
'values' => array( 'moderations' ),
),
),
),
),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_setting_enable_merge_tag( $endpoint ) {
return array(
'name' => $endpoint . '_enable_merge_tag',
'type' => 'checkbox',
'label' => __( 'Merge Tag', 'gravityforms-openai' ),
'description' => __( 'Enable getting the output of the OpenAI result using a merge tag.', 'gravityforms-openai' ),
'choices' => array(
array(
'name' => $endpoint . '_enable_merge_tag',
'label' => __( 'Enable Merge Tag', 'gravityforms' ),
),
),
'fields' => array(
array(
'name' => 'merge_tag_preview_' . $endpoint,
'type' => 'html',
'html' => rgget( 'fid' ) ? '<style>
#openai_merge_tag_usage {
line-height: 1.6rem;
}
#openai_merge_tag_usage ul {
padding: 0 0 0 1rem;
}
#openai_merge_tag_usage ul li {
list-style: disc;
}
</style>
<div id="openai_merge_tag_usage"><strong>Usage:</strong><br />
<ul>
<li><code>{openai_feed_' . rgget( 'fid' ) . '}</code></li>
</ul>
<strong>Usage as a <a href="https://gravitywiz.com/documentation/gravity-forms-populate-anything/#live-merge-tags" target="_blank">Live Merge Tag</a>:</strong><br />
<ul>
<li><code>@{:FIELDID:openai_feed_' . rgget( 'fid' ) . '}</code><br />Replace <code>FIELDID</code> accordingly. Automatically refreshes in the form if the specified field ID changes.</li>
<li><code>@{all_fields:openai_feed_' . rgget( 'fid' ) . '}</code><br />Automatically refreshes in the form if any field value changes.</li>
</ul><div></div>' : 'Save feed to see merge tags.',
'dependency' => array(
'live' => true,
'fields' => array(
array(
'field' => $endpoint . '_enable_merge_tag',
),
),
),
),
),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_setting_map_result_to_field( $endpoint ) {
return array(
'name' => $endpoint . '_map_result_to_field',
'type' => 'field_select',
'label' => __( 'Map Result to Field', 'gravityforms-openai' ),
'description' => __( 'Take the result and attach it to a field\'s value upon submission.', 'gravityforms-openai' ),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_advanced_setting_timeout( $endpoint ) {
$default = rgar( rgar( $this->default_settings, $endpoint ), 'timeout' );
return array(
'name' => $endpoint . '_' . 'timeout',
'tooltip' => 'Enter the number of seconds to wait for OpenAI to respond.',
'label' => 'Timeout',
'type' => 'text',
'class' => 'small',
'required' => false,
'default_value' => $default,
// translators: placeholder is a number
'description' => sprintf( __( 'Default: <code>%d</code> seconds.', 'gravityforms-openai' ), $default ),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_advanced_setting_max_tokens( $endpoint ) {
$default = rgar( rgar( $this->default_settings, $endpoint ), 'max_tokens' );
return array(
'name' => $endpoint . '_' . 'max_tokens',
'tooltip' => __( 'The maximum number of <a href="https://beta.openai.com/tokenizer" target="_blank">tokens</a> to generate in the completion.
<br /><br />
The token count of your prompt plus max_tokens cannot exceed the model\'s context
length. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).', 'gravityforms-openai' ),
'label' => 'Max Tokens',
'type' => 'text',
'class' => 'small',
'required' => false,
'default_value' => $default,
// translators: placeholder is a number
'description' => sprintf( __( 'Default: <code>%d</code>', 'gravityforms-openai' ), $default ),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_advanced_setting_temperature( $endpoint ) {
$default = rgar( rgar( $this->default_settings, $endpoint ), 'temperature' );
return array(
'name' => $endpoint . '_' . 'temperature',
'tooltip' => __( 'What <a href="https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277" target="_blank">sampling</a>
temperature to use. Higher values means the model will take more risks. Try 0.9 for more
creative applications, and 0 (argmax sampling) for ones with a well-defined answer.
<br /><br />
We generally recommend altering this or <code>top_p</code> but not both.', 'gravityforms-openai' ),
'label' => 'Temperature',
'type' => 'text',
'class' => 'small',
'required' => false,
'default_value' => $default,
// translators: placeholder is a number
'description' => sprintf( __( 'Default: <code>%d</code>', 'gravityforms-openai' ), $default ),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_advanced_setting_top_p( $endpoint ) {
$default = rgar( rgar( $this->default_settings, $endpoint ), 'top_p' );
return array(
'name' => $endpoint . '_' . 'top_p',
'tooltip' => __( 'An alternative to sampling with temperature, called nucleus sampling,
where the model considers the results of the tokens with top_p probability mass. So 0.1
means only the tokens comprising the top 10% probability mass are considered.
<br /><br />
We generally recommend altering this or temperature but not both.', 'gravityforms-openai' ),
'label' => 'Top-p',
'type' => 'text',
'class' => 'small',
'required' => false,
'default_value' => $default,
// translators: placeholder is a number
'description' => sprintf( __( 'Default: <code>%d</code>', 'gravityforms-openai' ), $default ),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_advanced_setting_frequency_penalty( $endpoint ) {
$default = rgar( rgar( $this->default_settings, $endpoint ), 'frequency_penalty' );
return array(
'name' => $endpoint . '_' . 'frequency_penalty',
'tooltip' => __( 'Number between -2.0 and 2.0. Positive values penalize new tokens based
on their existing frequency in the text so far, decreasing the model\'s likelihood to
repeat the same line verbatim.
<br /><br />
<a href="https://beta.openai.com/docs/api-reference/parameter-details" target="_blank">See more information about frequency and presence penalties.</a>', 'gravityforms-openai' ),
'label' => 'Frequency Penalty',
'type' => 'text',
'class' => 'small',
'required' => false,
'default_value' => $default,
// translators: placeholder is a number
'description' => sprintf( __( 'Default: <code>%d</code>', 'gravityforms-openai' ), $default ),
);
}
/**
* @param $endpoint string The OpenAI endpoint.
*
* @return array
*/
public function feed_advanced_setting_presence_penalty( $endpoint ) {
$default = rgar( rgar( $this->default_settings, $endpoint ), 'presence_penalty' );
return array(
'name' => $endpoint . '_' . 'presence_penalty',
'tooltip' => __( 'Number between -2.0 and 2.0. Positive values penalize new tokens based
on whether they appear in the text so far, increasing the model\'s likelihood to talk
about new topics.
<br /><br />
<a href="https://beta.openai.com/docs/api-reference/parameter-details" target="_blank">See more information about frequency and presence penalties.</a>', 'gravityforms-openai' ),
'label' => 'Presence Penalty',
'type' => 'text',
'class' => 'small',
'required' => false,
'default_value' => $default,
// translators: placeholder is a number
'description' => sprintf( __( 'Default: <code>%d</code>', 'gravityforms-openai' ), $default ),
);
}
/**
* Processes the feed and sends the data to OpenAI.
*
* @param array $feed
* @param array $entry
* @param array $form
*
* @return array|void|null
*/
public function process_feed( $feed, $entry, $form ) {
$feed = $this->transform_feed( $feed );
$endpoint = $feed['meta']['endpoint'];
switch ( $endpoint ) {
case 'chat/completions':
$entry = $this->process_endpoint_chat_completions( $feed, $entry, $form );
break;
case 'moderations':
$this->process_endpoint_moderations( $feed, $entry, $form );
break;
default:
// translators: placeholder is an unknown OpenAI endpoint.
$this->add_feed_error( sprintf( __( 'Unknown endpoint: %s' ), $endpoint ), $feed, $entry, $form );
break;
}
return $entry;
}
/**
* Process chat endpoint.
*
* @param $feed array The current feed being processed.
* @param $entry array The current entry being processed.
* @param $form array The current form being processed.
*
* @return array Modified entry.
*/
public function process_endpoint_chat_completions( $feed, $entry, $form ) {
$model = $feed['meta']['chat_completions_model'];
$message = $feed['meta']['chat_completions_message'];
// Parse the merge tags in the message.
$message = GFCommon::replace_variables( $message, $form, $entry, false, false, false, 'text' );
// Allow filtering the message
$message = apply_filters( 'gf_openai_chat_completions_message', $message, $entry, $feed, $form );
GFAPI::add_note( $entry['id'], 0, 'OpenAI Request (' . $feed['meta']['feed_name'] . ')', sprintf( __( 'Sent request to OpenAI chat/completions endpoint.', 'gravityforms-openai' ) ) );
// translators: placeholders are the feed name, model, prompt
$this->log_debug( __METHOD__ . '(): ' . sprintf( __( 'Sent request to OpenAI. Feed: %1$s, Endpoint: chat, Model: %2$s, Message: %3$s', 'gravityforms-openai' ), $feed['meta']['feed_name'], $model, $message ) );
$response = $this->make_request( 'chat/completions', array(
'messages' => array(
array(
'role' => 'user',
'content' => $message,
),
),
'model' => $model,
), $feed );
if ( is_wp_error( $response ) ) {
// If there was an error, log it and return.
$this->add_feed_error( $response->get_error_message(), $feed, $entry, $form );
return $entry;
}
// Parse the response and add it as an entry note.
$response_data = json_decode( $response['body'], true );
if ( rgar( $response_data, 'error' ) ) {
$this->add_feed_error( $response_data['error']['message'], $feed, $entry, $form );
return $entry;
}
$text = $this->get_text_from_response( $response_data );
if ( ! is_wp_error( $text ) ) {
GFAPI::add_note( $entry['id'], 0, 'OpenAI Response (' . $feed['meta']['feed_name'] . ')', $text );
$entry = $this->maybe_save_result_to_field( $feed, $entry, $form, $text );
} else {
$this->add_feed_error( $text->get_error_message(), $feed, $entry, $form );
}
gform_add_meta( $entry['id'], 'openai_response_' . $feed['id'], $response['body'] );
return $entry;
}
/**
* Saves the result to the selected field if configured.
*
* @return array Modified entry.
*/
public function maybe_save_result_to_field( $feed, $entry, $form, $text ) {
$endpoint = rgars( $feed, 'meta/endpoint' );
$map_result_to_field = rgar( rgar( $feed, 'meta' ), $endpoint . '_map_result_to_field' );
if ( ! is_numeric( $map_result_to_field ) ) {
return $entry;
}
$field = GFAPI::get_field( $form, (int) $map_result_to_field );
if ( rgar( $field, 'useRichTextEditor' ) ) {
$text = wp_kses_post( $text );
} else {
// br2nl
$text = preg_replace( '/<br\s?\/?>/ius', "\n", str_replace( "\n", '', str_replace( "\r", '', htmlspecialchars_decode( $text ) ) ) );
$text = wp_strip_all_tags( $text );
}
$entry[ $map_result_to_field ] = $text;
GFAPI::update_entry_field( $entry['id'], $map_result_to_field, $text );
gf_do_action( array( 'gf_openai_post_save_result_to_field', $form['id'] ), $text );
return $entry;
}
/**
* Process moderations endpoint.
*
* @param $feed array The current feed being processed.
* @param $entry array The current entry being processed.
* @param $form array The current form being processed.
*
* @return boolean Whether the entry was flagged or not.
*/
public function process_endpoint_moderations( $feed, $entry, $form ) {
$model = $feed['meta']['moderations_model'];
$input = $feed['meta']['moderations_input'];