api.ts
12.7 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import type {
ChunkRecord, ConfigResponse, DataSource, DocumentItem, DuplicatePair, EdgeDetail,
GraphPayload, GraphStats, InfoResponse, JobItem, NodeDetail, OntologyResponse,
QueryBrief, SmInstruction, SmMetric, SmMetricIssue, SmModel, SmRelation,
SqlIssue, SqlPair, SqlRelationRec, SqlRunBrief,
} 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_entities: number; removed_relations: number; 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}`),
documentEntities: (id: number) =>
req<{ total: number; items: { id: string; label: string; type: string; degree: number; description: string }[] }>(
`/api/documents/${id}/entities`),
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}`),
// 图谱
graph: (p: {
type?: string; relation?: string; keyword?: string;
docId?: number | null; minDegree?: number; limit?: number;
}) => {
const q = new URLSearchParams();
if (p.type) q.set("type", p.type);
if (p.relation) q.set("relation", p.relation);
if (p.keyword) q.set("keyword", p.keyword);
if (p.docId != null) q.set("doc_id", String(p.docId));
if (p.minDegree) q.set("min_degree", String(p.minDegree));
q.set("limit", String(p.limit ?? 500));
return req<GraphPayload>(`/api/graph?${q}`);
},
ego: (node: string, hops = 1, limit = 300) =>
req<GraphPayload>(`/api/graph/ego?node=${encodeURIComponent(node)}&hops=${hops}&limit=${limit}`),
graphStats: () => req<GraphStats>("/api/graph/stats"),
searchNodes: (q: string, limit = 10) =>
req<{ id: string; label: string; type: string; degree: number; description: string; match: string }[]>(
`/api/graph/search?q=${encodeURIComponent(q)}&limit=${limit}`),
node: (id: string) => req<NodeDetail>(`/api/node?id=${encodeURIComponent(id)}`)
.then((n) => fillArrays(n, ["aliases", "out_edges", "in_edges", "sources"])),
updateNode: (body: { id: string; type?: string; description?: string; verified?: boolean }) =>
req<{ ok: boolean; node: NodeDetail }>("/api/node", put(body)),
createNode: (body: { id: string; type?: string; label?: string; description?: string }) =>
req<{ ok: boolean; node: NodeDetail }>("/api/node", json(body)),
edge: (source: string, target: string, relation: string) =>
req<EdgeDetail>(`/api/edge?source=${encodeURIComponent(source)}&target=${
encodeURIComponent(target)}&relation=${encodeURIComponent(relation)}`).then((e) => fillArrays(e, ["sources"])),
updateEdge: (body: { source: string; target: string; relation: string; description?: string; verified?: boolean }) =>
req<{ ok: boolean }>("/api/edge", put(body)),
createEdge: (body: { source: string; target: string; relation: string; description?: string }) =>
req<{ ok: boolean }>("/api/edge", json(body)),
duplicates: (limit = 200) => req<DuplicatePair[]>(`/api/graph/duplicates?limit=${limit}`),
mergeNodes: (keep: string, drop: string[]) =>
req<{ ok: boolean; merged: string[] }>("/api/graph/merge", json({ keep, drop })),
deleteNodes: (ids: string[]) =>
req<{ ok: boolean; removed: number }>("/api/graph/nodes/delete", json({ ids })),
clearGraph: () => req<{ ok: boolean }>("/api/graph/clear", { method: "POST" }),
exportUrl: (format: "json" | "graphml") => `/api/graph/export?format=${format}`,
// 原文片段(提问的推理链里点证据看原文)
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 })),
ontology: () => req<OntologyResponse>("/api/ontology"),
saveOntology: (entity_types: string[], relation_types: string[]) =>
req<{ ok: boolean }>("/api/ontology", put({ entity_types, relation_types })),
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`),
sqlMetrics: (dsId: number) => req<SmMetric[]>(`/api/sql/datasources/${dsId}/metrics`),
metricIssues: (dsId: number) => req<SmMetricIssue[]>(`/api/sql/datasources/${dsId}/metrics/issues`),
/** 给还没分类的规则补一个分类。只填空,不覆盖人工改过的(指标在本体里按函数类别组织) */
categorize: (dsId: number) =>
req<{ ok: boolean; instructions: number }>(`/api/sql/datasources/${dsId}/categorize`, { method: "POST" }),
sqlInstructions: (dsId = 0) => req<SmInstruction[]>(`/api/sql/instructions?ds_id=${dsId}`),
upsertInstruction: (body: Record<string, unknown>) =>
req<{ ok: boolean; id: number }>("/api/sql/instructions", json(body)),
deleteInstruction: (id: number) =>
req<{ ok: boolean }>(`/api/sql/instructions/${id}`, { method: "DELETE" }),
validateSql: (body: { ds_id: number; sql: string }) =>
req<{ ok: boolean; sql: string; limited: boolean; tables: string[]; issues: SqlIssue[] }>(
"/api/sql/validate", json(body)),
runSql: (body: { ds_id: number; sql: string; question?: string; thread_id?: string; origin_sql?: string }) =>
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;
}) => req<{ ok: boolean; text: string }>("/api/sql/summarize", json(body)),
sqlRuns: (dsId?: number, limit = 30) =>
req<SqlRunBrief[]>(`/api/sql/runs?limit=${limit}${dsId ? `&ds_id=${dsId}` : ""}`),
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" }),
};