fix(ai): stop false WP AI priority and harden summary-suggest

Prefer configured theme OpenAI provider over incomplete WP AI Client stubs,
return clearer status codes/messages for summary generation, and improve
block-editor content collection for AI 摘要 on post-new.
This commit is contained in:
2026-07-13 08:47:15 +08:00
parent 344f28f89b
commit 62310891e5
3 changed files with 143 additions and 42 deletions
@@ -204,24 +204,78 @@ class AKSRT_Admin_AI_Controller extends AKSRT_Admin_Controller_Base {
}
$params = $this->get_json_params($request);
$content = wp_kses_post((string) ($params['content'] ?? ''));
$max_len = max(50, min(500, (int) ($params['max_length'] ?? 200)));
if (trim(wp_strip_all_tags($content)) === '') {
return $this->error(__('内容不能为空', 'aksrt'));
// Accept JSON body or form body (some admin contexts strip JSON).
if ($params === []) {
$params = $request->get_params();
if (!is_array($params)) {
$params = [];
}
}
$prompt = AKSRT_AI_Prompt::get_instance()->build_summary_prompt($content, $max_len);
$result = AKSRT_AI::get_instance()->generate_text($prompt, [
'max_tokens' => min(600, $max_len * 2),
$title = sanitize_text_field((string) ($params['title'] ?? ''));
$raw = (string) ($params['content'] ?? '');
// Keep readable text; strip tags for emptiness / prompt length.
$plain = trim(wp_strip_all_tags(html_entity_decode($raw, ENT_QUOTES | ENT_HTML5, 'UTF-8')));
$content = $plain !== '' ? $plain : trim(wp_strip_all_tags(wp_kses_post($raw)));
$max_len = max(50, min(500, (int) ($params['max_length'] ?? 200)));
if ($content === '') {
return $this->error(__('内容不能为空,请先在编辑器填写正文后再生成摘要', 'aksrt'), 422);
}
$ai = AKSRT_AI::get_instance();
if (!$ai->is_available()) {
return $this->error(
__('AI 服务未启用或未配置。请到「扩展 → AI 辅助」启用并填写 API Key(或配置 WordPress AI Connectors)。', 'aksrt'),
503
);
}
// Prefer excerpt-oriented prompt when title is present.
$prompt_builder = AKSRT_AI_Prompt::get_instance();
if ($title !== '' && method_exists($prompt_builder, 'build_excerpt_prompt')) {
$prompt = $prompt_builder->build_excerpt_prompt($title, $content);
} else {
$prompt = $prompt_builder->build_summary_prompt($content, $max_len);
}
$result = $ai->generate_text($prompt, [
'max_tokens' => min(600, max(120, $max_len * 2)),
'temperature' => 0.5,
'system_instruction' => __('你是中文内容编辑,只输出摘要正文,不要标题、前缀或 Markdown。', 'aksrt'),
]);
if (!empty($result['success'])) {
return $this->success(['data' => ['summary' => $result['content']]]);
$summary = trim((string) ($result['content'] ?? ''));
if ($summary === '') {
return $this->error(__('AI 返回内容为空,请稍后重试或检查模型配置', 'aksrt'), 502);
}
// Soft trim to requested length (characters).
if (function_exists('mb_substr') && mb_strlen($summary) > $max_len + 20) {
$summary = mb_substr($summary, 0, $max_len);
}
return $this->success([
'data' => [
'summary' => $summary,
'backend' => (string) ($result['backend'] ?? ''),
],
]);
}
return $this->error((string) ($result['message'] ?? __('生成失败', 'aksrt')));
$message = trim((string) ($result['message'] ?? ''));
if ($message === '') {
$message = __('生成失败', 'aksrt');
}
// Upstream/provider failures are not client validation errors.
$status = 502;
if (str_contains($message, '未启用') || str_contains($message, '未配置')) {
$status = 503;
} elseif (str_contains($message, '频繁')) {
$status = 429;
}
return $this->error($message, $status);
}
public function tags_suggest(WP_REST_Request $request): WP_REST_Response {
+44 -24
View File
@@ -111,16 +111,20 @@ class AKSRT_AI {
}
/**
* WordPress 核心 AI Client 是否可用。
* WordPress 核心 AI Client 是否真正可用。
*
* 仅有函数存根不够:没有 Connectors / wp_supports_ai=false 时不应抢占主题 provider。
*/
public function is_wp_ai_available(): bool {
if (!function_exists('wp_ai_client_prompt')) {
return false;
}
if (function_exists('wp_supports_ai') && !wp_supports_ai()) {
return false;
// Prefer the official capability gate when present.
if (function_exists('wp_supports_ai')) {
return (bool) wp_supports_ai();
}
return true;
// Without wp_supports_ai, do not claim availability (avoids false-positive 400s).
return false;
}
/**
@@ -128,28 +132,37 @@ class AKSRT_AI {
*/
public function is_theme_provider_available(): bool {
$config = $this->get_config();
$provider = sanitize_key((string) ($config['provider'] ?? self::PROVIDER_NONE));
$api_key = trim((string) ($config['api_key'] ?? ''));
$api_base = trim((string) ($config['api_base'] ?? ''));
return !empty($config['enabled'])
&& ($config['provider'] ?? self::PROVIDER_NONE) !== self::PROVIDER_NONE
&& !empty($config['api_key']);
&& $provider !== self::PROVIDER_NONE
&& $provider !== ''
&& $api_key !== ''
&& $api_base !== '';
}
/**
* 任一后端可用即可生成。
*/
public function is_available(): bool {
return $this->is_wp_ai_available() || $this->is_theme_provider_available();
return $this->is_theme_provider_available() || $this->is_wp_ai_available();
}
/**
* 当前优先后端标识。
*
* Theme provider wins when explicitly configured — WP AI stubs often exist
* without a working connector and previously produced opaque 400 failures.
*/
public function resolve_backend(): string {
if ($this->is_wp_ai_available()) {
return 'wp_ai';
}
if ($this->is_theme_provider_available()) {
return 'theme';
}
if ($this->is_wp_ai_available()) {
return 'wp_ai';
}
return 'none';
}
@@ -205,28 +218,35 @@ class AKSRT_AI {
? (string) $options['system_instruction']
: __('你是一个内容助手,提供建议性内容。输出仅作为参考建议,不会自动应用到线上内容。', 'aksrt');
// 1) Prefer WP AI Client
$last_error = [
'success' => false,
'message' => __('AI 服务未启用或未配置。请配置 WordPress AI Connectors,或在「扩展 → AI 辅助」填写 API Key。', 'aksrt'),
];
// 1) Prefer explicitly configured theme OpenAI-compatible provider.
if ($this->is_theme_provider_available()) {
$theme_result = $this->generate_via_theme($prompt, $system, $options);
$this->record_call();
if (!empty($theme_result['success'])) {
$theme_result['backend'] = 'theme';
return $theme_result;
}
$last_error = $theme_result;
// Fall through to WP AI if available.
}
// 2) WordPress AI Client (Connectors).
if ($this->is_wp_ai_available()) {
$wp_result = $this->generate_via_wp_ai($prompt, $system, $options);
$this->record_call();
if (!empty($wp_result['success'])) {
$this->record_call();
$wp_result['backend'] = 'wp_ai';
return $wp_result;
}
// Fall through to theme if configured
if (!$this->is_theme_provider_available()) {
$this->record_call();
return $wp_result;
}
$last_error = $wp_result;
}
// 2) Theme OpenAI-compatible
$theme_result = $this->generate_via_theme($prompt, $system, $options);
$this->record_call();
if (!empty($theme_result['success'])) {
$theme_result['backend'] = 'theme';
}
return $theme_result;
return $last_error;
}
/**