fix: preserve native model parameters and align official Claude reasoning
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomUUID, createHash } from 'node:crypto';
|
||||
import { chromium, _electron } from 'playwright';
|
||||
import { expect } from 'playwright/test';
|
||||
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
import { HostController } from '../src/core/desktop/host-controller.mjs';
|
||||
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
|
||||
import { projectEnvironment } from '../src/core/process-environment.mjs';
|
||||
import { catalogModel } from '../src/shared/contracts/model-catalog.mjs';
|
||||
import { openWorkbenchTool } from './ui-navigation.mjs';
|
||||
|
||||
const desktop = process.argv.includes('--desktop');
|
||||
assert.ok(process.argv.slice(2).every(value => value === '--desktop'));
|
||||
assert.ok(process.env.AGENT_WORKBENCH_QA_APP_ROOT, 'Use an independent candidate build');
|
||||
const appRoot = fs.realpathSync.native(process.env.AGENT_WORKBENCH_QA_APP_ROOT);
|
||||
const directory = path.resolve('.qa/m1-model-parameters-2026-11-06', (desktop ? 'electron-' : 'web-') + randomUUID());
|
||||
fs.mkdirSync(directory, { recursive: true }); console.log('EVIDENCE ' + directory);
|
||||
const disposers = [], t = { after: fn => disposers.push(fn) }, f = fixture(t, { modernDefaults: true });
|
||||
const requests = [], checks = [], screenshots = [], errors = [], externalBlocked = [];
|
||||
const format = { type: 'json_schema', schema: { type: 'object', properties: { result: { type: 'string' } } } };
|
||||
const model = http.createServer(async (req, res) => {
|
||||
const chunks = []; for await (const chunk of req) chunks.push(chunk);
|
||||
const body = JSON.parse(Buffer.concat(chunks)); requests.push({ route: req.url, body });
|
||||
if (req.url.endsWith('/messages')) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ type: 'message', id: 'owned-msg', role: 'assistant', model: body.model,
|
||||
content: [{ type: 'text', text: 'OK' }], stop_reason: 'end_turn', usage: { input_tokens: 11, output_tokens: 1 } }));
|
||||
} else if (req.url.endsWith('/responses')) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify({ id: 'owned-resp', model: body.model, status: 'completed',
|
||||
output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'OK' }] }], usage: { input_tokens: 11, output_tokens: 1 } }));
|
||||
} else {
|
||||
res.writeHead(200, { 'Content-Type': 'text/event-stream' });
|
||||
res.end('data: ' + JSON.stringify({ model: body.model, choices: [{ index: 0, delta: { content: 'OK' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n');
|
||||
}
|
||||
});
|
||||
await new Promise(resolve => model.listen(0, '127.0.0.1', resolve));
|
||||
const provider = Object.create(Provider.prototype); provider.apiKey = '';
|
||||
const hub = provider.modelHub(f.store), members = {};
|
||||
for (const [key, protocol, name] of [
|
||||
['opus', 'anthropic-messages', 'claude-opus-5-5'], ['fable', 'anthropic-messages', 'claude-fable-5-1'],
|
||||
['sonnet', 'anthropic-messages', 'claude-sonnet-5-5'], ['haiku', 'anthropic-messages', 'claude-haiku-5-5'],
|
||||
['responses', 'responses', 'owned-responses'], ['chat', 'chat-completions', 'owned-chat'],
|
||||
['negative', 'anthropic-messages', 'owned-negative'], ['unknown', 'anthropic-messages', 'owned-unknown'],
|
||||
]) members[key] = hub.upsert({ name: '自有验证 · ' + key, model: name, protocol, requiresKey: false,
|
||||
baseUrl: 'http://127.0.0.1:' + model.address().port + '/v1', streaming: key === 'chat',
|
||||
capabilityDeclarations: { streaming: key === 'chat' ? 'supported' : 'unknown' },
|
||||
nativeParameters: protocol === 'anthropic-messages' ? { thinking: { type: 'adaptive', display: 'summarized' }, output_config: { effort: 'high', format } }
|
||||
: protocol === 'responses' ? { reasoning: { effort: 'high', summary: 'auto' }, text: { format } }
|
||||
: { thinking: { type: 'enabled', custom: { untouched: true } }, reasoning_effort: 'high', stream_options: { include_usage: false, include_obfuscation: false } } });
|
||||
hub.connection(members.negative.id).upstreamModel = catalogModel({ id: members.negative.model, capabilities: {
|
||||
thinking: { supported: true, types: Object.fromEntries(['disabled', 'enabled', 'adaptive', 'between_tools'].map(value => [value, false])) },
|
||||
effort: { supported: true, low: false, medium: false, high: false, xhigh: false, max: false },
|
||||
} });
|
||||
hub.save(); f.store.close();
|
||||
let host, browser, application, controller, page, window, result, desktopStdout = '', desktopStderr = '';
|
||||
const form = () => page.getByRole('form', { name: '原生请求参数', exact: true });
|
||||
const field = label => form().getByLabel(label, { exact: true });
|
||||
const json = () => field('原生参数 JSON');
|
||||
const parameters = async () => JSON.parse(await json().inputValue());
|
||||
const current = async key => (await host.api('/model-center')).connections.find(row => row.id === members[key].id);
|
||||
const mark = name => { checks.push(name); console.log('PASS ' + name); };
|
||||
async function resize(width, height = 960) {
|
||||
if (window) { await window.evaluate((win, size) => win.setContentSize(size.width, size.height), { width, height }); await until(() => page.evaluate(w => innerWidth === w, width)); }
|
||||
else await page.setViewportSize({ width, height });
|
||||
}
|
||||
async function edit(key) {
|
||||
if (!await page.getByRole('dialog', { name: '模型中心', exact: true }).count()) await openWorkbenchTool(page, '打开模型中心');
|
||||
await page.locator('.mc-connection[data-connection-id="' + members[key].id + '"]').getByRole('button', { name: '推理与能力', exact: true }).click();
|
||||
await expect(form()).toBeVisible();
|
||||
}
|
||||
async function save(key, expected) {
|
||||
await form().getByRole('button', { name: '保存原生参数', exact: true }).click(); await expect(form()).toHaveCount(0);
|
||||
assert.deepEqual((await current(key)).nativeParameters, expected);
|
||||
}
|
||||
async function probe(key) {
|
||||
const before = requests.length; await host.api('/model-center/probe', { id: members[key].id, scope: key === 'chat' ? 'streaming' : 'text' });
|
||||
assert.equal(requests.length, before + 1); return requests.at(-1).body;
|
||||
}
|
||||
async function options(label) { return field(label).locator('option').evaluateAll(nodes => nodes.map(node => ({ value: node.value, disabled: node.disabled, label: node.textContent }))); }
|
||||
async function shot(name, anchor = '推理模式') {
|
||||
await field(anchor).scrollIntoViewIfNeeded();
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'No page overflow');
|
||||
const filename = path.join(directory, name + '.png'); await page.screenshot({ path: filename, scale: 'css' });
|
||||
screenshots.push({ file: path.basename(filename), sha256: createHash('sha256').update(fs.readFileSync(filename)).digest('hex') });
|
||||
fs.writeFileSync(path.join(directory, name + '.txt'), await form().innerText());
|
||||
}
|
||||
try {
|
||||
if (desktop) {
|
||||
const socket = net.createServer(); await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve)); const port = socket.address().port; await new Promise(resolve => socket.close(resolve));
|
||||
assert.notEqual(port, 4318); controller = new HostController({ appRoot, dataRoot: f.data, port, nodePath: process.execPath, timeoutMs: 60000 }); await controller.start();
|
||||
host = { url: controller.url, api: (route, input) => controller.api(route, input === undefined ? {} : { method: 'POST', input }) };
|
||||
const executable = desktopExecutableIdentity(appRoot).path;
|
||||
application = await _electron.launch({ executablePath: executable, args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot,
|
||||
'--data-root', f.data, '--node', process.execPath, '--port', String(port), '--hidden-window'], cwd: appRoot, env: projectEnvironment(), timeout: 60000 });
|
||||
application.process().stdout?.on('data', bytes => { desktopStdout += bytes.toString('utf8'); });
|
||||
application.process().stderr?.on('data', bytes => { desktopStderr += bytes.toString('utf8'); });
|
||||
page = await application.firstWindow(); window = await application.browserWindow(page); await window.evaluate(win => win.showInactive());
|
||||
} else {
|
||||
host = await launchWorkbench(t, f.data, {}, { appRoot }); assert.notEqual(new URL(host.url).port, '4318');
|
||||
browser = await chromium.launch({ channel: 'msedge', headless: true }); page = await browser.newPage();
|
||||
}
|
||||
page.on('pageerror', cause => errors.push(cause.message));
|
||||
await page.route('**/*', route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin === new URL(host.url).origin || ['data:', 'blob:'].includes(url.protocol)) return route.continue();
|
||||
externalBlocked.push(url.origin); return route.abort();
|
||||
});
|
||||
await resize(1280); await page.goto(host.url);
|
||||
await edit('opus');
|
||||
let modes = await options('推理模式');
|
||||
for (const value of ['disabled', 'enabled', 'between_tools']) assert.equal(modes.find(row => row.value === value).disabled, true);
|
||||
assert.equal(modes.find(row => row.value === 'adaptive').disabled, false);
|
||||
await expect(form()).toContainText('Anthropic 官方推理说明');
|
||||
await field('推理强度').selectOption('max');
|
||||
let expected = await parameters(); assert.deepEqual(expected.output_config, { effort: 'max', format }); assert.equal(expected.thinking.display, 'summarized');
|
||||
await field('推理模式').selectOption('default'); assert.deepEqual((await parameters()).thinking, { type: 'adaptive', display: 'summarized' });
|
||||
await shot('opus-1280'); await save('opus', expected);
|
||||
let wire = await probe('opus'); assert.deepEqual(wire.output_config, expected.output_config); assert.deepEqual(wire.thinking, expected.thinking); assert.equal(wire.max_tokens, 128000);
|
||||
await page.reload(); await edit('opus'); assert.deepEqual(await parameters(), expected);
|
||||
await field('推理强度').selectOption(''); expected = await parameters(); assert.deepEqual(expected.output_config, { format });
|
||||
await save('opus', expected); await edit('opus'); assert.deepEqual(await parameters(), expected);
|
||||
await field('参数配置档').selectOption('anthropic'); assert.deepEqual(await parameters(), expected);
|
||||
await field('推理模式').selectOption('enabled'); expected = await parameters(); assert.deepEqual(expected.thinking, { type: 'enabled', display: 'summarized', budget_tokens: 1024 });
|
||||
assert.equal((await options('推理模式')).find(row => row.value === 'default').disabled, true);
|
||||
await save('opus', expected); wire = await probe('opus'); assert.deepEqual(wire.thinking, expected.thinking);
|
||||
await edit('opus'); await field('参数配置档').selectOption('auto'); assert.deepEqual(await parameters(), expected);
|
||||
await expect(form()).toContainText('原值仍完整保留');
|
||||
await shot('opus-custom-preserved-1280'); await save('opus', expected);
|
||||
mark('Opus official choices, sibling fields, valid default reset, explicit compatibility override and save/reopen/local wire');
|
||||
|
||||
await edit('fable'); modes = await options('推理模式');
|
||||
for (const value of ['disabled', 'enabled', 'between_tools']) assert.equal(modes.find(row => row.value === value).disabled, true);
|
||||
await field('推理强度').selectOption('xhigh'); expected = await parameters(); assert.deepEqual(expected.output_config.format, format);
|
||||
await save('fable', expected); wire = await probe('fable'); assert.deepEqual(wire.output_config, expected.output_config);
|
||||
mark('Fable only offers adaptive mode and preserves format with xhigh');
|
||||
|
||||
await edit('sonnet'); await field('推理模式').selectOption('between_tools');
|
||||
assert.equal((await options('推理强度')).find(row => row.value === 'xhigh').disabled, true);
|
||||
await field('推理强度').selectOption('high'); expected = await parameters(); assert.deepEqual(expected.thinking, { type: 'between_tools', display: 'summarized' });
|
||||
await shot('sonnet-between-tools-1280'); await save('sonnet', expected); wire = await probe('sonnet'); assert.deepEqual(wire.thinking, expected.thinking);
|
||||
await edit('sonnet'); await field('推理模式').selectOption('adaptive'); await field('推理强度').selectOption('xhigh');
|
||||
assert.equal((await options('推理模式')).find(row => row.value === 'between_tools').disabled, true);
|
||||
await field('推理强度').selectOption('high'); await field('推理模式').selectOption('between_tools');
|
||||
await resize(390, 844); await shot('sonnet-controls-390');
|
||||
await json().scrollIntoViewIfNeeded(); await shot('sonnet-json-390', '原生参数 JSON');
|
||||
const button = form().getByRole('button', { name: '保存原生参数', exact: true }); await button.scrollIntoViewIfNeeded();
|
||||
const box = await button.boundingBox(); assert.ok(box && box.x >= 0 && box.x + box.width <= 391); await save('sonnet', expected);
|
||||
await page.reload(); await edit('sonnet'); assert.deepEqual(await parameters(), expected);
|
||||
await form().getByRole('button', { name: '取消', exact: true }).click(); await resize(1280);
|
||||
mark('Sonnet between_tools/high and adaptive/xhigh conditions, 390px controls, JSON, save and reload');
|
||||
|
||||
await edit('haiku'); await field('推理模式').selectOption('disabled'); await expect(field('推理强度')).toBeEnabled();
|
||||
assert.equal((await options('推理强度')).find(row => row.value === 'max').disabled, true);
|
||||
await field('推理强度').selectOption('low'); expected = await parameters(); await save('haiku', expected);
|
||||
wire = await probe('haiku'); assert.deepEqual(wire.thinking, expected.thinking); assert.equal(wire.output_config.effort, 'low');
|
||||
mark('Haiku disabled mode retains selectable low/medium/high and independent display/format');
|
||||
|
||||
await edit('responses'); await field('推理强度').selectOption('max'); expected = await parameters(); assert.deepEqual(expected.reasoning, { effort: 'max', summary: 'auto' });
|
||||
await save('responses', expected); wire = await probe('responses'); assert.deepEqual(wire.reasoning, expected.reasoning); assert.equal(wire.max_output_tokens, undefined);
|
||||
await edit('responses'); await field('推理模式').selectOption('default'); expected = await parameters(); assert.deepEqual(expected.reasoning, { summary: 'auto' }); assert.deepEqual(expected.text, { format });
|
||||
await save('responses', expected);
|
||||
mark('Responses effort edit/default preserve reasoning.summary and text.format, with no optional output cap');
|
||||
|
||||
await edit('chat'); expected = await parameters(); await field('参数配置档').selectOption('openai'); assert.deepEqual(await parameters(), expected);
|
||||
await field('推理强度').selectOption('max'); expected = await parameters(); assert.deepEqual(expected.thinking, { type: 'enabled', custom: { untouched: true } });
|
||||
await save('chat', expected); wire = await probe('chat'); assert.deepEqual(wire.stream_options, expected.stream_options); assert.deepEqual(wire.thinking, expected.thinking); assert.equal(wire.max_tokens, undefined);
|
||||
await page.reload(); await edit('chat'); assert.deepEqual(await parameters(), expected); await form().getByRole('button', { name: '取消', exact: true }).click();
|
||||
mark('Profile switch and Chat controls preserve opaque thinking and explicit streaming options through persistence and actual SSE wire');
|
||||
|
||||
await edit('negative'); modes = await options('推理模式'); assert.ok(modes.filter(row => row.value !== 'default').every(row => row.disabled));
|
||||
assert.equal((await options('推理强度')).filter(row => row.value !== '').every(row => row.disabled), true);
|
||||
expected = await parameters(); await expect(form()).toContainText('原值仍完整保留');
|
||||
await shot('explicit-negative-1280'); await save('negative', expected);
|
||||
await edit('unknown'); await expect(form()).toContainText('未取得的型号能力待确认');
|
||||
assert.equal((await options('推理模式')).find(row => row.value === 'default').disabled, true);
|
||||
expected = await parameters(); expected.thinking.type = 'owned-custom-mode'; expected.output_config.effort = 'owned-custom-effort';
|
||||
await json().fill(JSON.stringify(expected, null, 2)); await expect(field('推理模式')).toHaveValue('owned-custom-mode');
|
||||
await expect(field('推理强度')).toHaveValue('owned-custom-effort'); await expect(form()).toContainText('原值仍完整保留');
|
||||
await resize(390, 844); await shot('custom-values-390'); await save('unknown', expected);
|
||||
await page.reload(); await edit('unknown'); assert.deepEqual(await parameters(), expected);
|
||||
mark('Explicit all-negative declarations stay negative, missing metadata stays unconfirmed, custom values stay visible and persisted');
|
||||
|
||||
const state = await host.api('/model-center'); assert.equal(state.attempts.length, requests.length);
|
||||
assert.equal(requests.length, 7); assert.deepEqual(errors, []); assert.deepEqual(externalBlocked, []);
|
||||
result = { success: true, appRoot, actualElectron: desktop, checks, screenshots, errors, externalBlocked, hostUrl: host.url,
|
||||
syntheticRequests: requests.length, realModelRequests: 0, realCredentialsRead: 0, productionWrites: 0, viewportWidths: [1280, 390] };
|
||||
} catch (cause) {
|
||||
if (page) { await page.screenshot({ path: path.join(directory, 'failure.png') }).catch(() => {}); fs.writeFileSync(path.join(directory, 'failure.txt'), await page.locator('body').innerText().catch(() => '')); }
|
||||
result = { success: false, appRoot, actualElectron: desktop, checks, screenshots, errors, externalBlocked, error: cause.stack, syntheticRequests: requests.length, realModelRequests: 0 };
|
||||
} finally {
|
||||
fs.writeFileSync(path.join(directory, 'requests.json'), JSON.stringify(requests, null, 2));
|
||||
if (application) await application.close(); if (browser) await browser.close();
|
||||
if (controller && await controller.health()) await controller.stop();
|
||||
await host?.close?.(); await new Promise(resolve => { model.closeAllConnections(); model.close(resolve); });
|
||||
for (const dispose of disposers.reverse()) await dispose();
|
||||
if (desktop) { fs.writeFileSync(path.join(directory, 'desktop-stdout.txt'), desktopStdout); fs.writeFileSync(path.join(directory, 'desktop-stderr.txt'), desktopStderr); }
|
||||
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
|
||||
}
|
||||
console.log(JSON.stringify({ directory, ...result })); if (!result.success) process.exitCode = 1;
|
||||
@@ -1,7 +1,6 @@
|
||||
import { messagesOutputSetting } from '../shared/contracts/model-capacity.mjs';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
|
||||
import { changeReasoningSetting, modelParameterProfile, reasoningSetting } from '../shared/contracts/model-parameter-profiles.mjs';
|
||||
import { ReasoningSettings } from './ReasoningSettings';
|
||||
import type { CatalogModel } from '../shared/contracts/model-catalog.mjs';
|
||||
|
||||
@@ -24,19 +23,12 @@ export function NativeParameters({ connection, busy, onCancel, onSave, execution
|
||||
}}>
|
||||
<h3>{connection.name} · 推理与原生参数</h3>
|
||||
<p className="mc-help">参数按所选协议原字段发送,并封存在实际请求中。具体模型是否接受这些选项,以服务响应为准;未填写的选项采用上游默认值。</p>
|
||||
<ReasoningSettings connection={connection} parameters={parameters} profile={profile} busy={busy} onChange={updateParameters} onProfile={value => {
|
||||
if (parameters) {
|
||||
const before = { ...connection, parameterProfile: profile }, after = { ...connection, parameterProfile: value };
|
||||
if (modelParameterProfile(before).thinking !== modelParameterProfile(after).thinking) {
|
||||
updateParameters(changeReasoningSetting(after, parameters, 'mode', reasoningSetting(before, parameters).mode));
|
||||
}
|
||||
}
|
||||
setProfile(value);
|
||||
}} />
|
||||
<ReasoningSettings connection={connection} parameters={parameters} profile={profile} busy={busy} onChange={updateParameters} onProfile={setProfile} />
|
||||
<label>输出上限字段<select aria-label="输出上限字段" value={field} disabled={busy} onChange={event => setField(event.target.value)}>{(connection.protocol === 'responses' ? ['max_output_tokens'] : connection.protocol === 'anthropic-messages' ? ['max_tokens'] : ['max_tokens', 'max_completion_tokens']).map(value => <option key={value}>{value}</option>)}</select></label>
|
||||
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? 'Messages 协议必须带 max_tokens;当前 ' + String(messagesOutputSetting(connection).value) + '(' + ({ explicit_native: '显式原生参数', upstream_catalog: '上游目录最大输出', official_model_spec: 'Anthropic 官方同步输出规格', connection_declaration: '连接声明,非已验证最大值' }[messagesOutputSetting(connection).source] ?? '') + ')。可在 JSON 中显式设置;本地不裁剪输出。' : executionMode === 'unrestricted' ? '默认不附加输出上限;可在 JSON 中显式填写上游参数,服务是否接受以原始响应为准。' : '数值沿用当前任务和连接的输出预算。'}消息、工具、接口和凭据由各自设置管理。</p>
|
||||
<label>原生参数 JSON<textarea aria-label="原生参数 JSON" rows={7} maxLength={executionMode === 'unrestricted' ? undefined : 8192} spellCheck={false} value={text} disabled={busy} onChange={event => setText(event.target.value)} /></label>
|
||||
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? '已接入 temperature(0–1)、top_p、top_k、stop_sequences、thinking、output_config.effort。' : connection.protocol === 'responses' ? '已接入 temperature、top_p、parallel_tool_calls、reasoning.effort、text.verbosity。' : '已接入 temperature、top_p、seed、parallel_tool_calls、reasoning_effort、verbosity、DeepSeek thinking。'}推理控件与 JSON 编辑同一份参数,其他字段保存时会给出具体提示。</p>
|
||||
<p className="mc-help">推理控件与 JSON 编辑同一份参数;切换配置档保留原 JSON,可按目标接口自行调整。{executionMode === 'unrestricted' ? '其他原生字段按原值发送,是否接受以上游原始响应为准;消息、工具、传输与凭据由工作台对应设置管理。'
|
||||
: connection.protocol === 'anthropic-messages' ? '当前受限模式仅支持已接入的采样、停止序列、thinking 与 output_config.effort。' : connection.protocol === 'responses' ? '当前受限模式仅支持已接入的采样、并行工具、reasoning.effort 与 text.verbosity。' : '当前受限模式仅支持已接入的采样、并行工具、推理强度、verbosity 与 DeepSeek thinking。'}</p>
|
||||
{error && <p className="mc-card-warning" role="alert">{error}</p>}
|
||||
<div className="mc-actions"><button className="button secondary" type="button" disabled={busy} onClick={onCancel}>取消</button><button className="button primary" disabled={busy} type="submit">保存原生参数</button></div>
|
||||
</form>;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { changeReasoningSetting, modelFeatureRows, modelParameterProfile, parame
|
||||
import type { NativeConnection } from './NativeParameters';
|
||||
|
||||
const effortLabels: Record<string, string> = { minimal: '最低', low: '低', medium: '中', high: '高', xhigh: '很高', max: '最高' };
|
||||
const modeLabels: Record<string, string> = { disabled: '关闭推理', enabled: '开启推理', adaptive: '开启 · 自适应推理', between_tools: '仅工具之间推理' };
|
||||
export function ReasoningSettings({ connection, parameters, profile, busy, onProfile, onChange }: {
|
||||
connection: NativeConnection; parameters: Record<string, unknown> | null; profile: string; busy: boolean;
|
||||
onProfile: (value: string) => void; onChange: (value: Record<string, unknown>) => void;
|
||||
@@ -10,6 +11,12 @@ export function ReasoningSettings({ connection, parameters, profile, busy, onPro
|
||||
const setting = reasoningSetting(configured, parameters ?? {}), disabled = busy || !parameters;
|
||||
const change = (field: string, value: string | number) => { if (parameters) onChange(changeReasoningSetting(configured, parameters, field, value)); };
|
||||
const efforts = [...new Set([...resolved.efforts, ...(setting.effort ? [setting.effort] : [])])];
|
||||
const modes = [...new Set([...(connection.protocol === 'anthropic-messages' ? ['disabled', 'enabled', 'adaptive', 'between_tools'] : ['disabled', 'enabled']), ...(setting.mode !== 'default' ? [setting.mode] : [])])];
|
||||
const modeAllowed = (mode: string) => resolved.modes.includes(mode) && (!resolved.modeEfforts[mode]
|
||||
|| resolved.modeEfforts[mode].includes(setting.effort || resolved.defaultEffort || ''));
|
||||
const effortAllowed = (effort: string) => resolved.efforts.includes(effort) && (!resolved.modeEfforts[setting.mode]
|
||||
|| resolved.modeEfforts[setting.mode].includes(effort));
|
||||
const customSetting = setting.mode !== 'default' && !modeAllowed(setting.mode) || !!setting.effort && !effortAllowed(setting.effort);
|
||||
return <fieldset className="mc-reasoning">
|
||||
<legend>推理设置</legend>
|
||||
<div className="mc-form-grid">
|
||||
@@ -17,21 +24,27 @@ export function ReasoningSettings({ connection, parameters, profile, busy, onPro
|
||||
{parameterProfiles(connection.protocol).map(value => <option key={value.id} value={value.id}>{value.label}</option>)}
|
||||
</select></label>
|
||||
<label>推理模式<select aria-label="推理模式" value={setting.mode} disabled={disabled} onChange={event => change('mode', event.target.value)}>
|
||||
<option value="default">跟随模型默认</option><option value="disabled" disabled={!resolved.modes.includes('disabled')}>关闭推理</option>
|
||||
<option value="enabled" disabled={!resolved.modes.includes('enabled')}>{connection.protocol === 'anthropic-messages' ? '开启 · 指定推理预算' : '开启推理'}</option>
|
||||
{connection.protocol === 'anthropic-messages' && <option value="adaptive" disabled={!resolved.modes.includes('adaptive')}>开启 · 自适应推理</option>}
|
||||
<option value="default" disabled={!setting.canResetMode}>{resolved.thinking && setting.thinkingSiblings && setting.canResetMode ? `恢复型号默认模式(${resolved.defaultMode})` : '跟随模型默认'}</option>{modes.map(value => <option key={value} value={value} disabled={!modeAllowed(value)}>
|
||||
{value === 'enabled' && connection.protocol === 'anthropic-messages' ? '开启 · 指定推理预算' : modeLabels[value] ?? `已配置 · ${value}`}
|
||||
{!resolved.modes.includes(value) ? '(未声明支持)' : !modeAllowed(value) ? '(需 high 或更低强度)' : ''}
|
||||
</option>)}
|
||||
</select></label>
|
||||
<label>推理强度<select aria-label="推理强度" value={setting.effort} disabled={disabled || setting.mode === 'disabled' || !resolved.efforts.length && !setting.effort} onChange={event => change('effort', event.target.value)}>
|
||||
<option value="">跟随模型默认</option>{efforts.map(value => <option key={value} value={value}>{effortLabels[value] ?? value}({value})</option>)}
|
||||
<label>推理强度<select aria-label="推理强度" value={setting.effort} disabled={disabled || !resolved.thinking && setting.mode === 'disabled' || !resolved.efforts.length && !setting.effort} onChange={event => change('effort', event.target.value)}>
|
||||
<option value="">跟随模型默认</option>{efforts.map(value => <option key={value} value={value} disabled={!effortAllowed(value)}>{effortLabels[value] ?? value}({value}){!effortAllowed(value) ? ' · 当前组合不支持' : ''}</option>)}
|
||||
</select></label>
|
||||
{connection.protocol === 'anthropic-messages' && setting.mode === 'enabled' && <label>推理预算 tokens<input aria-label="推理预算 tokens" type="number" min={1024} step={1} value={setting.budget} disabled={disabled} onChange={event => change('budget', Number(event.target.value))} /></label>}
|
||||
</div>
|
||||
<p className="mc-help">当前格式:{resolved.label}。{resolved.source}。自定义代理可按实际兼容格式选择配置档,保存后用于新任务。</p>
|
||||
<p className="mc-help">强度越高通常需要更多时间和输出 tokens;推理与最终答复共用原输出预算。具体型号支持的开关和档位以上游为准,设置不会自动提高预算。</p>
|
||||
{connection.upstreamModel && <p className="mc-help">已同步该型号的上游目录声明;提供了档位或模式时,按声明限制可选项。目录没有提供的能力仍待确认。</p>}
|
||||
{connection.protocol === 'anthropic-messages' ? <p className="mc-help">指定预算至少 1024 tokens,且须小于本次任务实际输出上限。指定预算的能力检测使用当前输出上限,会消耗模型额度;自适应模式与强度需服务支持。</p>
|
||||
<p className="mc-help">当前格式:{resolved.label}。{resolved.source}。自定义代理可选择兼容配置档;原生 JSON 可保留自定义值,实际是否接受以上游响应为准。</p>
|
||||
{resolved.officialSource && <p className="mc-help"><a href={resolved.officialSource.url} target="_blank" rel="noreferrer">Anthropic 官方推理说明</a> · 核对于 {resolved.officialSource.checkedAt};型号默认强度 {resolved.defaultEffort}。目录声明、官方规格与真实线路支持分别记录。</p>}
|
||||
<p className="mc-help">更高强度通常需要更多时间和输出 tokens。本地默认不限,实际用量和容量以上游为准。控件只修改对应字段;模式恢复默认保留独立强度和其他原生选项。</p>
|
||||
{resolved.thinking && setting.thinkingSiblings && <p className="mc-help">保留 display 等 thinking 选项时仍需 type。{setting.canResetMode ? `恢复默认使用该型号的 ${resolved.defaultMode} 模式;` : '当前没有可确认的默认模式,请选具体模式;'}如需整个 thinking 恢复默认,可在 JSON 中明确删除该对象。</p>}
|
||||
{Object.keys(resolved.modeEfforts).length > 0 && <p className="mc-help">该型号的{resolved.modeEfforts.between_tools ? '“仅工具之间推理”' : '“关闭推理”'}仅适用于 low / medium / high,不能与 xhigh / max 同用。请先调整强度或切换模式。</p>}
|
||||
{customSetting && <p className="mc-card-warning">JSON 中的已配置值或组合不在当前已知支持范围,原值仍完整保留。可改选已知可用选项,或保留自定义参数由上游处理。</p>}
|
||||
{connection.protocol === 'anthropic-messages' ? resolved.modes.includes('enabled') || setting.mode === 'enabled'
|
||||
? <p className="mc-help">旧式指定预算只适用于支持 thinking.enabled 的型号,至少 1024 tokens 且需小于上游 max_tokens;新型号优先采用其官方模式。切换到其他模式会移除旧式 budget_tokens,保留 display 等字段。</p>
|
||||
: <p className="mc-help">该型号不使用旧式指定推理预算;按可用模式和强度发送,未填写的字段采用上游默认值。</p>
|
||||
: resolved.id === 'deepseek' && connection.protocol === 'chat-completions' ? <p className="mc-help">DeepSeek 使用 thinking 开关与 low / high / max 强度;工具往返携带对应的原生推理状态。</p>
|
||||
: <p className="mc-help">关闭推理发送 none,仅适用于接受该值的型号;GPT-6.1 Sol 不支持 none / minimal。可选择受支持的强度或保留默认。</p>}
|
||||
: <p className="mc-help">关闭推理通过该协议的 effort: none 表达,仅适用于接受该值的型号;具体支持范围以上游为准。</p>}
|
||||
{!parameters && <p className="mc-card-warning">请先修正下方 JSON,推理控件会同步恢复。</p>}
|
||||
<details className="mc-feature-scope"><summary>查看接口能力与接入范围</summary>
|
||||
<p>品牌、型号与模型列表用于匹配配置,能力声明和单项检测结果按原来源保留。型号列表通常不包含完整功能元数据。</p>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export interface CatalogModel {
|
||||
id: string; name: string; owner: string; lifecycle: string | null; contextLimit: number | null; maxOutputTokens: number | null;
|
||||
capabilityDeclarations: Record<string, string>; features: Record<string, string>; efforts: string[]; modes: string[]; parameters: string[]; metadataSource: string;
|
||||
effortSupport?: Record<string, string>; modeSupport?: Record<string, string>;
|
||||
}
|
||||
export interface CatalogPreview {
|
||||
id: string; entries: CatalogModel[]; fetchedAt: string; expiresAt: string; complete: boolean; warning: string;
|
||||
|
||||
@@ -34,14 +34,16 @@ export function catalogModel(item, config = {}) {
|
||||
if (Array.isArray(output) && output.includes('text') && declarations.text === 'unknown') declarations.text = 'supported';
|
||||
const parameters = Array.isArray(item.supported_parameters) ? [...new Set(item.supported_parameters.filter(value => typeof value === 'string' && (unrestricted(config) || value.length <= 80)))].slice(0, ceiling(config, 80)) : [];
|
||||
if (declarations.tools === 'unknown' && parameters.includes('tools')) declarations.tools = 'supported';
|
||||
const efforts = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].filter(value => supported(caps.effort?.[value]) === 'supported');
|
||||
const modes = ['disabled', 'enabled', 'adaptive'].filter(value => supported(caps.thinking?.types?.[value]) === 'supported');
|
||||
const effortSupport = Object.fromEntries(['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].map(value => [value, supported(caps.effort?.[value])]));
|
||||
const modeSupport = Object.fromEntries(['disabled', 'enabled', 'adaptive', 'between_tools'].map(value => [value, supported(caps.thinking?.types?.[value])]));
|
||||
const efforts = Object.keys(effortSupport).filter(value => effortSupport[value] === 'supported');
|
||||
const modes = Object.keys(modeSupport).filter(value => modeSupport[value] === 'supported');
|
||||
const features = Object.fromEntries(['thinking', 'effort', 'pdf_input', 'structured_outputs', 'server_tools', 'code_execution', 'batch', 'citations', 'context_management'].map(key => [key, supported(caps[key])]));
|
||||
return { id, name: field(item.display_name ?? item.displayName ?? item.name ?? id), owner: field(item.owned_by ?? item.provider, 100),
|
||||
lifecycle: ['active', 'deprecated', 'retired'].includes(item.lifecycle) ? item.lifecycle : null,
|
||||
contextLimit: positive(item.context_length ?? item.max_input_tokens ?? item.context_window ?? item.inputTokenLimit),
|
||||
maxOutputTokens: positive(item.max_output_tokens ?? item.max_tokens ?? item.top_provider?.max_completion_tokens ?? item.outputTokenLimit),
|
||||
capabilityDeclarations: declarations, features, efforts, modes, parameters,
|
||||
capabilityDeclarations: declarations, features, efforts, modes, effortSupport, modeSupport, parameters,
|
||||
metadataSource: 'upstream-model-list' };
|
||||
}
|
||||
|
||||
|
||||
@@ -7,8 +7,10 @@ export const reasoningEfforts: string[];
|
||||
export const messagesEfforts: string[];
|
||||
export function parameterProfiles(protocol: string): { id: string; label: string }[];
|
||||
export function parameterProfileSettings(protocol: string, value?: string): string;
|
||||
export function modelParameterProfile(connection: ParameterConnection): { id: string; label: string; source: string; efforts: string[]; thinking: boolean; modes: string[] };
|
||||
export function modelParameterProfile(connection: ParameterConnection): { id: string; label: string; source: string; sourceKind: string;
|
||||
officialSource: { url: string; effortUrl: string; checkedAt: string } | null; efforts: string[]; thinking: boolean; modes: string[];
|
||||
modeEfforts: Record<string, readonly string[]>; defaultMode: string | null; defaultEffort: string | null };
|
||||
export function assertModelParameterSupport(connection: ParameterConnection, parameters: Record<string, unknown>): void;
|
||||
export function reasoningSetting(connection: ParameterConnection, parameters: Record<string, unknown>): { mode: string; effort: string; budget: number };
|
||||
export function reasoningSetting(connection: ParameterConnection, parameters: Record<string, unknown>): { mode: string; effort: string; budget: number; canResetMode: boolean; thinkingSiblings: boolean };
|
||||
export function changeReasoningSetting(connection: ParameterConnection, parameters: Record<string, unknown>, field: string, value: string | number): Record<string, unknown>;
|
||||
export function modelFeatureRows(connection: ParameterConnection): { name: string; upstream: string; local: string }[];
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { officialModelParameters } from './official-model-parameters.mjs';
|
||||
|
||||
export const reasoningEfforts = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
||||
export const messagesEfforts = ['low', 'medium', 'high', 'xhigh', 'max'];
|
||||
const labels = { auto: '自动匹配', openai: 'OpenAI 兼容', anthropic: 'Claude Messages 兼容', deepseek: 'DeepSeek 兼容' };
|
||||
@@ -14,55 +16,86 @@ export function parameterProfileSettings(protocol, value = 'auto') {
|
||||
|
||||
// A profile describes the adapter's fields. It is not evidence that a vendor,
|
||||
// proxy or particular model supports every field in that protocol.
|
||||
function declaredChoices(metadata, field, supportField, feature, fallback, official) {
|
||||
if (metadata?.features?.[feature] === 'unsupported') return [];
|
||||
const values = metadata?.[field] ?? [], support = metadata?.[supportField];
|
||||
if (support && Object.values(support).some(value => value !== 'unknown')) {
|
||||
return [...new Set([...fallback, ...values, ...Object.keys(support)])].filter(value => support[value] === 'supported'
|
||||
|| support[value] !== 'unsupported' && (values.includes(value) || official && fallback.includes(value)));
|
||||
}
|
||||
return values.length ? values : fallback;
|
||||
}
|
||||
|
||||
export function modelParameterProfile(connection) {
|
||||
const protocol = connection.protocol ?? 'chat-completions';
|
||||
const selected = parameterProfileSettings(protocol, connection.parameterProfile);
|
||||
const official = selected === 'auto' && protocol === 'anthropic-messages' ? officialModelParameters(connection.model) : null;
|
||||
const deepseek = connection.brand === 'DeepSeek' || /^deepseek(?:-|$)/i.test(connection.model ?? '')
|
||||
|| /^https:\/\/api\.deepseek\.com(?:\/|$)/i.test(connection.baseUrl ?? '') || !!connection.nativeParameters?.thinking && protocol === 'chat-completions';
|
||||
const id = selected !== 'auto' ? selected : deepseek ? 'deepseek' : protocol === 'anthropic-messages' ? 'anthropic' : 'openai';
|
||||
const metadata = connection.upstreamModel;
|
||||
const id = selected !== 'auto' ? selected : official ? 'anthropic' : deepseek ? 'deepseek' : protocol === 'anthropic-messages' ? 'anthropic' : 'openai';
|
||||
const metadata = !connection.model || connection.upstreamModel?.id === connection.model ? connection.upstreamModel : null;
|
||||
const choices = id === 'deepseek' ? ['low', 'high', 'max'] : protocol === 'anthropic-messages' ? messagesEfforts : reasoningEfforts.filter(value => value !== 'none');
|
||||
return { id, label: labels[id], source: selected === 'auto' ? '按品牌、型号与协议匹配,可手动更改' : '用户选择的兼容格式',
|
||||
efforts: metadata?.features?.effort === 'unsupported' ? [] : metadata?.efforts?.length ? choices.filter(value => metadata.efforts.includes(value)) : choices,
|
||||
modes: metadata?.features?.thinking === 'unsupported' ? [] : metadata?.modes?.length ? metadata.modes : ['disabled', 'enabled', ...(protocol === 'anthropic-messages' ? ['adaptive'] : [])],
|
||||
const modes = official?.modes ?? ['disabled', 'enabled', ...(protocol === 'anthropic-messages' ? ['adaptive', 'between_tools'] : [])];
|
||||
return { id, label: labels[id], source: metadata ? '优先采用相符型号的上游目录声明,缺失项再匹配官方规格或兼容格式'
|
||||
: official ? '按 Anthropic 官方精确型号规格匹配' : selected === 'auto' ? '按品牌、型号与协议匹配;未取得的型号能力待确认' : '用户选择的兼容格式,不套用官方型号后备选项',
|
||||
sourceKind: metadata ? 'upstream_model_list' : official ? 'official_model_spec' : 'compatibility_profile',
|
||||
officialSource: official ? { url: official.sourceUrl, effortUrl: official.effortSourceUrl, checkedAt: official.checkedAt } : null,
|
||||
efforts: declaredChoices(metadata, 'efforts', 'effortSupport', 'effort', official?.efforts ?? choices, !!official),
|
||||
modes: declaredChoices(metadata, 'modes', 'modeSupport', 'thinking', modes, !!official),
|
||||
modeEfforts: official?.modeEfforts ?? {}, defaultMode: official?.defaultMode ?? null, defaultEffort: official?.defaultEffort ?? null,
|
||||
thinking: protocol === 'anthropic-messages' || id === 'deepseek' && protocol === 'chat-completions' };
|
||||
}
|
||||
|
||||
export function assertModelParameterSupport(connection, parameters) {
|
||||
const metadata = connection.upstreamModel;
|
||||
const metadata = !connection.model || connection.upstreamModel?.id === connection.model ? connection.upstreamModel : null;
|
||||
if (!metadata) return;
|
||||
const effort = parameters.reasoning_effort ?? parameters.reasoning?.effort ?? parameters.output_config?.effort;
|
||||
const mode = parameters.thinking?.type;
|
||||
if (effort && (metadata.features?.effort === 'unsupported' || effort !== 'none' && metadata.efforts?.length && !metadata.efforts.includes(effort)))
|
||||
if (effort && (metadata.features?.effort === 'unsupported' || metadata.effortSupport?.[effort] === 'unsupported' || effort !== 'none' && metadata.efforts?.length && !metadata.efforts.includes(effort)))
|
||||
throw Object.assign(new Error('上游目录声明该型号不支持所选推理强度,请选择支持的档位或保留默认。'), { status: 400 });
|
||||
if (mode && (metadata.features?.thinking === 'unsupported' || metadata.modes?.length && !metadata.modes.includes(mode)))
|
||||
if (mode && (metadata.features?.thinking === 'unsupported' || metadata.modeSupport?.[mode] === 'unsupported' || metadata.modes?.length && !metadata.modes.includes(mode)))
|
||||
throw Object.assign(new Error('上游目录声明该型号不支持所选推理模式,请选择支持的模式或保留默认。'), { status: 400 });
|
||||
}
|
||||
|
||||
export function reasoningSetting(connection, parameters) {
|
||||
const profile = modelParameterProfile(connection), protocol = connection.protocol;
|
||||
const effort = protocol === 'anthropic-messages' ? parameters.output_config?.effort : protocol === 'responses' ? parameters.reasoning?.effort : parameters.reasoning_effort;
|
||||
const thinkingSiblings = parameters.thinking && Object.keys(parameters.thinking).some(key => !['type', 'budget_tokens'].includes(key));
|
||||
return { mode: profile.thinking ? parameters.thinking?.type ?? 'default' : effort === 'none' ? 'disabled' : effort ? 'enabled' : 'default',
|
||||
effort: effort === 'none' ? '' : effort ?? '', budget: parameters.thinking?.budget_tokens ?? 1024 };
|
||||
effort: effort === 'none' ? '' : effort ?? '', budget: parameters.thinking?.budget_tokens ?? 1024,
|
||||
canResetMode: !profile.thinking || !thinkingSiblings || !!profile.defaultMode && profile.modes.includes(profile.defaultMode), thinkingSiblings: !!thinkingSiblings };
|
||||
}
|
||||
|
||||
export function changeReasoningSetting(connection, parameters, field, value) {
|
||||
const next = structuredClone(parameters), profile = modelParameterProfile(connection), protocol = connection.protocol;
|
||||
const effortField = protocol === 'anthropic-messages' ? 'output_config' : protocol === 'responses' ? 'reasoning' : 'reasoning_effort';
|
||||
const editObject = (key, updates, remove = []) => {
|
||||
const original = next[key], updated = { ...(original && typeof original === 'object' && !Array.isArray(original) ? original : {}), ...updates };
|
||||
for (const name of remove) delete updated[name];
|
||||
if (Object.keys(updated).length) next[key] = updated; else delete next[key];
|
||||
};
|
||||
const setEffort = effort => {
|
||||
if (!effort) delete next[effortField];
|
||||
else next[effortField] = effortField === 'reasoning_effort' ? effort : { effort };
|
||||
if (effortField !== 'reasoning_effort') editObject(effortField, effort ? { effort } : {}, effort ? [] : ['effort']);
|
||||
else if (effort) next[effortField] = effort; else delete next[effortField];
|
||||
};
|
||||
if (field === 'effort') setEffort(value);
|
||||
else if (field === 'budget') next.thinking = { type: 'enabled', budget_tokens: value };
|
||||
else if (field === 'budget') editObject('thinking', { type: 'enabled', budget_tokens: value });
|
||||
else if (field === 'mode') {
|
||||
if (value === 'default') { delete next.thinking; setEffort(''); }
|
||||
if (value === 'default') {
|
||||
if (!profile.thinking) setEffort('');
|
||||
else {
|
||||
const setting = reasoningSetting(connection, parameters);
|
||||
// A thinking object with display/other options still requires type.
|
||||
// Use an exact known default, or leave the configuration intact.
|
||||
if (setting.canResetMode) editObject('thinking', setting.thinkingSiblings ? { type: profile.defaultMode } : {},
|
||||
setting.thinkingSiblings ? ['budget_tokens'] : ['type', 'budget_tokens']);
|
||||
}
|
||||
}
|
||||
else if (profile.thinking) {
|
||||
next.thinking = value === 'enabled' && protocol === 'anthropic-messages'
|
||||
? { type: value, budget_tokens: parameters.thinking?.budget_tokens ?? 1024 } : { type: value };
|
||||
if (value === 'disabled') setEffort('');
|
||||
editObject('thinking', value === 'enabled' && protocol === 'anthropic-messages'
|
||||
? { type: value, budget_tokens: parameters.thinking?.budget_tokens ?? 1024 } : { type: value },
|
||||
value === 'enabled' && protocol === 'anthropic-messages' ? [] : ['budget_tokens']);
|
||||
} else {
|
||||
delete next.thinking;
|
||||
setEffort(value === 'disabled' ? 'none' : reasoningSetting(connection, parameters).effort || (profile.efforts.includes('medium') ? 'medium' : profile.efforts[0] ?? ''));
|
||||
}
|
||||
}
|
||||
@@ -76,9 +109,9 @@ export function modelFeatureRows(connection) {
|
||||
{ name: '文本 / 工具调用', upstream: declared('text') + ' / ' + declared('tools'), local: '已接入,可单独检测' },
|
||||
{ name: '流式输出', upstream: declared('streaming'), local: '已接入,按连接开关发送' },
|
||||
{ name: '图像输入', upstream: declared('vision'), local: '已接入 PNG,可单独检测' },
|
||||
{ name: '推理模式 / 强度', upstream: connection.upstreamModel ? `${states[connection.upstreamModel.features?.thinking ?? 'unknown']} / ${connection.upstreamModel.efforts?.join('、') || states[connection.upstreamModel.features?.effort ?? 'unknown']}` : '依型号与兼容服务支持范围', local: '按配置档发送,受原输出预算约束' },
|
||||
{ name: '推理模式 / 强度', upstream: modelParameterProfile(connection).source, local: '按原生字段发送;本地默认不限,协议条件以上游为准' },
|
||||
{ name: '语音 / 视频 / 服务端工具', upstream: '需供应商提供相应协议', local: '尚未接入' },
|
||||
{ name: '结构化输出约束', upstream: states[connection.upstreamModel?.features?.structured_outputs ?? 'unknown'], local: '尚未接入,参数保存时明确拒绝' },
|
||||
{ name: '结构化输出约束', upstream: states[connection.upstreamModel?.features?.structured_outputs ?? 'unknown'], local: '开放模式可透传约束参数;完整结果校验流程待接入' },
|
||||
...(connection.upstreamModel ? [{ name: 'PDF / 服务端工具 / 批处理', upstream: ['pdf_input', 'server_tools', 'batch'].map(key => states[connection.upstreamModel.features?.[key] ?? 'unknown']).join(' / '), local: '目录声明已同步,执行能力尚未接入' }] : []),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ function wireBody(config, messages, tools) {
|
||||
});
|
||||
if (protocol === 'anthropic-messages') return messagesBody(config, messages, tools, native);
|
||||
if (protocol === 'chat-completions') return { model: config.model, messages: cleanMessages, tools, tool_choice: 'auto', ...(!isPassthrough(config) ? { [native.outputTokenField]: config.maxOutputTokens } : {}), stream, ...native.nativeParameters,
|
||||
...(stream ? { stream_options: { include_usage: true } } : {}) };
|
||||
...(stream && !Object.hasOwn(native.nativeParameters, 'stream_options') ? { stream_options: { include_usage: true } } : {}) };
|
||||
const input = messages.flatMap(message => {
|
||||
if (message.role === 'tool') return [{ type: 'function_call_output', call_id: message.tool_call_id, output: message.content }];
|
||||
if (message.role === 'assistant') {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Exact Messages IDs checked against Anthropic's thinking and effort articles
|
||||
// on 2026-11-06. These are published defaults, not proof of proxy support.
|
||||
// Broader provider/version discovery belongs to the capability registry.
|
||||
const sourceUrl = 'https://platform.claude.com/docs/en/build-with-claude/thinking';
|
||||
const effortSourceUrl = 'https://platform.claude.com/docs/en/build-with-claude/effort';
|
||||
const efforts = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
|
||||
const lowerEfforts = Object.freeze(['low', 'medium', 'high']);
|
||||
const entries = [
|
||||
['claude-fable-5-1', ['adaptive'], 'high', {}],
|
||||
['claude-opus-5-5', ['adaptive'], 'medium', {}],
|
||||
['claude-sonnet-5-5', ['adaptive', 'between_tools'], 'high', { between_tools: lowerEfforts }],
|
||||
['claude-haiku-5-5', ['disabled', 'adaptive'], 'medium', { disabled: lowerEfforts }],
|
||||
];
|
||||
const models = Object.freeze(Object.fromEntries(entries.map(([model, modes, defaultEffort, modeEfforts]) => [model,
|
||||
Object.freeze({ model, modes: Object.freeze(modes), efforts, defaultMode: 'adaptive', defaultEffort, modeEfforts: Object.freeze(modeEfforts),
|
||||
sourceUrl, effortSourceUrl, checkedAt: '2026-11-06', source: 'official_model_spec' })])));
|
||||
|
||||
export function officialModelParameters(model) {
|
||||
return typeof model === 'string' && Object.hasOwn(models, model) ? models[model] : null;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import http from 'node:http';
|
||||
import { changeReasoningSetting, modelParameterProfile, assertModelParameterSupport, reasoningSetting } from '../src/shared/contracts/model-parameter-profiles.mjs';
|
||||
import { officialModelParameters } from '../src/shared/contracts/official-model-parameters.mjs';
|
||||
import { catalogModel } from '../src/shared/contracts/model-catalog.mjs';
|
||||
import { completionBody, actualRequest } from '../src/shared/contracts/model-request.mjs';
|
||||
import { nativeParameterSettings } from '../src/shared/contracts/native-parameters.mjs';
|
||||
import { Provider } from '../src/server/provider.mjs';
|
||||
|
||||
const open = { executionMode: 'unrestricted', capacityMode: 'passthrough', mode: 'compatible', baseUrl: 'http://127.0.0.1:1/v1' };
|
||||
const messages = { ...open, protocol: 'anthropic-messages', model: 'claude-opus-5-5' };
|
||||
const responses = { ...open, protocol: 'responses', model: 'owned-responses' };
|
||||
const chat = { ...open, protocol: 'chat-completions', model: 'owned-chat' };
|
||||
const format = { type: 'json_schema', schema: { type: 'object', properties: { result: { type: 'string' } } } };
|
||||
|
||||
test('effort edits and reset preserve summary, format and unrelated nested native fields', () => {
|
||||
for (const [connection, key, siblings] of [
|
||||
[responses, 'reasoning', { summary: 'auto', opaque_option: { audit: ['unchanged'] } }],
|
||||
[messages, 'output_config', { format, opaque_option: { audit: ['unchanged'] } }],
|
||||
]) {
|
||||
const original = { [key]: { effort: 'high', ...structuredClone(siblings) }, metadata: { owner: 'owned-test' } };
|
||||
const snapshot = structuredClone(original);
|
||||
const changed = changeReasoningSetting(connection, original, 'effort', 'max');
|
||||
assert.deepEqual(changed, { ...snapshot, [key]: { effort: 'max', ...siblings } });
|
||||
assert.deepEqual(changeReasoningSetting(connection, changed, 'effort', ''), { ...snapshot, [key]: siblings });
|
||||
assert.deepEqual(original, snapshot);
|
||||
assert.notEqual(changed[key].opaque_option, original[key].opaque_option);
|
||||
assert.deepEqual(changeReasoningSetting(connection, { [key]: { effort: 'high' } }, 'effort', ''), {});
|
||||
}
|
||||
});
|
||||
|
||||
test('Messages mode/default/budget controls keep independent effort and thinking display', () => {
|
||||
const connection = { ...messages, parameterProfile: 'anthropic' };
|
||||
const original = { output_config: { effort: 'high', format }, thinking: { type: 'enabled', budget_tokens: 4096, display: 'summarized', custom: { stable: true } } };
|
||||
const snapshot = structuredClone(original);
|
||||
for (const mode of ['adaptive', 'disabled', 'between_tools']) {
|
||||
const changed = changeReasoningSetting(connection, original, 'mode', mode);
|
||||
assert.deepEqual(changed, { output_config: snapshot.output_config, thinking: { type: mode, display: 'summarized', custom: { stable: true } } });
|
||||
}
|
||||
const defaultMode = changeReasoningSetting(connection, original, 'mode', 'default');
|
||||
assert.deepEqual(defaultMode, snapshot, 'Unknown default must not strip required type or unrelated fields');
|
||||
assert.equal(reasoningSetting(connection, original).canResetMode, false);
|
||||
assert.deepEqual(changeReasoningSetting(messages, original, 'mode', 'default'), {
|
||||
output_config: snapshot.output_config, thinking: { type: 'adaptive', display: 'summarized', custom: { stable: true } },
|
||||
});
|
||||
const contradicted = { ...messages, upstreamModel: catalogModel({ id: messages.model, capabilities: { thinking: { types: { adaptive: false } } } }) };
|
||||
assert.equal(reasoningSetting(contradicted, original).canResetMode, false);
|
||||
assert.deepEqual(changeReasoningSetting(contradicted, original, 'mode', 'default'), snapshot);
|
||||
assert.deepEqual(changeReasoningSetting(connection, original, 'budget', 8192), { ...snapshot, thinking: { ...snapshot.thinking, budget_tokens: 8192 } });
|
||||
assert.deepEqual(changeReasoningSetting(connection, { thinking: { type: 'adaptive', display: 'summarized' } }, 'mode', 'enabled'), {
|
||||
thinking: { type: 'enabled', display: 'summarized', budget_tokens: 1024 },
|
||||
});
|
||||
assert.deepEqual(changeReasoningSetting(connection, { thinking: { type: 'enabled', budget_tokens: 1024 } }, 'mode', 'default'), {});
|
||||
assert.deepEqual(original, snapshot);
|
||||
});
|
||||
|
||||
test('Responses on/off/default and dialect changes retain sibling fields', () => {
|
||||
const original = { reasoning: { effort: 'high', summary: 'auto' }, thinking: { type: 'enabled', display: 'custom-visible' } };
|
||||
assert.deepEqual(changeReasoningSetting(responses, original, 'mode', 'disabled'), {
|
||||
reasoning: { effort: 'none', summary: 'auto' }, thinking: original.thinking,
|
||||
});
|
||||
assert.deepEqual(changeReasoningSetting(responses, original, 'mode', 'default'), { reasoning: { summary: 'auto' }, thinking: original.thinking });
|
||||
assert.deepEqual(changeReasoningSetting(responses, { reasoning: { summary: 'auto' } }, 'mode', 'enabled'), { reasoning: { summary: 'auto', effort: 'medium' } });
|
||||
});
|
||||
|
||||
for (const [model, modes, defaultEffort, conditionalMode] of [
|
||||
['claude-fable-5-1', ['adaptive'], 'high', null],
|
||||
['claude-opus-5-5', ['adaptive'], 'medium', null],
|
||||
['claude-sonnet-5-5', ['adaptive', 'between_tools'], 'high', 'between_tools'],
|
||||
['claude-haiku-5-5', ['disabled', 'adaptive'], 'medium', 'disabled'],
|
||||
]) test('exact official Messages profile for ' + model, () => {
|
||||
const profile = modelParameterProfile({ ...messages, model });
|
||||
assert.deepEqual(profile.modes, modes);
|
||||
assert.deepEqual(profile.efforts, ['low', 'medium', 'high', 'xhigh', 'max']);
|
||||
assert.equal(profile.defaultEffort, defaultEffort);
|
||||
assert.equal(profile.sourceKind, 'official_model_spec');
|
||||
assert.equal(profile.officialSource.url, 'https://platform.claude.com/docs/en/build-with-claude/thinking');
|
||||
assert.deepEqual(profile.modeEfforts, conditionalMode ? { [conditionalMode]: ['low', 'medium', 'high'] } : {});
|
||||
assert.equal(profile.modes.includes('enabled'), false);
|
||||
assert.equal(Object.isFrozen(officialModelParameters(model).modes), true);
|
||||
});
|
||||
|
||||
test('exact-ID fallback does not guess aliases or other protocols; explicit compatibility and native values remain available', () => {
|
||||
assert.equal(officialModelParameters('claude-opus-5-5-custom'), null);
|
||||
assert.equal(officialModelParameters('claude-opus-5-5-20261106'), null);
|
||||
assert.equal(modelParameterProfile({ ...chat, model: messages.model }).sourceKind, 'compatibility_profile');
|
||||
const manual = { ...messages, parameterProfile: 'anthropic' };
|
||||
assert.equal(modelParameterProfile(manual).modes.includes('enabled'), true);
|
||||
assert.equal(modelParameterProfile(manual).officialSource, null);
|
||||
const native = { thinking: { type: 'enabled', budget_tokens: 1024, display: 'summarized' }, output_config: { effort: 'max', format } };
|
||||
assert.deepEqual(nativeParameterSettings(messages.protocol, native, undefined, 'auto', open).nativeParameters, native);
|
||||
const body = completionBody({ ...messages, nativeParameters: native }, [{ role: 'user', content: 'owned' }], []);
|
||||
assert.deepEqual(body.thinking, native.thinking);
|
||||
assert.deepEqual(body.output_config, native.output_config);
|
||||
assert.equal(body.max_tokens, 128000);
|
||||
});
|
||||
|
||||
test('catalog preserves between_tools and explicit negative modes/efforts instead of treating them as absent', () => {
|
||||
const item = { id: 'owned-model', capabilities: { thinking: { supported: true, types: {
|
||||
adaptive: { supported: false }, enabled: false, disabled: false, between_tools: { supported: true },
|
||||
} }, effort: { supported: true, low: false, medium: false, high: false, xhigh: false, max: false } } };
|
||||
const upstreamModel = catalogModel(item), connection = { ...messages, model: item.id, upstreamModel };
|
||||
assert.deepEqual(upstreamModel.modes, ['between_tools']);
|
||||
assert.equal(upstreamModel.modeSupport.adaptive, 'unsupported');
|
||||
assert.equal(upstreamModel.effortSupport.high, 'unsupported');
|
||||
assert.deepEqual(modelParameterProfile(connection).modes, ['between_tools']);
|
||||
assert.deepEqual(modelParameterProfile(connection).efforts, []);
|
||||
const allNegative = catalogModel({ ...item, capabilities: { ...item.capabilities,
|
||||
thinking: { supported: true, types: Object.fromEntries(['adaptive', 'disabled', 'enabled', 'between_tools'].map(mode => [mode, false])) } } });
|
||||
assert.deepEqual(modelParameterProfile({ ...connection, upstreamModel: allNegative }).modes, []);
|
||||
assert.throws(() => assertModelParameterSupport({ ...connection, upstreamModel: allNegative }, { thinking: { type: 'adaptive' } }), /不支持/);
|
||||
const absent = catalogModel({ id: item.id });
|
||||
assert.equal(modelParameterProfile({ ...connection, upstreamModel: absent }).modes.includes('enabled'), true);
|
||||
const officialAbsent = modelParameterProfile({ ...messages, upstreamModel: catalogModel({ id: messages.model }) });
|
||||
assert.deepEqual(officialAbsent.modes, ['adaptive']);
|
||||
});
|
||||
|
||||
test('stale catalog identity is ignored; actual upstream positive and negative facts retain their provenance', () => {
|
||||
const stale = catalogModel({ id: 'different-model', capabilities: { thinking: false, effort: false } });
|
||||
assert.deepEqual(modelParameterProfile({ ...messages, upstreamModel: stale }).modes, ['adaptive']);
|
||||
const upstreamModel = catalogModel({ id: messages.model, capabilities: { thinking: { supported: true, types: { enabled: true, adaptive: false } } } });
|
||||
const profile = modelParameterProfile({ ...messages, upstreamModel });
|
||||
assert.equal(profile.sourceKind, 'upstream_model_list');
|
||||
assert.deepEqual(profile.modes, ['enabled']);
|
||||
});
|
||||
|
||||
test('explicit stream_options survive each routed Chat request without mutation; absence alone adds usage default', () => {
|
||||
for (const stream_options of [{ include_usage: false, include_obfuscation: false }, {}, null]) {
|
||||
const nativeParameters = { stream_options, custom: { preserve: ['owned'] } }, original = structuredClone(nativeParameters);
|
||||
const member = { id: 'owned-member', ...chat, streaming: true, nativeParameters };
|
||||
const planned = completionBody({ ...chat, modelRouting: { members: [member] } }, [{ role: 'user', content: 'owned' }], []);
|
||||
const body = actualRequest(planned, member);
|
||||
assert.deepEqual(body.stream_options, stream_options);
|
||||
assert.deepEqual(body.custom, original.custom);
|
||||
assert.deepEqual(nativeParameters, original);
|
||||
assert.equal(body.max_tokens, undefined);
|
||||
assert.equal(body.max_completion_tokens, undefined);
|
||||
}
|
||||
assert.deepEqual(completionBody({ ...chat, streaming: true }, [], []).stream_options, { include_usage: true });
|
||||
assert.equal(completionBody(chat, [], []).stream_options, undefined);
|
||||
});
|
||||
|
||||
test('actual local HTTP wire preserves edited objects, explicit stream options and provider errors without retry', async t => {
|
||||
const requests = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const chunks = []; for await (const chunk of req) chunks.push(chunk);
|
||||
const body = JSON.parse(Buffer.concat(chunks)); requests.push({ route: req.url, body });
|
||||
if (body.model === 'owned-error') {
|
||||
res.writeHead(400, { 'content-type': 'application/json', 'request-id': 'owned-fidelity-400' });
|
||||
res.end(JSON.stringify({ error: { type: 'owned_upstream_error', message: 'owned original upstream rejection' } }));
|
||||
} else if (req.url.endsWith('/chat/completions')) {
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
||||
res.end('data: ' + JSON.stringify({ model: body.model, choices: [{ index: 0, delta: { content: 'owned local answer' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n');
|
||||
} else if (req.url.endsWith('/responses')) {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ id: 'owned-resp', model: body.model, status: 'completed', output: [{ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'owned local answer' }] }], usage: { input_tokens: 7, output_tokens: 3 } }));
|
||||
} else {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ id: 'owned-msg', type: 'message', role: 'assistant', model: body.model, content: [{ type: 'text', text: 'owned local answer' }], stop_reason: 'end_turn', usage: { input_tokens: 7, output_tokens: 3 } }));
|
||||
}
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
|
||||
// Do not construct Provider: that constructor reads the optional real env Key.
|
||||
const provider = Object.create(Provider.prototype); provider.apiKey = '';
|
||||
provider.fetcher = (url, options) => { assert.equal(new URL(url).hostname, '127.0.0.1'); return fetch(url, options); };
|
||||
const baseUrl = 'http://127.0.0.1:' + server.address().port + '/v1';
|
||||
const nativeMessages = changeReasoningSetting(messages, { output_config: { effort: 'high', format }, thinking: { type: 'adaptive', display: 'summarized' } }, 'effort', 'max');
|
||||
const nativeResponses = changeReasoningSetting(responses, { reasoning: { summary: 'auto' }, text: { format } }, 'effort', 'high');
|
||||
const configs = [
|
||||
{ ...chat, streaming: true, nativeParameters: { stream_options: { include_usage: false, include_obfuscation: false } } },
|
||||
{ ...responses, nativeParameters: nativeResponses },
|
||||
{ ...messages, nativeParameters: nativeMessages },
|
||||
];
|
||||
for (const config of configs) {
|
||||
const result = await provider.complete({ ...config, baseUrl }, [{ role: 'user', content: 'owned fixture only' }], undefined, undefined, undefined, null, []);
|
||||
assert.equal(result.message.content, 'owned local answer');
|
||||
const wire = requests.at(-1).body;
|
||||
for (const [key, value] of Object.entries(config.nativeParameters)) assert.deepEqual(wire[key], value);
|
||||
assert.equal(wire.max_tokens, config.protocol === 'anthropic-messages' ? 128000 : undefined);
|
||||
assert.equal(wire.max_output_tokens, undefined);
|
||||
if (config.streaming) assert.equal(result.usage, null, 'missing usage stays unknown');
|
||||
}
|
||||
const progress = [];
|
||||
await assert.rejects(provider.complete({ ...messages, baseUrl, model: 'owned-error', nativeParameters: { max_tokens: 4096 } },
|
||||
[{ role: 'user', content: 'owned fixture only' }], undefined, undefined, value => progress.push(value), null, []), cause => {
|
||||
assert.match(cause.message, /owned original upstream rejection/);
|
||||
assert.equal(cause.diagnostic.upstream.requestId, 'owned-fidelity-400');
|
||||
return true;
|
||||
});
|
||||
assert.equal(requests.length, 4);
|
||||
assert.equal(progress.find(value => value.consumption)?.consumption.usageStatus, 'unknown');
|
||||
});
|
||||
Reference in New Issue
Block a user