-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathSynthesisTaskTab.tsx
More file actions
582 lines (562 loc) · 19.6 KB
/
SynthesisTaskTab.tsx
File metadata and controls
582 lines (562 loc) · 19.6 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
import { useState, useEffect } from "react";
import { Card, Button, Table, Modal, message, Tooltip, Form, Input, Select } from "antd";
import {
Plus,
ArrowUp,
ArrowDown,
Sparkles,
} from "lucide-react";
import { FolderOpenOutlined, DeleteOutlined, EyeOutlined, ExperimentOutlined } from "@ant-design/icons";
import { Link, useNavigate } from "react-router";
import { useTranslation } from "react-i18next";
import { SearchControls } from "@/components/SearchControls";
import { formatDateTime } from "@/utils/unit";
import {
querySynthesisTasksUsingGet,
deleteSynthesisTaskByIdUsingDelete,
archiveSynthesisTaskToDatasetUsingPost,
} from "@/pages/SynthesisTask/synthesis-api";
import { createDatasetUsingPost } from "@/pages/DataManagement/dataset.api";
import { createEvaluationTaskUsingPost } from "@/pages/DataEvaluation/evaluation.api";
import { queryModelListUsingGet } from "@/pages/SettingsPage/settings.apis";
import { ModelI } from "@/pages/SettingsPage/ModelAccess";
interface SynthesisTask {
id: string;
name: string;
description?: string;
status: string;
synthesis_type: string;
model_id: string;
progress?: number;
result_data_location?: string;
text_split_config?: {
chunk_size: number;
chunk_overlap: number;
};
synthesis_config?: {
temperature?: number | null;
prompt_template?: string;
synthesis_count?: number | null;
};
source_file_id?: string[];
total_files?: number;
processed_files?: number;
total_chunks?: number;
processed_chunks?: number;
total_synthesis_data?: number;
created_at: string;
updated_at?: string;
created_by?: string;
updated_by?: string;
}
export default function SynthesisTaskTab() {
const { t } = useTranslation();
const navigate = useNavigate();
const [searchQuery, setSearchQuery] = useState("");
const [tasks, setTasks] = useState<SynthesisTask[]>([]);
const [filterStatus, setFilterStatus] = useState("all");
const [sortBy, setSortBy] = useState<"createdAt" | "name">("createdAt");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [evalModalVisible, setEvalModalVisible] = useState(false);
const [currentEvalTask, setCurrentEvalTask] = useState<SynthesisTask | null>(null);
const [evalLoading, setEvalLoading] = useState(false);
const [models, setModels] = useState<ModelI[]>([]);
const [modelLoading, setModelLoading] = useState(false);
const [archiveModalVisible, setArchiveModalVisible] = useState(false);
const [currentArchiveTask, setCurrentArchiveTask] = useState<SynthesisTask | null>(null);
const [archiveFormat, setArchiveFormat] = useState<string>("alpaca");
const [evalForm] = Form.useForm();
// 获取任务列表
const loadTasks = async () => {
setLoading(true);
try {
const params = {
page: page,
page_size: pageSize,
} as {
page?: number;
page_size?: number;
synthesis_type?: string;
status?: string;
name?: string;
};
if (searchQuery) params.name = searchQuery;
if (filterStatus !== "all") params.synthesis_type = filterStatus;
const res = await querySynthesisTasksUsingGet(params);
setTasks(res?.data?.content || []);
setTotal(res?.data?.totalElements || 0);
} catch {
setTasks([]);
setTotal(0);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadTasks();
// eslint-disable-next-line
}, [searchQuery, filterStatus, page, pageSize]);
// 类型映射
const typeMap: Record<string, string> = {
QA: t('synthesisTask.home.typeMap.qa'),
COT: t('synthesisTask.home.typeMap.cot'),
};
// 表格列
const ellipsisStyle = {
maxWidth: 100,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
display: "inline-block",
verticalAlign: "middle",
};
const taskColumns = [
{
title: (
<Button
type="text"
onClick={() => {
if (sortBy === "name") {
setSortOrder(sortOrder === "asc" ? "desc" : "asc");
} else {
setSortBy("name");
setSortOrder("desc");
}
}}
className="h-auto p-0 font-semibold text-gray-700 hover:bg-transparent"
>
{t('synthesisTask.home.columns.taskName')}
{sortBy === "name" &&
(sortOrder === "asc" ? (
<ArrowUp className="w-3 h-3 ml-1" />
) : (
<ArrowDown className="w-3 h-3 ml-1" />
))}
</Button>
),
dataIndex: "name",
key: "name",
fixed: "left" as const,
width: 160,
render: (_: unknown, task: SynthesisTask) => (
<div className="flex items-center gap-3">
<div className="w-8 h-8 bg-blue-500 rounded-lg flex items-center justify-center shadow-sm">
<span className="text-white font-bold text-base">
{task.synthesis_type?.toUpperCase()?.slice(0, 1) || "T"}
</span>
</div>
<Tooltip title={task.name} placement="top">
<div style={{ ...ellipsisStyle, maxWidth: 100 }}>
<Link to={`/data/synthesis/task/${task.id}`}>{task.name}</Link>
</div>
</Tooltip>
</div>
),
},
{
title: t('synthesisTask.home.columns.taskId'),
dataIndex: "id",
key: "id",
width: 140,
render: (id: string) => (
<Tooltip title={id} placement="top">
<span style={{ ...ellipsisStyle, maxWidth: 140 }}>{id}</span>
</Tooltip>
),
},
{
title: t('synthesisTask.home.columns.type'),
dataIndex: "synthesis_type",
key: "synthesis_type",
width: 100,
render: (type: string) => (
<Tooltip title={typeMap[type] || type} placement="top">
<span style={{ ...ellipsisStyle, maxWidth: 100 }}>{typeMap[type] || type}</span>
</Tooltip>
),
},
{
title: t('synthesisTask.home.columns.fileCount'),
dataIndex: "total_files",
key: "total_files",
width: 70,
render: (num: number, task: SynthesisTask) => (
<Tooltip title={num ?? (task.source_file_id?.length ?? 0)} placement="top">
<span style={{ ...ellipsisStyle, maxWidth: 70 }}>{num ?? (task.source_file_id?.length ?? 0)}</span>
</Tooltip>
),
},
{
title: t('synthesisTask.home.columns.createdAt'),
dataIndex: "created_at",
key: "created_at",
width: 200,
render: (val: string) => (
<Tooltip title={formatDateTime(val)} placement="top">
<span style={{ ...ellipsisStyle, maxWidth: 200 }}>{formatDateTime(val)}</span>
</Tooltip>
),
},
{
title: t('synthesisTask.home.columns.actions'),
key: "actions",
fixed: "right" as const,
width: 160,
render: (_: unknown, task: SynthesisTask) => (
<div className="flex items-center justify-start gap-1">
<Tooltip title={t('synthesisTask.actions.viewDetail')}>
<Button
onClick={() => navigate(`/data/synthesis/task/${task.id}`)}
className="hover:bg-blue-50 p-1 h-7 w-7 flex items-center justify-center"
type="text"
icon={<EyeOutlined />}
/>
</Tooltip>
<Tooltip title={t('synthesisTask.actions.evaluate')}>
<Button
type="text"
className="hover:bg-purple-50 p-1 h-7 w-7 flex items-center justify-center text-purple-600"
icon={<ExperimentOutlined />}
onClick={() => openEvalModal(task)}
/>
</Tooltip>
<Tooltip title={t('synthesisTask.actions.archive')}>
<Button
type="text"
className="hover:bg-green-50 p-1 h-7 w-7 flex items-center justify-center text-green-600"
icon={<FolderOpenOutlined />}
onClick={() => openArchiveModal(task)}
/>
</Tooltip>
<Tooltip title={t('synthesisTask.actions.delete')}>
<Button
danger
type="text"
className="hover:bg-red-50 p-1 h-7 w-7 flex items-center justify-center"
icon={<DeleteOutlined />}
onClick={() => {
Modal.confirm({
title: t('synthesisTask.home.confirm.deleteTitle'),
content: t('synthesisTask.home.confirm.deleteDesc', { name: task.name }),
okText: t('dataManagement.confirm.deleteConfirm'),
okType: "danger",
cancelText: t('dataManagement.confirm.deleteCancel'),
onOk: async () => {
try {
await deleteSynthesisTaskByIdUsingDelete(task.id);
message.success(t('synthesisTask.messages.deleteSuccess'));
loadTasks();
} catch {
message.error(t('synthesisTask.messages.deleteFailed'));
}
},
});
}}
/>
</Tooltip>
</div>
),
},
];
const handleArchiveTask = async (task: SynthesisTask, format: string = "alpaca") => {
try {
const randomSuffix = Math.random().toString(36).slice(2, 8);
const datasetReq: {
name: string;
description: string;
datasetType: string;
category: string;
format: string;
status: string;
} = {
name: `${task.name}-合成数据留用${randomSuffix}`,
description: `由合成任务 ${task.id} 留用生成`,
datasetType: "TEXT",
category: "SYNTHESIS",
format: "JSONL",
status: "DRAFT",
};
const datasetRes = await createDatasetUsingPost(datasetReq);
const datasetId = datasetRes?.data?.id;
if (!datasetId) {
message.error(t('synthesisTask.home.archive.datasetFailed'));
return;
}
await archiveSynthesisTaskToDatasetUsingPost(task.id, datasetId, format);
message.success(t('synthesisTask.home.archive.success'));
navigate(`/data/management/detail/${datasetId}`);
} catch (e) {
console.error(e);
message.error(t('synthesisTask.home.archive.failed'));
}
};
const openArchiveModal = (task: SynthesisTask) => {
setCurrentArchiveTask(task);
setArchiveFormat("alpaca");
setArchiveModalVisible(true);
};
const handleArchiveConfirm = async () => {
if (!currentArchiveTask) return;
setArchiveModalVisible(false);
await handleArchiveTask(currentArchiveTask, archiveFormat);
};
const openEvalModal = (task: SynthesisTask) => {
setCurrentEvalTask(task);
setEvalModalVisible(true);
evalForm.setFieldsValue({
name: `${task.name}-数据评估`,
taskType: task.synthesis_type || "QA",
evalMethod: "AUTO",
});
// 懒加载模型列表
if (!models.length) {
loadModels();
}
};
const loadModels = async () => {
try {
setModelLoading(true);
const { data } = await queryModelListUsingGet({ page: 0, size: 1000 });
setModels(data?.content || []);
} catch (e) {
console.error(e);
message.error(t('synthesisTask.messages.fetchModelsFailed'));
} finally {
setModelLoading(false);
}
};
const chatModelOptions = models
.filter((m) => m.type === "CHAT")
.map((m) => ({
label: `${m.modelName} (${m.provider})`,
value: m.id,
}));
const handleCreateEvaluation = async () => {
if (!currentEvalTask) return;
try {
const values = await evalForm.validateFields();
setEvalLoading(true);
const taskType = currentEvalTask.synthesis_type || "QA";
const payload = {
name: values.name,
taskType,
evalMethod: values.evalMethod,
sourceType: "SYNTHESIS",
sourceId: currentEvalTask.id,
sourceName: currentEvalTask.name,
evalConfig: {
modelId: values.modelId,
dimensions: [
{
dimension: "问题是否独立",
description:
"仅分析问题,问题的主体和客体都比较明确,即使有省略,也符合语言习惯。在不需要补充其他信息的情况下不会引起疑惑。",
},
{
dimension: "语法是否错误",
description:
"问题为疑问句,答案为陈述句; 不存在词语搭配不当的情况;连接词和标点符号不存在错用情况;逻辑混乱的情况不存在;语法结构都正确且完整。",
},
{
dimension: "回答是否有针对性",
description:
"回答应对问题中的所有疑问点提供正面、直接的回答,不应引起疑惑。同时,答案不应有任何内容的遗漏,需构成一个完整的陈述。",
},
],
},
};
await createEvaluationTaskUsingPost(payload);
message.success(t('synthesisTask.messages.evaluationCreated'));
setEvalModalVisible(false);
setCurrentEvalTask(null);
evalForm.resetFields();
} catch (error) {
const err = error as { errorFields?: unknown; response?: { data?: { message?: string } } };
if (err?.errorFields) return; // 表单校验错误
message.error(err?.response?.data?.message || t('synthesisTask.messages.evaluationCreateFailed'));
} finally {
setEvalLoading(false);
}
};
return (
<div className="space-y-4">
{/* 搜索和筛选 */}
<SearchControls
searchTerm={searchQuery}
onSearchChange={setSearchQuery}
searchPlaceholder={t('synthesisTask.home.searchPlaceholder')}
filters={[
{
key: "status",
label: t('synthesisTask.home.filters.type'),
options: [
{ label: t('synthesisTask.home.filters.allTypes'), value: "all" },
{ label: t('synthesisTask.home.typeMap.qa'), value: "QA" },
{ label: t('synthesisTask.home.typeMap.cot'), value: "COT" },
],
},
]}
selectedFilters={{ status: [filterStatus] }}
onFiltersChange={(filters) => {
setFilterStatus(filters.status?.[0] || "all");
}}
showFilters
showViewToggle={false}
/>
{/* 任务表格 */}
<Card>
<Table
columns={taskColumns}
dataSource={tasks}
rowKey="id"
loading={loading}
pagination={{
current: page,
pageSize: pageSize,
total: total,
onChange: (p, ps) => {
setPage(p);
setPageSize(ps);
},
showSizeChanger: true,
}}
scroll={{ x: "max-content" }}
locale={{
emptyText: (
<div className="text-center py-12">
<Sparkles className="w-12 h-12 text-gray-400 mx-auto mb-3" />
<h3 className="text-base font-semibold text-gray-900 mb-2">
{searchQuery ? t('synthesisTask.home.empty.noMatch') : t('synthesisTask.home.empty.title')}
</h3>
<p className="text-gray-500 mb-4 text-sm">
{searchQuery ? t('synthesisTask.home.empty.noMatch') : t('synthesisTask.home.empty.createFirst')}
</p>
{!searchQuery && filterStatus === "all" && (
<Button
onClick={() => navigate("/data/synthesis/task/create")}
className="bg-gradient-to-r from-blue-500 to-indigo-500 hover:from-blue-600 hover:to-indigo-600 shadow-lg"
>
<Plus className="w-3 h-3 mr-1" />
{t('synthesisTask.actions.createSynthesisTask')}
</Button>
)}
</div>
),
}}
/>
</Card>
<Modal
title={t('synthesisTask.home.confirm.archiveTitle')}
open={archiveModalVisible}
onCancel={() => {
setArchiveModalVisible(false);
setCurrentArchiveTask(null);
}}
onOk={handleArchiveConfirm}
okText={t('synthesisTask.actions.archive')}
cancelText={t('synthesisTask.actions.cancel')}
>
<div>
<p>{t('synthesisTask.home.confirm.archiveContent', { name: currentArchiveTask?.name })}</p>
<div style={{ marginTop: 16 }}>
<span style={{ marginRight: 8 }}>导出格式:</span>
<Select
value={archiveFormat}
style={{ width: 120 }}
options={[
{ label: "Alpaca", value: "alpaca" },
{ label: "ShareGPT", value: "sharegpt" },
{ label: "原始格式", value: "raw" },
]}
onChange={(value) => {
setArchiveFormat(value);
}}
/>
</div>
</div>
</Modal>
<Modal
title={t('synthesisTask.home.modal.evalTitle')}
open={evalModalVisible}
onCancel={() => {
setEvalModalVisible(false);
setCurrentEvalTask(null);
evalForm.resetFields();
}}
onOk={handleCreateEvaluation}
confirmLoading={evalLoading}
okText={t('synthesisTask.home.modal.startEval')}
cancelText={t('synthesisTask.actions.cancel')}
>
<Form
form={evalForm}
layout="vertical"
initialValues={{
evalMethod: "AUTO",
}}
>
<Form.Item
label={t('synthesisTask.home.modal.evalName')}
name="name"
rules={[{ required: true, message: t('synthesisTask.home.modal.evalNameRequired') }]}
>
<Input placeholder={t('synthesisTask.home.modal.placeholders.evalName')} />
</Form.Item>
<Form.Item
label={t('synthesisTask.home.modal.taskType')}
name="taskType"
>
<Select
disabled
options={[
{
label:
currentEvalTask?.synthesis_type === "COT"
? t('synthesisTask.home.modal.evalMethod.cot')
: t('synthesisTask.home.modal.evalMethod.qa'),
value: currentEvalTask?.synthesis_type || "QA",
},
]}
/>
</Form.Item>
<Form.Item
label={t('synthesisTask.home.modal.evalMethod')}
name="evalMethod"
rules={[{ required: true, message: t('synthesisTask.home.modal.evalMethodRequired') }]}
>
<Select
options={[
{ label: t('synthesisTask.home.modal.evalMethod.auto'), value: "AUTO" },
]}
/>
</Form.Item>
<Form.Item
label="评估模型"
name="modelId"
rules={[{ required: true, message: "请选择评估模型" }]}
>
<Select
placeholder={modelLoading ? "加载模型中..." : "请选择用于评估的模型"}
loading={modelLoading}
options={chatModelOptions}
showSearch
optionFilterProp="label"
/>
</Form.Item>
{currentEvalTask && (
<Form.Item label="评估对象">
<div className="text-xs text-gray-500">
源类型:合成任务(SYNTHESIS)<br />
源名称:{currentEvalTask.name}
</div>
</Form.Item>
)}
</Form>
</Modal>
</div>
);
}