PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.8.1
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.8.1
4.9.1 4.9.0 4.8.2 4.8.1 4.8.0 4.7.0 4.6.2 4.6.1 4.6.0 4.5.6 4.5.5 4.5.4 4.5.3 4.5.2 4.5.1 4.5.0 4.4.1 4.4.0 3.3.4 3.4.0 3.4.1 3.4.2 3.5.0 3.5.1 3.5.2 All 199 releases
betterdocs / includes / Utils / AIHelper.php

AIHelper.php in BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot 4.8.1, at includes/Utils/AIHelper.php

495 lines 17.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace WPDeveloper\BetterDocs\Utils;
4
5 use WPDeveloper\BetterDocs\Core\Settings;
6 use WPDeveloper\BetterDocs\AI\ProviderFactory;
7
8 class AIHelper {
9
10 /**
11 * Settings instance
12 *
13 * @var Settings
14 */
15 private $settings;
16
17 public function __construct( Settings $settings ) {
18 $this->settings = $settings;
19 }
20
21 /**
22 * Build a provider factory bound to the current settings.
23 *
24 * @return ProviderFactory
25 */
26 private function factory() {
27 return new ProviderFactory( $this->settings );
28 }
29
30 /**
31 * Get the API key for the active AI platform.
32 *
33 * @return string
34 */
35 public function get_api_key() {
36 $factory = $this->factory();
37 return $factory->api_key_for( $factory->active_platform() );
38 }
39
40 /**
41 * Check if OpenAI API key is configured
42 *
43 * @return bool
44 */
45 public function has_api_key() {
46 $api_key = $this->get_api_key();
47 return ! empty( $api_key );
48 }
49
50 /**
51 * Validate OpenAI API key
52 *
53 * @param string $api_key Optional API key to validate, uses stored key if not provided
54 * @return array Array with 'valid' boolean and 'message' string
55 */
56 public function validate_api_key( $api_key = '' ) {
57 if ( empty( $api_key ) ) {
58 $api_key = $this->get_api_key();
59 }
60
61 if ( empty( $api_key ) ) {
62 return array(
63 'valid' => false,
64 'message' => 'Please Insert your <a href="/admin.php?page=betterdocs-settings#betterdocs-ai">API Key</a> to use AI features.'
65 );
66 }
67
68 $factory = $this->factory();
69 return $factory->validate( $factory->active_platform(), $api_key );
70 }
71
72 /**
73 * Minimum token policy by (feature context, model family). Used as the
74 * single source of truth for:
75 * - server-side save validation (Core/Settings.php)
76 * - field UI props sent to the React notice (Core/Settings.php)
77 * - runtime payload floor in the provider layer (AI\Providers\BaseProvider::floor_tokens)
78 *
79 * Override the whole map (or any cell) via the `betterdocs_ai_min_tokens`
80 * filter. Returns 0 when no minimum applies (unknown context or model).
81 *
82 * @param string $context Feature key, e.g. 'write_with_ai' or 'article_summary'.
83 * @param string $model OpenAI model identifier.
84 * @return int Minimum recommended max_tokens for that pair.
85 */
86 public static function get_min_tokens( $context, $model ) {
87 $family = self::token_family( $model );
88 $map = apply_filters( 'betterdocs_ai_min_tokens', array(
89 'write_with_ai' => array( 'gpt-4' => 2500, 'gpt-5' => 4500, 'gpt-5.5' => 10000 ),
90 'article_summary' => array( 'gpt-4' => 1500, 'gpt-5' => 2500, 'gpt-5.5' => 10000 ),
91 ) );
92 return isset( $map[ $context ][ $family ] ) ? (int) $map[ $context ][ $family ] : 0;
93 }
94
95 /**
96 * Map a model id to its token-floor family key.
97 *
98 * gpt-5.x point releases (gpt-5.5, gpt-5.1, ...) generate much larger, slower
99 * responses and need a heavier floor than the base gpt-5 family, so they get
100 * their own 'gpt-5.5' key. Plain gpt-5* stays 'gpt-5'; everything else 'gpt-4'.
101 *
102 * @param string $model OpenAI model identifier.
103 * @return string Family key used in the min-token map.
104 */
105 private static function token_family( $model ) {
106 if ( self::is_gpt5_point_release( $model ) ) {
107 return 'gpt-5.5';
108 }
109 return ( 0 === strpos( (string) $model, 'gpt-5' ) ) ? 'gpt-5' : 'gpt-4';
110 }
111
112 /**
113 * Whether a model is a gpt-5.x point release (gpt-5.5, gpt-5.1, ...), which
114 * use the newer reasoning_effort vocabulary and need a heavier token floor.
115 *
116 * @param string $model OpenAI model identifier.
117 * @return bool
118 */
119 public static function is_gpt5_point_release( $model ) {
120 return (bool) preg_match( '/^gpt-5\.\d/', (string) $model );
121 }
122
123 /**
124 * Return the threshold map for one context, in {family => min} shape, so
125 * Settings.php can serialize it onto a field for the React notice to read.
126 *
127 * @param string $context Feature key.
128 * @return array<string,int>
129 */
130 public static function get_min_tokens_map( $context ) {
131 return array(
132 'gpt-4' => self::get_min_tokens( $context, 'gpt-4o' ),
133 'gpt-5' => self::get_min_tokens( $context, 'gpt-5' ),
134 'gpt-5.5' => self::get_min_tokens( $context, 'gpt-5.5' ),
135 );
136 }
137
138 /**
139 * Make a chat-completion request to the active AI platform.
140 *
141 * Provider-agnostic: the platform, model, key, payload shape and parsing are
142 * resolved by ProviderFactory. The model is the global `ai_model`; callers
143 * may still override per request via $options['model'].
144 *
145 * @param array $messages Array of messages for the chat completion.
146 * @param array $options Optional parameters (model, max_tokens, temperature, timeout).
147 * @return string|\WP_Error API response content or error.
148 */
149 public function make_openai_request( $messages, $options = array() ) {
150 $defaults = array(
151 'max_tokens' => (int) $this->settings->get( 'article_summary_max_token', 1500 ),
152 'temperature' => 0.7,
153 'timeout' => 50,
154 'context' => 'article_summary',
155 );
156
157 $options = wp_parse_args( $options, $defaults );
158
159 $result = $this->factory()->make()->chat( $messages, $options );
160
161 if ( is_wp_error( $result ) ) {
162 return $result;
163 }
164
165 return $result['content'];
166 }
167
168 /**
169 * Analyze article quality using OpenAI
170 *
171 * @param string $content Article content to analyze
172 * @param string $title Article title (optional)
173 * @return array|\WP_Error Analysis result with score and feedback
174 */
175 public function analyze_article_quality( $content, $title = '' ) {
176 if ( empty( $content ) ) {
177 return new \WP_Error( 'empty_content', 'Article content cannot be empty.' );
178 }
179
180 // Create analysis prompt
181 $prompt = $this->build_quality_analysis_prompt( $content, $title );
182
183 $messages = array(
184 array(
185 'role' => 'system',
186 'content' => 'You are an expert content analyst specializing in documentation quality assessment. Provide detailed, actionable feedback to help improve article quality.'
187 ),
188 array(
189 'role' => 'user',
190 'content' => $prompt
191 )
192 );
193
194 $options = array(
195 'max_tokens' => 2000,
196 'temperature' => 0.3 // Lower temperature for more consistent analysis
197 );
198
199 $response = $this->make_openai_request( $messages, $options );
200
201 if ( is_wp_error( $response ) ) {
202 return $response;
203 }
204
205 // Parse the AI response into structured data
206 return $this->parse_quality_analysis_response( $response );
207 }
208
209 /**
210 * Build the prompt for article quality analysis
211 *
212 * @param string $content Article content
213 * @param string $title Article title
214 * @return string Formatted prompt
215 */
216 private function build_quality_analysis_prompt( $content, $title = '' ) {
217 $title_section = ! empty( $title ) ? "Title: {$title}\n\n" : '';
218
219 $prompt = "Please analyze the following documentation article for quality and provide a comprehensive assessment:\n\n";
220 $prompt .= $title_section;
221 $prompt .= "Content:\n{$content}\n\n";
222 $prompt .= "Please evaluate the article based on these criteria and provide your response in the following JSON format:\n\n";
223 $prompt .= "{\n";
224 $prompt .= ' "overall_score": 91,';
225 $prompt .= ' "scores": {';
226 $prompt .= ' "clarity": 90,';
227 $prompt .= ' "completeness": 92,';
228 $prompt .= ' "relevance": 95,';
229 $prompt .= ' "structure": 87,';
230 $prompt .= ' "readability": 88';
231 $prompt .= ' },';
232 $prompt .= ' "feedback": {';
233 $prompt .= ' "strengths": ["Clear headings", "Good use of examples"],';
234 $prompt .= ' "improvements": ["Add more detailed explanations in section 2", "Include troubleshooting steps"],';
235 $prompt .= ' "suggestions": ["Consider adding screenshots", "Break down complex paragraphs"]';
236 $prompt .= ' },';
237 $prompt .= ' "priority": "medium"';
238 $prompt .= "}\n\n";
239 $prompt .= "Scoring criteria (0-100):\n";
240 $prompt .= "- Clarity: How clear and understandable is the content?\n";
241 $prompt .= "- Completeness: Does it cover the topic thoroughly?\n";
242 $prompt .= "- Relevance: Is the content relevant to the stated purpose?\n";
243 $prompt .= "- Structure: Is the content well-organized with proper headings?\n";
244 $prompt .= "- Readability: Is it easy to read and follow?\n\n";
245 $prompt .= "Priority levels: low (80+), medium (60-79), high (below 60)\n";
246 $prompt .= "Provide specific, actionable feedback that content creators can implement.";
247
248 return $prompt;
249 }
250
251 /**
252 * Parse AI response into structured quality analysis data
253 *
254 * @param string $response Raw AI response
255 * @return array|\WP_Error Parsed analysis data
256 */
257 private function parse_quality_analysis_response( $response ) {
258 // Try to extract JSON from the response
259 $json_start = strpos( $response, '{' );
260 $json_end = strrpos( $response, '}' );
261
262 if ( false === $json_start || false === $json_end ) {
263 return new \WP_Error( 'parse_error', 'Could not find valid JSON in AI response.' );
264 }
265
266 $json_string = substr( $response, $json_start, $json_end - $json_start + 1 );
267 $data = json_decode( $json_string, true );
268
269 if ( json_last_error() !== JSON_ERROR_NONE ) {
270 return new \WP_Error( 'json_error', 'Invalid JSON in AI response: ' . json_last_error_msg() );
271 }
272
273 // Validate required fields
274 $required_fields = array( 'overall_score', 'scores', 'feedback' );
275 foreach ( $required_fields as $field ) {
276 if ( ! isset( $data[ $field ] ) ) {
277 return new \WP_Error( 'missing_field', "Missing required field: {$field}" );
278 }
279 }
280
281 // Ensure scores are within valid range
282 $data[ 'overall_score' ] = max( 0, min( 100, intval( $data[ 'overall_score' ] ) ) );
283
284 if ( isset( $data[ 'scores' ] ) && is_array( $data[ 'scores' ] ) ) {
285 foreach ( $data[ 'scores' ] as $key => $score ) {
286 $data[ 'scores' ][ $key ] = max( 0, min( 100, intval( $score ) ) );
287 }
288 }
289
290 // Set default priority if not provided
291 if ( ! isset( $data[ 'priority' ] ) ) {
292 $overall_score = $data[ 'overall_score' ];
293 if ( $overall_score >= 80 ) {
294 $data[ 'priority' ] = 'low';
295 } elseif ( $overall_score >= 60 ) {
296 $data[ 'priority' ] = 'medium';
297 } else {
298 $data[ 'priority' ] = 'high';
299 }
300 }
301
302 return $data;
303 }
304
305 /**
306 * Save article quality score as post meta
307 *
308 * @param int $post_id Post ID
309 * @param array $quality_data Quality analysis data
310 * @return bool Success status
311 */
312 public function save_article_quality_score( $post_id, $quality_data ) {
313 if ( empty( $post_id ) || ! is_array( $quality_data ) ) {
314 return false;
315 }
316
317 // Save the complete analysis data
318 $saved = update_post_meta( $post_id, '_betterdocs_article_quality_analysis', $quality_data );
319
320 // Save just the overall score for easy querying
321 update_post_meta( $post_id, '_betterdocs_article_quality_score', $quality_data[ 'overall_score' ] );
322
323 // Save analysis timestamp
324 update_post_meta( $post_id, '_betterdocs_article_quality_analyzed_at', current_time( 'mysql' ) );
325
326 return false !== $saved;
327 }
328
329 /**
330 * Get article quality score from post meta
331 *
332 * @param int $post_id Post ID
333 * @return array|false Quality analysis data or false if not found
334 */
335 public function get_article_quality_score( $post_id ) {
336 if ( empty( $post_id ) ) {
337 return false;
338 }
339
340 $quality_data = get_post_meta( $post_id, '_betterdocs_article_quality_analysis', true );
341
342 if ( empty( $quality_data ) ) {
343 return false;
344 }
345
346 // Add timestamp if available
347 $analyzed_at = get_post_meta( $post_id, '_betterdocs_article_quality_analyzed_at', true );
348 if ( $analyzed_at ) {
349 $quality_data[ 'analyzed_at' ] = $analyzed_at;
350 }
351
352 return $quality_data;
353 }
354
355 /**
356 * Check if article needs re-analysis based on last modified date
357 *
358 * @param int $post_id Post ID
359 * @return bool True if re-analysis is needed
360 */
361 public function needs_reanalysis( $post_id ) {
362 $analyzed_at = get_post_meta( $post_id, '_betterdocs_article_quality_analyzed_at', true );
363
364 if ( empty( $analyzed_at ) ) {
365 return true; // Never analyzed
366 }
367
368 $post = get_post( $post_id );
369 if ( ! $post ) {
370 return false;
371 }
372
373 // Check if post was modified after last analysis
374 $post_modified = strtotime( $post->post_modified );
375 $analyzed_timestamp = strtotime( $analyzed_at );
376
377 return $post_modified > $analyzed_timestamp;
378 }
379
380 /**
381 * Create a system message for OpenAI
382 *
383 * @param string $content System message content
384 * @return array Message array
385 */
386 public function create_system_message( $content ) {
387 return array(
388 'role' => 'system',
389 'content' => $content
390 );
391 }
392
393 /**
394 * Create a user message for OpenAI
395 *
396 * @param string $content User message content
397 * @return array Message array
398 */
399 public function create_user_message( $content ) {
400 return array(
401 'role' => 'user',
402 'content' => $content
403 );
404 }
405
406 /**
407 * Create messages array for article summarization
408 *
409 * @param string $title Article title
410 * @param string $content Article content
411 * @return array Messages array
412 */
413 public function create_summary_messages( $title, $content ) {
414 $system_message = $this->create_system_message(
415 'You are a helpful assistant that creates concise, informative summaries of documentation articles. Always format your response in clean HTML with paragraph tags. Do not use markdown formatting, code blocks, or backticks. Return only the HTML content without any wrapper formatting.'
416 );
417
418 $user_prompt = "Please provide a concise summary of the following article titled '{$title}'. The summary should be 2-3 paragraphs long, highlighting the main points and key takeaways. Format the response in HTML with proper paragraph tags. Do not wrap the response in markdown code blocks or use any markdown formatting.\n\nArticle content:\n{$content}";
419
420 $user_message = $this->create_user_message( $user_prompt );
421
422 return array( $system_message, $user_message );
423 }
424
425 /**
426 * Create messages array for content generation
427 *
428 * @param string $prompt User prompt
429 * @param string $keywords Optional keywords
430 * @return array Messages array
431 */
432 public function create_content_messages( $prompt, $keywords = '' ) {
433 $system_message = $this->create_system_message(
434 'You are a helpful assistant who writes documentation for users.'
435 );
436
437 $user_message = $this->create_user_message( $prompt );
438
439 return array( $system_message, $user_message );
440 }
441
442 /**
443 * Sanitize and prepare content for AI processing
444 *
445 * @param string $content Raw content
446 * @param int $max_length Maximum length to keep
447 * @return string Sanitized content
448 */
449 public function prepare_content_for_ai( $content, $max_length = 4000 ) {
450 // Strip HTML tags and decode entities
451 $content = wp_strip_all_tags( $content );
452 $content = html_entity_decode( $content, ENT_QUOTES, 'UTF-8' );
453
454 // Remove extra whitespace
455 $content = preg_replace( '/\s+/', ' ', $content );
456 $content = trim( $content );
457
458 // Limit length
459 if ( strlen( $content ) > $max_length ) {
460 $content = substr( $content, 0, $max_length );
461 // Try to cut at a word boundary
462 $last_space = strrpos( $content, ' ' );
463 if ( false !== $last_space && $last_space > $max_length * 0.8 ) {
464 $content = substr( $content, 0, $last_space );
465 }
466 $content .= '...';
467 }
468
469 return $content;
470 }
471
472 /**
473 * Check if AI features are enabled
474 *
475 * @return bool
476 */
477 public function is_ai_enabled() {
478 return $this->settings->get( 'enable_write_with_ai', true ) && $this->has_api_key();
479 }
480
481 /**
482 * Get AI usage statistics (placeholder for future implementation)
483 *
484 * @return array Usage statistics
485 */
486 public function get_usage_stats() {
487 // This could be implemented to track API usage, costs, etc.
488 return array(
489 'requests_today' => 0,
490 'tokens_used' => 0,
491 'cost_estimate' => 0
492 );
493 }
494 }
495