ChatGPT.php
4.81 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
<?php
/**
* ChatGPT service class.
*
* @package LearnDash\Core
*/
namespace LearnDash\Core\Services;
use Exception;
/**
* ChatGPT client class.
*
* @since 4.6.0
*/
class ChatGPT {
/**
* OpenAI API key.
*
* @since 4.6.0
*
* @var string
*/
private $api_key;
/**
* ChatGPT API url.
*
* @since 4.6.0
*
* @var string
*/
private $api_url = 'https://api.openai.com/v1/chat/completions';
/**
* Constructor.
*
* @param string $api_key OpenAI API key.
*
* @since 4.6.0
*
* @return void
*/
public function __construct( string $api_key ) {
$this->api_key = $api_key;
}
/**
* Get API key.
*
* @since 4.6.0
*
* @return string
*/
public function get_api_key(): string {
return $this->api_key;
}
/**
* Send request to ChatGPT API url.
*
* @since 4.6.0
*
* @throws Exception Throw exception with error message and response code if request failed for any reason.
*
* @param string $method Request method.
* @param array<string, mixed> $body Request body.
* @param array<string, mixed> $headers Request headers.
* @param array<string, mixed> $args Request args.
*
* @return string Response.
*/
public function request( $method = 'GET', $body = [], $headers = [], $args = [] ): string {
$body = wp_parse_args( $body, [] );
$api_key = $this->api_key;
$headers = wp_parse_args(
$headers,
[
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key,
]
);
$args = wp_parse_args(
$args,
[
'method' => $method,
'body' => wp_json_encode( $body ),
'headers' => $headers,
'timeout' => 30,
]
);
$response = wp_remote_request( $this->api_url, $args );
unset( $api_key );
unset( $headers );
unset( $args );
$code = wp_remote_retrieve_response_code( $response );
$body = wp_remote_retrieve_body( $response );
if ( is_wp_error( $response ) || $code !== 200 ) {
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
if ( mb_stristr( $error_message, 'curl error 28' ) ) {
$error_message .= '. ' . esc_html__( 'You might have entered too many lessons. Please try it again with maximum 20-30 lessons. If the issue persists, please check your server or Open AI service status.', 'learndash' );
}
} else {
$body = json_decode( $body, true );
$error_message = is_array( $body ) && isset( $body['error']['message'] ) ? $body['error']['message'] : '';
if ( empty( $error_message ) ) {
$error_code = is_array( $body ) && isset( $body['error']['code'] ) ? $body['error']['code'] : '';
switch ( $error_code ) {
case 'invalid_api_key':
$error_message = __( 'Invalid OpenAI API key. Please check your API key.', 'learndash' );
break;
default:
$error_message = wp_sprintf(
// translators: Error code.
__( 'Code: %s', 'learndash' ),
$error_code
);
break;
}
}
}
$code = is_int( $code ) ? $code : 500;
throw new Exception(
sprintf(
// translators: Error message.
esc_html__( 'Error: %s', 'learndash' ),
$error_message
),
$code
);
}
return $body;
}
/**
* Send request.
*
* @since 4.6.0
*
* @throws Exception Throw exception with error message and response code if request failed for any reason.
*
* @param string $command Command for the request.
*
* @return string
*/
public function send_command( $command ): string {
// Extract values from the command.
preg_match( "/Outline (\d+) lessons for a '(.+)' course on the topic of '(.+)'./", $command, $matches );
$lesson_count = $matches[1];
$course_name = $matches[2];
$course_idea = $matches[3];
$prompt = "Create a numbered bullet list with {$lesson_count} lesson titles for a '{$course_name}' course on the topic of '{$course_idea}'.";
$messages = [
[
'role' => 'system',
'content' => 'You are a helpful assistant.',
],
[
'role' => 'user',
'content' => $prompt,
],
];
/**
* Filters the data to send to ChatGPT API.
*
* @since 4.6.0
*
* @param array<string, mixed> $data Data to send to ChatGPT API.
* @param string $command Command for the request.
*
* @return array<string, mixed>
*/
$data = apply_filters(
'learndash_service_chatgpt_send_command_data',
[
'model' => 'gpt-3.5-turbo',
'messages' => $messages,
'max_tokens' => 3000,
'temperature' => 0.9,
'top_p' => 0.7,
],
$command
);
$response = $this->request(
'POST',
$data
);
$response_data = json_decode( $response, true );
$response_text = is_array( $response_data ) && isset( $response_data['choices'][0]['message']['content'] ) ? $response_data['choices'][0]['message']['content'] : '';
return $response_text;
}
}