feat(webui): show resolved Auto API in preset selector
This commit is contained in:
1 parent
994ce51502
commit
73a27e0726
28 files changed
+464
-259
No files matched your search
@@ -1,18 +1,11 @@
|
||||
import { useId } from "react";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { ToggleButton } from "@/components/settings/ToggleButton";
|
||||
import { SettingsRow } from "@/components/settings/shared/SettingsControls";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ModelAPIConfig, ProviderRequestAPI, SettingsPayload } from "@/lib/types";
|
||||
|
||||
export function modelAPIConfigurable(provider: SettingsPayload["providers"][number] | undefined): boolean {
|
||||
if (Array.isArray(provider?.request_apis)) {
|
||||
@@ -32,115 +25,87 @@ export function modelAPISelection(api: ModelAPIConfig | null | undefined): strin
|
||||
|
||||
export function ModelAPIControl({
|
||||
provider,
|
||||
automaticAPI,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
provider: SettingsPayload["providers"][number] | undefined;
|
||||
automaticAPI?: ProviderRequestAPI;
|
||||
value: ModelAPIConfig | null;
|
||||
onChange: (api: ModelAPIConfig | null) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const helpId = useId();
|
||||
const fallbackHelpId = useId();
|
||||
const [pointerFocus, setPointerFocus] = useState(false);
|
||||
const requestAPIs = Array.isArray(provider?.request_apis) ? provider.request_apis : undefined;
|
||||
const configurable = modelAPIConfigurable(provider);
|
||||
const fixedAPI = requestAPIs?.length === 1 ? requestAPIs[0] : undefined;
|
||||
const fixedLabels = {
|
||||
const labels = {
|
||||
responses: "Responses",
|
||||
chat_completions: "Chat Completions",
|
||||
anthropic_messages: "Anthropic Messages",
|
||||
bedrock_converse: "Bedrock Converse",
|
||||
transcription: t("settings.models.apiTranscription"),
|
||||
};
|
||||
const fixedLabel = fixedAPI ? fixedLabels[fixedAPI] : undefined;
|
||||
const fixedLabel = fixedAPI ? labels[fixedAPI] : undefined;
|
||||
const selection = modelAPISelection(value);
|
||||
const selectedAPI = selection === "prefer_responses" ? "responses"
|
||||
: selection === "prefer_chat" ? "chat_completions" : selection;
|
||||
const allowChatFallback = selection === "prefer_responses";
|
||||
const options = [
|
||||
{
|
||||
value: "auto", label: t("settings.models.apiAuto"),
|
||||
help: t("settings.models.requestAPIHelp"),
|
||||
},
|
||||
{
|
||||
value: "responses", label: "Responses",
|
||||
help: t("settings.models.apiResponsesHelp"),
|
||||
},
|
||||
{
|
||||
value: "chat_completions", label: "Chat Completions",
|
||||
help: t("settings.models.apiChatHelp"),
|
||||
value: "auto",
|
||||
label: automaticAPI
|
||||
? `${t("settings.models.apiAuto")} (${labels[automaticAPI]})`
|
||||
: t("settings.models.apiAuto"),
|
||||
},
|
||||
{ value: "responses", label: "Responses" },
|
||||
{ value: "chat_completions", label: "Chat Completions" },
|
||||
];
|
||||
const selected = options.find((option) => option.value === selectedAPI);
|
||||
const help = !configurable
|
||||
? t("settings.models.apiProviderManagedHelp", { provider: provider?.label })
|
||||
: selectedAPI === "responses"
|
||||
? t(allowChatFallback ? "settings.models.apiResponsesFallbackHelp" : "settings.models.apiResponsesOnlyHelp")
|
||||
: selected?.help;
|
||||
if (!configurable && !fixedLabel) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<SettingsRow title={t("settings.models.requestAPI")}>
|
||||
{configurable ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
aria-label={t("settings.models.requestAPI")}
|
||||
aria-describedby={helpId}
|
||||
className="h-9 w-full justify-between gap-3 rounded-full px-3 text-[13px]"
|
||||
>
|
||||
<span className="truncate">{selected?.label}</span>
|
||||
<ChevronDown className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-[min(340px,calc(100vw-2rem))]">
|
||||
<DropdownMenuRadioGroup value={selectedAPI} onValueChange={(api) => {
|
||||
if (api === selectedAPI) return;
|
||||
if (api === "auto") onChange(null);
|
||||
else if (api === "responses" || api === "chat_completions") {
|
||||
onChange({ supported_apis: [api], preferred_api: api });
|
||||
}
|
||||
}}>
|
||||
{options.map((option) => (
|
||||
<DropdownMenuRadioItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
aria-label={option.label}
|
||||
className="items-start py-2.5"
|
||||
>
|
||||
<span>
|
||||
<span className="block text-[13px]">{option.label}</span>
|
||||
<span className="mt-0.5 block text-[12px] leading-5 text-muted-foreground">
|
||||
{option.help}
|
||||
</span>
|
||||
</span>
|
||||
</DropdownMenuRadioItem>
|
||||
))}
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Select value={selectedAPI} onValueChange={(api) => {
|
||||
if (api === selectedAPI) return;
|
||||
if (api === "auto") onChange(null);
|
||||
else if (api === "responses" || api === "chat_completions") {
|
||||
onChange({ supported_apis: [api], preferred_api: api });
|
||||
}
|
||||
}}>
|
||||
<SelectTrigger
|
||||
aria-label={t("settings.models.requestAPI")}
|
||||
className={cn("w-full rounded-full", pointerFocus && "focus-visible:ring-0")}
|
||||
onPointerDown={() => setPointerFocus(true)}
|
||||
onKeyDown={() => setPointerFocus(false)}
|
||||
onBlur={() => setPointerFocus(false)}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent
|
||||
onPointerUpCapture={() => setPointerFocus(true)}
|
||||
onPointerDownOutside={() => setPointerFocus(true)}
|
||||
onKeyDownCapture={() => setPointerFocus(false)}
|
||||
onEscapeKeyDown={() => setPointerFocus(false)}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<span className="block text-[13px] text-muted-foreground sm:text-right">{fixedLabel}</span>
|
||||
)}
|
||||
</SettingsRow>
|
||||
<p id={helpId} className="-mt-1 px-4 pb-3 text-[12px] leading-5 text-muted-foreground sm:px-5">
|
||||
{help}
|
||||
</p>
|
||||
{configurable && selectedAPI === "responses" ? (
|
||||
<div className="mx-4 mb-3 flex items-start justify-between gap-4 rounded-xl bg-muted/30 px-3 py-3 sm:mx-5">
|
||||
<div className="min-w-0">
|
||||
<p className="text-[12px] font-medium leading-5 text-foreground">{t("settings.models.apiFallback")}</p>
|
||||
<p id={fallbackHelpId} className="mt-0.5 text-[12px] leading-5 text-muted-foreground">
|
||||
{t("settings.models.apiFallbackHelp")}
|
||||
</p>
|
||||
<p className="text-[13px] leading-5 text-foreground">{t("settings.models.apiFallback")}</p>
|
||||
</div>
|
||||
<div className="pt-0.5">
|
||||
<ToggleButton
|
||||
checked={allowChatFallback}
|
||||
aria-describedby={fallbackHelpId}
|
||||
label={t("settings.models.apiFallback")}
|
||||
onChange={(checked) => onChange({
|
||||
supported_apis: checked ? ["responses", "chat_completions"] : ["responses"],
|
||||
|
||||
@@ -43,7 +43,8 @@ import {
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ModelAPIConfig, SettingsPayload } from "@/lib/types";
|
||||
import { fetchAutomaticModelAPI } from "@/lib/api";
|
||||
import type { AutomaticModelAPIPayload, ModelAPIConfig, SettingsPayload } from "@/lib/types";
|
||||
|
||||
export interface AgentSettingsDraft {
|
||||
model: string;
|
||||
@@ -237,6 +238,29 @@ export function ModelsSettings({
|
||||
const tx = (key: string, fallback: string, values?: Record<string, unknown>) =>
|
||||
t(key, { defaultValue: fallback, ...(values ?? {}) });
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [automaticAPI, setAutomaticAPI] = useState<{
|
||||
scope: string;
|
||||
result: AutomaticModelAPIPayload;
|
||||
} | null>(null);
|
||||
const automaticAPIScope = JSON.stringify([
|
||||
token, form.provider, form.model, form.reasoningEffort, settings.providers,
|
||||
]);
|
||||
useEffect(() => {
|
||||
if (!editorOpen || settings.model_api_resolution_supported !== true || !form.model.trim()) return;
|
||||
let cancelled = false;
|
||||
const timer = window.setTimeout(() => {
|
||||
void fetchAutomaticModelAPI(token, form.provider, form.model, form.reasoningEffort)
|
||||
.then((result) => {
|
||||
if (!cancelled) setAutomaticAPI({ scope: automaticAPIScope, result });
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setAutomaticAPI(null);
|
||||
});
|
||||
}, 150);
|
||||
return () => { cancelled = true; window.clearTimeout(timer); };
|
||||
}, [editorOpen, settings.model_api_resolution_supported, automaticAPIScope, token, form]);
|
||||
const resolvedAutomaticAPI = settings.model_api_resolution_supported === true
|
||||
&& automaticAPI?.scope === automaticAPIScope ? automaticAPI.result : null;
|
||||
const editorTriggerRef = useRef<HTMLElement | null>(null);
|
||||
const presetNameInputRef = useRef<HTMLInputElement>(null);
|
||||
const suggestedPresetNameRef = useRef<string | null>(null);
|
||||
@@ -509,8 +533,9 @@ export function ModelsSettings({
|
||||
</SettingsRow>
|
||||
<ModelAPIControl
|
||||
provider={selectedProvider ?? settings.providers.find(
|
||||
(provider) => provider.name === selectedPreset?.resolved_provider,
|
||||
(provider) => provider.name === (resolvedAutomaticAPI?.provider ?? selectedPreset?.resolved_provider),
|
||||
)}
|
||||
automaticAPI={resolvedAutomaticAPI?.api}
|
||||
value={form.api}
|
||||
onChange={(api) => setForm((prev) => ({ ...prev, api }))}
|
||||
/>
|
||||
|
||||
@@ -718,15 +718,8 @@
|
||||
"presetNamePlaceholder": "e.g. Fast writing",
|
||||
"advancedOptions": "Advanced options",
|
||||
"requestAPI": "API connection",
|
||||
"requestAPIHelp": "Let nanobot choose for this provider and model. Usually no changes needed.",
|
||||
"apiAuto": "Automatic (recommended)",
|
||||
"apiResponsesHelp": "Use when your provider requires the Responses API.",
|
||||
"apiChatHelp": "Use the provider’s Chat Completions endpoint.",
|
||||
"apiAuto": "Auto",
|
||||
"apiFallback": "Try Chat Completions if Responses is unsupported",
|
||||
"apiFallbackHelp": "Retries with the same model. Your provider must support both APIs.",
|
||||
"apiResponsesOnlyHelp": "Uses Responses only, without switching to Chat Completions.",
|
||||
"apiResponsesFallbackHelp": "Uses Responses first, then tries Chat Completions for compatibility errors.",
|
||||
"apiProviderManagedHelp": "{{provider}} manages this connection. No configuration needed.",
|
||||
"apiTranscription": "Transcription",
|
||||
"contextSummary": "Context {{context}}",
|
||||
"outputSummary": "Max {{max}} tokens",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "p. ej., Escritura rápida",
|
||||
"advancedOptions": "Opciones avanzadas",
|
||||
"requestAPI": "Conexión API",
|
||||
"requestAPIHelp": "nanobot elige según el proveedor y el modelo. Normalmente no es necesario cambiar nada.",
|
||||
"apiAuto": "Automático (recomendado)",
|
||||
"apiResponsesHelp": "Elige esta opción si tu proveedor exige la API Responses.",
|
||||
"apiChatHelp": "Usa la API Chat Completions del proveedor.",
|
||||
"apiAuto": "Auto",
|
||||
"apiFallback": "Probar Chat Completions si Responses no es compatible",
|
||||
"apiFallbackHelp": "Reintenta con el mismo modelo. El proveedor debe admitir ambas API.",
|
||||
"apiResponsesOnlyHelp": "Usa solo Responses, sin cambiar a Chat Completions.",
|
||||
"apiResponsesFallbackHelp": "Usa Responses primero y prueba Chat Completions si hay errores de compatibilidad.",
|
||||
"apiProviderManagedHelp": "{{provider}} gestiona esta conexión. No requiere configuración.",
|
||||
"apiTranscription": "Transcripción",
|
||||
"contextSummary": "Contexto {{context}}",
|
||||
"outputSummary": "Máx. {{max}} tokens",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "p. ex. Rédaction rapide",
|
||||
"advancedOptions": "Options avancées",
|
||||
"requestAPI": "Connexion API",
|
||||
"requestAPIHelp": "nanobot choisit selon le fournisseur et le modèle. Aucune modification n’est généralement nécessaire.",
|
||||
"apiAuto": "Automatique (recommandé)",
|
||||
"apiResponsesHelp": "À choisir si le fournisseur exige l’API Responses.",
|
||||
"apiChatHelp": "Utilise l’API Chat Completions du fournisseur.",
|
||||
"apiAuto": "Auto",
|
||||
"apiFallback": "Essayer Chat Completions si Responses n’est pas pris en charge",
|
||||
"apiFallbackHelp": "Réessaie avec le même modèle. Le fournisseur doit prendre en charge les deux API.",
|
||||
"apiResponsesOnlyHelp": "Utilise uniquement Responses, sans passer à Chat Completions.",
|
||||
"apiResponsesFallbackHelp": "Utilise Responses, puis essaie Chat Completions en cas d’erreur de compatibilité.",
|
||||
"apiProviderManagedHelp": "{{provider}} gère cette connexion. Aucune configuration nécessaire.",
|
||||
"apiTranscription": "Transcription",
|
||||
"contextSummary": "Contexte {{context}}",
|
||||
"outputSummary": "Max. {{max}} tokens",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "mis. Menulis cepat",
|
||||
"advancedOptions": "Opsi lanjutan",
|
||||
"requestAPI": "Koneksi API",
|
||||
"requestAPIHelp": "nanobot memilih sesuai penyedia dan model. Biasanya tidak perlu diubah.",
|
||||
"apiAuto": "Otomatis (disarankan)",
|
||||
"apiResponsesHelp": "Pilih jika penyedia mengharuskan API Responses.",
|
||||
"apiChatHelp": "Menggunakan API Chat Completions dari penyedia.",
|
||||
"apiAuto": "Otomatis",
|
||||
"apiFallback": "Coba Chat Completions jika Responses tidak didukung",
|
||||
"apiFallbackHelp": "Mencoba ulang dengan model yang sama. Penyedia harus mendukung kedua API.",
|
||||
"apiResponsesOnlyHelp": "Hanya menggunakan Responses, tanpa beralih ke Chat Completions.",
|
||||
"apiResponsesFallbackHelp": "Menggunakan Responses terlebih dahulu, lalu mencoba Chat Completions jika terjadi masalah kompatibilitas.",
|
||||
"apiProviderManagedHelp": "{{provider}} mengelola koneksi ini. Tidak perlu konfigurasi manual.",
|
||||
"apiTranscription": "Transkripsi",
|
||||
"contextSummary": "Konteks {{context}}",
|
||||
"outputSummary": "Maks. {{max}} token",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "例:文章作成用",
|
||||
"advancedOptions": "詳細オプション",
|
||||
"requestAPI": "API 接続",
|
||||
"requestAPIHelp": "nanobot がプロバイダーとモデルに合わせて選択します。通常は変更不要です。",
|
||||
"apiAuto": "自動(推奨)",
|
||||
"apiResponsesHelp": "プロバイダーが Responses API を指定している場合に選択します。",
|
||||
"apiChatHelp": "プロバイダーの Chat Completions API を使用します。",
|
||||
"apiAuto": "自動",
|
||||
"apiFallback": "Responses が非対応の場合は Chat Completions を試す",
|
||||
"apiFallbackHelp": "同じモデルで再試行します。プロバイダーが両方の API に対応している必要があります。",
|
||||
"apiResponsesOnlyHelp": "Responses のみを使用し、Chat Completions には切り替えません。",
|
||||
"apiResponsesFallbackHelp": "Responses を優先し、互換性エラー時に Chat Completions を試します。",
|
||||
"apiProviderManagedHelp": "{{provider}} が接続を管理します。手動設定は不要です。",
|
||||
"apiTranscription": "音声文字起こし",
|
||||
"contextSummary": "コンテキスト {{context}}",
|
||||
"outputSummary": "最大 {{max}} トークン",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "예: 빠른 작성",
|
||||
"advancedOptions": "고급 옵션",
|
||||
"requestAPI": "API 연결",
|
||||
"requestAPIHelp": "nanobot이 공급자와 모델에 맞게 선택합니다. 일반적으로 변경할 필요가 없습니다.",
|
||||
"apiAuto": "자동 선택 (권장)",
|
||||
"apiResponsesHelp": "공급자가 Responses API를 요구할 때 선택하세요.",
|
||||
"apiChatHelp": "공급자의 Chat Completions API를 사용합니다.",
|
||||
"apiAuto": "자동",
|
||||
"apiFallback": "Responses를 지원하지 않으면 Chat Completions 시도",
|
||||
"apiFallbackHelp": "같은 모델로 재시도합니다. 공급자가 두 API를 모두 지원해야 합니다.",
|
||||
"apiResponsesOnlyHelp": "Responses만 사용하며 Chat Completions로 전환하지 않습니다.",
|
||||
"apiResponsesFallbackHelp": "Responses를 먼저 사용하고 호환성 오류가 발생하면 Chat Completions를 시도합니다.",
|
||||
"apiProviderManagedHelp": "{{provider}}에서 연결을 관리합니다. 수동 설정이 필요하지 않습니다.",
|
||||
"apiTranscription": "음성 전사",
|
||||
"contextSummary": "컨텍스트 {{context}}",
|
||||
"outputSummary": "최대 {{max}} 토큰",
|
||||
|
||||
@@ -532,15 +532,8 @@
|
||||
"presetNamePlaceholder": "ex.: Escrita rápida",
|
||||
"advancedOptions": "Opções avançadas",
|
||||
"requestAPI": "Conexão API",
|
||||
"requestAPIHelp": "O nanobot escolhe conforme o provedor e o modelo. Geralmente não é preciso alterar.",
|
||||
"apiAuto": "Automático (recomendado)",
|
||||
"apiResponsesHelp": "Escolha quando o provedor exigir a API Responses.",
|
||||
"apiChatHelp": "Usa a API Chat Completions do provedor.",
|
||||
"apiAuto": "Auto",
|
||||
"apiFallback": "Tentar Chat Completions se Responses não for compatível",
|
||||
"apiFallbackHelp": "Tenta novamente com o mesmo modelo. O provedor deve aceitar ambas as APIs.",
|
||||
"apiResponsesOnlyHelp": "Usa apenas Responses, sem alternar para Chat Completions.",
|
||||
"apiResponsesFallbackHelp": "Usa Responses primeiro e tenta Chat Completions em caso de erro de compatibilidade.",
|
||||
"apiProviderManagedHelp": "{{provider}} gerencia esta conexão. Nenhuma configuração necessária.",
|
||||
"apiTranscription": "Transcrição",
|
||||
"contextSummary": "Contexto {{context}}",
|
||||
"outputSummary": "Máx. {{max}} tokens",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "ví dụ: Viết nhanh",
|
||||
"advancedOptions": "Tùy chọn nâng cao",
|
||||
"requestAPI": "Kết nối API",
|
||||
"requestAPIHelp": "nanobot tự chọn theo nhà cung cấp và mô hình. Thường không cần thay đổi.",
|
||||
"apiAuto": "Tự động (khuyến nghị)",
|
||||
"apiResponsesHelp": "Chọn khi nhà cung cấp yêu cầu API Responses.",
|
||||
"apiChatHelp": "Sử dụng API Chat Completions của nhà cung cấp.",
|
||||
"apiAuto": "Tự động",
|
||||
"apiFallback": "Thử Chat Completions nếu Responses không được hỗ trợ",
|
||||
"apiFallbackHelp": "Thử lại với cùng mô hình. Nhà cung cấp phải hỗ trợ cả hai API.",
|
||||
"apiResponsesOnlyHelp": "Chỉ dùng Responses, không chuyển sang Chat Completions.",
|
||||
"apiResponsesFallbackHelp": "Dùng Responses trước, rồi thử Chat Completions khi có lỗi tương thích.",
|
||||
"apiProviderManagedHelp": "{{provider}} quản lý kết nối này. Không cần cấu hình thủ công.",
|
||||
"apiTranscription": "Chuyển giọng nói thành văn bản",
|
||||
"contextSummary": "Ngữ cảnh {{context}}",
|
||||
"outputSummary": "Tối đa {{max}} token",
|
||||
|
||||
@@ -718,15 +718,8 @@
|
||||
"presetNamePlaceholder": "例如:快速写作",
|
||||
"advancedOptions": "高级选项",
|
||||
"requestAPI": "连接方式",
|
||||
"requestAPIHelp": "nanobot 根据服务商和模型自动选择,通常无需修改。",
|
||||
"apiAuto": "自动选择(推荐)",
|
||||
"apiResponsesHelp": "服务商要求使用 Responses 接口时选择。",
|
||||
"apiChatHelp": "使用服务商的 Chat Completions 接口。",
|
||||
"apiAuto": "自动",
|
||||
"apiFallback": "Responses 不兼容时尝试 Chat Completions",
|
||||
"apiFallbackHelp": "使用同一模型重试,需要服务商同时支持两种接口。",
|
||||
"apiResponsesOnlyHelp": "只使用 Responses,不自动切换到 Chat Completions。",
|
||||
"apiResponsesFallbackHelp": "先使用 Responses,不兼容时尝试 Chat Completions。",
|
||||
"apiProviderManagedHelp": "由 {{provider}} 管理,无需手动配置。",
|
||||
"apiTranscription": "语音转写",
|
||||
"contextSummary": "上下文 {{context}}",
|
||||
"outputSummary": "输出上限 {{max}} Token",
|
||||
|
||||
@@ -834,15 +834,8 @@
|
||||
"presetNamePlaceholder": "例如:快速寫作",
|
||||
"advancedOptions": "進階選項",
|
||||
"requestAPI": "連線方式",
|
||||
"requestAPIHelp": "nanobot 依服務商和模型自動選擇,通常無需修改。",
|
||||
"apiAuto": "自動選擇(建議)",
|
||||
"apiResponsesHelp": "服務商要求使用 Responses 介面時選擇。",
|
||||
"apiChatHelp": "使用服務商的 Chat Completions 介面。",
|
||||
"apiAuto": "自動",
|
||||
"apiFallback": "Responses 不相容時嘗試 Chat Completions",
|
||||
"apiFallbackHelp": "使用同一模型重試,需要服務商同時支援兩種介面。",
|
||||
"apiResponsesOnlyHelp": "只使用 Responses,不自動切換到 Chat Completions。",
|
||||
"apiResponsesFallbackHelp": "先使用 Responses,不相容時嘗試 Chat Completions。",
|
||||
"apiProviderManagedHelp": "由 {{provider}} 管理,無需手動設定。",
|
||||
"apiTranscription": "語音轉錄",
|
||||
"contextSummary": "上下文 {{context}}",
|
||||
"outputSummary": "輸出上限 {{max}} Token",
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AutomationChatsPayload,
|
||||
AutomationChatUpdate,
|
||||
AutomationsPayload,
|
||||
AutomaticModelAPIPayload,
|
||||
AutomationUpdatePayload,
|
||||
ChannelConfigurePayload,
|
||||
ChannelConnectPayload,
|
||||
@@ -1045,6 +1046,27 @@ export async function cancelMcpOAuth(
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchAutomaticModelAPI(
|
||||
token: string,
|
||||
provider: string,
|
||||
model: string,
|
||||
reasoningEffort: string,
|
||||
base: string = "",
|
||||
): Promise<AutomaticModelAPIPayload> {
|
||||
const query = new URLSearchParams({ provider, model, reasoning_effort: reasoningEffort });
|
||||
const payload = await request<unknown>(
|
||||
`${base}/api/settings/model-api?${query}`, token, undefined, API_READ_TIMEOUT_MS,
|
||||
);
|
||||
if (typeof payload !== "object" || payload === null) throw new Error("Invalid model API resolution");
|
||||
const result = payload as Record<string, unknown>;
|
||||
const api = result.api;
|
||||
if (typeof result.provider !== "string" || (
|
||||
api !== "chat_completions" && api !== "responses" && api !== "anthropic_messages"
|
||||
&& api !== "bedrock_converse" && api !== "transcription"
|
||||
)) throw new Error("Invalid model API resolution");
|
||||
return { provider: result.provider, api };
|
||||
}
|
||||
|
||||
export async function fetchProviderModels(
|
||||
token: string,
|
||||
provider: string,
|
||||
|
||||
+11
-3
@@ -600,6 +600,14 @@ export interface ModelAPIConfig {
|
||||
preferred_api?: "chat_completions" | "responses" | null;
|
||||
}
|
||||
|
||||
export type ProviderRequestAPI =
|
||||
"chat_completions" | "responses" | "anthropic_messages" | "bedrock_converse" | "transcription";
|
||||
|
||||
export interface AutomaticModelAPIPayload {
|
||||
provider: string;
|
||||
api: ProviderRequestAPI;
|
||||
}
|
||||
|
||||
interface ProviderModelInfo {
|
||||
id: string;
|
||||
label?: string | null;
|
||||
@@ -702,6 +710,8 @@ export interface SettingsPayload {
|
||||
model_call_order_editable: boolean;
|
||||
/** Whether an actual legacy model configuration is available to convert. */
|
||||
model_configuration_migratable?: boolean;
|
||||
/** Host can resolve the default request API for an unsaved model configuration. */
|
||||
model_api_resolution_supported?: boolean;
|
||||
created_model_preset?: string;
|
||||
created_provider?: string;
|
||||
providers: Array<{
|
||||
@@ -718,9 +728,7 @@ export interface SettingsPayload {
|
||||
model_catalog?: ProviderModelsPayload["catalog_kind"];
|
||||
model_api_configurable?: boolean;
|
||||
/** Request formats implemented by the host's provider adapter. */
|
||||
request_apis?: Array<
|
||||
"chat_completions" | "responses" | "anthropic_messages" | "bedrock_converse" | "transcription"
|
||||
>;
|
||||
request_apis?: ProviderRequestAPI[];
|
||||
api_type?: "auto" | "chat_completions" | "responses";
|
||||
oauth_account?: string | null;
|
||||
oauth_expires_at?: number | null;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import type { SettingsPayload } from "@/lib/types";
|
||||
import { requestMutationMock, jsonResponse, settingsPayload, renderSettingsView, openPopover, installSettingsViewTestHooks } from "@/tests/settings-test-utils";
|
||||
@@ -110,8 +110,8 @@ describe("Settings models", () => {
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
expect(screen.getAllByRole("menuitemradio")).toHaveLength(3);
|
||||
fireEvent.click(screen.getByRole("menuitemradio", { name: "Responses" }));
|
||||
expect(screen.getAllByRole("option")).toHaveLength(3);
|
||||
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
|
||||
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
@@ -135,16 +135,97 @@ describe("Settings models", () => {
|
||||
await togglePresetEditor();
|
||||
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).toBeChecked();
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
fireEvent.click(screen.getByRole("menuitemradio", { name: "Responses" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "Responses" }));
|
||||
expect(screen.getByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).toBeChecked();
|
||||
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
fireEvent.click(screen.getByRole("menuitemradio", { name: "Automatic (recommended)" }));
|
||||
fireEvent.click(screen.getByRole("option", { name: "Auto" }));
|
||||
expect(screen.queryByRole("switch", { name: "Try Chat Completions if Responses is unsupported" })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenLastCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", api: null }, 20_000,
|
||||
));
|
||||
expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(false);
|
||||
});
|
||||
|
||||
it("shows the host's automatic API and discards an older reasoning resolution", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_api_resolution_supported = true;
|
||||
payload.model_presets[0].provider = "openai";
|
||||
payload.providers = [{
|
||||
name: "openai", label: "OpenAI", configured: true,
|
||||
request_apis: ["chat_completions", "responses"],
|
||||
}];
|
||||
let finishHigh!: (response: Response) => void;
|
||||
const highResponse = new Promise<Response>((resolve) => { finishHigh = resolve; });
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
if (url.pathname !== "/api/settings/model-api") return jsonResponse(payload);
|
||||
if (url.searchParams.get("reasoning_effort") === "high") return highResponse;
|
||||
return jsonResponse({ provider: "openai", api: "chat_completions" });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
|
||||
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
|
||||
await openPopover(screen.getByLabelText("API connection"));
|
||||
expect(screen.getByRole("option", { name: "Auto (Chat Completions)" })).toHaveAttribute("aria-selected", "true");
|
||||
fireEvent.click(screen.getByRole("option", { name: "Auto (Chat Completions)" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
|
||||
fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "high" } });
|
||||
await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("reasoning_effort=high"))).toBe(true));
|
||||
fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "none" } });
|
||||
await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("reasoning_effort=none"))).toBe(true));
|
||||
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
|
||||
await act(async () => { finishHigh(jsonResponse({ provider: "openai", api: "responses" })); });
|
||||
expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)");
|
||||
expect(requestMutationMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("updates the Auto label from a valid host result without changing the preset declaration", async () => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_api_resolution_supported = true;
|
||||
payload.model_presets[0].provider = "openai";
|
||||
payload.providers = [{
|
||||
name: "openai", label: "OpenAI", configured: true,
|
||||
request_apis: ["chat_completions", "responses"],
|
||||
}];
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url = new URL(String(input), "http://localhost");
|
||||
if (url.pathname !== "/api/settings/model-api") return jsonResponse(payload);
|
||||
return jsonResponse({
|
||||
provider: "openai", api: url.searchParams.get("reasoning_effort") === "high" ? "responses" : "chat_completions",
|
||||
});
|
||||
}));
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Chat Completions)"));
|
||||
fireEvent.click(screen.getByRole("button", { name: /Advanced options/ }));
|
||||
fireEvent.change(screen.getByLabelText("Reasoning effort"), { target: { value: "high" } });
|
||||
await waitFor(() => expect(screen.getByLabelText("API connection")).toHaveTextContent("Auto (Responses)"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(requestMutationMock).toHaveBeenCalledWith(
|
||||
"settings.model_configuration.update", { name: "primary", reasoning_effort: "high" }, 20_000,
|
||||
));
|
||||
});
|
||||
|
||||
it.each(["future_api", null])("leaves the automatic API unconfirmed for an unsupported host result (%s)", async (api) => {
|
||||
const payload = settingsPayload();
|
||||
payload.model_api_resolution_supported = true;
|
||||
payload.providers = [{
|
||||
name: "openai", label: "OpenAI", configured: true,
|
||||
request_apis: ["chat_completions", "responses"],
|
||||
}];
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => String(input).includes("/model-api?")
|
||||
? jsonResponse({ provider: "openai", api }) : jsonResponse(payload));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/model-api?"))).toBe(true));
|
||||
await act(async () => { await Promise.resolve(); });
|
||||
expect(screen.getByLabelText("API connection")).toHaveTextContent(/^Auto$/);
|
||||
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it.each([undefined, ["future_api"], "responses"])("hides API controls when host support is unconfirmed (%s)", async (requestAPIs) => {
|
||||
@@ -155,7 +236,7 @@ describe("Settings models", () => {
|
||||
})));
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
expect(screen.queryByRole("button", { name: "API connection" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("combobox", { name: "API connection" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses the host's API declaration and preserves an existing Chat preference when renaming", async () => {
|
||||
@@ -184,7 +265,7 @@ describe("Settings models", () => {
|
||||
["openai_codex", "OpenAI Codex", "responses", "Responses"],
|
||||
["anthropic", "Anthropic", "anthropic_messages", "Anthropic Messages"],
|
||||
["bedrock", "AWS Bedrock", "bedrock_converse", "Bedrock Converse"],
|
||||
] as const)("explains the provider-managed connection for %s", async (provider, label, api, apiLabel) => {
|
||||
] as const)("shows the fixed connection for %s", async (provider, label, api, apiLabel) => {
|
||||
const payload = settingsPayload();
|
||||
payload.providers = [{ name: provider, label, configured: true, request_apis: [api] }];
|
||||
payload.model_presets[0].provider = provider;
|
||||
@@ -193,8 +274,7 @@ describe("Settings models", () => {
|
||||
renderSettingsView({ initialSection: "models" });
|
||||
await togglePresetEditor();
|
||||
expect(screen.getByText(apiLabel, { exact: true })).toBeVisible();
|
||||
expect(screen.getByText(`${label} manages this connection. No configuration needed.`)).toBeVisible();
|
||||
expect(screen.queryByRole("button", { name: "API connection" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("combobox", { name: "API connection" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("switch")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user