Spaces:
Runtime error
Runtime error
File size: 11,659 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | "use client";
import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Badge, Button, Input, Modal, Select } from "@/shared/components";
type CompatibleMode = "openai" | "anthropic" | "cc";
type CompatibleProviderNode = { id: string } & Record<string, unknown>;
interface AddCompatibleProviderModalProps {
isOpen: boolean;
mode: CompatibleMode;
title?: string;
onClose: () => void;
onCreated: (node: CompatibleProviderNode) => void;
}
interface CompatibleFormState {
name: string;
prefix: string;
apiType: string;
baseUrl: string;
chatPath: string;
modelsPath: string;
}
const CC_DEFAULT_CHAT_PATH = "/v1/messages?beta=true";
const MODE_DEFAULTS: Record<
CompatibleMode,
{
baseUrl: string;
type: "openai-compatible" | "anthropic-compatible";
compatMode?: "cc";
chatPath: string;
hasApiType: boolean;
hasModelsPath: boolean;
hasWarning: boolean;
}
> = {
openai: {
baseUrl: "https://api.openai.com/v1",
type: "openai-compatible",
chatPath: "",
hasApiType: true,
hasModelsPath: true,
hasWarning: false,
},
anthropic: {
baseUrl: "https://api.anthropic.com/v1",
type: "anthropic-compatible",
chatPath: "",
hasApiType: false,
hasModelsPath: true,
hasWarning: false,
},
cc: {
baseUrl: "",
type: "anthropic-compatible",
compatMode: "cc",
chatPath: CC_DEFAULT_CHAT_PATH,
hasApiType: false,
hasModelsPath: false,
hasWarning: true,
},
};
function createInitialForm(mode: CompatibleMode): CompatibleFormState {
const defaults = MODE_DEFAULTS[mode];
return {
name: "",
prefix: "",
apiType: "chat",
baseUrl: defaults.baseUrl,
chatPath: defaults.chatPath,
modelsPath: "",
};
}
export default function AddCompatibleProviderModal({
isOpen,
mode,
title,
onClose,
onCreated,
}: AddCompatibleProviderModalProps) {
const t = useTranslations("providers");
const defaults = MODE_DEFAULTS[mode];
const [formData, setFormData] = useState<CompatibleFormState>(() => createInitialForm(mode));
const [submitting, setSubmitting] = useState(false);
const [checkKey, setCheckKey] = useState("");
const [checkModelId, setCheckModelId] = useState("");
const [validating, setValidating] = useState(false);
const [validationResult, setValidationResult] = useState<
null | { valid: boolean; error?: string | null; method?: string | null }
>(null);
const [showAdvanced, setShowAdvanced] = useState(false);
const apiTypeOptions = useMemo(
() => [
{ value: "chat", label: t("chatCompletions") },
{ value: "responses", label: t("responsesApi") },
{ value: "embeddings", label: t("embeddings") },
{ value: "audio-transcriptions", label: t("audioTranscriptions") },
{ value: "audio-speech", label: t("audioSpeech") },
{ value: "images-generations", label: t("imagesGenerations") },
],
[t]
);
useEffect(() => {
if (!isOpen) return;
setFormData(createInitialForm(mode));
setValidationResult(null);
setCheckKey("");
setShowAdvanced(false);
}, [isOpen, mode]);
const modalTitle =
title ||
(mode === "openai"
? t("addOpenAICompatible")
: mode === "anthropic"
? t("addAnthropicCompatible")
: t("addCcCompatible"));
const namePlaceholder =
mode === "cc"
? t("ccCompatibleNamePlaceholder")
: t("compatibleProdPlaceholder", {
type: mode === "openai" ? t("openai") : t("anthropic"),
});
const nameHint = mode === "cc" ? t("ccCompatibleNameHint") : t("nameHint");
const prefixPlaceholder =
mode === "openai"
? t("openaiPrefixPlaceholder")
: mode === "cc"
? t("ccCompatiblePrefixPlaceholder")
: t("anthropicPrefixPlaceholder");
const prefixHint = mode === "cc" ? t("ccCompatiblePrefixHint") : t("prefixHint");
const baseUrlPlaceholder =
mode === "openai"
? t("openaiBaseUrlPlaceholder")
: mode === "cc"
? t("ccCompatibleBaseUrlPlaceholder")
: t("anthropicBaseUrlPlaceholder");
const baseUrlHint =
mode === "cc"
? t("ccCompatibleBaseUrlHint")
: t("compatibleBaseUrlHint", {
type: mode === "openai" ? t("openai") : t("anthropic"),
});
const chatPathPlaceholder =
mode === "openai" ? "/v1/chat/completions" : mode === "cc" ? CC_DEFAULT_CHAT_PATH : "/messages";
const chatPathHint = mode === "cc" ? t("ccCompatibleChatPathHint") : t("chatPathHint");
const advancedId = `advanced-settings-${mode}`;
const hasRequiredFields = Boolean(
formData.name.trim() && formData.prefix.trim() && formData.baseUrl.trim()
);
const canValidate = Boolean(checkKey.trim() && formData.baseUrl.trim());
const resetAfterCreate = () => {
setFormData(createInitialForm(mode));
setCheckKey("");
setValidationResult(null);
setShowAdvanced(false);
};
const handleSubmit = async () => {
if (!hasRequiredFields) return;
setSubmitting(true);
try {
const body: Record<string, unknown> = {
name: formData.name,
prefix: formData.prefix,
baseUrl: formData.baseUrl,
type: defaults.type,
chatPath: formData.chatPath || (mode === "cc" ? CC_DEFAULT_CHAT_PATH : ""),
};
if (defaults.hasApiType) body.apiType = formData.apiType;
if (defaults.hasModelsPath) body.modelsPath = formData.modelsPath || "";
if (defaults.compatMode) body.compatMode = defaults.compatMode;
const res = await fetch("/api/provider-nodes", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = (await res.json()) as { node: CompatibleProviderNode };
if (res.ok) {
onCreated(data.node);
resetAfterCreate();
}
} catch (error) {
console.log(`Error creating ${mode} compatible node:`, error);
} finally {
setSubmitting(false);
}
};
const handleValidate = async () => {
setValidating(true);
try {
const body: Record<string, unknown> = {
baseUrl: formData.baseUrl,
apiKey: checkKey,
type: defaults.type,
};
if (defaults.hasModelsPath) body.modelsPath = formData.modelsPath || "";
if (defaults.compatMode) {
body.compatMode = defaults.compatMode;
body.chatPath = formData.chatPath || CC_DEFAULT_CHAT_PATH;
}
const trimmedModelId = checkModelId.trim();
if (trimmedModelId) body.modelId = trimmedModelId;
const res = await fetch("/api/provider-nodes/validate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json();
setValidationResult({
valid: !!data.valid,
error: data.error ?? null,
method: data.method ?? null,
});
} catch {
setValidationResult({ valid: false, error: "Network error" });
} finally {
setValidating(false);
}
};
return (
<Modal isOpen={isOpen} title={modalTitle} onClose={onClose}>
<div className="flex flex-col gap-4">
{defaults.hasWarning && (
<div className="rounded-lg border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-sm text-text-muted">
<div className="flex items-start gap-2">
<span className="material-symbols-outlined mt-0.5 text-[18px] text-amber-500">
warning
</span>
<p>{t("ccCompatibleValidationHint")}</p>
</div>
</div>
)}
<Input
label={t("nameLabel")}
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder={namePlaceholder}
hint={nameHint}
/>
<Input
label={t("prefixLabel")}
value={formData.prefix}
onChange={(e) => setFormData({ ...formData, prefix: e.target.value })}
placeholder={prefixPlaceholder}
hint={prefixHint}
/>
{defaults.hasApiType && (
<Select
label={t("apiTypeLabel")}
options={apiTypeOptions}
value={formData.apiType}
onChange={(e) => setFormData({ ...formData, apiType: e.target.value })}
/>
)}
<Input
label={t("baseUrlLabel")}
value={formData.baseUrl}
onChange={(e) => setFormData({ ...formData, baseUrl: e.target.value })}
placeholder={baseUrlPlaceholder}
hint={baseUrlHint}
/>
<button
type="button"
className="text-sm text-text-muted hover:text-text-primary flex items-center gap-1"
onClick={() => setShowAdvanced(!showAdvanced)}
aria-expanded={showAdvanced}
aria-controls={advancedId}
>
<span
className={`transition-transform ${showAdvanced ? "rotate-90" : ""}`}
aria-hidden="true"
>
{">"}
</span>
{t("advancedSettings")}
</button>
{showAdvanced && (
<div id={advancedId} className="flex flex-col gap-3 pl-2 border-l-2 border-border">
<Input
label={t("chatPathLabel")}
value={formData.chatPath}
onChange={(e) => setFormData({ ...formData, chatPath: e.target.value })}
placeholder={chatPathPlaceholder}
hint={chatPathHint}
/>
{defaults.hasModelsPath && (
<Input
label={t("modelsPathLabel")}
value={formData.modelsPath}
onChange={(e) => setFormData({ ...formData, modelsPath: e.target.value })}
placeholder={t("modelsPathPlaceholder")}
hint={t("modelsPathHint")}
/>
)}
</div>
)}
<div className="flex gap-2">
<Input
label={t("apiKeyForCheck")}
type="password"
value={checkKey}
onChange={(e) => setCheckKey(e.target.value)}
className="flex-1"
/>
<div className="pt-6">
<Button
onClick={handleValidate}
disabled={!canValidate || validating}
variant="secondary"
>
{validating ? t("checking") : t("check")}
</Button>
</div>
</div>
<Input
label={t("testModelIdLabel")}
value={checkModelId}
onChange={(e) => setCheckModelId(e.target.value)}
placeholder={t("testModelIdPlaceholder")}
hint={t("testModelIdHint")}
/>
{validationResult && (
<div className="flex flex-col gap-1">
<Badge variant={validationResult.valid ? "success" : "error"}>
{validationResult.valid ? t("valid") : t("invalid")}
</Badge>
{validationResult.error && (
<span
className={`text-sm ${validationResult.valid ? "text-text-muted" : "text-red-500"}`}
>
{validationResult.error}
</span>
)}
</div>
)}
<div className="flex gap-2">
<Button onClick={handleSubmit} fullWidth disabled={!hasRequiredFields || submitting}>
{submitting ? t("creating") : t("add")}
</Button>
<Button onClick={onClose} variant="ghost" fullWidth>
{t("cancel")}
</Button>
</div>
</div>
</Modal>
);
}
|