PluginProbe
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot / 4.9.2
BetterDocs – AI Documentation, Knowledge Base, MCP Server, Docs, Wikis, FAQ & Chatbot v4.9.2
4.9.2 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 All 200 releases
← All changes | includes/Core/WriteWithAI.php +261 -299 4.7.04.9.2 View file →
@@ -12,8 +12,10 @@
12 12 use WPDeveloper\BetterDocs\Core\PostType;
13 13
14 14 use WPDeveloper\BetterDocs\Utils\Helper;
15 15 use WPDeveloper\BetterDocs\Utils\AIHelper;
16 + use WPDeveloper\BetterDocs\AI\ProviderFactory;
17 + use WPDeveloper\BetterDocs\AI\ModelRegistry;
16 18 use WPDeveloper\BetterDocs\Utils\AIUsage;
17 19 use WPDeveloper\BetterDocs\REST\AIEdit;
18 20
19 21 class WriteWithAI extends Base {
@@ -49,11 +51,32 @@
49 51 if ( 'docs' !== $post_type ) {
50 52 return;
51 53 }
52 54
53 - $api_key = $this->get_api_key();
55 + $factory = new ProviderFactory( $this->settings );
56 + $api_key = $factory->api_key_for( $factory->active_platform() );
54 57 $has_key = ! empty( $api_key );
55 58
59 + // Resolve the *active* AI platform + model (multi-platform aware) so the
60 + // modal reflects the current Settings → AI selection instead of the legacy
61 + // OpenAI-only `write_with_ai_model` key.
62 + $active_platform = $factory->active_platform();
63 + $active_model = $factory->active_model();
64 + $platform_labels = ModelRegistry::platforms();
65 + $model_labels = ModelRegistry::models( $active_platform );
66 +
67 + // Glossary suggestions are existing-terms-only, and the glossaries taxonomy is only
68 + // registered for Pro (see Core\PostType::register_glossaries_taxonomy). So the "Suggest
69 + // glossaries" control must require, on top of the two settings, that Pro is active AND at
70 + // least one glossary term exists — otherwise the modal advertises an offer that can never
71 + // return anything. Mirrors the Docs-AI-suite availability check in Core\DocsAISuite.
72 + $glossary_count = wp_count_terms( array( 'taxonomy' => 'glossaries', 'hide_empty' => false ) );
73 + $has_glossary_terms = ! is_wp_error( $glossary_count ) && (int) $glossary_count > 0;
74 + $glossary_suggestions_enabled = (bool) $this->settings->get( 'enable_glossaries', false )
75 + && (bool) $this->settings->get( 'show_glossary_suggestions', true )
76 + && betterdocs()->is_pro_active()
77 + && $has_glossary_terms;
78 +
56 79 // Write with AI — loads even without a key so the modal can show its
57 80 // "add an API key" banner (matches the legacy inline form behavior).
58 81 betterdocs()->assets->enqueue( 'betterdocs-write-with-ai', 'blocks/write-with-ai.js' );
59 82 betterdocs()->assets->enqueue( 'betterdocs-write-with-ai-style', 'blocks/write-with-ai-style.css' );
@@ -69,9 +92,15 @@
69 92 // Term-suggestion (Docs AI Suite) wiring reused by the Write-with-AI
70 93 // preview step. Endpoint + gate mirror REST\DocsAISuite / Core\DocsAISuite.
71 94 'rest_suggest_url' => esc_url_raw( rest_url( 'betterdocs/v1/ai-suggest-terms' ) ),
72 95 'suggest_terms_enabled' => (bool) $this->settings->get( 'enable_docs_ai_suite', true ),
73 - 'model' => $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' ),
96 + // Glossary suggestions follow the glossary feature AND real availability
97 + // (Pro active + at least one glossary term); see the computation above.
98 + 'glossary_suggestions_enabled' => $glossary_suggestions_enabled,
99 + 'platform' => $active_platform,
100 + 'platform_label' => isset( $platform_labels[ $active_platform ] ) ? $platform_labels[ $active_platform ] : ucfirst( (string) $active_platform ),
101 + 'model' => $active_model,
102 + 'model_label' => isset( $model_labels[ $active_model ] ) ? $model_labels[ $active_model ] : $active_model,
74 103 'max_token' => (int) $this->settings->get( 'ai_autowrite_max_token', 2500 ),
75 104 'settings_url' => esc_url( admin_url( 'admin.php?page=betterdocs-settings#betterdocs-ai' ) ),
76 105 'woo_active' => class_exists( 'WooCommerce' ),
77 106 'is_multilingual_active' => Helper::is_multilingual_active(),
@@ -118,54 +147,21 @@
118 147 }
119 148
120 149 public function isValidAPIKey( $apiKey ) {
121 150 if ( empty( $apiKey ) ) {
122 - $api_response[ 'valid' ] = false;
123 - $api_response[ 'message' ] = 'Please Insert your <a href="/admin.php?page=betterdocs-settings#betterdocs-ai">OpenAI API Key</a> to use this Write with AI feature.';
124 -
125 - return $api_response;
151 + return array(
152 + 'valid' => false,
153 + 'message' => 'Please Insert your <a href="/admin.php?page=betterdocs-settings#betterdocs-ai">API Key</a> to use this Write with AI feature.'
154 + );
126 155 }
127 156
128 - $api_response = array();
129 -
130 - $response = wp_safe_remote_get(
131 - 'https://api.openai.com/v1/engines',
132 - array(
133 - 'headers' => array(
134 - 'Content-Type' => 'application/json',
135 - 'Authorization' => 'Bearer ' . $apiKey,
136 - ),
137 - 'timeout' => 15,
138 - )
139 - );
140 -
141 - if ( is_wp_error( $response ) ) {
142 - $api_response[ 'valid' ] = false;
143 - $api_response[ 'message' ] = $response->get_error_message();
144 - return $api_response;
145 - }
146 -
147 - $httpCode = (int) wp_remote_retrieve_response_code( $response );
148 - $body = wp_remote_retrieve_body( $response );
149 -
150 - if ( 200 === $httpCode ) {
151 - $api_response[ 'valid' ] = true;
152 - $api_response[ 'message' ] = 'Valid API Key';
153 - } else {
154 - $responseData = json_decode( $body, true );
155 - $messageData = ! empty( $responseData[ 'error' ] ) ? $responseData[ 'error' ] : array();
156 - $api_response[ 'valid' ] = false;
157 - $api_response[ 'message' ] = ! empty( $messageData[ 'message' ] ) ? $messageData[ 'message' ] : 'Invalid API Key';
158 - }
159 -
160 - // print_r($response);
161 -
162 - return $api_response;
157 + $factory = new ProviderFactory( $this->settings );
158 + return $factory->validate( $factory->active_platform(), $apiKey );
163 159 }
164 160
165 161 public function get_api_key() {
166 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
167 - return $api_key;
162 + $factory = new ProviderFactory( $this->settings );
163 + return $factory->api_key_for( $factory->active_platform() );
168 164 }
169 165
170 166 /**
171 167 * The built-in "Default" instruction body.
@@ -371,8 +367,170 @@
371 367
372 368 return apply_filters( 'betterdocs_write_with_ai_system_prompt', $prompt );
373 369 }
374 370
371 + /**
372 + * Build the system + user messages and chat options shared by the
373 + * Write-with-AI generator and the in-editor AI-Edit endpoint. Routes through
374 + * the active AI platform (ProviderFactory), so it works for every provider.
375 + *
376 + * @param string $prompt
377 + * @param int|null $max_tokens Optional cap override (e.g. a "large" doc).
378 + * @param array $extra_system Optional extra system messages.
379 + * @return array array( array $messages, array $options )
380 + */
381 + private function ai_request_args( $prompt, $max_tokens = null, $extra_system = array() ) {
382 + $messages = array_merge(
383 + array( array( 'role' => 'system', 'content' => $this->get_system_prompt() ) ),
384 + $this->normalize_extra_system( $extra_system ),
385 + array( array( 'role' => 'user', 'content' => $prompt ) )
386 + );
387 +
388 + return array( $messages, $this->ai_chat_options( $max_tokens ) );
389 + }
390 +
391 + /**
392 + * Assemble the chat options passed to the active provider. Document
393 + * generation is long-running on every platform: reasoning models (gpt-5*)
394 + * and larger non-OpenAI models (e.g. Claude Opus) routinely need well over
395 + * the old 50s default to return a full doc, which timed them out mid-
396 + * generation. Give every request a generous ceiling; fast models simply
397 + * finish early and are unaffected.
398 + *
399 + * @param int|null $max_tokens Optional token cap override.
400 + * @param float|null $temperature Optional sampling temperature.
401 + * @return array
402 + */
403 + private function ai_chat_options( $max_tokens = null, $temperature = null ) {
404 + $timeout = 300;
405 + if ( function_exists( 'set_time_limit' ) ) {
406 + set_time_limit( 300 );
407 + }
408 +
409 + $options = array(
410 + 'max_tokens' => null !== $max_tokens ? (int) $max_tokens : (int) $this->settings->get( 'ai_autowrite_max_token', 2500 ),
411 + 'context' => 'write_with_ai',
412 + 'timeout' => $timeout,
413 + );
414 +
415 + if ( null !== $temperature ) {
416 + $options['temperature'] = $temperature;
417 + }
418 +
419 + return $options;
420 + }
421 +
422 + public function generate_openai_response( $prompt, $keywords, $max_tokens = null, $extra_system = array() ) {
423 + try {
424 + list( $messages, $options ) = $this->ai_request_args( $prompt, $max_tokens, $extra_system );
425 +
426 + $result = ( new ProviderFactory( $this->settings ) )->make()->chat( $messages, $options );
427 +
428 + if ( is_wp_error( $result ) ) {
429 + return $result->get_error_message();
430 + }
431 +
432 + return $result['content'];
433 + } catch ( \Exception $error ) {
434 + return 'Error: ' . $error->getMessage();
435 + }
436 + }
437 +
438 + /**
439 + * Generate documentation from an uploaded image using a vision-capable model.
440 + *
441 + * Mirrors generate_openai_response() but sends the picture alongside the text
442 + * prompt as an OpenAI-format multimodal user message
443 + * (`content: [ {type:text}, {type:image_url} ]`). The OpenAI-compatible
444 + * provider forwards that message array to the wire verbatim, so no provider
445 + * change is needed. Only OpenAI vision models are wired — Claude and Gemini
446 + * use a different image envelope, so they are refused with a clear error
447 + * instead of being sent a payload they would reject.
448 + *
449 + * @param string $prompt Composed instruction prompt.
450 + * @param array $image { data_uri:string, mime:string }.
451 + * @param int|null $max_tokens Optional token cap.
452 + * @param array $extra_system Extra system messages (instruction sets).
453 + * @return string|\WP_Error Generated content, or WP_Error on guard/failure.
454 + */
455 + public function generate_vision_response( $prompt, $image, $max_tokens = null, $extra_system = array() ) {
456 + if ( empty( $image['data_uri'] ) ) {
457 + return new \WP_Error( 'ai_vision_no_image', __( 'No image data to send to the AI.', 'betterdocs' ) );
458 + }
459 +
460 + $factory = new ProviderFactory( $this->settings );
461 + $platform = $factory->active_platform();
462 + $model = $factory->active_model( $platform );
463 +
464 + if ( ! $this->platform_supports_vision( $platform, $model ) ) {
465 + return new \WP_Error(
466 + 'ai_no_vision',
467 + sprintf(
468 + /* translators: 1: AI platform id, 2: model name. */
469 + __( 'The configured AI model (%1$s / %2$s) can\'t read images. Switch to an OpenAI vision model such as GPT-4o or GPT-4o mini in BetterDocs → Settings → AI Content Suite, or upload a PDF/DOCX/TXT instead.', 'betterdocs' ),
470 + $platform,
471 + '' !== (string) $model ? $model : 'default'
472 + )
473 + );
474 + }
475 +
476 + try {
477 + $messages = array_merge(
478 + array( array( 'role' => 'system', 'content' => $this->get_system_prompt() ) ),
479 + $this->normalize_extra_system( $extra_system ),
480 + array(
481 + array(
482 + 'role' => 'user',
483 + 'content' => array(
484 + array( 'type' => 'text', 'text' => (string) $prompt ),
485 + array( 'type' => 'image_url', 'image_url' => array( 'url' => (string) $image['data_uri'] ) ),
486 + ),
487 + ),
488 + )
489 + );
490 +
491 + $result = $factory->make()->chat( $messages, $this->ai_chat_options( $max_tokens ) );
492 +
493 + if ( is_wp_error( $result ) ) {
494 + return $result;
495 + }
496 +
497 + return $result['content'];
498 + } catch ( \Exception $error ) {
499 + return new \WP_Error( 'ai_vision_failed', 'Error: ' . $error->getMessage() );
500 + }
501 + }
502 +
503 + /**
504 + * Whether the active platform + model can accept image input in the OpenAI
505 + * multimodal format. Deliberately conservative: only OpenAI vision model
506 + * families qualify, because Claude and Gemini require a different image
507 + * envelope this path does not build. gpt-3.5 (text-only) is excluded.
508 + *
509 + * @param string $platform
510 + * @param string $model
511 + * @return bool
512 + */
513 + protected function platform_supports_vision( $platform, $model ) {
514 + if ( 'openai' !== $platform ) {
515 + return false;
516 + }
517 +
518 + $model = strtolower( (string) $model );
519 +
520 + if ( '' === $model || false !== strpos( $model, 'gpt-3.5' ) ) {
521 + return false;
522 + }
523 +
524 + foreach ( array( 'gpt-4o', 'gpt-4.1', 'gpt-4-turbo', 'gpt-4-vision', 'chatgpt-4o', 'gpt-5', 'o1', 'o3', 'o4' ) as $family ) {
525 + if ( false !== strpos( $model, $family ) ) {
526 + return true;
527 + }
528 + }
529 +
530 + return false;
531 + }
532 +
375 533 public function get_outline_system_prompt() {
376 534 $prompt = <<<'PROMPT'
377 535 You are a Senior Technical Writer. Produce a documentation OUTLINE only — not the full article.
378 536
@@ -400,9 +558,9 @@
400 558
401 559 if ( empty( $result['success'] ) ) {
402 560 return array(
403 561 'success' => false,
404 - 'error' => isset( $result['error'] ) ? $result['error'] : 'OpenAI error',
562 + 'error' => isset( $result['error'] ) ? $result['error'] : 'AI error',
405 563 );
406 564 }
407 565
408 566 $outline = $this->parse_outline( (string) $result['content'] );
@@ -457,251 +615,96 @@
457 615
458 616 return $outline;
459 617 }
460 618
461 - public function generate_openai_response( $prompt, $keywords, $max_tokens = null, $extra_system = array() ) {
462 - try {
463 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
464 - // Caller may raise the cap (e.g. a "large" doc) above the saved default.
465 - $max_tokens = null !== $max_tokens ? (int) $max_tokens : $this->settings->get( 'ai_autowrite_max_token', 2500 );
466 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
467 -
468 - $api_endpoint = 'https://api.openai.com/v1/chat/completions'; // Update the endpoint based on OpenAI API version
469 -
470 - $messages = array_merge(
471 - array(
472 - array(
473 - 'role' => 'system',
474 - 'content' => $this->get_system_prompt()
475 - )
476 - ),
477 - $this->normalize_extra_system( $extra_system ),
478 - array(
479 - array(
480 - 'role' => 'user',
481 - 'content' => $prompt
482 - )
483 - )
484 - );
485 -
486 - $request_body = AIHelper::build_openai_payload(
487 - $model,
488 - $messages,
489 - $max_tokens,
490 - null,
491 - 'write_with_ai'
492 - );
493 -
494 - $request_options = array(
495 - 'headers' => array(
496 - 'Content-Type' => 'application/json',
497 - 'Authorization' => 'Bearer ' . $api_key
498 - ),
499 - 'body' => json_encode( $request_body ),
500 - 'timeout' => 300
501 - );
502 -
503 - // GPT-5.5 reasoning can run well past the default limits; give PHP and
504 - // the HTTP call room to finish (still subject to server php-fpm/nginx limits).
505 - if ( function_exists( 'set_time_limit' ) ) {
506 - set_time_limit( 300 ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running AI generation needs an extended limit; still bounded by server fpm/nginx timeouts.
507 - }
508 -
509 - $response = wp_remote_post( $api_endpoint, $request_options );
510 -
511 - if ( is_wp_error( $response ) ) {
512 - return 'Error: ' . $response->get_error_message();
513 - } else {
514 - $body = wp_remote_retrieve_body( $response );
515 -
516 - $data = json_decode( $body, true );
517 -
518 - if ( ! empty( $data[ 'error' ] ) ) {
519 - return $data[ 'error' ][ 'message' ];
520 - }
521 -
522 - return $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ]; // Update this line to get the assistant's message
523 - }
524 - } catch ( Exception $error ) {
525 - return 'Error: ' . $error->getMessage();
526 - }
527 - }
528 -
529 619 public function generate_openai_response_ai_edit( $prompt, $extra_system = array() ) {
530 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
531 - $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 2500 );
532 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
620 + $factory = new ProviderFactory( $this->settings );
621 + $model = $factory->active_model();
533 622
534 - $api_endpoint = 'https://api.openai.com/v1/chat/completions';
535 -
536 623 $messages = array_merge(
537 - array(
538 - array(
539 - 'role' => 'system',
540 - 'content' => $this->get_system_prompt()
541 - )
542 - ),
624 + array( array( 'role' => 'system', 'content' => $this->get_system_prompt() ) ),
543 625 $this->normalize_extra_system( $extra_system ),
544 - array(
545 - array(
546 - 'role' => 'user',
547 - 'content' => $prompt
548 - )
549 - )
626 + array( array( 'role' => 'user', 'content' => $prompt ) )
550 627 );
551 628
552 - $payload = AIHelper::build_openai_payload(
553 - $model,
554 - $messages,
555 - $max_tokens,
556 - null,
557 - 'write_with_ai'
558 - );
629 + $result = $factory->make()->chat( $messages, $this->ai_chat_options() );
559 630
560 - $request_options = array(
561 - 'headers' => array(
562 - 'Content-Type' => 'application/json',
563 - 'Authorization' => 'Bearer ' . $api_key
564 - ),
565 - 'body' => wp_json_encode( $payload ),
566 - 'timeout' => 300
567 - );
568 -
569 - // GPT-5.5 reasoning can run well past the default limits; give PHP and
570 - // the HTTP call room to finish (still subject to server php-fpm/nginx limits).
571 - if ( function_exists( 'set_time_limit' ) ) {
572 - set_time_limit( 300 ); // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running AI generation needs an extended limit; still bounded by server fpm/nginx timeouts.
573 - }
574 -
575 - $response = wp_remote_post( $api_endpoint, $request_options );
576 -
577 - if ( is_wp_error( $response ) ) {
631 + if ( is_wp_error( $result ) ) {
578 632 return array(
579 633 'success' => false,
580 - 'error' => $response->get_error_message(),
581 - 'model' => $model
634 + 'error' => $result->get_error_message(),
635 + 'model' => $model
582 636 );
583 637 }
584 638
585 - $body = wp_remote_retrieve_body( $response );
586 - $data = json_decode( $body, true );
639 + $usage = isset( $result['usage'] ) && is_array( $result['usage'] ) ? $result['usage'] : array();
587 640
588 - if ( ! empty( $data[ 'error' ] ) ) {
589 - return array(
590 - 'success' => false,
591 - 'error' => isset( $data[ 'error' ][ 'message' ] ) ? $data[ 'error' ][ 'message' ] : 'OpenAI error',
592 - 'model' => $model,
593 - 'raw' => $data
594 - );
595 - }
596 -
597 - $content = isset( $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] ) ? $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] : '';
598 - $usage = isset( $data[ 'usage' ] ) && is_array( $data[ 'usage' ] ) ? $data[ 'usage' ] : array();
599 -
600 641 return array(
601 - 'success' => true,
602 - 'content' => $content,
603 - 'model' => $model,
604 - 'prompt_tokens' => isset( $usage[ 'prompt_tokens' ] ) ? (int) $usage[ 'prompt_tokens' ] : null,
605 - 'completion_tokens' => isset( $usage[ 'completion_tokens' ] ) ? (int) $usage[ 'completion_tokens' ] : null,
606 - 'total_tokens' => isset( $usage[ 'total_tokens' ] ) ? (int) $usage[ 'total_tokens' ] : null,
607 - 'finish_reason' => isset( $data[ 'choices' ][ 0 ][ 'finish_reason' ] ) ? $data[ 'choices' ][ 0 ][ 'finish_reason' ] : null
642 + 'success' => true,
643 + 'content' => $result['content'],
644 + 'model' => isset( $result['model'] ) ? $result['model'] : $model,
645 + 'prompt_tokens' => isset( $usage['prompt_tokens'] ) ? $usage['prompt_tokens'] : null,
646 + 'completion_tokens' => isset( $usage['completion_tokens'] ) ? $usage['completion_tokens'] : null,
647 + 'total_tokens' => isset( $usage['total_tokens'] ) ? $usage['total_tokens'] : null,
648 + 'finish_reason' => isset( $result['finish_reason'] ) ? $result['finish_reason'] : null
608 649 );
609 650 }
610 651
611 652 /**
612 - * Generic chat completion using the Write-with-AI model/token/key settings.
653 + * Generic chat completion using the active Write-with-AI platform/model/token
654 + * settings. Shared by lightweight, plain-text generators (glossary definitions,
655 + * FAQ answers, outlines) that need the same dynamic model as Write with AI /
656 + * AI Edit but a caller-supplied system prompt instead of the doc-authoring HTML
657 + * prompt. Routes through ProviderFactory so every provider is supported.
613 658 *
614 - * Shared by lightweight, plain-text generators (glossary definitions, FAQ answers)
615 - * that need the same dynamic model as Write with AI / AI Edit but a caller-supplied
616 - * system prompt instead of the doc-authoring HTML prompt. Returns the same structured
617 - * array shape as {@see self::generate_openai_response_ai_edit()}.
618 - *
619 659 * @param string $user_prompt The user message.
620 660 * @param string $system_prompt Optional system message (omitted when empty).
661 + * @param array $extra_system Optional extra system messages.
621 662 * @return array { success:bool, content?:string, error?:string, model:string, *_tokens?:int }
622 663 */
623 664 public function generate_text( $user_prompt, $system_prompt = '', $extra_system = array() ) {
624 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
625 - $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 2500 );
626 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
665 + $factory = new ProviderFactory( $this->settings );
666 + $model = $factory->active_model();
627 667
628 668 $messages = array();
629 669 if ( $system_prompt !== '' ) {
630 - $messages[] = array(
631 - 'role' => 'system',
632 - 'content' => $system_prompt
633 - );
670 + $messages[] = array( 'role' => 'system', 'content' => $system_prompt );
634 671 }
635 672 foreach ( $this->normalize_extra_system( $extra_system ) as $extra ) {
636 673 $messages[] = $extra;
637 674 }
638 - $messages[] = array(
639 - 'role' => 'user',
640 - 'content' => $user_prompt
641 - );
675 + $messages[] = array( 'role' => 'user', 'content' => $user_prompt );
642 676
643 - $api_endpoint = 'https://api.openai.com/v1/chat/completions';
677 + $result = $factory->make()->chat( $messages, $this->ai_chat_options() );
644 678
645 - $payload = AIHelper::build_openai_payload( $model, $messages, $max_tokens, null, 'write_with_ai' );
646 -
647 - $request_options = array(
648 - 'headers' => array(
649 - 'Content-Type' => 'application/json',
650 - 'Authorization' => 'Bearer ' . $api_key
651 - ),
652 - 'body' => wp_json_encode( $payload ),
653 - 'timeout' => 300
654 - );
655 -
656 - // GPT-5.5 reasoning can run well past the default limits; give PHP and
657 - // the HTTP call room to finish (still subject to server php-fpm/nginx limits).
658 - if ( function_exists( 'set_time_limit' ) ) {
659 - set_time_limit( 300 );
660 - }
661 -
662 - $response = wp_remote_post( $api_endpoint, $request_options );
663 -
664 - if ( is_wp_error( $response ) ) {
679 + if ( is_wp_error( $result ) ) {
665 680 return array(
666 681 'success' => false,
667 - 'error' => $response->get_error_message(),
682 + 'error' => $result->get_error_message(),
668 683 'model' => $model
669 684 );
670 685 }
671 686
672 - $body = wp_remote_retrieve_body( $response );
673 - $data = json_decode( $body, true );
687 + $usage = isset( $result['usage'] ) && is_array( $result['usage'] ) ? $result['usage'] : array();
674 688
675 - if ( ! empty( $data[ 'error' ] ) ) {
676 - return array(
677 - 'success' => false,
678 - 'error' => isset( $data[ 'error' ][ 'message' ] ) ? $data[ 'error' ][ 'message' ] : 'OpenAI error',
679 - 'model' => $model,
680 - 'raw' => $data
681 - );
682 - }
683 -
684 - $content = isset( $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] ) ? $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] : '';
685 - $usage = isset( $data[ 'usage' ] ) && is_array( $data[ 'usage' ] ) ? $data[ 'usage' ] : array();
686 -
687 689 return array(
688 690 'success' => true,
689 - 'content' => $content,
690 - 'model' => $model,
691 - 'prompt_tokens' => isset( $usage[ 'prompt_tokens' ] ) ? (int) $usage[ 'prompt_tokens' ] : null,
692 - 'completion_tokens' => isset( $usage[ 'completion_tokens' ] ) ? (int) $usage[ 'completion_tokens' ] : null,
693 - 'total_tokens' => isset( $usage[ 'total_tokens' ] ) ? (int) $usage[ 'total_tokens' ] : null,
694 - 'finish_reason' => isset( $data[ 'choices' ][ 0 ][ 'finish_reason' ] ) ? $data[ 'choices' ][ 0 ][ 'finish_reason' ] : null
691 + 'content' => $result['content'],
692 + 'model' => isset( $result['model'] ) ? $result['model'] : $model,
693 + 'prompt_tokens' => isset( $usage['prompt_tokens'] ) ? $usage['prompt_tokens'] : null,
694 + 'completion_tokens' => isset( $usage['completion_tokens'] ) ? $usage['completion_tokens'] : null,
695 + 'total_tokens' => isset( $usage['total_tokens'] ) ? $usage['total_tokens'] : null,
696 + 'finish_reason' => isset( $result['finish_reason'] ) ? $result['finish_reason'] : null
695 697 );
696 698 }
697 699
698 700 /**
699 - * Generate an OpenAI chat completion with a caller-supplied system + user
700 - * prompt. Mirrors generate_openai_response_ai_edit() (same key/model/token
701 - * floor/timeout handling and return shape) but does NOT force the
702 - * documentation-writer system prompt, so callers such as the Docs AI Suite
703 - * (taxonomy suggestions, excerpts) can supply task-appropriate instructions.
701 + * Generate a chat completion with a caller-supplied system + user prompt.
702 + * Mirrors generate_openai_response_ai_edit() (same model/token floor/timeout
703 + * handling and return shape) but does NOT force the documentation-writer
704 + * system prompt, so callers such as the Docs AI Suite (taxonomy suggestions,
705 + * excerpts) can supply task-appropriate instructions. Routes through the active
706 + * provider via ProviderFactory.
704 707 *
705 708 * @param string $system_prompt System instruction for the model.
706 709 * @param string $user_prompt User message / content payload.
707 710 * @param float|null $temperature Optional sampling temperature (ignored for gpt-5*).
@@ -707,77 +710,36 @@
707 710 * @param float|null $temperature Optional sampling temperature (ignored for gpt-5*).
708 711 * @return array{success:bool,content?:string,error?:string,model:string,...}
709 712 */
710 713 public function generate_openai_response_raw( $system_prompt, $user_prompt, $temperature = null ) {
711 - $api_key = $this->settings->get( 'ai_autowrite_api_key', '' );
712 - $max_tokens = $this->settings->get( 'ai_autowrite_max_token', 2500 );
713 - $model = $this->settings->get( 'write_with_ai_model', 'gpt-4o-mini' );
714 + $factory = new ProviderFactory( $this->settings );
715 + $model = $factory->active_model();
714 716
715 - $api_endpoint = 'https://api.openai.com/v1/chat/completions';
716 -
717 - $payload = AIHelper::build_openai_payload(
718 - $model,
719 - array(
720 - array(
721 - 'role' => 'system',
722 - 'content' => $system_prompt
723 - ),
724 - array(
725 - 'role' => 'user',
726 - 'content' => $user_prompt
727 - )
728 - ),
729 - $max_tokens,
730 - $temperature,
731 - 'write_with_ai'
717 + $messages = array(
718 + array( 'role' => 'system', 'content' => $system_prompt ),
719 + array( 'role' => 'user', 'content' => $user_prompt )
732 720 );
733 721
734 - $request_options = array(
735 - 'headers' => array(
736 - 'Content-Type' => 'application/json',
737 - 'Authorization' => 'Bearer ' . $api_key
738 - ),
739 - 'body' => wp_json_encode( $payload ),
740 - 'timeout' => 300
741 - );
722 + $result = $factory->make()->chat( $messages, $this->ai_chat_options( null, $temperature ) );
742 723
743 - if ( function_exists( 'set_time_limit' ) ) {
744 - set_time_limit( 300 );
745 - }
746 -
747 - $response = wp_remote_post( $api_endpoint, $request_options );
748 -
749 - if ( is_wp_error( $response ) ) {
724 + if ( is_wp_error( $result ) ) {
750 725 return array(
751 726 'success' => false,
752 - 'error' => $response->get_error_message(),
753 - 'model' => $model
727 + 'error' => $result->get_error_message(),
728 + 'model' => $model
754 729 );
755 730 }
756 731
757 - $body = wp_remote_retrieve_body( $response );
758 - $data = json_decode( $body, true );
732 + $usage = isset( $result['usage'] ) && is_array( $result['usage'] ) ? $result['usage'] : array();
759 733
760 - if ( ! empty( $data[ 'error' ] ) ) {
761 - return array(
762 - 'success' => false,
763 - 'error' => isset( $data[ 'error' ][ 'message' ] ) ? $data[ 'error' ][ 'message' ] : 'OpenAI error',
764 - 'model' => $model,
765 - 'raw' => $data
766 - );
767 - }
768 -
769 - $content = isset( $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] ) ? $data[ 'choices' ][ 0 ][ 'message' ][ 'content' ] : '';
770 - $usage = isset( $data[ 'usage' ] ) && is_array( $data[ 'usage' ] ) ? $data[ 'usage' ] : array();
771 -
772 734 return array(
773 - 'success' => true,
774 - 'content' => $content,
775 - 'model' => $model,
776 - 'prompt_tokens' => isset( $usage[ 'prompt_tokens' ] ) ? (int) $usage[ 'prompt_tokens' ] : null,
777 - 'completion_tokens' => isset( $usage[ 'completion_tokens' ] ) ? (int) $usage[ 'completion_tokens' ] : null,
778 - 'total_tokens' => isset( $usage[ 'total_tokens' ] ) ? (int) $usage[ 'total_tokens' ] : null,
779 - 'finish_reason' => isset( $data[ 'choices' ][ 0 ][ 'finish_reason' ] ) ? $data[ 'choices' ][ 0 ][ 'finish_reason' ] : null
735 + 'success' => true,
736 + 'content' => $result['content'],
737 + 'model' => isset( $result['model'] ) ? $result['model'] : $model,
738 + 'prompt_tokens' => isset( $usage['prompt_tokens'] ) ? $usage['prompt_tokens'] : null,
739 + 'completion_tokens' => isset( $usage['completion_tokens'] ) ? $usage['completion_tokens'] : null,
740 + 'total_tokens' => isset( $usage['total_tokens'] ) ? $usage['total_tokens'] : null,
741 + 'finish_reason' => isset( $result['finish_reason'] ) ? $result['finish_reason'] : null
780 742 );
781 743 }
782 744
783 745 public function generate_openai_content_callback() {