rag-api.ts 4.45 KB
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 });
}