Files
mnote/wolai-frontend/convex/_utils/lightrag.ts
T
2026-01-18 05:13:53 +08:00

48 lines
1.4 KiB
TypeScript

type IngestTextArgs = {
fileSource: string;
text: string;
};
export async function lightragIngestText(args: IngestTextArgs): Promise<{ trackId: string | null }> {
const baseUrl = (process.env.LIGHTRAG_URL || "").trim().replace(/\/+$/, "");
if (!baseUrl) {
throw new Error("缺少环境变量:LIGHTRAG_URL");
}
const fileSource = String(args.fileSource ?? "").trim();
if (!fileSource) {
throw new Error("缺少 fileSource");
}
const text = String(args.text ?? "");
if (!text.trim()) {
return { trackId: null };
}
const apiKey = (process.env.LIGHTRAG_API_KEY || "").trim();
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (apiKey) {
headers["X-API-Key"] = apiKey;
}
// 说明:LightRAG(>=1.4.x) 使用 /documents/text 作为“文本入库”接口。
const resp = await fetch(`${baseUrl}/documents/text`, {
method: "POST",
headers,
body: JSON.stringify({ text, file_source: fileSource }),
});
if (!resp.ok) {
const raw = await resp.text().catch(() => "");
throw new Error(`LightRAG 入库失败:HTTP ${resp.status} ${raw.slice(0, 500)}`);
}
const data = (await resp.json().catch(() => null)) as unknown;
const trackId = (() => {
if (!data || typeof data !== "object") return null;
const v = (data as Record<string, unknown>).track_id;
return typeof v === "string" ? v : null;
})();
return { trackId };
}