Files
TJWaterFrontend_Refine/src/lib/chatModels.ts
T
jiang 7d2ae87e39
Build Push and Deploy / docker-image (push) Successful in 1m6s
Build Push and Deploy / deploy-fallback-log (push) Has been skipped
feat(chat): load model options from backend
2026-06-10 19:50:43 +08:00

75 lines
1.9 KiB
TypeScript

import { apiFetch } from "@/lib/apiFetch";
import { config } from "@config/config";
import type { AgentModel } from "./chatStream";
export type AgentModelIcon = "bolt" | "sparkle";
export type AgentModelOption = {
id: AgentModel;
label: string;
description?: string;
icon?: AgentModelIcon;
};
export type AgentModelConfig = {
defaultModel?: AgentModel;
models: AgentModelOption[];
};
const isObjectRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const normalizeModelOption = (value: unknown): AgentModelOption | null => {
if (!isObjectRecord(value) || typeof value.id !== "string") {
return null;
}
const id = value.id.trim();
if (!id) {
return null;
}
const label =
typeof value.label === "string" && value.label.trim()
? value.label.trim()
: id;
const description =
typeof value.description === "string" && value.description.trim()
? value.description.trim()
: undefined;
const icon =
value.icon === "bolt" || value.icon === "sparkle" ? value.icon : undefined;
return {
id,
label,
description,
icon,
};
};
export const fetchAgentModels = async (): Promise<AgentModelConfig> => {
const response = await apiFetch(`${config.AGENT_URL}/api/v1/agent/chat/models`, {
method: "GET",
projectHeaderMode: "include",
userHeaderMode: "include",
skipAuthRedirect: true,
});
if (!response.ok) {
throw new Error(await response.text());
}
const payload = (await response.json()) as {
default_model?: unknown;
models?: unknown[];
};
const models = (payload.models ?? [])
.map(normalizeModelOption)
.filter((model): model is AgentModelOption => Boolean(model));
const defaultModel =
typeof payload.default_model === "string" && payload.default_model.trim()
? payload.default_model.trim()
: models[0]?.id;
return {
defaultModel,
models,
};
};