mirror of
https://github.com/Wx-2025/ST-Amily2-Chat-Optimisation.git
synced 2026-06-13 09:15:50 +00:00
### 新功能 - **翰林院向量化质量升级**: - **边界感知切块**:替换四个来源(聊天记录/小说/世界书/手动)的纯字符硬切——优先在段落边界断开,其次句末标点(含中文引号闭合),极端长串才硬切;句子/对话不再被拦腰截断,embedding 质量同步受益。仅影响新录入,已有向量无需重建 - **注入时序重排**:检索结果注入提示词前按时序重排(聊天记录按楼层、小说按卷/章/节——中文数字章节号可解析),rerank 只决定"选哪些块",不再决定呈现顺序;修复"不打不相识的剧情之后紧跟关系亲密"这类因按相关度排序导致的认知时间错乱 - **断层提示**:聊天记录相邻块楼层跳跃时自动插入"与上文相隔约 N 楼,并非连续发生"提示行,消除中间剧情缺失造成的割裂感 - **时间标识**:新录入的聊天记录块在来源标识中带上消息发送时间(ST 向量存储不持久化元数据,时间必须写入块文本才能在检索后取回;旧格式块兼容解析) - **记忆块工作流(memory-blocks)**:剧情优化新增"自定义记忆块"体系——占位符驱动的并发工作流框架 - 在剧情优化面板「匹配替换 (sulv)」下方可增删自定义块:每个块定义一个占位符,执行剧情优化时主/拦截提示词中的占位符会被块的产出替换 - **静态块**:直接输出固定内容;**AI 调用块**:用所选 API 功能槽独立请求一次,把回复(或其中指定 `<标签>` 的内容)作为替换值 - 原有 sulv1-4 速率占位符迁入同一框架,行为与旧版逐字节一致 - 块定义为纯 JSON、随设置持久化,为后续导入导出与战斗系统接入预留扩展点 - 框架层新增**顺序拼接式 Chain**(`composeChain`):与占位符替换并列的第二种组合范式——同链的块并发执行后按 `order` 排序、以 `separator` 拼接并可选 `header/footer` 包裹,产出一个完整注入块;为记忆注入合成块与战斗系统"底部战报块"预留的承载结构,本版本暂无 UI 入口 - **API 连接配置**: - 角色世界书(cwb)与一键生卡(autoCharCard)纳入旧配置自动迁移:老用户首次加载会把旧 URL / Key / 模型自动迁移为连接配置并分配槽位(一键生卡仅在规划者与执行者配置一致或规划者为空时迁移,避免悄悄改变行为) - **profile 已分配时参数控件 informational 化**:主面板 / 并发剧情优化 / 角色世界书 / 术语表的温度、maxTokens 控件在槽位分配 profile 后自动禁用并显示"由连接配置控制"提示,消除"改了没效果"的用户陷阱 - **profile 状态卡新增"本设备无 Key"警示**:API Key 仅保存在最初填写它的设备/浏览器上(安全设计,不随云端设置同步),换设备后状态卡会直接亮出警示徽标,不必等到调用报错才发现 ### 修复 - **独立聊天记忆从摆设变真功能(原作遗留坑)**:此前向量数据"随卡不随聊天"——开启"独立聊天记忆"后录入仍存进角色库、查询却去查一个从未被写入过的聊天集合、计数恒为 0,整体静默失效。现已重构为聊天级分桶: - 独立模式下,聊天记录类向量按当前聊天隔离存储与检索,同一张卡开多个聊天(不同剧情线)的记忆互不污染 - 小说 / 世界书 / 手动录入属于"知识",仍随角色卡跨聊天共享;全局库不受影响 - 知识管理列表为聊天专属库显示"聊天级"徽标;聊天级库禁止移动到全局 - 统一模式(默认关闭独立记忆)的存量数据与行为完全不变 - 已知限制:聊天专属记忆跟随聊天文件,重命名聊天文件会使其失联(与 ST 官方向量扩展同等限制) - **超级排序截断顺序修正**:开启"超级排序"时,时序重排发生在 top_n 截断之前,导致保留的是"时序最早"而非"最相关"的块,检索结果长期偏向最旧的聊天记录。现改为先按相关度截取 top_n、再做时序排序 - **翰林院向量化失败("向量化块数量不识别"反馈)**: - 一次性清洗 profile-sync 历史污染:`retrieval/rerank.apiKey` 中的掩码占位符在持久层根治(此前仅读取侧防御);`apiEndpoint` / `rerank.apiMode` 的非法值(如被旧版写入的空字符串)归一化为 `custom` - 修复 `apiEndpoint` 为空/非法时请求被硬定向到 `api.openai.com`、无视用户自定义 URL 的问题(CSP 拦截 / 401 的元凶) - 修复**本地代理(LM Studio/Ollama)模式**自始就缺少 URL 分支、同样被错误定向到 openai.com 的问题 - API 模式下拉补全 `OpenAI 官方` / `Azure` 选项;默认 API 模式改为 `custom`(与默认 URL 配套),新用户不再因选项缺失导致首次保存写入空值 - profile-sync 给下拉框赋不存在选项值的污染源头修复(影响所有模块面板,不止翰林院) - **Rerank "API Key 未提供"报错升级**:当原因是"连接配置在本设备没有可用 Key"时,报错会直接说明 Key 的设备本地性并指引到 API 连接配置重新填写(向量化 Google 直连、获取模型列表同步处理) - **旧配置迁移**:一键生卡迁移时排除掩码占位符,避免把历史污染的假 Key 迁入新连接配置 - **超级记忆稳定性专项**(针对"工作不大稳定"反馈,4 处根因一次修复): - **切聊天竞态污染**:CHAT_CHANGED 时超级记忆立即全量同步,而表格系统延迟 100ms 才加载新聊天的表格,导致【旧聊天】的表格内容被写进【新角色】的记忆世界书;两边表名不同时旧表条目无 GC 兜底会**永久残留**("记忆串台"元凶)。现 CHAT_CHANGED 只确保世界书存在,新状态同步交由 `loadTables()` 完成后的自动推送,单次且时序正确 - **死代码双轨存储拆除**:`saveStateToMetadata` / `tryRestoreStateFromMetadata` 把表格状态写到 `msg.metadata`——该字段非 ST 持久化位(同 v2.2.5 二次填表修过的坑),写入即蒸发、恢复永远为空,且每次同步还白调一次 `saveChat()`。整条链路删除,表格状态唯一信源为表格系统的 `msg.extra.amily2_tables_data` - **`awaitSync()` 穿透**:同步队列正忙时 `pushUpdate` 会用一个立即 resolve 的空 Promise 覆盖 `_syncPromise`,Pipeline Stage 4 等待形同虚设、后续阶段在同步未完成时被放行。现忙时不覆盖,正在运行的 drain 循环自然吃掉新入队项 - **开关打开不生效**:启动时若总开关为关,初始化早退且不注册监听器;此后在 UI 勾选开关只写设置,超级记忆直到刷新页面前都是死的。现勾选即触发初始化(幂等) - 附带:`forceSyncAll` 的表格角色推断改为复用 `events-schema.inferTableRole`,消除两处重复逻辑漂移风险;每次切聊天的双倍全量同步(restore 路径一次 + 显式一次)随死代码移除归一 ### 重构 - 表格核心 `manager.js` 瘦身(约 1050 → 600 行):19 个 UI 突变操作拆分至 `actions/ui-mutations.js`,SuperMemory 事件分发拆分至 `events-dispatch.js`;全部经 re-export 保持兼容,外部调用路径零改动 - 角色世界书最后 2 处散乱的厂商 URL 判断迁移至 `detectVendor` 统一入口,业务路径上不再有硬编码的 URL substring 判断
721 lines
26 KiB
JavaScript
721 lines
26 KiB
JavaScript
import { state } from './cwb_state.js';
|
||
import { logError, showToastr, escapeHtml } from './cwb_utils.js';
|
||
import { getRequestHeaders } from '/script.js';
|
||
import { extensionName } from '../../utils/settings.js';
|
||
import { extension_settings, getContext } from "/scripts/extensions.js";
|
||
import { compatibleTriggerSlash } from '../../core/tavernhelper-compatibility.js';
|
||
import { getSlotProfile, providerToApiMode } from '../../core/api/api-resolver.js';
|
||
import { configManager } from '../../utils/config/ConfigManager.js';
|
||
import { detectVendor } from '../../utils/api-vendor.js';
|
||
|
||
function normalizeApiResponse(responseData) {
|
||
let data = responseData;
|
||
if (typeof data === 'string') {
|
||
try {
|
||
data = JSON.parse(data);
|
||
} catch (e) {
|
||
console.error(`[${extensionName}] API响应JSON解析失败:`, e);
|
||
return { error: { message: 'Invalid JSON response' } };
|
||
}
|
||
}
|
||
if (data && typeof data.data === 'object' && data.data !== null && !Array.isArray(data.data)) {
|
||
if (Object.hasOwn(data.data, 'data')) {
|
||
data = data.data;
|
||
}
|
||
}
|
||
if (data && data.choices && data.choices[0]) {
|
||
return { content: data.choices[0].message?.content?.trim() };
|
||
}
|
||
if (data && data.content) {
|
||
return { content: data.content.trim() };
|
||
}
|
||
if (data && data.data) {
|
||
return { data: data.data };
|
||
}
|
||
if (data && data.error) {
|
||
return { error: data.error };
|
||
}
|
||
return data;
|
||
}
|
||
|
||
|
||
async function getCwbApiSettings() {
|
||
// 优先读取槽位分配的 Profile
|
||
const profile = await getSlotProfile('cwb');
|
||
if (profile) {
|
||
return {
|
||
apiMode: providerToApiMode(profile.provider),
|
||
apiUrl: profile.apiUrl,
|
||
apiKey: profile.apiKey ?? '',
|
||
model: profile.model,
|
||
tavernProfile: '',
|
||
temperature: profile.temperature ?? 0.7,
|
||
maxTokens: profile.maxTokens ?? 65000,
|
||
};
|
||
}
|
||
|
||
// 降级:读旧 extension_settings
|
||
const settings = extension_settings[extensionName] || {};
|
||
return {
|
||
apiMode: settings.cwb_api_mode || 'openai_test',
|
||
apiUrl: settings.cwb_api_url?.trim() || '',
|
||
apiKey: configManager.get('cwb_api_key') || '',
|
||
model: settings.cwb_api_model || '',
|
||
tavernProfile: settings.cwb_tavern_profile || '',
|
||
temperature: settings.cwb_temperature ?? 0.7,
|
||
maxTokens: settings.cwb_max_tokens ?? 65000
|
||
};
|
||
}
|
||
|
||
async function callCwbSillyTavernPreset(messages, options) {
|
||
console.log('[CWB-ST预设] 使用SillyTavern预设调用');
|
||
|
||
const context = getContext();
|
||
if (!context) {
|
||
throw new Error('无法获取SillyTavern上下文');
|
||
}
|
||
|
||
const profileId = options.tavernProfile;
|
||
if (!profileId) {
|
||
throw new Error('未配置SillyTavern预设ID');
|
||
}
|
||
|
||
let originalProfile = '';
|
||
let responsePromise;
|
||
|
||
try {
|
||
originalProfile = await compatibleTriggerSlash('/profile');
|
||
console.log(`[CWB-ST预设] 当前配置文件: ${originalProfile}`);
|
||
|
||
const targetProfile = context.extensionSettings?.connectionManager?.profiles?.find(p => p.id === profileId);
|
||
if (!targetProfile) {
|
||
throw new Error(`未找到配置文件ID: ${profileId}`);
|
||
}
|
||
|
||
const targetProfileName = targetProfile.name;
|
||
console.log(`[CWB-ST预设] 目标配置文件: ${targetProfileName}`);
|
||
|
||
const currentProfile = await compatibleTriggerSlash('/profile');
|
||
if (currentProfile !== targetProfileName) {
|
||
console.log(`[CWB-ST预设] 切换配置文件: ${currentProfile} -> ${targetProfileName}`);
|
||
const escapedProfileName = targetProfileName.replace(/"/g, '\\"');
|
||
await compatibleTriggerSlash(`/profile await=true "${escapedProfileName}"`);
|
||
}
|
||
|
||
if (!context.ConnectionManagerRequestService) {
|
||
throw new Error('ConnectionManagerRequestService不可用');
|
||
}
|
||
|
||
console.log(`[CWB-ST预设] 通过配置文件 ${targetProfileName} 发送请求`);
|
||
responsePromise = context.ConnectionManagerRequestService.sendRequest(
|
||
targetProfile.id,
|
||
messages,
|
||
options.maxTokens || 65000
|
||
);
|
||
|
||
} finally {
|
||
try {
|
||
const currentProfileAfterCall = await compatibleTriggerSlash('/profile');
|
||
if (originalProfile && originalProfile !== currentProfileAfterCall) {
|
||
console.log(`[CWB-ST预设] 恢复原始配置文件: ${currentProfileAfterCall} -> ${originalProfile}`);
|
||
const escapedOriginalProfile = originalProfile.replace(/"/g, '\\"');
|
||
await compatibleTriggerSlash(`/profile await=true "${escapedOriginalProfile}"`);
|
||
}
|
||
} catch (restoreError) {
|
||
console.error('[CWB-ST预设] 恢复配置文件失败:', restoreError);
|
||
}
|
||
}
|
||
|
||
const result = await responsePromise;
|
||
|
||
if (!result) {
|
||
throw new Error('未收到API响应');
|
||
}
|
||
|
||
const normalizedResult = normalizeApiResponse(result);
|
||
if (normalizedResult.error) {
|
||
throw new Error(normalizedResult.error.message || 'SillyTavern预设API调用失败');
|
||
}
|
||
|
||
return normalizedResult.content;
|
||
}
|
||
|
||
async function callCwbOpenAITest(messages, options) {
|
||
// 参数验证
|
||
if (!Array.isArray(messages) || messages.length === 0) {
|
||
throw new Error('消息数组不能为空');
|
||
}
|
||
|
||
if (!options?.apiUrl?.trim()) {
|
||
throw new Error('API URL 不能为空');
|
||
}
|
||
|
||
if (!options?.model?.trim()) {
|
||
throw new Error('模型名称不能为空');
|
||
}
|
||
|
||
// 确保所有必需的参数都存在且有效
|
||
const validatedOptions = {
|
||
maxTokens: Math.max(1, parseInt(options.maxTokens ?? 65000)),
|
||
temperature: Math.max(0, Math.min(2, parseFloat(options.temperature ?? 1))),
|
||
top_p: Math.max(0, Math.min(1, parseFloat(options.top_p ?? 1))),
|
||
apiUrl: options.apiUrl.trim(),
|
||
apiKey: (options.apiKey || '').trim(),
|
||
model: options.model.trim()
|
||
};
|
||
|
||
// 验证消息格式
|
||
const validatedMessages = messages.map((msg, index) => {
|
||
if (!msg || typeof msg !== 'object') {
|
||
throw new Error(`消息 ${index} 格式无效`);
|
||
}
|
||
if (!msg.role || !['system', 'user', 'assistant'].includes(msg.role)) {
|
||
throw new Error(`消息 ${index} 的角色无效`);
|
||
}
|
||
if (!msg.content || typeof msg.content !== 'string') {
|
||
throw new Error(`消息 ${index} 的内容无效`);
|
||
}
|
||
return {
|
||
role: msg.role,
|
||
content: msg.content.trim()
|
||
};
|
||
});
|
||
|
||
const isGoogleApi = (await detectVendor(validatedOptions.apiUrl)) === 'google';
|
||
|
||
const requestBody = {
|
||
chat_completion_source: 'openai',
|
||
max_tokens: validatedOptions.maxTokens,
|
||
messages: validatedMessages,
|
||
model: validatedOptions.model,
|
||
proxy_password: validatedOptions.apiKey,
|
||
reverse_proxy: validatedOptions.apiUrl,
|
||
stream: false,
|
||
temperature: validatedOptions.temperature,
|
||
top_p: validatedOptions.top_p
|
||
};
|
||
|
||
if (!isGoogleApi) {
|
||
Object.assign(requestBody, {
|
||
custom_prompt_post_processing: 'strict',
|
||
enable_web_search: false,
|
||
frequency_penalty: 0,
|
||
group_names: [],
|
||
include_reasoning: false,
|
||
presence_penalty: 0.12,
|
||
reasoning_effort: 'medium',
|
||
request_images: false,
|
||
});
|
||
}
|
||
|
||
try {
|
||
const response = await fetch('/api/backends/chat-completions/generate', {
|
||
method: 'POST',
|
||
headers: {
|
||
...getRequestHeaders(),
|
||
'Content-Type': 'application/json'
|
||
},
|
||
body: JSON.stringify(requestBody)
|
||
});
|
||
|
||
if (!response.ok) {
|
||
let errorText;
|
||
try {
|
||
errorText = await response.text();
|
||
} catch (e) {
|
||
errorText = '无法读取错误响应';
|
||
}
|
||
|
||
// 根据HTTP状态码提供更具体的错误信息
|
||
let errorMessage = `CWB OpenAI Test API请求失败 (${response.status})`;
|
||
if (response.status === 400) {
|
||
errorMessage += ': 请求格式错误,请检查参数配置';
|
||
} else if (response.status === 401) {
|
||
errorMessage += ': 认证失败,请检查API密钥';
|
||
} else if (response.status === 403) {
|
||
errorMessage += ': 访问被拒绝,请检查权限设置';
|
||
} else if (response.status === 429) {
|
||
errorMessage += ': 请求频率超限,请稍后重试';
|
||
} else if (response.status >= 500) {
|
||
errorMessage += ': 服务器错误,请稍后重试';
|
||
}
|
||
errorMessage += errorText ? ` - ${errorText}` : '';
|
||
|
||
throw new Error(errorMessage);
|
||
}
|
||
|
||
let responseData;
|
||
try {
|
||
responseData = await response.json();
|
||
} catch (e) {
|
||
throw new Error('API返回的响应不是有效的JSON格式');
|
||
}
|
||
|
||
// 使用标准化响应处理
|
||
const normalizedResponse = normalizeApiResponse(responseData);
|
||
|
||
if (normalizedResponse.error) {
|
||
throw new Error(normalizedResponse.error.message || 'API返回错误响应');
|
||
}
|
||
|
||
if (normalizedResponse.content) {
|
||
return normalizedResponse.content;
|
||
}
|
||
|
||
// 兼容直接响应格式
|
||
if (responseData?.choices?.[0]?.message?.content) {
|
||
return responseData.choices[0].message.content.trim();
|
||
}
|
||
|
||
throw new Error('API响应格式不正确或未包含有效内容');
|
||
|
||
} catch (error) {
|
||
if (error.name === 'TypeError' && error.message.includes('fetch')) {
|
||
throw new Error('网络连接失败,请检查网络状态');
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
export async function callCwbAPI(systemPrompt, userPromptContent, options = {}) {
|
||
const apiSettings = await getCwbApiSettings();
|
||
|
||
const finalOptions = {
|
||
maxTokens: apiSettings.maxTokens,
|
||
temperature: apiSettings.temperature,
|
||
model: apiSettings.model,
|
||
apiUrl: apiSettings.apiUrl,
|
||
apiKey: apiSettings.apiKey,
|
||
apiMode: apiSettings.apiMode,
|
||
tavernProfile: apiSettings.tavernProfile,
|
||
...options
|
||
};
|
||
|
||
if (finalOptions.apiMode !== 'sillytavern_preset') {
|
||
if (!finalOptions.apiUrl || !finalOptions.model || !finalOptions.apiKey) {
|
||
throw new Error('API配置不完整,请检查URL、Key和模型配置');
|
||
}
|
||
} else {
|
||
if (!finalOptions.tavernProfile) {
|
||
throw new Error('未配置SillyTavern预设ID');
|
||
}
|
||
}
|
||
|
||
const systemPromptContent = options.isTestCall ? systemPrompt : `${state.currentBreakArmorPrompt}\n\n${systemPrompt}`;
|
||
|
||
const messages = [
|
||
{ role: 'system', content: systemPromptContent },
|
||
{ role: 'user', content: userPromptContent },
|
||
];
|
||
|
||
console.groupCollapsed(`[CWB] 统一API调用 @ ${new Date().toLocaleTimeString()}`);
|
||
console.log("【请求参数】:", {
|
||
mode: finalOptions.apiMode,
|
||
model: finalOptions.model,
|
||
maxTokens: finalOptions.maxTokens,
|
||
temperature: finalOptions.temperature,
|
||
messagesCount: messages.length
|
||
});
|
||
console.log("【消息内容】:", messages);
|
||
|
||
// 格式化并打印完整的提示词
|
||
const fullPromptText = messages.map(msg => `[${msg.role}]\n${msg.content}`).join('\n\n');
|
||
console.log("【完整提示词】:\n", fullPromptText);
|
||
|
||
try {
|
||
let responseContent;
|
||
|
||
switch (finalOptions.apiMode) {
|
||
case 'openai_test':
|
||
responseContent = await callCwbOpenAITest(messages, finalOptions);
|
||
break;
|
||
case 'sillytavern_preset':
|
||
responseContent = await callCwbSillyTavernPreset(messages, finalOptions);
|
||
break;
|
||
default:
|
||
throw new Error(`未支持的API模式: ${finalOptions.apiMode}`);
|
||
}
|
||
|
||
if (!responseContent) {
|
||
throw new Error('未能获取AI响应内容');
|
||
}
|
||
|
||
console.log("【AI回复】:", responseContent);
|
||
console.groupEnd();
|
||
|
||
return responseContent.trim();
|
||
|
||
} catch (error) {
|
||
console.error(`[CWB] API调用发生错误:`, error);
|
||
console.groupEnd();
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
export async function loadModels($panel) {
|
||
const apiSettings = await getCwbApiSettings();
|
||
const $modelSelect = $panel.find('#cwb-api-model');
|
||
const $apiStatus = $panel.find('#cwb-api-status');
|
||
|
||
$apiStatus.text('状态: 正在加载模型列表...').css('color', '#61afef');
|
||
showToastr('info', '正在加载模型列表...');
|
||
|
||
try {
|
||
let models = [];
|
||
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
const context = getContext();
|
||
if (!context?.extensionSettings?.connectionManager?.profiles) {
|
||
throw new Error('无法获取SillyTavern配置文件列表');
|
||
}
|
||
|
||
const targetProfile = context.extensionSettings.connectionManager.profiles.find(p => p.id === apiSettings.tavernProfile);
|
||
if (!targetProfile) {
|
||
throw new Error(`未找到配置文件ID: ${apiSettings.tavernProfile}`);
|
||
}
|
||
|
||
if (targetProfile.openai_model) {
|
||
models.push({ id: targetProfile.openai_model, name: targetProfile.openai_model });
|
||
}
|
||
|
||
if (models.length === 0) {
|
||
throw new Error('当前预设未配置模型');
|
||
}
|
||
|
||
} else {
|
||
if (!apiSettings.apiUrl || !apiSettings.apiKey) {
|
||
throw new Error('API URL或Key未配置');
|
||
}
|
||
|
||
const response = await fetch('/api/backends/chat-completions/status', {
|
||
method: 'POST',
|
||
headers: {
|
||
...getRequestHeaders(),
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
reverse_proxy: apiSettings.apiUrl,
|
||
proxy_password: apiSettings.apiKey,
|
||
chat_completion_source: 'openai'
|
||
})
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errorText = await response.text();
|
||
throw new Error(`HTTP ${response.status}: ${errorText}`);
|
||
}
|
||
|
||
const rawData = await response.json();
|
||
const modelList = Array.isArray(rawData) ? rawData : (rawData.data || rawData.models || []);
|
||
|
||
if (!Array.isArray(modelList)) {
|
||
const errorMessage = 'API未返回有效的模型列表数组';
|
||
throw new Error(errorMessage);
|
||
}
|
||
|
||
models = modelList
|
||
.map(m => {
|
||
const modelIdRaw = m.name || m.id || m.model || m;
|
||
const modelName = String(modelIdRaw).replace(/^models\//, '');
|
||
return {
|
||
id: modelName,
|
||
name: modelName
|
||
};
|
||
})
|
||
.filter(m => m.id)
|
||
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
||
}
|
||
|
||
$modelSelect.empty();
|
||
if (models.length > 0) {
|
||
models.forEach(model => {
|
||
$modelSelect.append(jQuery('<option>', { value: model.id, text: model.name }));
|
||
});
|
||
showToastr('success', `成功加载 ${models.length} 个模型!`);
|
||
} else {
|
||
showToastr('warning', 'API未返回任何可用模型。');
|
||
}
|
||
|
||
} catch (error) {
|
||
logError('加载模型列表时出错:', error);
|
||
showToastr('error', `加载模型列表失败: ${error.message}`);
|
||
} finally {
|
||
await updateApiStatusDisplay($panel);
|
||
}
|
||
}
|
||
|
||
export async function fetchCwbModels() {
|
||
console.log('[CWB] 开始获取模型列表');
|
||
|
||
const apiSettings = await getCwbApiSettings();
|
||
|
||
try {
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
const context = getContext();
|
||
if (!context?.extensionSettings?.connectionManager?.profiles) {
|
||
throw new Error('无法获取SillyTavern配置文件列表');
|
||
}
|
||
|
||
const targetProfile = context.extensionSettings.connectionManager.profiles.find(p => p.id === apiSettings.tavernProfile);
|
||
if (!targetProfile) {
|
||
throw new Error(`未找到配置文件ID: ${apiSettings.tavernProfile}`);
|
||
}
|
||
|
||
const models = [];
|
||
if (targetProfile.openai_model) {
|
||
models.push({ id: targetProfile.openai_model, name: targetProfile.openai_model });
|
||
}
|
||
|
||
if (models.length === 0) {
|
||
throw new Error('当前预设未配置模型');
|
||
}
|
||
|
||
console.log('[CWB] SillyTavern预设模式获取到模型:', models);
|
||
return models;
|
||
|
||
} else {
|
||
if (!apiSettings.apiUrl || !apiSettings.apiKey) {
|
||
throw new Error('API URL或Key未配置');
|
||
}
|
||
|
||
const response = await fetch('/api/backends/chat-completions/status', {
|
||
method: 'POST',
|
||
headers: {
|
||
...getRequestHeaders(),
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
reverse_proxy: apiSettings.apiUrl,
|
||
proxy_password: apiSettings.apiKey,
|
||
chat_completion_source: 'openai'
|
||
})
|
||
});
|
||
|
||
if (!response.ok) {
|
||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||
}
|
||
|
||
const rawData = await response.json();
|
||
const models = Array.isArray(rawData) ? rawData : (rawData.data || rawData.models || []);
|
||
|
||
if (!Array.isArray(models)) {
|
||
const errorMessage = 'API未返回有效的模型列表数组';
|
||
throw new Error(errorMessage);
|
||
}
|
||
|
||
const formattedModels = models
|
||
.map(m => {
|
||
const modelIdRaw = m.name || m.id || m.model || m;
|
||
const modelName = String(modelIdRaw).replace(/^models\//, '');
|
||
return {
|
||
id: modelName,
|
||
name: modelName
|
||
};
|
||
})
|
||
.filter(m => m.id)
|
||
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
||
|
||
console.log('[CWB] 全兼容模式获取到模型:', formattedModels);
|
||
return formattedModels;
|
||
}
|
||
} catch (error) {
|
||
console.error('[CWB] 获取模型列表失败:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
// 简单的测试连接函数 - 基于 JqyhApi.js 模式
|
||
export async function testCwbConnection() {
|
||
console.log('[CWB] 开始API连接测试');
|
||
|
||
const apiSettings = await getCwbApiSettings();
|
||
|
||
if (apiSettings.apiMode !== 'sillytavern_preset' && (!apiSettings.apiUrl || !apiSettings.apiKey || !apiSettings.model)) {
|
||
showToastr('error', 'API配置不完整,请检查URL、Key和模型', 'CWB API连接测试失败');
|
||
return false;
|
||
}
|
||
if (apiSettings.apiMode === 'sillytavern_preset' && !apiSettings.tavernProfile) {
|
||
showToastr('error', 'SillyTavern预设ID未配置', 'CWB API连接测试失败');
|
||
return false;
|
||
}
|
||
|
||
try {
|
||
showToastr('info', '正在发送测试消息"你好!"...', 'CWB API连接测试');
|
||
|
||
const userName = window.SillyTavern.getContext?.()?.name1 || '用户';
|
||
const systemPrompt = `接下来用户会使用测试按钮测试api连接是否正常,请回复ta连接是正常的,称呼用户为:“${userName}大人”,并复述群号1060183271,告知ta,本扩展开发者:“诗与酒.”正静待ta的入驻。`;
|
||
const response = await callCwbAPI(systemPrompt, '你好!', { isTestCall: true });
|
||
|
||
if (response && response.trim()) {
|
||
console.log('[CWB] 测试消息响应:', response);
|
||
const formattedResponse = response.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>');
|
||
showToastr('success', `连接测试成功!AI回复: "${formattedResponse}"`, { escapeHtml: false }, 'CWB API连接测试成功');
|
||
return true;
|
||
} else {
|
||
throw new Error('API未返回有效响应');
|
||
}
|
||
|
||
} catch (error) {
|
||
console.error('[CWB] 连接测试失败:', error);
|
||
showToastr('error', `连接测试失败: ${error.message}`, 'CWB API连接测试失败');
|
||
return false;
|
||
}
|
||
}
|
||
|
||
export async function fetchModelsAndConnect($panel) {
|
||
const apiSettings = await getCwbApiSettings();
|
||
const $modelSelect = $panel.find('#cwb-api-model');
|
||
const $apiStatus = $panel.find('#cwb-api-status');
|
||
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
if (!apiSettings.tavernProfile) {
|
||
showToastr('warning', '请先选择SillyTavern预设。');
|
||
$apiStatus.text('状态: 请先选择SillyTavern预设').css('color', 'orange');
|
||
return;
|
||
}
|
||
} else {
|
||
const apiUrl = $panel.find('#cwb-api-url').val().trim();
|
||
if (!apiUrl) {
|
||
showToastr('warning', '请输入API基础URL。');
|
||
$apiStatus.text('状态:请输入API基础URL').css('color', 'orange');
|
||
return;
|
||
}
|
||
}
|
||
|
||
$apiStatus.text('状态: 正在加载模型列表...').css('color', '#61afef');
|
||
showToastr('info', '正在加载模型列表...');
|
||
|
||
try {
|
||
const models = await fetchCwbModels();
|
||
|
||
$modelSelect.empty();
|
||
if (models.length > 0) {
|
||
models.forEach(model => {
|
||
$modelSelect.append(jQuery('<option>', { value: model.id, text: model.name }));
|
||
});
|
||
showToastr('success', `成功加载 ${models.length} 个模型!`);
|
||
} else {
|
||
showToastr('warning', 'API未返回任何可用模型。');
|
||
}
|
||
|
||
} catch (error) {
|
||
logError('加载模型列表时出错:', error);
|
||
showToastr('error', `加载模型列表失败: ${error.message}`);
|
||
} finally {
|
||
await updateApiStatusDisplay($panel);
|
||
}
|
||
}
|
||
|
||
|
||
export async function updateApiStatusDisplay($panel) {
|
||
if (!$panel) return;
|
||
const $apiStatus = $panel.find('#cwb-api-status');
|
||
const apiSettings = await getCwbApiSettings();
|
||
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
if (apiSettings.tavernProfile) {
|
||
$apiStatus.html(
|
||
`模式: <span style="color:lightgreen;">SillyTavern预设</span><br>预设ID: <span style="color:lightgreen;">${escapeHtml(apiSettings.tavernProfile)}</span>`
|
||
);
|
||
} else {
|
||
$apiStatus.html(
|
||
`模式: SillyTavern预设 - <span style="color:orange;">请选择预设</span>`
|
||
);
|
||
}
|
||
} else {
|
||
if (apiSettings.apiUrl && apiSettings.model) {
|
||
$apiStatus.html(
|
||
`模式: <span style="color:lightgreen;">全兼容</span><br>URL: <span style="color:lightgreen;word-break:break-all;">${escapeHtml(apiSettings.apiUrl)}</span><br>模型: <span style="color:lightgreen;">${escapeHtml(apiSettings.model)}</span>`
|
||
);
|
||
} else if (apiSettings.apiUrl) {
|
||
$apiStatus.html(
|
||
`模式: 全兼容<br>URL: ${escapeHtml(apiSettings.apiUrl)} - <span style="color:orange;">请加载并选择模型</span>`
|
||
);
|
||
} else {
|
||
$apiStatus.html(
|
||
`模式: 全兼容 - <span style="color:#ffcc80;">请配置API URL</span>`
|
||
);
|
||
}
|
||
}
|
||
}
|
||
|
||
export async function callCustomOpenAI(messages) {
|
||
const apiSettings = await getCwbApiSettings();
|
||
|
||
if (apiSettings.apiMode === 'sillytavern_preset') {
|
||
return await callCwbSillyTavernPreset(messages, { tavernProfile: apiSettings.tavernProfile, maxTokens: 65000 });
|
||
} else {
|
||
if (!state.customApiConfig.url || !state.customApiConfig.model) {
|
||
throw new Error('API URL/Model未配置。');
|
||
}
|
||
|
||
const isGoogleApi = (await detectVendor(state.customApiConfig.url)) === 'google';
|
||
|
||
const requestBody = {
|
||
messages: messages,
|
||
model: state.customApiConfig.model,
|
||
temperature: 1,
|
||
top_p: 1,
|
||
max_tokens: 65000,
|
||
stream: false,
|
||
chat_completion_source: 'openai',
|
||
reverse_proxy: state.customApiConfig.url,
|
||
proxy_password: state.customApiConfig.apiKey,
|
||
};
|
||
|
||
if (!isGoogleApi) {
|
||
Object.assign(requestBody, {
|
||
frequency_penalty: 0,
|
||
presence_penalty: 0.12,
|
||
group_names: [],
|
||
include_reasoning: false,
|
||
reasoning_effort: 'medium',
|
||
enable_web_search: false,
|
||
request_images: false,
|
||
custom_prompt_post_processing: 'strict',
|
||
});
|
||
}
|
||
|
||
const fullApiUrl = '/api/backends/chat-completions/generate';
|
||
const headers = { ...getRequestHeaders(), 'Content-Type': 'application/json' };
|
||
const body = JSON.stringify(requestBody);
|
||
|
||
try {
|
||
const response = await fetch(fullApiUrl, {
|
||
method: 'POST',
|
||
headers: headers,
|
||
body: body,
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errTxt = await response.text();
|
||
throw new Error(`API请求失败: ${response.status} ${errTxt}`);
|
||
}
|
||
const data = await response.json();
|
||
|
||
if (data.choices && data.choices[0]?.message?.content) {
|
||
return data.choices[0].message.content.trim();
|
||
}
|
||
|
||
throw new Error('API响应格式不正确。');
|
||
|
||
} catch (error) {
|
||
console.error('[CWB] API Call Failed:', error);
|
||
throw error;
|
||
}
|
||
}
|
||
}
|
||
export class CWBApiService {
|
||
static async callAPI(systemPrompt, userPromptContent, options = {}) {
|
||
return await callCwbAPI(systemPrompt, userPromptContent, options);
|
||
}
|
||
|
||
static async getSettings() {
|
||
return await getCwbApiSettings();
|
||
}
|
||
|
||
static async loadModels($panel) {
|
||
return await loadModels($panel);
|
||
}
|
||
}
|