mirror of
https://github.com/Ed1s0nZ/CyberStrikeAI.git
synced 2026-11-23 04:41:41 +01:00
feat(web): surface context window detection in AI channel settings
This commit is contained in:
1 parent
d7e8a29dfe
commit
3964f325bd
6 files changed
+214
-5
No files matched your search
@@ -5403,6 +5403,14 @@ html[data-theme="dark"] .conversation-reasoning-card:not(.conversation-reasoning
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
#detect-context-result.is-success {
|
||||
color: var(--success-color, #38a169);
|
||||
}
|
||||
|
||||
#detect-context-result.is-error {
|
||||
color: var(--danger-color, #e53e3e);
|
||||
}
|
||||
|
||||
.ai-channel-reasoning-toggle {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
@@ -3093,6 +3093,25 @@
|
||||
"maxCompletionTokens": "Max Output Tokens",
|
||||
"maxCompletionTokensPlaceholder": "32768",
|
||||
"maxCompletionTokensHint": "Maximum tokens for a single model response. Default: 32768",
|
||||
"contextWindow": "Model Context Window (tokens)",
|
||||
"contextWindowPlaceholder": "131072",
|
||||
"contextWindowHint": "Native model window used to validate and clamp the budget. For local models, match the server num_ctx/ctx-size.",
|
||||
"contextProfile": "Context Optimization Profile",
|
||||
"contextProfileAuto": "General (default)",
|
||||
"contextProfileLocal": "Local model (32K-256K optimized)",
|
||||
"contextProfileHint": "The local profile tightens compaction triggers, tool-output limits, and always-visible tools. It only tightens existing settings.",
|
||||
"detectContext": "Auto-detect",
|
||||
"detectContextFillRequired": "Fill in Base URL and model first",
|
||||
"detectedContext": "Detected {tokens} tokens",
|
||||
"effectiveBudget": "Effective budget {tokens} tokens",
|
||||
"contextWarnWindowUnknown": "No window set for the local profile; assuming 32768",
|
||||
"contextWarnWindowSmall": "Window below 16384; tool-using agents may be unreliable",
|
||||
"contextWarnBudgetClamped": "Max context budget was clamped to the model window",
|
||||
"contextWarnBudgetExceedsWindow": "Configured budget exceeds the model window; it will be clamped at runtime",
|
||||
"contextWarnOllamaV1": "Ollama's /v1 endpoint ignores num_ctx; set OLLAMA_CONTEXT_LENGTH or a Modelfile parameter",
|
||||
"contextWarnOllamaRuntime": "Ollama may cap the window below the model maximum based on VRAM; check ollama ps after loading",
|
||||
"contextWarnRuntimeUnknown": "Runtime window could not be confirmed and may be below the model maximum",
|
||||
"contextWarnUnknown": "No context window detected; enter it manually",
|
||||
"openaiReasoningTitle": "Reasoning settings",
|
||||
"openaiReasoningHint": "Default reasoning settings for this AI channel; chat Session settings can override them.",
|
||||
"openaiReasoningProfile": "Wire profile",
|
||||
|
||||
@@ -3106,6 +3106,25 @@
|
||||
"maxCompletionTokens": "Макс. токенов ответа",
|
||||
"maxCompletionTokensPlaceholder": "32768",
|
||||
"maxCompletionTokensHint": "Максимум токенов одного ответа модели. По умолчанию: 32768",
|
||||
"contextWindow": "Окно контекста модели (токены)",
|
||||
"contextWindowPlaceholder": "131072",
|
||||
"contextWindowHint": "Собственное окно модели для проверки и ограничения бюджета. Для локальных моделей укажите серверный num_ctx/ctx-size.",
|
||||
"contextProfile": "Профиль оптимизации контекста",
|
||||
"contextProfileAuto": "Общий (по умолчанию)",
|
||||
"contextProfileLocal": "Локальная модель (32K-256K)",
|
||||
"contextProfileHint": "Локальный профиль ужесточает пороги сжатия, лимиты вывода инструментов и число постоянных инструментов. Он только уменьшает существующие значения.",
|
||||
"detectContext": "Автоопределение",
|
||||
"detectContextFillRequired": "Сначала заполните Base URL и модель",
|
||||
"detectedContext": "Обнаружено {tokens} токенов",
|
||||
"effectiveBudget": "Эффективный бюджет {tokens} токенов",
|
||||
"contextWarnWindowUnknown": "Для локального профиля не задано окно; используется 32768",
|
||||
"contextWarnWindowSmall": "Окно меньше 16384; агент с инструментами может работать нестабильно",
|
||||
"contextWarnBudgetClamped": "Бюджет контекста ограничен размером окна модели",
|
||||
"contextWarnBudgetExceedsWindow": "Бюджет превышает окно модели и будет ограничен во время работы",
|
||||
"contextWarnOllamaV1": "Эндпоинт Ollama /v1 игнорирует num_ctx; задайте OLLAMA_CONTEXT_LENGTH или параметр Modelfile",
|
||||
"contextWarnOllamaRuntime": "Ollama может уменьшить окно ниже максимума модели в зависимости от VRAM; проверьте ollama ps",
|
||||
"contextWarnRuntimeUnknown": "Не удалось подтвердить рабочее окно; оно может быть меньше максимума модели",
|
||||
"contextWarnUnknown": "Окно контекста не обнаружено; укажите его вручную",
|
||||
"openaiReasoningTitle": "Настройки рассуждения",
|
||||
"openaiReasoningHint": "Настройки рассуждения этого канала ИИ по умолчанию; настройки сессии чата могут их переопределить.",
|
||||
"openaiReasoningProfile": "Профиль передачи",
|
||||
|
||||
@@ -3081,6 +3081,25 @@
|
||||
"maxCompletionTokens": "最大输出 Token 数",
|
||||
"maxCompletionTokensPlaceholder": "32768",
|
||||
"maxCompletionTokensHint": "单次模型回复的输出上限,默认 32768",
|
||||
"contextWindow": "模型上下文窗口(Token)",
|
||||
"contextWindowPlaceholder": "131072",
|
||||
"contextWindowHint": "模型原生窗口;用于校验并收紧预算。本地模型请按服务端 num_ctx/ctx-size 填写。",
|
||||
"contextProfile": "上下文优化档位",
|
||||
"contextProfileAuto": "通用(默认)",
|
||||
"contextProfileLocal": "本地模型(32K-256K 优化)",
|
||||
"contextProfileHint": "本地档位会收紧压缩触发、工具输出阈值和常驻工具数;只收紧不放大已有配置。",
|
||||
"detectContext": "自动检测",
|
||||
"detectContextFillRequired": "请先填写 Base URL 和模型",
|
||||
"detectedContext": "检测到 {tokens} tokens",
|
||||
"effectiveBudget": "有效预算 {tokens} tokens",
|
||||
"contextWarnWindowUnknown": "本地档位未填写窗口,按 32768 估算",
|
||||
"contextWarnWindowSmall": "窗口小于 16384,带工具的 agent 可能无法稳定运行",
|
||||
"contextWarnBudgetClamped": "最大上下文预算已按模型窗口收紧",
|
||||
"contextWarnBudgetExceedsWindow": "填写的预算超过模型窗口,运行时会自动收紧",
|
||||
"contextWarnOllamaV1": "Ollama 的 /v1 接口忽略 num_ctx,请在服务端设置 OLLAMA_CONTEXT_LENGTH 或 Modelfile",
|
||||
"contextWarnOllamaRuntime": "Ollama 可能按显存把窗口压到模型上限以下,建议启动后查看 ollama ps",
|
||||
"contextWarnRuntimeUnknown": "无法确认运行时窗口,可能小于模型上限",
|
||||
"contextWarnUnknown": "未检测到上下文窗口,请手动填写",
|
||||
"openaiReasoningTitle": "推理设置",
|
||||
"openaiReasoningHint": "作为该 AI 通道的默认推理设置;对话页「会话设置」可覆盖。",
|
||||
"openaiReasoningProfile": "线路 profile",
|
||||
|
||||
+132
-5
@@ -2626,6 +2626,8 @@ function ensureAIConfigShape(cfg) {
|
||||
model: oa.model || '',
|
||||
max_total_tokens: oa.max_total_tokens || 120000,
|
||||
max_completion_tokens: oa.max_completion_tokens || 0,
|
||||
context_window: oa.context_window || 0,
|
||||
context_profile: oa.context_profile || '',
|
||||
reasoning: oa.reasoning || {}
|
||||
};
|
||||
}
|
||||
@@ -2644,6 +2646,8 @@ function readAIChannelFromMainForm(id) {
|
||||
model: document.getElementById('openai-model')?.value.trim() || '',
|
||||
max_total_tokens: parseInt(document.getElementById('openai-max-total-tokens')?.value, 10) || 120000,
|
||||
max_completion_tokens: maxCompletionTokens,
|
||||
context_window: parseInt(document.getElementById('openai-context-window')?.value, 10) || 0,
|
||||
context_profile: document.getElementById('openai-context-profile')?.value || '',
|
||||
reasoning: {
|
||||
...(prev.reasoning || {}),
|
||||
mode: document.getElementById('openai-reasoning-mode')?.value || 'auto',
|
||||
@@ -2676,6 +2680,10 @@ function writeAIChannelToMainForm(id) {
|
||||
if (maxTokensEl) maxTokensEl.value = ch.max_total_tokens || 120000;
|
||||
const maxCompletionTokensEl = document.getElementById('openai-max-completion-tokens');
|
||||
if (maxCompletionTokensEl) maxCompletionTokensEl.value = ch.max_completion_tokens || 32768;
|
||||
const contextWindowEl = document.getElementById('openai-context-window');
|
||||
if (contextWindowEl) contextWindowEl.value = ch.context_window || '';
|
||||
const contextProfileEl = document.getElementById('openai-context-profile');
|
||||
if (contextProfileEl) contextProfileEl.value = ['auto', 'local'].includes(String(ch.context_profile || '').toLowerCase()) ? String(ch.context_profile).toLowerCase() : 'auto';
|
||||
const r = ch.reasoning || {};
|
||||
const modeEl = document.getElementById('openai-reasoning-mode');
|
||||
if (modeEl) {
|
||||
@@ -2780,7 +2788,11 @@ function bindAIChannelEditorPreviewSync() {
|
||||
'openai-provider',
|
||||
'openai-api-key',
|
||||
'openai-base-url',
|
||||
'openai-model'
|
||||
'openai-model',
|
||||
'openai-max-total-tokens',
|
||||
'openai-max-completion-tokens',
|
||||
'openai-context-window',
|
||||
'openai-context-profile'
|
||||
];
|
||||
ids.forEach((fieldId) => {
|
||||
const el = document.getElementById(fieldId);
|
||||
@@ -3128,6 +3140,8 @@ function createAIChannelFromForm() {
|
||||
model: '',
|
||||
max_total_tokens: 120000,
|
||||
max_completion_tokens: 32768,
|
||||
context_window: 0,
|
||||
context_profile: '',
|
||||
reasoning: { mode: 'auto', effort: '', profile: 'auto', allow_client_reasoning: true }
|
||||
};
|
||||
selectedAIChannelId = id;
|
||||
@@ -3222,14 +3236,17 @@ async function probeSelectedAIChannels() {
|
||||
channel_id: id,
|
||||
base_url: ch.base_url || '',
|
||||
api_key: ch.api_key || '',
|
||||
model: ch.model || ''
|
||||
model: ch.model || '',
|
||||
max_total_tokens: parseInt(ch.max_total_tokens, 10) || 0,
|
||||
context_profile: ch.context_profile || ''
|
||||
})
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (response.ok && result.success) {
|
||||
okCount += 1;
|
||||
const latency = result.latency_ms ? ` ${result.latency_ms}ms` : '';
|
||||
aiChannelProbeResults[id] = { status: 'ready', message: settingsT('settingsBasic.aiChannelReadyWithLatency', '可用{latency}').replace('{latency}', latency) };
|
||||
const context = result.context_window ? ` · ${result.context_window} tokens` : '';
|
||||
aiChannelProbeResults[id] = { status: 'ready', message: settingsT('settingsBasic.aiChannelReadyWithLatency', '可用{latency}').replace('{latency}', latency) + context };
|
||||
} else {
|
||||
aiChannelProbeResults[id] = { status: 'failed', message: formatConnectionTestError(result.error || settingsT('settingsBasic.testFailed', '连接失败')).message };
|
||||
}
|
||||
@@ -3291,6 +3308,7 @@ if (typeof window !== 'undefined') {
|
||||
window.copyAIChannelFromForm = copyAIChannelFromForm;
|
||||
window.deleteSelectedAIChannel = deleteSelectedAIChannel;
|
||||
window.probeSelectedAIChannels = probeSelectedAIChannels;
|
||||
window.detectAIContext = detectAIContext;
|
||||
window.deleteCheckedAIChannels = deleteCheckedAIChannels;
|
||||
}
|
||||
|
||||
@@ -3877,6 +3895,111 @@ function showConnectionTestFailure(resultEl, errorText) {
|
||||
}
|
||||
|
||||
// 测试OpenAI连接
|
||||
function contextWarningText(code) {
|
||||
const messages = {
|
||||
local_context_window_unknown: settingsT('settingsBasic.contextWarnWindowUnknown', '本地档位未填写窗口,按 32768 估算'),
|
||||
local_context_window_small: settingsT('settingsBasic.contextWarnWindowSmall', '窗口小于 16384,带工具的 agent 可能无法稳定运行'),
|
||||
max_total_tokens_clamped: settingsT('settingsBasic.contextWarnBudgetClamped', '最大上下文预算已按模型窗口收紧'),
|
||||
configured_budget_exceeds_context_window: settingsT('settingsBasic.contextWarnBudgetExceedsWindow', '填写的预算超过模型窗口,运行时会自动收紧'),
|
||||
ollama_v1_ignores_num_ctx: settingsT('settingsBasic.contextWarnOllamaV1', 'Ollama 的 /v1 接口忽略 num_ctx,请在服务端设置 OLLAMA_CONTEXT_LENGTH 或 Modelfile'),
|
||||
ollama_runtime_context_unknown: settingsT('settingsBasic.contextWarnOllamaRuntime', 'Ollama 可能按显存把窗口压到模型上限以下,建议启动后查看 ollama ps'),
|
||||
context_runtime_unknown: settingsT('settingsBasic.contextWarnRuntimeUnknown', '无法确认运行时窗口,可能小于模型上限'),
|
||||
context_window_unknown: settingsT('settingsBasic.contextWarnUnknown', '未检测到上下文窗口,请手动填写')
|
||||
};
|
||||
return messages[code] || code;
|
||||
}
|
||||
|
||||
function formatDetectedContext(result) {
|
||||
if (!result || !result.context_window) return '';
|
||||
const parts = [settingsT('settingsBasic.detectedContext', '检测到 {tokens} tokens').replace('{tokens}', String(result.context_window))];
|
||||
if (result.effective_max_total_tokens) {
|
||||
parts.push(settingsT('settingsBasic.effectiveBudget', '有效预算 {tokens} tokens').replace('{tokens}', String(result.effective_max_total_tokens)));
|
||||
}
|
||||
if (result.context_backend) parts.push(result.context_backend);
|
||||
if (result.context_source) parts.push(result.context_source);
|
||||
if (Array.isArray(result.context_warnings)) {
|
||||
result.context_warnings.forEach((code) => parts.push(contextWarningText(code)));
|
||||
}
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
function applyDetectedContext(result) {
|
||||
if (!result || !result.context_window) return;
|
||||
const input = document.getElementById('openai-context-window');
|
||||
if (input && !String(input.value || '').trim()) {
|
||||
input.value = String(result.context_window);
|
||||
}
|
||||
const resultEl = document.getElementById('detect-context-result');
|
||||
if (resultEl) {
|
||||
resultEl.textContent = formatDetectedContext(result);
|
||||
resultEl.className = 'form-inline-result is-success';
|
||||
}
|
||||
}
|
||||
|
||||
async function detectAIContext() {
|
||||
const btn = document.getElementById('detect-context-btn');
|
||||
const resultEl = document.getElementById('detect-context-result');
|
||||
const provider = document.getElementById('openai-provider')?.value || 'openai_compatible';
|
||||
const baseUrl = document.getElementById('openai-base-url')?.value.trim() || '';
|
||||
const apiKey = document.getElementById('openai-api-key')?.value.trim() || '';
|
||||
const model = document.getElementById('openai-model')?.value.trim() || '';
|
||||
const channelId = normalizeAIChannelId(selectedAIChannelId || currentConfig?.ai?.default_channel || 'default');
|
||||
if (!baseUrl || !model) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = settingsT('settingsBasic.detectContextFillRequired', '请先填写 Base URL 和模型');
|
||||
resultEl.className = 'form-inline-result is-error';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (btn) {
|
||||
btn.style.pointerEvents = 'none';
|
||||
btn.style.opacity = '0.5';
|
||||
}
|
||||
if (resultEl) {
|
||||
resultEl.textContent = settingsT('settingsBasic.testing', '测试中...');
|
||||
resultEl.className = 'form-inline-result is-muted';
|
||||
}
|
||||
try {
|
||||
const response = await apiFetch('/api/config/detect-context', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
provider: provider,
|
||||
channel_id: channelId,
|
||||
base_url: baseUrl,
|
||||
api_key: apiKey,
|
||||
model: model,
|
||||
max_total_tokens: parseInt(document.getElementById('openai-max-total-tokens')?.value, 10) || 0,
|
||||
context_profile: document.getElementById('openai-context-profile')?.value || ''
|
||||
})
|
||||
});
|
||||
const result = await response.json().catch(() => ({}));
|
||||
if (result.success && result.context_window) {
|
||||
applyDetectedContext(result);
|
||||
if (resultEl) {
|
||||
resultEl.textContent = formatDetectedContext(result);
|
||||
resultEl.className = 'form-inline-result is-success';
|
||||
}
|
||||
} else {
|
||||
const message = result.error || contextWarningText('context_window_unknown');
|
||||
if (resultEl) {
|
||||
resultEl.textContent = formatConnectionTestError(message).message;
|
||||
resultEl.className = 'form-inline-result is-error';
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (resultEl) {
|
||||
resultEl.textContent = formatConnectionTestError(error.message || '测试出错').message;
|
||||
resultEl.className = 'form-inline-result is-error';
|
||||
}
|
||||
} finally {
|
||||
if (btn) {
|
||||
btn.style.pointerEvents = '';
|
||||
btn.style.opacity = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function testOpenAIConnection() {
|
||||
const btn = document.getElementById('test-openai-btn');
|
||||
const resultEl = document.getElementById('test-openai-result');
|
||||
@@ -3918,7 +4041,9 @@ async function testOpenAIConnection() {
|
||||
channel_id: channelId,
|
||||
base_url: baseUrl,
|
||||
api_key: apiKey,
|
||||
model: model
|
||||
model: model,
|
||||
max_total_tokens: parseInt(document.getElementById('openai-max-total-tokens')?.value, 10) || 0,
|
||||
context_profile: document.getElementById('openai-context-profile')?.value || ''
|
||||
})
|
||||
});
|
||||
|
||||
@@ -3927,9 +4052,11 @@ async function testOpenAIConnection() {
|
||||
if (result.success) {
|
||||
const latency = result.latency_ms ? ` (${result.latency_ms}ms)` : '';
|
||||
const modelInfo = result.model ? ` [${result.model}]` : '';
|
||||
const message = (typeof window.t === 'function' ? window.t('settingsBasic.testSuccess') : '连接成功') + modelInfo + latency;
|
||||
const contextInfo = result.context_window ? ` · ${result.context_window} tokens` : '';
|
||||
const message = (typeof window.t === 'function' ? window.t('settingsBasic.testSuccess') : '连接成功') + modelInfo + latency + contextInfo;
|
||||
aiChannelProbeResults[channelId] = { status: 'ready', message };
|
||||
if (isTestingSameChannel()) {
|
||||
applyDetectedContext(result);
|
||||
setConnectionTestResult(resultEl, 'is-success', message);
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -3764,6 +3764,23 @@
|
||||
<input type="number" id="openai-max-completion-tokens" data-i18n="settingsBasic.maxCompletionTokensPlaceholder" data-i18n-attr="placeholder" placeholder="16384" min="1" step="256" />
|
||||
<small class="form-hint" data-i18n="settingsBasic.maxCompletionTokensHint">单次模型回复的输出上限,默认 16384</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="openai-context-window"><span data-i18n="settingsBasic.contextWindow">模型上下文窗口(Token)</span></label>
|
||||
<div class="model-pick-row">
|
||||
<input type="number" id="openai-context-window" data-i18n="settingsBasic.contextWindowPlaceholder" data-i18n-attr="placeholder" placeholder="131072" min="0" step="1024" />
|
||||
<a href="javascript:void(0)" id="detect-context-btn" class="model-pick-fetch-link" onclick="detectAIContext()" data-i18n="settingsBasic.detectContext">自动检测</a>
|
||||
</div>
|
||||
<small class="form-hint" data-i18n="settingsBasic.contextWindowHint">模型原生窗口;用于校验并收紧预算。本地模型请按服务端 num_ctx/ctx-size 填写。</small>
|
||||
<span id="detect-context-result" class="form-inline-result"></span>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="openai-context-profile"><span data-i18n="settingsBasic.contextProfile">上下文优化档位</span></label>
|
||||
<select id="openai-context-profile">
|
||||
<option value="auto" data-i18n="settingsBasic.contextProfileAuto">通用(默认)</option>
|
||||
<option value="local" data-i18n="settingsBasic.contextProfileLocal">本地模型(32K-256K 优化)</option>
|
||||
</select>
|
||||
<small class="form-hint" data-i18n="settingsBasic.contextProfileHint">本地档位会收紧压缩触发、工具输出阈值和常驻工具数;只收紧不放大已有配置。</small>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
Reference in new issue
Block a user