importApi.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { API_BASE_URL, getAgentHeaders } from "@/lib/config";
  2. // 导入结果
  3. export interface ImportResult {
  4. success_count: number;
  5. failed_count: number;
  6. failed_files: string[];
  7. errors: string[];
  8. message?: string;
  9. }
  10. // 导入文档(文件上传)
  11. export async function importDocuments(
  12. knowledgeBaseId: number,
  13. files: File[]
  14. ): Promise<ImportResult> {
  15. const formData = new FormData();
  16. formData.append("knowledge_base_id", knowledgeBaseId.toString());
  17. for (const file of files) {
  18. formData.append("files", file);
  19. }
  20. const res = await fetch(`${API_BASE_URL}/import/documents`, {
  21. method: "POST",
  22. headers: getAgentHeaders(),
  23. body: formData,
  24. });
  25. if (!res.ok) {
  26. const error = await res.json().catch(() => ({}));
  27. throw new Error((error as { error?: string }).error || "导入文档失败");
  28. }
  29. const text = await res.text();
  30. if (!text || text.trim() === "") {
  31. throw new Error("服务器返回为空,请检查后端是否正常");
  32. }
  33. try {
  34. const data = JSON.parse(text) as ImportResult;
  35. return {
  36. success_count: data.success_count ?? 0,
  37. failed_count: data.failed_count ?? 0,
  38. failed_files: data.failed_files ?? [],
  39. errors: data.errors ?? [],
  40. message: data.message,
  41. };
  42. } catch {
  43. throw new Error("服务器返回格式错误,请检查后端接口");
  44. }
  45. }
  46. // 从 URL 导入文档
  47. export interface ImportFromUrlsRequest {
  48. knowledge_base_id: number;
  49. urls: string[];
  50. }
  51. export async function importFromUrls(data: ImportFromUrlsRequest): Promise<ImportResult> {
  52. const res = await fetch(`${API_BASE_URL}/import/urls`, {
  53. method: "POST",
  54. headers: { "Content-Type": "application/json", ...getAgentHeaders() },
  55. body: JSON.stringify(data),
  56. });
  57. if (!res.ok) {
  58. const error = await res.json().catch(() => ({}));
  59. throw new Error((error as { error?: string }).error || "导入 URL 失败");
  60. }
  61. const text = await res.text();
  62. if (!text || text.trim() === "") {
  63. throw new Error("服务器返回为空,请检查后端是否正常");
  64. }
  65. try {
  66. const data = JSON.parse(text) as ImportResult;
  67. return {
  68. success_count: data.success_count ?? 0,
  69. failed_count: data.failed_count ?? 0,
  70. failed_files: data.failed_files ?? [],
  71. errors: data.errors ?? [],
  72. message: data.message,
  73. };
  74. } catch {
  75. throw new Error("服务器返回格式错误,请检查后端接口");
  76. }
  77. }