%PDF- %PDF-
| Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/ |
| Current File : //home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/useModels.ts |
import { useCallback, useEffect, useState } from "react";
import { apiRequest } from "@/lib/api";
import type { ModelInfo, TestModelResponse } from "@/types/api";
const CACHE_KEY = "models.list.v1";
const CACHE_TTL_MS = 60_000;
interface CacheEntry {
at: number;
models: ModelInfo[];
}
function readCache(): ModelInfo[] | null {
try {
const raw = sessionStorage.getItem(CACHE_KEY);
if (!raw) return null;
const entry = JSON.parse(raw) as CacheEntry;
if (!entry || typeof entry.at !== "number" || !Array.isArray(entry.models))
return null;
if (Date.now() - entry.at > CACHE_TTL_MS) return null;
return entry.models;
} catch {
return null;
}
}
function writeCache(models: ModelInfo[]) {
try {
const entry: CacheEntry = { at: Date.now(), models };
sessionStorage.setItem(CACHE_KEY, JSON.stringify(entry));
} catch {
/* abaikan (sessionStorage penuh / tidak tersedia) */
}
}
export function useModels() {
const [models, setModels] = useState<ModelInfo[]>(() => readCache() ?? []);
const [loading, setLoading] = useState(() => readCache() === null);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
const cached = readCache();
if (cached) {
setModels(cached);
setError(null);
setLoading(false);
return;
}
setLoading(true);
apiRequest<{ models: ModelInfo[] }>("/me/models")
.then((res) => {
setModels(res.models);
writeCache(res.models);
setError(null);
})
.catch((e: Error) => setError(e.message))
.finally(() => setLoading(false));
}, []);
useEffect(() => {
load();
}, [load]);
const test = useCallback(
async (model: string, prompt: string): Promise<TestModelResponse> => {
const res = await apiRequest<TestModelResponse>("/me/test-model", {
method: "POST",
body: {
model,
messages: [{ role: "user", content: prompt }],
},
});
return res;
},
[],
);
return { models, loading, error, refresh: load, test };
}