rag-api.ts
4.45 KB
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
import type { RagChunk, RagFile } from "./rag-types";
// 统一走同源 /api(由 src/app/api/[...path]/route.ts 流式代理到后端)
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "/api";
export async function fetchRagFiles(search = ""): Promise<{ files: RagFile[]; total: number }> {
const res = await fetch(`${API_BASE}/rag/files?page=1&page_size=100&search=${encodeURIComponent(search)}`);
if (!res.ok) throw new Error("获取 RAG 文件列表失败");
return res.json();
}
export async function uploadRagFiles(files: File[]) {
const init = await fetch(`${API_BASE}/rag/upload/init`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ files: files.map((file) => ({ name: file.name })) }),
});
const initData = await init.json();
if (!init.ok) throw new Error(initData.detail || "初始化上传失败");
for (const file of files) {
const fileId = initData.mapping[file.name];
if (!fileId) continue;
const form = new FormData();
form.append("file", file);
const res = await fetch(`${API_BASE}/rag/upload/${encodeURIComponent(fileId)}`, { method: "POST", body: form });
if (!res.ok) throw new Error(`${file.name} 上传失败`);
}
return initData;
}
export async function postRagAction(path: string, body?: Record<string, unknown>) {
const options: RequestInit = { method: "POST" };
if (body) {
options.headers = { "Content-Type": "application/json" };
options.body = JSON.stringify(body);
}
const res = await fetch(`${API_BASE}${path}`, options);
if (!res.ok) {
const text = await res.text();
let detail = "操作失败";
try {
const data = JSON.parse(text);
detail = data.detail || data.error || detail;
} catch {}
throw new Error(detail);
}
return res.json();
}
export async function deleteRagAction(path: string) {
const res = await fetch(`${API_BASE}${path}`, { method: "DELETE" });
if (!res.ok) {
const text = await res.text();
let detail = "操作失败";
try {
const data = JSON.parse(text);
detail = data.detail || data.error || detail;
} catch {}
throw new Error(detail);
}
return res.json();
}
export async function fetchRagChunks(fileId: string): Promise<RagChunk[]> {
const res = await fetch(`${API_BASE}/rag/chunks/${encodeURIComponent(fileId)}`);
if (!res.ok) throw new Error("获取切片失败");
const data = await res.json();
return data.chunks || [];
}
export async function fetchRagStats() {
const res = await fetch(`${API_BASE}/rag/stats`);
if (!res.ok) throw new Error("获取统计失败");
return res.json();
}
export function streamRagQuery(
payload: { query: string; history: { role: string; content: string }[]; sessionId: string },
onEvent: (event: { type: string; content?: string; data?: unknown }) => void,
) {
const controller = new AbortController();
fetch(`${API_BASE}/rag/query`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
signal: controller.signal,
})
.then(async (res) => {
if (!res.ok) throw new Error(await res.text());
if (!res.body) throw new Error("浏览器不支持流式响应");
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const events = buffer.split("\n\n");
buffer = events.pop() || "";
for (const raw of events) {
const line = raw.split("\n").find((item) => item.startsWith("data: "));
if (!line) continue;
const data = line.slice(6);
if (data === "[INIT]") continue;
if (data === "[DONE]") continue;
onEvent(JSON.parse(data));
}
}
})
.catch((error) => {
if (error instanceof Error && error.name === "AbortError") return;
onEvent({ type: "error", content: error instanceof Error ? error.message : String(error) });
});
return controller;
}
export async function fetchRagChunk(chunkId: string): Promise<RagChunk> {
const res = await fetch(`${API_BASE}/rag/chunk/${encodeURIComponent(chunkId)}`);
if (!res.ok) throw new Error("获取片段详情失败");
const data = await res.json();
return data.chunk;
}
export async function clearRagHistory(sessionId: string) {
return postRagAction("/rag/clear_history", { sessionId });
}