api.ts 10.2 KB
import type {
  ChunkRecord, ConfigResponse, DataSource, DocumentItem, DuplicatePair, EdgeDetail,
  GraphPayload, GraphStats, InfoResponse, JobItem, NodeDetail, OntologyResponse,
  ProbeResult, ProbeTable, QueryBrief, SmMetric, SmMetricIssue, SmModel, SmRelation,
  SqlIssue, SqlPair, SqlRelationRec, SqlThread, SqlThreadTurn,
} from "./types";


/** 接口返回里的数组字段缺了就补空数组(图谱节点的别名、出处等老数据可能没有)。 */
function fillArrays<T>(obj: T, keys: string[]): T {
  if (!obj || typeof obj !== "object") return obj;
  const o: any = { ...(obj as any) };
  for (const k of keys) if (!Array.isArray(o[k])) o[k] = [];
  return o as T;
}

export class ApiError extends Error {
  constructor(message: string, readonly status: number, readonly kind?: string) {
    super(message);
  }
}

async function req<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(path, init);
  if (!res.ok) {
    let detail = `HTTP ${res.status}`;
    let kind: string | undefined;
    try {
      const body = await res.json();
      detail = body.detail ?? detail;
      kind = body.kind;
    } catch {
      /* 非 JSON 错误体,保留状态码文案 */
    }
    throw new ApiError(detail, res.status, kind);
  }
  if (res.status === 204) return undefined as T;
  const ct = res.headers.get("content-type") ?? "";
  return (ct.includes("json") ? res.json() : res.text()) as Promise<T>;
}

