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:
kate522 committed 2026-07-13 08:47:15 +08:00
1 parent 344f28f89b
commit 62310891e5
3 files changed
+143 -42

No files matched your search

+35 -8
View File
@@ -78,8 +78,7 @@
function getEditorContent() { function getEditorContent() {
var content = ''; var content = '';
var ta = document.getElementById('content'); // Block editor first (post-new.php uses Gutenberg).
if (ta && ta.value) content = ta.value;
try { try {
if (window.wp && wp.data && wp.data.select) { if (window.wp && wp.data && wp.data.select) {
var ed = wp.data.select('core/editor'); var ed = wp.data.select('core/editor');
@@ -89,10 +88,27 @@
} }
} }
} catch (e) { /* ignore */ } } catch (e) { /* ignore */ }
// Strip tags for length check / API
if (!content) {
var ta = document.getElementById('content');
if (ta && ta.value) content = ta.value;
}
// TinyMCE classic.
try {
if (!content && window.tinymce && tinymce.get) {
var editor = tinymce.get('content');
if (editor && editor.getContent) {
content = editor.getContent({ format: 'text' }) || editor.getContent() || '';
}
}
} catch (e2) { /* ignore */ }
// Strip tags for API plain-text summary.
var div = document.createElement('div'); var div = document.createElement('div');
div.innerHTML = content || ''; div.innerHTML = content || '';
return (div.textContent || div.innerText || content || '').trim(); var plain = (div.textContent || div.innerText || content || '').replace(/\u00a0/g, ' ').trim();
return plain;
} }
function setExcerptValue(summary) { function setExcerptValue(summary) {
@@ -238,23 +254,34 @@
.then(function (res) { .then(function (res) {
setLoading(sumBtn, false, sumOriginal); setLoading(sumBtn, false, sumOriginal);
if (!res.ok || !res.json || res.json.success === false) { if (!res.ok || !res.json || res.json.success === false) {
var j = res.json || {};
var msg = var msg =
(res.json && (res.json.message || (res.json.data && res.json.data.message))) || j.message ||
(j.data && (j.data.message || (Array.isArray(j.data) && j.data[0] && j.data[0].message))) ||
I18N.failed || I18N.failed ||
'生成失败'; '生成失败';
if (res.status === 401 || res.status === 403) {
msg = I18N.needLogin || '登录已失效或权限不足,请刷新页面后重试';
}
notify(sumBtn, msg, 'error'); notify(sumBtn, msg, 'error');
return; return;
} }
var summary = (res.json.data && res.json.data.summary) || ''; var payload = res.json.data || {};
var summary = payload.summary || (payload.data && payload.data.summary) || '';
if (!summary) {
notify(sumBtn, I18N.failed || '生成失败:返回摘要为空', 'error');
return;
}
if (!setExcerptValue(summary)) { if (!setExcerptValue(summary)) {
notify(sumBtn, I18N.noExcerptField || '未找到摘要字段,请展开「摘要」面板', 'error'); notify(sumBtn, I18N.noExcerptField || '未找到摘要字段,请展开「摘要」面板', 'error');
return; return;
} }
notify(sumBtn, I18N.summarySuccess || '已填入摘要字段,请检查后更新保存', 'ok'); notify(sumBtn, I18N.summarySuccess || '已填入摘要字段,请检查后更新保存', 'ok');
}) })
.catch(function () { .catch(function (err) {
setLoading(sumBtn, false, sumOriginal); setLoading(sumBtn, false, sumOriginal);
notify(sumBtn, I18N.failed || '生成失败', 'error'); notify(sumBtn, (err && err.message) || I18N.failed || '生成失败', 'error');
}); });
}); });
})(); })();
@@ -204,24 +204,78 @@ class AKSRT_Admin_AI_Controller extends AKSRT_Admin_Controller_Base {
} }
$params = $this->get_json_params($request); $params = $this->get_json_params($request);
$content = wp_kses_post((string) ($params['content'] ?? '')); // Accept JSON body or form body (some admin contexts strip JSON).
$max_len = max(50, min(500, (int) ($params['max_length'] ?? 200))); if ($params === []) {
$params = $request->get_params();
if (trim(wp_strip_all_tags($content)) === '') { if (!is_array($params)) {
return $this->error(__('内容不能为空', 'aksrt')); $params = [];
}
} }
$prompt = AKSRT_AI_Prompt::get_instance()->build_summary_prompt($content, $max_len); $title = sanitize_text_field((string) ($params['title'] ?? ''));
$result = AKSRT_AI::get_instance()->generate_text($prompt, [ $raw = (string) ($params['content'] ?? '');
'max_tokens' => min(600, $max_len * 2), // 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, 'temperature' => 0.5,
'system_instruction' => __('你是中文内容编辑,只输出摘要正文,不要标题、前缀或 Markdown。', 'aksrt'),
]); ]);
if (!empty($result['success'])) { 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 { 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 { public function is_wp_ai_available(): bool {
if (!function_exists('wp_ai_client_prompt')) { if (!function_exists('wp_ai_client_prompt')) {
return false; return false;
} }
if (function_exists('wp_supports_ai') && !wp_supports_ai()) { // Prefer the official capability gate when present.
return false; 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 { public function is_theme_provider_available(): bool {
$config = $this->get_config(); $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']) return !empty($config['enabled'])
&& ($config['provider'] ?? self::PROVIDER_NONE) !== self::PROVIDER_NONE && $provider !== self::PROVIDER_NONE
&& !empty($config['api_key']); && $provider !== ''
&& $api_key !== ''
&& $api_base !== '';
} }
/** /**
* 任一后端可用即可生成。 * 任一后端可用即可生成。
*/ */
public function is_available(): bool { 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 { public function resolve_backend(): string {
if ($this->is_wp_ai_available()) {
return 'wp_ai';
}
if ($this->is_theme_provider_available()) { if ($this->is_theme_provider_available()) {
return 'theme'; return 'theme';
} }
if ($this->is_wp_ai_available()) {
return 'wp_ai';
}
return 'none'; return 'none';
} }
@@ -205,28 +218,35 @@ class AKSRT_AI {
? (string) $options['system_instruction'] ? (string) $options['system_instruction']
: __('你是一个内容助手,提供建议性内容。输出仅作为参考建议,不会自动应用到线上内容。', 'aksrt'); : __('你是一个内容助手,提供建议性内容。输出仅作为参考建议,不会自动应用到线上内容。', '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()) { if ($this->is_wp_ai_available()) {
$wp_result = $this->generate_via_wp_ai($prompt, $system, $options); $wp_result = $this->generate_via_wp_ai($prompt, $system, $options);
$this->record_call();
if (!empty($wp_result['success'])) { if (!empty($wp_result['success'])) {
$this->record_call();
$wp_result['backend'] = 'wp_ai'; $wp_result['backend'] = 'wp_ai';
return $wp_result; return $wp_result;
} }
// Fall through to theme if configured $last_error = $wp_result;
if (!$this->is_theme_provider_available()) {
$this->record_call();
return $wp_result;
}
} }
// 2) Theme OpenAI-compatible return $last_error;
$theme_result = $this->generate_via_theme($prompt, $system, $options);
$this->record_call();
if (!empty($theme_result['success'])) {
$theme_result['backend'] = 'theme';
}
return $theme_result;
} }
/** /**