feat(models): expose specification sources and precise reasoning options

This commit is contained in:
Agent Workbench Dev
2026-11-07 14:11:20 +08:00
parent ba4b449164
commit b5aaf1f7c6
10 changed files with 386 additions and 27 deletions
+11 -5
View File
@@ -3,6 +3,7 @@ import { api } from './api';
import type { CatalogPreview } from '../shared/contracts/model-catalog.mjs';
import { ModelErrorDetails } from './ModelErrorDetails';
import type { RuntimeFailure } from './types';
import { resolveModelSpecification } from '../shared/contracts/official-model-registry.mjs';
type Source = { id: string; revision: number; name: string; protocol: string; baseUrl: string; brand: string; enabled: boolean; credentialSource?: { connectionId: string } };
const initial = { name: '', brand: '自定义', protocol: 'chat-completions', baseUrl: 'https://api.openai.com/v1', messagesAuth: 'api-key', requiresKey: true };
@@ -91,16 +92,21 @@ export function ModelCatalog({ sources, sourceId = '', busy, onSaved, onClose }:
<p className="mc-help">以下为上游目录声明,尚未经过模型调用验证。{open ? '可选择上游返回的型号,目录、连接和自动池不设本地数量上限。' : `目录最多${preview.limits.catalog}项,本机最多${selectionLimit}个模型连接;单个自动池最多${poolLimit}个成员。`}</p>
<div className="mc-row-actions"><button className="button secondary" disabled={locked || !selectable.length || new Set([...chosen, ...selectable.map(value => value.id)]).size > selectionLimit} onClick={() => setChosen([...new Set([...chosen, ...selectable.map(value => value.id)])])}>选中当前筛选</button><button className="button secondary" disabled={locked || !chosen.length} onClick={() => setChosen([])}>清空选择</button></div>
<div className="mc-catalog-list" aria-label="上游模型列表">
{visible.map(value => <label className={'mc-catalog-model' + (chosen.includes(value.id) ? ' is-selected' : '')} key={value.id}>
{visible.map(value => {
const specification = resolveModelSpecification({ model: value.id, protocol: preview.source.protocol, baseUrl: preview.source.baseUrl, upstreamModel: value });
const context = specification.fields.contextLimit?.value, output = specification.fields.maxOutputTokens?.value;
const efforts = specification.fields.efforts?.value;
return <label className={'mc-catalog-model' + (chosen.includes(value.id) ? ' is-selected' : '')} key={value.id}>
<input type="checkbox" aria-label={'选择模型 ' + value.id} checked={chosen.includes(value.id)} disabled={locked || !open && value.lifecycle === 'retired' || !chosen.includes(value.id) && chosen.length >= selectionLimit} onChange={event => setChosen(event.target.checked ? [...chosen, value.id] : chosen.filter(id => id !== value.id))} />
<span><strong>{value.id}</strong>{value.name !== value.id && <span>{value.name}</span>}<small>{[value.owner, value.contextLimit && `上下文 ${value.contextLimit.toLocaleString()} tokens`, value.maxOutputTokens && `输出上限 ${value.maxOutputTokens.toLocaleString()}`, value.lifecycle && value.lifecycle !== 'active' && (value.lifecycle === 'retired' ? '已退役' : '待退役')].filter(Boolean).join(' · ') || '上游未提供详细元数据'}</small>
<small>{Object.entries(value.capabilityDeclarations).filter(([, state]) => state !== 'unknown').map(([capability, state]) => `${capabilityNames[capability]}${state === 'supported' ? '支持' : '不支持'}`).join(' · ') || '文本、工具、流式等能力待确认'}{value.efforts.length ? ` · 推理强度 ${value.efforts.join(' / ')}` : ''}</small></span>
</label>)}{!visible.length && <p className="mc-empty">{preview.entries.length ? '没有匹配的型号。可更改搜索条件。' : '上游返回了空目录。可核对连接或使用手动兼容入口。'}</p>}
<span><strong>{value.id}</strong>{value.name !== value.id && <span>{value.name}</span>}<small>{[value.owner, typeof context === 'number' && `上下文 ${context.toLocaleString()} tokens`, typeof output === 'number' && `输出上限 ${output.toLocaleString()}`, value.maxInputTokens && `输入上限 ${value.maxInputTokens.toLocaleString()}`, value.lifecycle && value.lifecycle !== 'active' && (value.lifecycle === 'retired' ? '已退役' : '待退役')].filter(Boolean).join(' · ') || '上游未提供详细元数据'}</small>
<small>{Object.keys(capabilityNames).map(capability => [capability, specification.fields['capabilities.' + capability]?.value]).filter(([, state]) => state && state !== 'unknown').map(([capability, state]) => `${capabilityNames[String(capability)]}${state === 'supported' ? '支持' : '不支持'}`).join(' · ') || '文本、工具、流式等能力待确认'}{Array.isArray(efforts) && efforts.length ? ` · 推理强度 ${efforts.join(' / ')}` : ''}</small>
{specification.officialRecord && <small>精确型号缺失项采用官方参考;保存后可查看逐字段来源。</small>}</span>
</label>; })}{!visible.length && <p className="mc-empty">{preview.entries.length ? '没有匹配的型号。可更改搜索条件。' : '上游返回了空目录。可核对连接或使用手动兼容入口。'}</p>}
</div>
<label className="mc-checkbox"><input type="checkbox" checked={declare} disabled={locked} onChange={event => setDeclare(event.target.checked)} />我确认所选型号可通过此协议处理文本及工具调用,仅补充目录未声明的项目</label>
<div className="mc-form-grid"><label>保存后的使用方式<select aria-label="模型使用方式" value={routing} disabled={locked} onChange={event => setRouting(event.target.value)}><option value="keep">保留当前选择,稍后手动使用</option><option value="manual">手动指定默认模型</option><option value="auto">自动适配所选模型</option></select></label>
{routing === 'manual' && <label>默认模型<select aria-label="目录默认模型" value={defaultModel} disabled={locked} onChange={event => setDefaultModel(event.target.value)}><option value="">请选择型号</option>{chosen.map(id => <option key={id}>{id}</option>)}</select></label>}</div>
{routing === 'auto' && <p className="mc-help">自动适配复用模型池,按任务所需能力、连接健康和可用并发筛选,再按轮询分配;同一运行优先保持型号。未确认能力的型号不会用于需要该能力的任务。</p>}
{routing === 'auto' && <p className="mc-help">自动适配复用模型池,优先选择声明适配的型号;默认开放模式在没有已知适配型号时保留未知能力后备,并记录实际选择依据。同一运行优先保持型号,上游错误按原结果保留。</p>}
<div className="mc-actions"><button className="button primary" disabled={locked || !chosen.length || routing === 'manual' && !chosen.includes(defaultModel) || routing === 'auto' && chosen.length > poolLimit} onClick={() => void save()}>{saving ? '正在保存…' : `保存所选 ${chosen.length} 个模型`}</button></div>
</>}
</section>;
+15 -6
View File
@@ -5,7 +5,7 @@ import type { Config, ModelSelection, ModelSnapshot, RuntimeFailure } from './ty
import './ModelCenter.css';
import { ModelRequestLedger, type ModelAttempt } from './ModelRequestLedger';
import { ModelWaitSettings, type WaitSettings } from './ModelWaitSettings';
import { NativeParameters } from './NativeParameters';
import { NativeParameters, type NativeConnection } from './NativeParameters';
import { ModelErrorDetails } from './ModelErrorDetails';
import { ModelBudgetSettings } from './ModelBudgetSettings';
import { DEFAULT_MODEL_CAPACITY, messagesOutputSetting, modelCapacityDeclaration } from '../shared/contracts/model-capacity.mjs';
@@ -13,14 +13,22 @@ import { modelRequestUrl, protocolLabel } from '../shared/contracts/model-endpoi
import { ModelNetworkDiagnostics } from './ModelNetworkDiagnostics';
import { ModelCatalog } from './ModelCatalog';
import type { CatalogModel } from '../shared/contracts/model-catalog.mjs';
import type { ModelSpecConnection } from '../shared/contracts/official-model-registry.mjs';
const previewUrl = (value: { protocol: string; baseUrl: string }) => { try { return modelRequestUrl(value); } catch { return '请填写有效的接口根地址'; } };
const upstreamCapacity = (value: { model: string; upstreamModel?: CatalogModel }, field: 'contextLimit' | 'maxOutputTokens') => {
const upstreamCapacity = (value: ModelSpecConnection, field: 'contextLimit' | 'maxOutputTokens') => {
const declaration = modelCapacityDeclaration(value, field);
return declaration ? declaration.value.toLocaleString() + ' tokens · ' + (declaration.source === 'official_model_spec' ? 'Anthropic 官方规格' : '上游目录') : '本地无限制 · 由上游决定';
return declaration ? declaration.value.toLocaleString() + ' tokens · ' + (declaration.source === 'official_model_spec' ? ({ anthropic: 'Anthropic', openai: 'OpenAI', deepseek: 'DeepSeek' }[declaration.provider ?? ''] ?? '供应商') + ' 官方规格'
: declaration.source === 'explicit_compatibility' ? '用户兼容覆盖' : '上游目录') : '本地无限制 · 由上游决定';
};
type Connection = { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel;
const protocolOutput = (value: ModelSpecConnection & { maxOutputTokens?: number }) => {
const output = messagesOutputSetting(value);
return output.source === 'upstream_optional' ? '默认省略 max_tokens · 官方 HTTP 可选字段'
: 'max_tokens = ' + String(output.value) + ' · ' + ({ upstream_catalog: '上游目录最大值', official_model_spec: '官方同步输出规格', explicit_native: '显式原生参数', explicit_compatibility: '用户兼容覆盖' }[output.source] ?? '连接声明,最大值未验证');
};
type Connection = NativeConnection & { id: string; name: string; brand: string; protocol: string; parameterProfile?: string; messagesAuth?: string; baseUrl: string; model: string; enabled: boolean; revision: number; hasKey: boolean; credentialSource?: { connectionId: string }; upstreamModel?: CatalogModel;
requiresKey: boolean; modelIdentityPolicy?: string; modelIdentityAliases?: string[]; modelIdentityAliasSource?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string; streaming?: boolean; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; capabilityEvidence?: { checkedAt: string }; contextLimit: number; maxOutputTokens: number; concurrency: number; status: string; activeRequests: number; savedCredential?: { status: string }; health: { state: string; reason?: string; cooldownUntil?: number } };
type Pool = { id?: string; name: string; members: { connectionId: string; weight: number }[]; strategy: string; sticky: boolean; maxAttempts: number; revision?: number; queueTimeoutMs: number };
type ImportRecord = { id: string; source: string; path: string; enabled: boolean; lastCheckedAt?: string; lastSyncedAt?: string; lastError?: string; lastResult?: { imported?: number; conflicts?: string[] } };
@@ -39,7 +47,7 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
const [view, setView] = useState<Center | null>(null);
const [runtimeConfig, setRuntimeConfig] = useState<Config | null>(null);
const [tab, setTab] = useState('connections');
const [draft, setDraft] = useState<typeof initial & { id?: string; revision?: number; upstreamModel?: CatalogModel; messagesAuth?: string; parameterProfile?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [draft, setDraft] = useState<typeof initial & ModelSpecConnection & { id?: string; revision?: number; upstreamModel?: CatalogModel; messagesAuth?: string; parameterProfile?: string; nativeParameters?: Record<string, unknown>; outputTokenField?: string }>(initial);
const [editing, setEditing] = useState(false), [key, setKey] = useState('');
const [nativeTarget, setNativeTarget] = useState<Connection | null>(null);
const [catalogSource, setCatalogSource] = useState<string | null>(null);
@@ -123,8 +131,9 @@ export function ModelCenter({ onConfig, busy, runModel }: { onConfig: (value: Co
{!connections.length && catalogSource === null && !editing && <div className="mc-empty"><strong>还没有模型连接</strong><p>从上游获取可用型号,选择后即可开始开发。</p></div>}
<div className="mc-connections">{connections.map(value => <article className={'mc-connection ' + (!value.enabled ? 'mc-disabled' : '')} key={value.id} data-connection-id={value.id}>
<div className="mc-card-heading"><span className="mc-service-icon"><Server size={20} /></span><div><h4>{value.name}</h4><span>{value.brand} · {protocolLabel(value.protocol)}{value.streaming ? ' · 流式开启' : ''}</span></div><span className={'mc-state mc-state-' + value.status}>{states[value.status]}</span></div>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议必填输出</dt><dd>max_tokens = {String(messagesOutputSetting(value).value)} · {messagesOutputSetting(value).source === 'upstream_catalog' ? '上游目录最大值' : messagesOutputSetting(value).source === 'official_model_spec' ? 'Anthropic 官方同步输出规格' : messagesOutputSetting(value).source === 'explicit_native' ? '显式原生参数' : '连接声明,最大值未验证'}</dd><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
<dl><dt>模型</dt><dd>{value.model || '尚未填写'}</dd><dt>请求地址</dt><dd>{previewUrl(value)}</dd>{value.protocol === 'anthropic-messages' && <><dt>协议输出参数</dt><dd>{protocolOutput(value)}</dd><dt>鉴权</dt><dd>{value.messagesAuth === 'bearer' ? 'Bearer' : 'x-api-key'} · anthropic-version 2023-06-01</dd></>}<dt>凭据</dt><dd>{value.credentialSource ? '共用 ' + (connections.find(source => source.id === value.credentialSource!.connectionId)?.name ?? '源连接') + (value.hasKey ? ' 的上游凭据' : ';请核对源连接是否启用及凭据') : value.hasKey ? value.savedCredential?.status === 'saved' ? '已设置,可从本机加密保存加载' : '已设置,重启需重新填写' : value.requiresKey ? '尚未填写' : '此服务可不填'}</dd><dt>当前请求</dt><dd>{value.activeRequests} 在途 · 并发 {value.concurrency === 0 ? '不限' : value.concurrency}</dd>{passthrough ? <><dt>模型最大上下文</dt><dd>{upstreamCapacity(value, 'contextLimit')}</dd><dt>模型最大输出</dt><dd>{upstreamCapacity(value, 'maxOutputTokens')}</dd></> : <><dt>连接容量声明</dt><dd>上下文 {value.contextLimit.toLocaleString()} · 输出 {value.maxOutputTokens.toLocaleString()}</dd></>}</dl>
{value.upstreamModel && <p className="mc-help">型号来自上游目录,能力按目录声明与显式设置保存;可在“推理与能力”查看已接入范围。</p>}
{!!value.modelSpecification?.conflicts.length && <p className="mc-help">有 {value.modelSpecification.conflicts.length} 项规格声明差异,可在“推理与能力”的“模型规格与来源”查看。原目录与显式设置分别保留。</p>}
<div className="mc-capabilities">{Object.entries(capabilityLabels).map(([key, title]) => <span key={key} data-capability={value.capabilities?.[key] ?? 'unknown'}>{title}:{capabilityStates[value.capabilities?.[key] ?? 'unknown']}</span>)}</div>
{value.health.reason && <p className="mc-card-warning">{value.health.reason}{!!value.health.cooldownUntil && value.health.cooldownUntil > Date.now() && ' · 冷却至 ' + new Date(value.health.cooldownUntil).toLocaleTimeString()}</p>}
<footer><button className="button secondary" disabled={locked || !value.enabled} onClick={() => void act(async () => { const result = await api<{ config: Config }>('/model-center/select', { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id }); onConfig(result.config, { type: value.id === 'legacy-default' ? 'legacy' : 'connection', id: value.id, name: value.name }); })}>{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? <Check size={14} /> : <Route size={14} />}{runtimeConfig?.mode !== 'demo' && selected?.id === value.id ? '当前使用' : '用于新任务'}</button>
+2 -2
View File
@@ -7,9 +7,9 @@ export type RoutingDecision = {
catalog?: { id: string; fetchedAt: string | null; lifecycle: string | null } }[];
};
const labels: Record<string, string> = { text: '文本', tools: '工具', streaming: '流式', vision: '视觉', audio: '语音',
verified: '已验证', protocol_declared: '连接声明支持', upstream_declared: '上游目录声明支持', unknown: '未验证', unsupported: '明确不支持',
verified: '已验证', protocol_declared: '连接声明支持', upstream_declared: '上游目录声明支持', official_declared: '官方规格声明支持', unknown: '未验证', unsupported: '明确不支持',
selected: '本次选中', eligible: '适配候选', excluded: '自动选择排除', unavailable: '当时不可用', lower_priority: '保留为未知后备',
'revision-bound-observation': '对应连接及凭据修订的观测', 'connection-declaration': '连接声明', 'upstream-model-list': '相符上游目录' };
'revision-bound-observation': '对应连接及凭据修订的观测', 'connection-declaration': '连接声明', 'upstream-model-list': '相符上游目录', 'official-model-spec': '官方精确型号规格', 'explicit-compatibility': '用户显式兼容覆盖', 'protocol-declaration': '协议声明' };
const reasons: Record<string, string> = { 'known-capabilities': '自动适配:已知能力满足请求', 'unverified-fallback': '自动适配:未知能力后备尝试(未验证)',
'no-eligible-candidate': '自动适配:没有可用适配成员', 'explicit-selection': '显式选择:按原配置透传', 'restricted-capabilities': '按手动限制模式核对能力' };
+27
View File
@@ -0,0 +1,27 @@
.model-specification-details { margin: 14px 0; border-top: 1px solid var(--line); padding-top: 8px; color: var(--ink); font-size: 12px; line-height: 1.7; min-width: 0; overflow-wrap: anywhere; }
.model-specification-details summary { cursor: pointer; color: var(--ink); padding: 8px 0; min-height: 40px; font-weight: 600; }
.model-specification-details p { margin: 8px 0 12px; color: var(--muted); }
.model-specification-details table { width: 100%; table-layout: fixed; border-collapse: collapse; }
.model-specification-details th, .model-specification-details td { padding: 12px 8px; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }
.model-specification-details thead th { color: var(--muted); font-weight: 500; }
.model-specification-details th:first-child { width: 25%; }
.model-specification-details th:nth-child(2) { width: 25%; }
.model-spec-source { display: grid; gap: 4px; }
.model-spec-source a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--accent); text-underline-offset: 3px; }
.model-specification-details code, .model-specification-details pre { font: 12px/1.7 var(--font-mono, Consolas, monospace); overflow-wrap: anywhere; white-space: pre-wrap; }
.model-spec-conflict { display: block; margin-top: 5px; font-size: 12px; color: var(--danger); font-weight: 600; }
.model-spec-alternatives { margin-top: 5px; }
.model-spec-alternatives > div { margin: 8px 0; border-left: 2px solid var(--line); padding-left: 8px; }
.model-spec-raw pre { border: 1px solid var(--line); padding: 12px; background: var(--surface); max-height: 32rem; overflow: auto; }
.mc-model-overrides { border-top: 1px solid var(--line); margin-top: 14px; padding-top: 8px; font-size: 12px; line-height: 1.7; }
.mc-model-overrides summary { padding: 8px 0; min-height: 40px; cursor: pointer; font-weight: 600; }
.mc-model-overrides label { display: grid; gap: 8px; margin: 12px 0; }
@media (max-width: 620px) {
.model-specification-details thead { display: none; }
.model-specification-details tbody, .model-specification-details tr { display: block; }
.model-specification-details tr { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); border-bottom: 1px solid var(--line); }
.model-specification-details th, .model-specification-details td { border: 0; min-width: 0; padding: 9px 0; }
.model-specification-details th:first-child { width: auto; padding-right: 10px; }
.model-specification-details td:last-child { grid-column: 1 / -1; padding-top: 0; }
.model-specification-details summary, .mc-model-overrides summary { min-height: 44px; }
}
+39
View File
@@ -0,0 +1,39 @@
import { resolveModelSpecification } from '../shared/contracts/official-model-registry.mjs';
import type { ModelSpecConnection, ModelSpecField, ModelSpecification } from '../shared/contracts/official-model-registry.mjs';
import './ModelSpecificationDetails.css';
const fields: Record<string, string> = { contextLimit: '最大上下文', maxInputTokens: '最大输入', maxOutputTokens: '最大输出', efforts: '推理强度', modes: '推理模式', defaultEffort: '默认强度', defaultMode: '默认模式', modeEfforts: '模式与强度组合', inputModalities: '输入类型', outputModalities: '输出类型', nativeTools: '供应商原生工具', lifecycle: '型号状态', aliasOf: '供应商型号映射', toolsCondition: '工具调用条件',
'capabilities.text': '文本', 'capabilities.tools': '工具调用', 'capabilities.streaming': '流式', 'capabilities.vision': '图像输入', 'capabilities.audio': '语音',
'features.thinking': '推理', 'features.effort': '强度选择', 'features.prompt_caching': '提示缓存', 'features.structured_outputs': '结构化输出', 'features.json_output': 'JSON 输出',
'request.systemPromptUpdate': '系统提示更新位置', 'request.maxTokensRequired': 'HTTP 必须带 max_tokens', 'request.versionHandling': 'API 版本处理', 'request.thinkingBudget': '推理预算处理', 'request.aliasAccepted': '上游接受旧型号名', 'request.originalModelRetired': '旧型号底层已退役' };
const kinds: Record<string, string> = { official_model_spec: '官方规格', upstream_catalog: '上游目录声明', explicit_compatibility: '用户兼容覆盖', connection_declaration: '用户连接声明', legacy_connection_declaration: '原连接声明(编辑来源未记录)', revision_bound_observation: '对应修订的实际观测', protocol_declaration: '协议声明' };
const states: Record<string, string> = { supported: '声明支持', unsupported: '声明不支持', unknown: '待确认', active: '可用', deprecated: '已弃用的旧名称', retired: '已退役', ignored: '上游忽略', 'reasoning-none': 'Chat 工具调用需 reasoning_effort=none', 'responses-only': '工具调用需 Responses', 'in-history': '可在历史中更新', 'leading-only': '仅允许开头的系统提示' };
const display = (value: unknown): string => value === null || value === undefined ? '未公布 / 未知' : Array.isArray(value) ? value.length ? value.map(display).join(' / ') : '无已声明选项'
: typeof value === 'number' ? value.toLocaleString() : typeof value === 'boolean' ? value ? '是' : '否' : typeof value === 'object' ? JSON.stringify(value) : states[String(value)] ?? String(value);
function Source({ fact }: { fact: Omit<ModelSpecField, 'alternatives' | 'conflict'> }) {
return <span className="model-spec-source"><span>{kinds[fact.kind] ?? fact.kind}{fact.checkedAt ? ' · ' + fact.checkedAt : ''}</span>
{fact.url && <a href={fact.url} target="_blank" rel="noreferrer">{fact.sourceId ?? '查看声明来源'}</a>}
{fact.apiVersion && <span>规格 API 版本 {fact.apiVersion}</span>}{fact.sha256 && <code>SHA256 {fact.sha256}</code>}{fact.note && <span>{fact.note}</span>}</span>;
}
export function ModelSpecificationDetails({ connection, specification }: { connection: ModelSpecConnection; specification?: ModelSpecification }) {
const value = specification ?? resolveModelSpecification(connection), catalog = connection.upstreamModel;
return <details className="model-specification-details">
<summary>模型规格与来源{value.conflicts.length > 0 ? ` · ${value.conflicts.length} 项声明差异` : ''}</summary>
<p>型号 {value.model || '尚未选择'} · {value.protocol} · 资料版本 {value.registryVersion}。官方规格、目录声明与本次线路观测分别保留。</p>
{value.officialRecord && <p>匹配到官方精确型号,规格 API 版本 {value.officialRecord.apiVersion};实际发送版本以请求账本为准。官方资料不代表这条代理线路已通过验证。</p>}
{connection.modelSpecificationFrozen && <p>这是该次运行封存的规格;后续目录刷新和设置不会改写它。</p>}
<table aria-label="模型规格来源表"><thead><tr><th>规格</th><th>当前参考值</th><th>来源</th></tr></thead><tbody>
{Object.entries(value.fields).map(([key, fact]) => <tr key={key} data-spec-field={key}>
<th scope="row">{fields[key] ?? key}</th><td>{display(fact.value)}{fact.conflict && <strong className="model-spec-conflict">存在声明差异</strong>}</td>
<td><Source fact={fact} />{fact.alternatives.length > 0 && <details className="model-spec-alternatives"><summary>查看其他 {fact.alternatives.length} 项来源</summary>
{fact.alternatives.map((other, index) => <div key={index}><strong>{display(other.value)}</strong><Source fact={other} /></div>)}</details>}</td>
</tr>)}
{!Object.keys(value.fields).length && <tr><td colSpan={3}>尚未取得型号规格。默认透传,由上游处理。</td></tr>}
</tbody></table>
{catalog?.rawItem && <details className="model-spec-raw"><summary>上游完整声明</summary>
<p>保存的是已解析、脱敏的 JSON 条目;不会把这些额外字段自动加入请求。{catalog.rawBytes !== undefined ? ` ${catalog.rawBytes.toLocaleString()} 字节。` : ''}</p>
<code>表示 {catalog.rawRepresentation ?? '旧目录未记录表示格式'}{catalog.rawSha256 ? ' · SHA256 ' + catalog.rawSha256 : ''}</code>
<pre tabIndex={0}>{JSON.stringify(catalog.rawItem, null, 2)}</pre>
</details>}
</details>;
}
+27 -5
View File
@@ -3,32 +3,54 @@ import { useEffect, useRef, useState } from 'react';
import { nativeParameterSettings } from '../shared/contracts/native-parameters.mjs';
import { ReasoningSettings } from './ReasoningSettings';
import type { CatalogModel } from '../shared/contracts/model-catalog.mjs';
import type { ModelSpecConnection } from '../shared/contracts/official-model-registry.mjs';
import { modelOverrideSettings, specificationField } from '../shared/contracts/official-model-registry.mjs';
import { ModelSpecificationDetails } from './ModelSpecificationDetails';
export type NativeConnection = { id: string; revision: number; name: string; protocol: string; model?: string; brand?: string; baseUrl?: string; parameterProfile?: string; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; nativeParameters?: Record<string, unknown>; outputTokenField?: string; upstreamModel?: CatalogModel; maxOutputTokens?: number };
export type NativeConnection = ModelSpecConnection & { id: string; revision: number; name: string; protocol: string; model?: string; brand?: string; baseUrl?: string; parameterProfile?: string; capabilityDeclarations?: Record<string, string>; capabilities?: Record<string, string>; nativeParameters?: Record<string, unknown>; outputTokenField?: string; upstreamModel?: CatalogModel; maxOutputTokens?: number };
export function NativeParameters({ connection, busy, onCancel, onSave, executionMode }: { connection: NativeConnection; busy: boolean; executionMode?: string; onCancel: () => void;
onSave: (input: { id: string; revision: number; nativeParameters: Record<string, unknown>; outputTokenField: string; parameterProfile?: string }) => Promise<void> }) {
onSave: (input: { id: string; revision: number; nativeParameters: Record<string, unknown>; outputTokenField: string; parameterProfile?: string; modelOverrides?: Record<string, unknown> }) => Promise<void> }) {
const [text, setText] = useState(JSON.stringify(connection.nativeParameters ?? {}, null, 2));
const [field, setField] = useState(connection.outputTokenField ?? (connection.protocol === 'responses' ? 'max_output_tokens' : 'max_tokens'));
const [error, setError] = useState('');
const [profile, setProfile] = useState(connection.parameterProfile ?? 'auto');
const initialOverrides = JSON.stringify(connection.modelOverrides ?? {}, null, 2);
const [overrideText, setOverrideText] = useState(initialOverrides);
let overrides = connection.modelOverrides ?? {};
try { overrides = modelOverrideSettings(JSON.parse(overrideText)); } catch { /* Preserve the invalid editor and last known specification. */ }
let parameters: Record<string, unknown> | null = null;
try { const parsed = JSON.parse(text); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) parameters = parsed; } catch { /* The original editor content remains editable. */ }
const updateParameters = (value: Record<string, unknown>) => { setText(JSON.stringify(value, null, 2)); setError(''); };
const configured = { ...connection, nativeParameters: parameters ?? connection.nativeParameters, parameterProfile: profile, modelOverrides: overrides };
const output = messagesOutputSetting(configured);
const optionalOutput = specificationField(configured, 'request.maxTokensRequired')?.value === false;
const outputSource = { explicit_native: '显式原生参数', upstream_catalog: '上游目录最大输出', official_model_spec: '官方同步输出规格', explicit_compatibility: '用户兼容覆盖', connection_declaration: '连接声明,非已验证最大值' }[output.source] ?? '';
const form = useRef<HTMLFormElement>(null);
useEffect(() => { form.current?.scrollIntoView({ block: 'nearest' }); }, []);
return <form ref={form} className="mc-editor mc-native" aria-label="原生请求参数" onSubmit={async event => {
event.preventDefault(); setError('');
try { const settings = nativeParameterSettings(connection.protocol, JSON.parse(text), field, profile, { executionMode }); await onSave({ id: connection.id, revision: connection.revision, ...settings }); }
try { const settings = nativeParameterSettings(connection.protocol, JSON.parse(text), field, profile, { executionMode });
const modelOverrides = modelOverrideSettings(JSON.parse(overrideText));
await onSave({ id: connection.id, revision: connection.revision, ...settings, ...(overrideText !== initialOverrides || connection.modelOverrides ? { modelOverrides } : {}) }); }
catch (cause) { setError(cause instanceof Error ? cause.message : '参数格式无效。'); }
}}>
<h3>{connection.name} · 推理与原生参数</h3>
<p className="mc-help">参数按所选协议原字段发送,并封存在实际请求中。具体模型是否接受这些选项,以服务响应为准;未填写的选项采用上游默认值。</p>
<ReasoningSettings connection={connection} parameters={parameters} profile={profile} busy={busy} onChange={updateParameters} onProfile={setProfile} />
<ReasoningSettings connection={configured} parameters={parameters} profile={profile} busy={busy} onChange={updateParameters} onProfile={setProfile} />
<ModelSpecificationDetails connection={configured} />
<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>
<p className="mc-help">{connection.protocol === 'anthropic-messages' ? optionalOutput ? '该型号的官方 HTTP 接口允许省略 max_tokens;' + (output.source === 'upstream_optional' ? '默认不附加输出上限;显式值按原值发送。' : '当前 max_tokens=' + String(output.value) + '(' + outputSource + '),按原值发送。')
: 'Messages 协议需带 max_tokens;当前 ' + String(output.value) + '(' + outputSource + ')。可在 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">推理控件与 JSON 编辑同一份参数;切换配置档保留原 JSON,可按目标接口自行调整。{executionMode === 'unrestricted' ? '其他原生字段按原值发送,是否接受以上游原始响应为准;消息、工具、传输与凭据由工作台对应设置管理。'
: connection.protocol === 'anthropic-messages' ? '当前受限模式仅支持已接入的采样、停止序列、thinking 与 output_config.effort。' : connection.protocol === 'responses' ? '当前受限模式仅支持已接入的采样、并行工具、reasoning.effort 与 text.verbosity。' : '当前受限模式仅支持已接入的采样、并行工具、推理强度、verbosity 与 DeepSeek thinking。'}</p>
<details className="mc-model-overrides"><summary>高级 · 兼容规格覆盖</summary>
<p className="mc-help">代理声明与官方不同,可显式填写容量、推理选项或能力。覆盖用于规格参考和选项;接口要求 max_tokens 时会采用对应最大输出值,显式原生参数优先。其他请求参数仍在上方 JSON 中设置。</p>
<label>兼容规格 JSON<textarea aria-label="兼容规格 JSON" rows={6} spellCheck={false} value={overrideText} disabled={busy} onChange={event => { setOverrideText(event.target.value); setError(''); }} /></label>
<p className="mc-help">支持 contextLimit、maxInputTokens、maxOutputTokens、efforts、modes、modeEfforts、defaultMode、defaultEffort、capabilities、features、inputModalities、outputModalities、nativeTools、lifecycle、note。null 表示未知,空数组表示没有已声明选项;填写 {'{}'} 恢复目录和官方后备。不会改写原运行。</p>
<button className="button secondary" type="button" disabled={busy} onClick={() => { setOverrideText('{}'); setError(''); }}>清除兼容覆盖</button>
</details>
{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>;
+6 -6
View File
@@ -7,11 +7,11 @@ export function ReasoningSettings({ connection, parameters, profile, busy, onPro
connection: NativeConnection; parameters: Record<string, unknown> | null; profile: string; busy: boolean;
onProfile: (value: string) => void; onChange: (value: Record<string, unknown>) => void;
}) {
const configured = { ...connection, parameterProfile: profile }, resolved = modelParameterProfile(configured);
const configured = { ...connection, nativeParameters: parameters ?? connection.nativeParameters, parameterProfile: profile }, resolved = modelParameterProfile(configured);
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 modes = [...new Set([...resolved.modes, ...(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]
@@ -25,22 +25,22 @@ export function ReasoningSettings({ connection, parameters, profile, busy, onPro
</select></label>
<label>推理模式<select aria-label="推理模式" value={setting.mode} disabled={disabled} onChange={event => change('mode', event.target.value)}>
<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}`}
{value === 'enabled' && resolved.thinkingBudget === 'required' ? '开启 · 指定推理预算' : modeLabels[value] ?? `已配置 · ${value}`}
{!resolved.modes.includes(value) ? '(未声明支持)' : !modeAllowed(value) ? '(需 high 或更低强度)' : ''}
</option>)}
</select></label>
<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>}
{connection.protocol === 'anthropic-messages' && resolved.thinkingBudget === 'required' && 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}。自定义代理可选择兼容配置档;原生 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>}
{resolved.officialSource && <p className="mc-help"><a href={resolved.officialSource.url} target="_blank" rel="noreferrer">{resolved.officialSource.provider === 'anthropic' ? 'Anthropic' : resolved.officialSource.provider === 'deepseek' ? 'DeepSeek' : 'OpenAI'} 官方推理说明</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'
{resolved.thinkingBudget === 'ignored' && connection.protocol === 'anthropic-messages' ? <p className="mc-help">该接口按官方声明忽略指定推理预算;使用模式和强度选择,不自动补 budget_tokens。已有原生值按原配置保留。</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>