const json = (body: unknown): RequestInit => ({
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

const put = (body: unknown): RequestInit => ({ ...json(body), method: "PUT" });

export const api = {
  info: () => req<InfoResponse>("/api/info"),
  overview: () => req<{
    info: InfoResponse; documents: DocumentItem[]; jobs: JobItem[];
    queries: QueryBrief[]; communities: { id: number; title: string; size: number; summary: string }[];
  }>("/api/overview"),

  // 文档
  documents: () => req<DocumentItem[]>("/api/documents"),
  document: (id: number) => req<DocumentItem>(`/api/documents/${id}`),
  upload: (file: File, onProgress?: (pct: number) => void) =>
    new Promise<DocumentItem>((resolve, reject) => {
      const fd = new FormData();
      fd.append("file", file);
      const xhr = new XMLHttpRequest();
      xhr.open("POST", "/api/documents");
      xhr.upload.onprogress = (e) => {
        if (e.lengthComputable) onProgress?.(Math.round((e.loaded / e.total) * 100));
      };
      xhr.onload = () => {
        let body: any = {};
        try { body = JSON.parse(xhr.responseText); } catch { /* ignore */ }
        if (xhr.status >= 200 && xhr.status < 300) resolve(body);
        else reject(new ApiError(body.detail ?? `HTTP ${xhr.status}`, xhr.status, body.kind));
      };
      xhr.onerror = () => reject(new ApiError("网络错误,上传失败", 0));
      xhr.send(fd);
    }),
  startExtract: (id: number) =>
    req<{ job_id: number; already_running: boolean; queue_depth?: number }>(
      `/api/documents/${id}/extract`, { method: "POST" }),
  deleteDocument: (id: number) =>
    req<{ ok: boolean; removed_chunks: number }>(
      `/api/documents/${id}`, { method: "DELETE" }),
  documentChunks: (id: number, preview = false) =>
    req<{ preview: boolean; encoding?: string; warnings?: string[]; chunks: ChunkRecord[] }>(
      `/api/documents/${id}/chunks?preview=${preview}`),
  documentContent: (id: number) =>
    req<{ text: string; encoding?: string; warnings?: string[]; filename?: string }>(
      `/api/documents/${id}/content`),

  // 任务
  jobs: (limit = 20) => req<JobItem[]>(`/api/jobs?limit=${limit}`),
  job: (id: number) => req<JobItem>(`/api/jobs/${id}`),

  // 原文片段(提问的推理链里点证据看原文)
  chunk: (id: string) => req<ChunkRecord>(`/api/ask/chunk?id=${encodeURIComponent(id)}`),

  // 设置
  config: () => req<ConfigResponse>("/api/config"),
  saveConfig: (items: Record<string, string>) =>
    req<{ ok: boolean; saved: string[] }>("/api/config", put({ items })),
  clearCache: () => req<{ ok: boolean }>("/api/cache/clear", { method: "POST" }),

  // 数据问答
  sqlMeta: () => req<{ supported_types: string[]; crypto_ready: boolean; row_limit: number; timeout_ms: number }>(
    "/api/sql/meta"),

  datasources: () => req<DataSource[]>("/api/sql/datasources"),
  createDatasource: (body: Record<string, unknown>) => req<DataSource>("/api/sql/datasources", json(body)),
  /** 本地文件数据源:CSV / Excel / JSON 导入成只读 SQLite。传 dsId 表示追加到已有的文件数据源。 */
  createFileDatasource: (name: string, files: File[], dsId = 0) => {
    const fd = new FormData();
    fd.append("name", name);
    fd.append("ds_id", String(dsId));
    files.forEach((f) => fd.append("files", f));
    return req<DataSource & { imported: { table: string; file: string; rows: number; columns: number }[] }>(
      "/api/sql/datasources/file", { method: "POST", body: fd });
  },
  updateDatasource: (id: number, body: Record<string, unknown>) =>
    req<DataSource>(`/api/sql/datasources/${id}`, put(body)),
  deleteDatasource: (id: number) =>
    req<{ ok: boolean }>(`/api/sql/datasources/${id}`, { method: "DELETE" }),
  testDatasource: (id: number) =>
    req<{ version: string; database: string; table_count: number; account_writable: boolean | null; warning?: string }>(
      `/api/sql/datasources/${id}/test`, { method: "POST" }),
  introspect: (id: number, resample = false) =>
    req<{ job_id: number; queued: boolean; queue_depth: number }>(
      `/api/sql/datasources/${id}/introspect?resample=${resample}`, { method: "POST" }),

  sqlModels: (dsId: number, enabledOnly = false) =>
    req<SmModel[]>(`/api/sql/datasources/${dsId}/models?enabled_only=${enabledOnly}`),
  updateSqlModel: (id: number, body: Record<string, unknown>) =>
    req<{ ok: boolean }>(`/api/sql/models/${id}`, put(body)),
  updateSqlColumn: (id: number, body: Record<string, unknown>) =>
    req<{ ok: boolean }>(`/api/sql/columns/${id}`, put(body)),
  enableSqlModels: (dsId: number, ids: number[], enabled: boolean) =>
    req<{ ok: boolean; changed: number }>(
      `/api/sql/datasources/${dsId}/models/enable`, json({ ids, enabled })),

  sqlRelations: (dsId: number) => req<SmRelation[]>(`/api/sql/datasources/${dsId}/relations`),
  upsertSqlRelation: (dsId: number, body: Record<string, unknown>) =>
    req<{ ok: boolean; id: number }>(`/api/sql/datasources/${dsId}/relations`, json(body)),
  deleteSqlRelation: (id: number) =>
    req<{ ok: boolean }>(`/api/sql/relations/${id}`, { method: "DELETE" }),
  mdlUrl: (dsId: number) => `/api/sql/datasources/${dsId}/mdl`,

  describeSchema: (dsId: number, body: { overwrite?: boolean; model_ids?: number[] } = {}) =>
    req<{ job_id: number; queued: boolean; queue_depth: number }>(
      `/api/sql/datasources/${dsId}/describe`, json({ overwrite: false, model_ids: [], ...body })),
  recommendRelations: (dsId: number) =>
    req<SqlRelationRec[]>(`/api/sql/datasources/${dsId}/relations/recommend`),

  /** SQL 调试台的会话 */
  sqlThreads: (dsId: number) => req<SqlThread[]>(`/api/sql/threads?ds_id=${dsId}`),
  sqlThread: (id: string) => req<SqlThread & { turns: SqlThreadTurn[] }>(`/api/sql/threads/${encodeURIComponent(id)}`),
  createSqlThread: (dsId: number, title = "") => req<SqlThread>("/api/sql/threads", json({ ds_id: dsId, title })),
  renameSqlThread: (id: string, title: string) =>
    req<SqlThread>(`/api/sql/threads/${encodeURIComponent(id)}`, put({ title })),
  deleteSqlThread: (id: string) =>
    req<{ ok: boolean }>(`/api/sql/threads/${encodeURIComponent(id)}`, { method: "DELETE" }),

  /** 测试连接 + 列出表,不保存。编辑时口令留空、带 ds_id 就用已存口令 */
  probeDatasource: (body: Record<string, unknown>) => req<ProbeResult>("/api/sql/datasources/probe", json(body)),
  /** 已保存数据源库里的全部表(不受表范围限制),选表用 */
  datasourceTables: (dsId: number) => req<ProbeTable[]>(`/api/sql/datasources/${dsId}/tables`),

  sqlMetrics: (dsId: number) => req<SmMetric[]>(`/api/sql/datasources/${dsId}/metrics`),
  metricIssues: (dsId: number) => req<SmMetricIssue[]>(`/api/sql/datasources/${dsId}/metrics/issues`),

  validateSql: (body: { ds_id: number; sql: string; scope?: "ask" | "debug" }) =>
    req<{ ok: boolean; sql: string; limited: boolean; tables: string[]; issues: SqlIssue[] }>(
      "/api/sql/validate", json(body)),
  runSql: (body: { ds_id?: number; run_id?: number; sql: string; question?: string; thread_id?: string; origin_sql?: string; scope?: "ask" | "debug"; replaces?: number }) =>
    req<{
      ok: boolean; run_id: number; pair_id: number; columns: string[]; rows: unknown[][];
      row_count: number; duration_ms: number; truncated: boolean; sql: string;
      limited: boolean; issues: SqlIssue[];
    }>("/api/sql/run", json(body)),

  /** 按需解释一条 SQL。默认折叠着,展开了才值得花一轮大模型往返 */
  explainSql: (body: { ds_id: number; question: string; sql: string }) =>
    req<{ ok: boolean; text: string }>("/api/sql/explain", json(body)),

  /** 手改 SQL 重跑之后补一份结论。/run 不经管线,自然也不会自带结论 */
  summarize: (body: {
    ds_id: number; question: string; columns: string[]; rows: unknown[][]; row_count: number; run_id?: number;
  }) => req<{ ok: boolean; text: string }>("/api/sql/summarize", json(body)),

  rateSqlRun: (id: number, rating: number) =>
    req<{ ok: boolean }>(`/api/sql/runs/${id}/rate?rating=${rating}`, { method: "POST" }),

  sqlPairs: (p: { dsId?: number; status?: string; keyword?: string; limit?: number } = {}) => {
    const q = new URLSearchParams();
    if (p.dsId) q.set("ds_id", String(p.dsId));
    if (p.status) q.set("status", p.status);
    if (p.keyword) q.set("keyword", p.keyword);
    q.set("limit", String(p.limit ?? 100));
    return req<SqlPair[]>(`/api/sql/pairs?${q}`);
  },
  createSqlPair: (body: Record<string, unknown>) => req<{ ok: boolean; id: number }>("/api/sql/pairs", json(body)),
  updateSqlPair: (id: number, body: Record<string, unknown>) => req<SqlPair>(`/api/sql/pairs/${id}`, put(body)),
  adoptSqlPair: (id: number) => req<SqlPair>(`/api/sql/pairs/${id}/adopt`, { method: "POST" }),
  deleteSqlPair: (id: number) => req<{ ok: boolean }>(`/api/sql/pairs/${id}`, { method: "DELETE" }),

};