@arcticdata/dsh-datarc-assistant 26.39.0 → 26.39.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -10
- package/api-operations.js +404 -0
- package/client.js +452 -87
- package/cordis.patch.yml +4 -4
- package/entry/SKILL.md +34 -0
- package/icon.png +0 -0
- package/index.js +35 -47
- package/locale/en.json +6 -6
- package/locale/zh.json +6 -6
- package/native-api.mjs +326 -0
- package/native-contracts.js +195 -0
- package/native-execution.js +184 -0
- package/native-runner.mjs +107 -0
- package/native-state.js +67 -0
- package/native-tools.js +241 -0
- package/operations.js +1260 -0
- package/package.json +65 -51
- package/{skills → runtime}/datarc-access-permissions/SKILL.md +30 -30
- package/{skills → runtime}/datarc-access-permissions/references/api.md +31 -31
- package/{skills → runtime}/datarc-access-permissions/references/write-order.md +16 -16
- package/{skills → runtime}/datarc-analysis-report/SKILL.md +125 -125
- package/{skills → runtime}/datarc-analysis-report/agents/openai.yaml +6 -6
- package/{skills → runtime}/datarc-analysis-report/references/analyst-frameworks.md +215 -215
- package/{skills → runtime}/datarc-analysis-report/references/api-contracts.md +478 -478
- package/{skills → runtime}/datarc-analysis-report/references/direct-card-fallback-design.md +66 -66
- package/{skills → runtime}/datarc-analysis-report/references/human-in-the-loop.md +142 -142
- package/{skills → runtime}/datarc-analysis-report/references/loop-personalization-policy.md +138 -138
- package/{skills → runtime}/datarc-analysis-report/references/manifest-example.json +779 -779
- package/{skills → runtime}/datarc-analysis-report/references/narrative-schema.md +160 -160
- package/{skills → runtime}/datarc-analysis-report/references/question-syntax.md +151 -151
- package/{skills → runtime}/datarc-analysis-report/scripts/run_analysis_report.py +2225 -2225
- package/{skills → runtime}/datarc-analysis-report/scripts/run_dataseek_cards.py +1914 -1914
- package/{skills → runtime}/datarc-analysis-report/scripts/test_run_analysis_report.py +5295 -5295
- package/{skills → runtime}/datarc-data-search/SKILL.md +243 -243
- package/{skills → runtime}/datarc-data-search/scripts/calculate.py +116 -116
- package/{skills → runtime}/datarc-data-search/scripts/data-search.mjs +628 -628
- package/{skills/datarc-dataseek-search → runtime/datarc-data-search}/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-data-search/scripts/search-result.mjs +211 -211
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/SKILL.md +59 -59
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/artifacts.md +36 -36
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/references/equivalence.md +30 -30
- package/{skills/datarc-data-search → runtime/datarc-dataseek-batch-evaluation}/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-dataseek-batch-evaluation/scripts/dataseek-batch-evaluation.mjs +1020 -1020
- package/{skills → runtime}/datarc-dataseek-search/SKILL.md +96 -96
- package/{skills/datarc-dataseek-batch-evaluation → runtime/datarc-dataseek-search}/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-dataseek-search/scripts/dataseek-search.mjs +257 -257
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/SKILL.md +44 -44
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/evals/evals.json +165 -165
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/dataset.md +77 -77
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/input-and-resolution.md +93 -93
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/interventions.md +64 -64
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/knowledge-and-prompts.md +47 -47
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/rollback.md +11 -11
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/references/verification-and-rollback.md +95 -95
- package/{skills → runtime}/datarc-dataseek-semantic-debugging/scripts/semantic-debugging.mjs +29 -29
- package/{skills → runtime}/datarc-dataseek-testset-generation/SKILL.md +47 -47
- package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/datarc-client.mjs +464 -464
- package/{skills → runtime}/datarc-dataseek-testset-generation/scripts/dataseek-testset-generation.mjs +526 -526
- package/{skills → runtime}/datarc-datasource/SKILL.md +97 -97
- package/{skills → runtime}/datarc-oauth/SKILL.md +50 -50
- package/{skills → runtime}/datarc-oauth/scripts/auth.mjs +192 -192
- package/{skills → runtime}/datarc-oauth/scripts/credentials.mjs +237 -237
- package/{skills → runtime}/datarc-report-add-card/SKILL.md +90 -90
- package/{skills → runtime}/datarc-report-add-card/agents/openai.yaml +4 -4
- package/runtime/datarc-report-add-card/scripts/datarc-client.mjs +464 -0
- package/{skills → runtime}/datarc-report-add-card/scripts/report-card.mjs +439 -439
- package/{skills → runtime}/datarc-semantic-alias/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-alias/scripts/alias-plan.mjs +422 -422
- package/{skills → runtime}/datarc-semantic-alias/scripts/alias.mjs +11 -11
- package/{skills → runtime}/datarc-semantic-calibration/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration-plan.mjs +683 -683
- package/{skills → runtime}/datarc-semantic-calibration/scripts/calibration.mjs +11 -11
- package/{skills → runtime}/datarc-semantic-core/SKILL.md +12 -12
- package/{skills → runtime}/datarc-semantic-core/scripts/artifact-journal.mjs +853 -830
- package/{skills → runtime}/datarc-semantic-core/scripts/canonical.mjs +48 -48
- package/{skills → runtime}/datarc-semantic-core/scripts/case-model.mjs +608 -608
- package/{skills → runtime}/datarc-semantic-core/scripts/cli.mjs +180 -180
- package/{skills → runtime}/datarc-semantic-core/scripts/datarc-client.mjs +180 -180
- package/{skills → runtime}/datarc-semantic-core/scripts/interpretation-pairs.mjs +57 -57
- package/{skills → runtime}/datarc-semantic-core/scripts/interventions.mjs +693 -693
- package/{skills → runtime}/datarc-semantic-core/scripts/live-resolution.mjs +305 -305
- package/{skills → runtime}/datarc-semantic-core/scripts/model-scope.mjs +49 -49
- package/{skills → runtime}/datarc-semantic-core/scripts/reproduction.mjs +330 -330
- package/{skills → runtime}/datarc-semantic-core/scripts/semantic-cli.mjs +799 -740
- package/{skills → runtime}/datarc-semantic-core/scripts/shared.mjs +312 -312
- package/{skills → runtime}/datarc-semantic-core/scripts/verification.mjs +1111 -1014
- package/{skills → runtime}/datarc-semantic-dataset/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-plan.mjs +749 -749
- package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset-preflight.mjs +813 -813
- package/{skills → runtime}/datarc-semantic-dataset/scripts/dataset.mjs +11 -11
- package/{skills → runtime}/datarc-semantic-knowledge/SKILL.md +38 -38
- package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-drafts.md +61 -61
- package/{skills → runtime}/datarc-semantic-knowledge/references/knowledge-generation.json +16 -16
- package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-draft.mjs +347 -347
- package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge-plan.mjs +848 -848
- package/{skills → runtime}/datarc-semantic-knowledge/scripts/knowledge.mjs +31 -31
- package/{skills → runtime}/datarc-semantic-prompt/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt-plan.mjs +598 -447
- package/{skills → runtime}/datarc-semantic-prompt/scripts/prompt.mjs +15 -15
- package/{skills → runtime}/datarc-semantic-synonym/SKILL.md +20 -20
- package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym-plan.mjs +688 -688
- package/{skills → runtime}/datarc-semantic-synonym/scripts/synonym.mjs +11 -11
- package/{skills → runtime}/datarc-viz-analysis-report/SKILL.md +108 -108
- package/{skills → runtime}/datarc-viz-analysis-report/assets/LICENSE-echarts.md +8 -8
- package/{skills → runtime}/datarc-viz-analysis-report/assets/echarts.min.js +45 -45
- package/{skills → runtime}/datarc-viz-analysis-report/references/api-contracts.md +163 -163
- package/{skills → runtime}/datarc-viz-analysis-report/references/derivation-log.md +157 -157
- package/{skills → runtime}/datarc-viz-analysis-report/references/evidence-framework.md +76 -76
- package/{skills → runtime}/datarc-viz-analysis-report/references/html-template.md +92 -92
- package/{skills → runtime}/datarc-viz-analysis-report/references/provenance-format.md +56 -56
- package/{skills → runtime}/datarc-viz-analysis-report/references/question-syntax.md +151 -151
- package/{skills → runtime}/datarc-viz-analysis-report/scripts/render_viz_report.py +1708 -1708
- package/{skills → runtime}/datarc-viz-analysis-report/scripts/test_render_viz_report.py +964 -964
- package/{skills → runtime}/datarc-workspace-configuration/SKILL.md +59 -59
- package/{skills → runtime}/datarc-workspace-configuration/references/artifacts.md +75 -75
- package/{skills → runtime}/datarc-workspace-configuration/references/verification.md +20 -20
- package/{skills → runtime}/datarc-workspace-configuration/scripts/configuration.mjs +722 -662
- package/{skills → runtime}/datarc-workspace-context/SKILL.md +43 -43
- package/{skills → runtime}/datarc-workspace-context/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-workspace-context/scripts/datarc-client.mjs +31 -31
- package/{skills → runtime}/datarc-workspace-context/scripts/query-display.mjs +114 -114
- package/{skills → runtime}/datarc-workspace-context/scripts/workspace-context.mjs +58 -58
- package/{skills → runtime}/datarc-workspace-custom-tables/SKILL.md +89 -89
- package/{skills → runtime}/datarc-workspace-custom-tables/scripts/datarc-client.mjs +165 -165
- package/{skills → runtime}/datarc-workspace-custom-tables/scripts/workspace-custom-tables.mjs +601 -601
- package/{skills → runtime}/datarc-workspace-keywords/SKILL.md +197 -197
- package/{skills → runtime}/datarc-workspace-keywords/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-workspace-keywords/references/api-fields.md +79 -79
- package/{skills → runtime}/datarc-workspace-keywords/references/derived-measures.md +177 -177
- package/{skills → runtime}/datarc-workspace-keywords/scripts/datarc-client.mjs +145 -145
- package/{skills → runtime}/datarc-workspace-keywords/scripts/workspace-keywords.mjs +2421 -2421
- package/{skills → runtime}/datarc-workspace-membership/SKILL.md +29 -29
- package/{skills → runtime}/datarc-workspace-membership/references/api.md +19 -19
- package/{skills → runtime}/datarc-workspace-modeling/SKILL.md +209 -209
- package/{skills → runtime}/datarc-workspace-modeling/agents/openai.yaml +4 -4
- package/{skills → runtime}/datarc-workspace-modeling/references/join-preview.md +38 -38
- package/{skills → runtime}/datarc-workspace-modeling/references/model-plan.md +300 -300
- package/{skills → runtime}/datarc-workspace-modeling/references/model-tags.md +95 -95
- package/{skills → runtime}/datarc-workspace-modeling/references/modeling-contract.json +29 -29
- package/{skills → runtime}/datarc-workspace-modeling/references/modeling-fixtures.json +2423 -2423
- package/{skills → runtime}/datarc-workspace-modeling/scripts/datarc-client.mjs +137 -137
- package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-model-tags.mjs +238 -238
- package/{skills → runtime}/datarc-workspace-modeling/scripts/workspace-modeling.mjs +1261 -1261
- package/skills-provider.js +51 -0
- package/workflow-index.json +434 -0
- package/icon.svg +0 -4
- package/skills/datarc-report-add-card/scripts/datarc-client.mjs +0 -464
- package/skills-index.json +0 -194
|
@@ -1,526 +1,526 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
-
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
4
|
-
import { pathToFileURL } from "node:url";
|
|
5
|
-
import {
|
|
6
|
-
createClient,
|
|
7
|
-
isGlobalError,
|
|
8
|
-
parseArgs,
|
|
9
|
-
required,
|
|
10
|
-
runCli,
|
|
11
|
-
} from "./datarc-client.mjs";
|
|
12
|
-
|
|
13
|
-
const STATUS_COLUMN = "生成_执行状态";
|
|
14
|
-
const ERROR_COLUMN = "生成_错误简述";
|
|
15
|
-
|
|
16
|
-
export function parseCsv(text) {
|
|
17
|
-
const rows = [];
|
|
18
|
-
let row = [];
|
|
19
|
-
let field = "";
|
|
20
|
-
let quoted = false;
|
|
21
|
-
const source = String(text).replace(/^\uFEFF/, "");
|
|
22
|
-
for (let index = 0; index < source.length; index += 1) {
|
|
23
|
-
const character = source[index];
|
|
24
|
-
if (quoted) {
|
|
25
|
-
if (character === '"' && source[index + 1] === '"') {
|
|
26
|
-
field += '"';
|
|
27
|
-
index += 1;
|
|
28
|
-
} else if (character === '"') quoted = false;
|
|
29
|
-
else field += character;
|
|
30
|
-
} else if (character === '"' && field === "") quoted = true;
|
|
31
|
-
else if (character === ",") {
|
|
32
|
-
row.push(field);
|
|
33
|
-
field = "";
|
|
34
|
-
} else if (character === "\n" || character === "\r") {
|
|
35
|
-
if (character === "\r" && source[index + 1] === "\n") index += 1;
|
|
36
|
-
row.push(field);
|
|
37
|
-
rows.push(row);
|
|
38
|
-
row = [];
|
|
39
|
-
field = "";
|
|
40
|
-
} else field += character;
|
|
41
|
-
}
|
|
42
|
-
if (quoted) throw new Error("CSV 存在未闭合的引号");
|
|
43
|
-
if (field !== "" || row.length) rows.push([...row, field]);
|
|
44
|
-
return rows.filter((item, index) => index === 0 || item.some(Boolean));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export function stringifyCsv(rows) {
|
|
48
|
-
return `${rows.map((row) => row.map(csvField).join(",")).join("\r\n")}\r\n`;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function extractFinalTokens(actions) {
|
|
52
|
-
const candidates = [];
|
|
53
|
-
visit(actions, (value) => {
|
|
54
|
-
if (value?.type === "answer" && Array.isArray(value.data?.tokens))
|
|
55
|
-
candidates.push(value.data.tokens);
|
|
56
|
-
});
|
|
57
|
-
return candidates.at(-1) ?? null;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function extractUnderstanding(message) {
|
|
61
|
-
const step = [...(message.history ?? [])].reverse().find(
|
|
62
|
-
(item) =>
|
|
63
|
-
item?.name === "理解问题" || item?.name === "Understand the problem",
|
|
64
|
-
);
|
|
65
|
-
if (!step) throw new Error("DataSeek 消息历史中缺少理解问题步骤");
|
|
66
|
-
const candidates = [
|
|
67
|
-
step.reasoning_content ?? step.reasoningContent,
|
|
68
|
-
Array.isArray(step.reasoning_content)
|
|
69
|
-
? step.reasoning_content.join("")
|
|
70
|
-
: undefined,
|
|
71
|
-
Array.isArray(step.reasoningContent)
|
|
72
|
-
? step.reasoningContent.join("")
|
|
73
|
-
: undefined,
|
|
74
|
-
step.result,
|
|
75
|
-
step.content,
|
|
76
|
-
Array.isArray(step.content) ? step.content.join("") : undefined,
|
|
77
|
-
];
|
|
78
|
-
for (const value of candidates) {
|
|
79
|
-
const result = findUnderstanding(value);
|
|
80
|
-
if (result) return result;
|
|
81
|
-
}
|
|
82
|
-
throw new Error("DataSeek 理解问题步骤没有可解析的结构化 JSON");
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function tokensToWords(tokens) {
|
|
86
|
-
const words = [];
|
|
87
|
-
visit(tokens, (value) => {
|
|
88
|
-
if (typeof value?.word === "string" && value.word.trim())
|
|
89
|
-
words.push(value.word.trim());
|
|
90
|
-
});
|
|
91
|
-
return words.join(" ");
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
export async function generate(args, options = {}) {
|
|
95
|
-
const inputPath = resolve(process.cwd(), required(args, "input"));
|
|
96
|
-
const outputPath = safeOutputFile(required(args, "output"));
|
|
97
|
-
if (inputPath.toLowerCase() === outputPath.toLowerCase())
|
|
98
|
-
throw new Error("--output 不得覆盖输入 CSV");
|
|
99
|
-
const workspaceId = required(args, "workspace-id");
|
|
100
|
-
const names = {
|
|
101
|
-
question: required(args, "question-column"),
|
|
102
|
-
understanding: args["understanding-column"] ?? "理解JSON",
|
|
103
|
-
tokens: args["tokens-column"] ?? "问题Token",
|
|
104
|
-
tokenWords: args["token-words-column"] ?? "问题TokenWord",
|
|
105
|
-
};
|
|
106
|
-
validateColumnRoles(names);
|
|
107
|
-
const rows = parseCsv(await readFile(inputPath, "utf8"));
|
|
108
|
-
if (!rows.length)
|
|
109
|
-
throw new Error("CSV 为空;请确认输入文件路径、内容和 UTF-8 编码后重试");
|
|
110
|
-
const header = rows[0];
|
|
111
|
-
if (new Set(header).size !== header.length)
|
|
112
|
-
throw new Error("CSV 表头存在重复列名;请将每列改为唯一名称后重试");
|
|
113
|
-
if (!header.includes(names.question))
|
|
114
|
-
throw new Error(`CSV 缺少问题列:${names.question}`);
|
|
115
|
-
const outputHeader = [...header];
|
|
116
|
-
insertColumnAfter(outputHeader, names.understanding, names.question);
|
|
117
|
-
insertColumnAfter(outputHeader, names.tokens, names.understanding);
|
|
118
|
-
insertColumnAfter(outputHeader, names.tokenWords, names.tokens);
|
|
119
|
-
for (const name of [STATUS_COLUMN, ERROR_COLUMN])
|
|
120
|
-
if (!outputHeader.includes(name)) outputHeader.push(name);
|
|
121
|
-
const client = options.client ?? createClient(options);
|
|
122
|
-
const intervalMs = positiveInteger(
|
|
123
|
-
args["poll-interval-ms"] ?? 2000,
|
|
124
|
-
"poll-interval-ms",
|
|
125
|
-
true,
|
|
126
|
-
);
|
|
127
|
-
const maxWaitMs = positiveInteger(
|
|
128
|
-
args["max-wait-ms"] ?? 600000,
|
|
129
|
-
"max-wait-ms",
|
|
130
|
-
);
|
|
131
|
-
const outputRows = [outputHeader];
|
|
132
|
-
await writeNewFile(outputPath, stringifyCsv(outputRows));
|
|
133
|
-
let success = 0;
|
|
134
|
-
let error = 0;
|
|
135
|
-
for (const values of rows.slice(1)) {
|
|
136
|
-
const source = Object.fromEntries(
|
|
137
|
-
header.map((name, index) => [name, values[index] ?? ""]),
|
|
138
|
-
);
|
|
139
|
-
const question = String(source[names.question] ?? "").trim();
|
|
140
|
-
let result;
|
|
141
|
-
try {
|
|
142
|
-
if (!question) throw new Error("原始问题为空");
|
|
143
|
-
result = await collectExpected(client, workspaceId, question, {
|
|
144
|
-
intervalMs,
|
|
145
|
-
maxWaitMs,
|
|
146
|
-
});
|
|
147
|
-
success += 1;
|
|
148
|
-
} catch (caught) {
|
|
149
|
-
if (isGlobalError(caught)) throw caught;
|
|
150
|
-
result = { status: "error", error: caught.message ?? String(caught) };
|
|
151
|
-
error += 1;
|
|
152
|
-
}
|
|
153
|
-
const output = Object.fromEntries(
|
|
154
|
-
outputHeader.map((name) => [name, source[name] ?? ""]),
|
|
155
|
-
);
|
|
156
|
-
output[names.understanding] = jsonCell(result.understanding);
|
|
157
|
-
output[names.tokens] = jsonCell(result.tokens);
|
|
158
|
-
output[names.tokenWords] = result.tokenWords ?? "";
|
|
159
|
-
output[STATUS_COLUMN] = result.status;
|
|
160
|
-
output[ERROR_COLUMN] = result.error ?? "";
|
|
161
|
-
outputRows.push(outputHeader.map((name) => output[name]));
|
|
162
|
-
await atomicWrite(outputPath, stringifyCsv(outputRows));
|
|
163
|
-
}
|
|
164
|
-
return { output: outputPath, total: rows.length - 1, success, error };
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
export async function snapshotWorkspace(args, options = {}) {
|
|
168
|
-
const workspaceId = required(args, "workspace-id");
|
|
169
|
-
const outputPath = safeOutputFile(required(args, "output"));
|
|
170
|
-
const valuesPerDimension = boundedInteger(
|
|
171
|
-
args["values-per-dimension"] ?? 3,
|
|
172
|
-
"values-per-dimension",
|
|
173
|
-
1,
|
|
174
|
-
20,
|
|
175
|
-
);
|
|
176
|
-
const maxDimensions = boundedInteger(
|
|
177
|
-
args["max-dimensions"] ?? 30,
|
|
178
|
-
"max-dimensions",
|
|
179
|
-
1,
|
|
180
|
-
200,
|
|
181
|
-
);
|
|
182
|
-
const maxCardinality = boundedInteger(
|
|
183
|
-
args["max-cardinality"] ?? 1000,
|
|
184
|
-
"max-cardinality",
|
|
185
|
-
1,
|
|
186
|
-
100000,
|
|
187
|
-
);
|
|
188
|
-
const client = options.client ?? createClient(options);
|
|
189
|
-
const context = await client.request(
|
|
190
|
-
"GET",
|
|
191
|
-
`/api/v2/account-projects/${workspaceId}/agent-context/`,
|
|
192
|
-
{ query: { format: "json" } },
|
|
193
|
-
);
|
|
194
|
-
const dimensions = uniqueDimensions(context.models ?? []).slice(
|
|
195
|
-
0,
|
|
196
|
-
maxDimensions,
|
|
197
|
-
);
|
|
198
|
-
const samples = [];
|
|
199
|
-
for (const dimension of dimensions) {
|
|
200
|
-
const body = {
|
|
201
|
-
prop: dimension.prop,
|
|
202
|
-
q: "",
|
|
203
|
-
count: 1,
|
|
204
|
-
tuids: dimension.modelUids,
|
|
205
|
-
};
|
|
206
|
-
try {
|
|
207
|
-
const count = await client.request(
|
|
208
|
-
"POST",
|
|
209
|
-
`/api/v2/account-projects/${workspaceId}/dimension-keywords/`,
|
|
210
|
-
{ body },
|
|
211
|
-
);
|
|
212
|
-
if (!Number.isFinite(Number(count)) || Number(count) > maxCardinality) {
|
|
213
|
-
samples.push({
|
|
214
|
-
...dimension,
|
|
215
|
-
count: Number.isFinite(Number(count)) ? Number(count) : null,
|
|
216
|
-
values: [],
|
|
217
|
-
status: "skipped",
|
|
218
|
-
reason: Number.isFinite(Number(count))
|
|
219
|
-
? `维度值数量超过 ${maxCardinality}`
|
|
220
|
-
: "维度值数量无效",
|
|
221
|
-
});
|
|
222
|
-
continue;
|
|
223
|
-
}
|
|
224
|
-
const tokens = await client.request(
|
|
225
|
-
"POST",
|
|
226
|
-
`/api/v2/account-projects/${workspaceId}/dimension-keywords/`,
|
|
227
|
-
{
|
|
228
|
-
body: {
|
|
229
|
-
...body,
|
|
230
|
-
count: undefined,
|
|
231
|
-
offset: 0,
|
|
232
|
-
limit: valuesPerDimension,
|
|
233
|
-
},
|
|
234
|
-
},
|
|
235
|
-
);
|
|
236
|
-
samples.push({
|
|
237
|
-
...dimension,
|
|
238
|
-
count: Number(count),
|
|
239
|
-
values: uniqueWords(tokens),
|
|
240
|
-
status: "success",
|
|
241
|
-
});
|
|
242
|
-
} catch (error) {
|
|
243
|
-
if (isGlobalError(error)) throw error;
|
|
244
|
-
samples.push({
|
|
245
|
-
...dimension,
|
|
246
|
-
count: null,
|
|
247
|
-
values: [],
|
|
248
|
-
status: "error",
|
|
249
|
-
reason: error.message ?? String(error),
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
const snapshot = {
|
|
254
|
-
schemaVersion: 1,
|
|
255
|
-
workspaceId: String(workspaceId),
|
|
256
|
-
workspace: context.workspace ?? null,
|
|
257
|
-
models: withoutEmbeddedExamples(context.models ?? []),
|
|
258
|
-
dimensionSamples: samples,
|
|
259
|
-
limits: { valuesPerDimension, maxDimensions, maxCardinality },
|
|
260
|
-
sampledAt: new Date().toISOString(),
|
|
261
|
-
};
|
|
262
|
-
await atomicWrite(outputPath, `${JSON.stringify(snapshot, null, 2)}\n`);
|
|
263
|
-
return {
|
|
264
|
-
output: outputPath,
|
|
265
|
-
models: snapshot.models.length,
|
|
266
|
-
dimensions: samples.length,
|
|
267
|
-
sampled: samples.filter((item) => item.status === "success").length,
|
|
268
|
-
skipped: samples.filter((item) => item.status === "skipped").length,
|
|
269
|
-
errors: samples.filter((item) => item.status === "error").length,
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
export async function collectExpected(client, workspaceId, question, poll) {
|
|
274
|
-
const thread = await client.request(
|
|
275
|
-
"POST",
|
|
276
|
-
`/api/v3/account-projects/${workspaceId}/threads/`,
|
|
277
|
-
{ body: {} },
|
|
278
|
-
);
|
|
279
|
-
const message = await client.request(
|
|
280
|
-
"POST",
|
|
281
|
-
`/api/v3/account-projects/${workspaceId}/threads/${thread.uid}/messages/`,
|
|
282
|
-
{ body: { message: question } },
|
|
283
|
-
);
|
|
284
|
-
const completed = await waitForMessage(
|
|
285
|
-
client,
|
|
286
|
-
workspaceId,
|
|
287
|
-
thread.uid,
|
|
288
|
-
message.id,
|
|
289
|
-
poll,
|
|
290
|
-
);
|
|
291
|
-
const understanding = extractUnderstanding(completed);
|
|
292
|
-
const unsupportedType = unsupportedQueryType(completed.current?.result);
|
|
293
|
-
if (unsupportedType)
|
|
294
|
-
throw new Error(
|
|
295
|
-
`当前测试集只支持直接单 query,不能保存 ${unsupportedType} 查询;请改写为单个问题后重试`,
|
|
296
|
-
);
|
|
297
|
-
const tokens = extractFinalTokens(completed.current?.result);
|
|
298
|
-
if (!tokens) throw new Error("DataSeek 最终 answer 缺少问题 Token");
|
|
299
|
-
const tokenWords = tokensToWords(tokens);
|
|
300
|
-
if (!tokenWords) throw new Error("DataSeek 最终问题 Token 缺少 word");
|
|
301
|
-
return { status: "success", understanding, tokens, tokenWords };
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
export async function execute(argv, options = {}) {
|
|
305
|
-
const args = parseArgs(argv);
|
|
306
|
-
if (args.help === true || args._[0] === "help" || !args._[0]) return help();
|
|
307
|
-
if (args._[0] === "snapshot") return snapshotWorkspace(args, options);
|
|
308
|
-
if (args._[0] === "generate") return generate(args, options);
|
|
309
|
-
throw new Error("命令应为 snapshot 或 generate");
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
async function waitForMessage(client, workspaceId, threadUid, messageId, options) {
|
|
313
|
-
const started = Date.now();
|
|
314
|
-
while (Date.now() - started <= options.maxWaitMs) {
|
|
315
|
-
const message = await client.request(
|
|
316
|
-
"GET",
|
|
317
|
-
`/api/v3/account-projects/${workspaceId}/threads/${threadUid}/messages/${messageId}/`,
|
|
318
|
-
);
|
|
319
|
-
if (message.current?.error) throw new Error(String(message.current.error));
|
|
320
|
-
if (Array.isArray(message.current?.result) && message.current.result.length)
|
|
321
|
-
return message;
|
|
322
|
-
await client.sleep(options.intervalMs);
|
|
323
|
-
}
|
|
324
|
-
const error = new Error(
|
|
325
|
-
"DataSeek 消息轮询超时;请调大 --max-wait-ms 后重试",
|
|
326
|
-
);
|
|
327
|
-
error.code = "TASK_TIMEOUT";
|
|
328
|
-
throw error;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
function safeOutputFile(value) {
|
|
332
|
-
if (typeof value !== "string" || !value || isAbsolute(value))
|
|
333
|
-
throw new Error("--output 必须是当前目录下的相对路径");
|
|
334
|
-
const root = resolve(process.cwd());
|
|
335
|
-
const target = resolve(root, value);
|
|
336
|
-
if (relative(root, target).startsWith(".."))
|
|
337
|
-
throw new Error("--output 不得超出当前目录");
|
|
338
|
-
return target;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
function positiveInteger(value, name, allowZero = false) {
|
|
342
|
-
const number = Number(value);
|
|
343
|
-
if (!Number.isInteger(number) || number < (allowZero ? 0 : 1))
|
|
344
|
-
throw new Error(
|
|
345
|
-
`--${name} 必须是${allowZero ? "非负" : "正"}整数(当前值:${value});请修改参数后重试`,
|
|
346
|
-
);
|
|
347
|
-
return number;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
function insertColumnAfter(header, name, precedingName) {
|
|
351
|
-
if (header.includes(name)) return;
|
|
352
|
-
const index = header.indexOf(precedingName);
|
|
353
|
-
header.splice(index < 0 ? header.length : index + 1, 0, name);
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
function validateColumnRoles(names) {
|
|
357
|
-
const roles = {
|
|
358
|
-
question: names.question,
|
|
359
|
-
understanding: names.understanding,
|
|
360
|
-
tokens: names.tokens,
|
|
361
|
-
tokenWords: names.tokenWords,
|
|
362
|
-
status: STATUS_COLUMN,
|
|
363
|
-
error: ERROR_COLUMN,
|
|
364
|
-
};
|
|
365
|
-
const seen = new Map();
|
|
366
|
-
for (const [role, rawName] of Object.entries(roles)) {
|
|
367
|
-
const name = String(rawName ?? "").trim();
|
|
368
|
-
if (!name) throw new Error(`${role} 列名不能为空`);
|
|
369
|
-
if (seen.has(name))
|
|
370
|
-
throw new Error(
|
|
371
|
-
`列名角色冲突:${seen.get(name)} 与 ${role} 均使用“${name}”`,
|
|
372
|
-
);
|
|
373
|
-
seen.set(name, role);
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
function boundedInteger(value, name, minimum, maximum) {
|
|
378
|
-
const number = Number(value);
|
|
379
|
-
if (!Number.isInteger(number) || number < minimum || number > maximum)
|
|
380
|
-
throw new Error(`--${name} 必须是 ${minimum} 到 ${maximum} 的整数`);
|
|
381
|
-
return number;
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
function uniqueDimensions(models) {
|
|
385
|
-
const dimensions = new Map();
|
|
386
|
-
for (const model of models) {
|
|
387
|
-
for (const dimension of model.dimensions ?? []) {
|
|
388
|
-
if (!Number.isInteger(Number(dimension.id))) continue;
|
|
389
|
-
const prop = `d${Number(dimension.id)}`;
|
|
390
|
-
const current = dimensions.get(prop) ?? {
|
|
391
|
-
id: Number(dimension.id),
|
|
392
|
-
prop,
|
|
393
|
-
name: dimension.name ?? prop,
|
|
394
|
-
description: dimension.description ?? null,
|
|
395
|
-
examples: [],
|
|
396
|
-
modelUids: [],
|
|
397
|
-
};
|
|
398
|
-
current.examples = [
|
|
399
|
-
...new Set([...current.examples, ...(dimension.examples ?? [])]),
|
|
400
|
-
];
|
|
401
|
-
if (model.uid && !current.modelUids.includes(model.uid))
|
|
402
|
-
current.modelUids.push(model.uid);
|
|
403
|
-
dimensions.set(prop, current);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
return [...dimensions.values()].sort((left, right) => left.id - right.id);
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
function uniqueWords(tokens) {
|
|
410
|
-
return [
|
|
411
|
-
...new Set(
|
|
412
|
-
(Array.isArray(tokens) ? tokens : [])
|
|
413
|
-
.map((token) => String(token?.word ?? "").trim())
|
|
414
|
-
.filter(Boolean),
|
|
415
|
-
),
|
|
416
|
-
];
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
function withoutEmbeddedExamples(models) {
|
|
420
|
-
return models.map((model) => ({
|
|
421
|
-
...model,
|
|
422
|
-
dimensions: (model.dimensions ?? []).map(({ examples: _examples, ...item }) =>
|
|
423
|
-
item,
|
|
424
|
-
),
|
|
425
|
-
}));
|
|
426
|
-
}
|
|
427
|
-
|
|
428
|
-
async function atomicWrite(path, content) {
|
|
429
|
-
await mkdir(dirname(path), { recursive: true });
|
|
430
|
-
const temporary = `${path}.tmp-${process.pid}`;
|
|
431
|
-
await writeFile(temporary, content, "utf8");
|
|
432
|
-
await rename(temporary, path);
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
async function writeNewFile(path, content) {
|
|
436
|
-
await mkdir(dirname(path), { recursive: true });
|
|
437
|
-
try {
|
|
438
|
-
await writeFile(path, content, { encoding: "utf8", flag: "wx" });
|
|
439
|
-
} catch (error) {
|
|
440
|
-
if (error?.code === "EEXIST")
|
|
441
|
-
throw new Error(
|
|
442
|
-
`输出文件已存在:${relative(process.cwd(), path)};请指定新的 --output 路径后重试`,
|
|
443
|
-
);
|
|
444
|
-
throw error;
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function jsonCell(value) {
|
|
449
|
-
return value === undefined ? "" : JSON.stringify(value);
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
function visit(value, callback, seen = new Set()) {
|
|
453
|
-
if (!value || typeof value !== "object" || seen.has(value)) return;
|
|
454
|
-
seen.add(value);
|
|
455
|
-
callback(value);
|
|
456
|
-
for (const child of Array.isArray(value) ? value : Object.values(value))
|
|
457
|
-
visit(child, callback, seen);
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
export function unsupportedQueryType(actions) {
|
|
461
|
-
let result = null;
|
|
462
|
-
visit(actions, (value) => {
|
|
463
|
-
if (!result && ["parallel", "chained"].includes(value?.type))
|
|
464
|
-
result = value.type;
|
|
465
|
-
});
|
|
466
|
-
return result;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
function findUnderstanding(value) {
|
|
470
|
-
if (value === null || value === undefined) return null;
|
|
471
|
-
if (Array.isArray(value)) {
|
|
472
|
-
for (const item of [...value].reverse()) {
|
|
473
|
-
const result = findUnderstanding(item);
|
|
474
|
-
if (result) return result;
|
|
475
|
-
}
|
|
476
|
-
return null;
|
|
477
|
-
}
|
|
478
|
-
if (typeof value === "object") {
|
|
479
|
-
if (
|
|
480
|
-
Object.hasOwn(value, "dimensions") &&
|
|
481
|
-
Object.hasOwn(value, "metrics") &&
|
|
482
|
-
Object.hasOwn(value, "time_range")
|
|
483
|
-
)
|
|
484
|
-
return value;
|
|
485
|
-
for (const item of Object.values(value)) {
|
|
486
|
-
const result = findUnderstanding(item);
|
|
487
|
-
if (result) return result;
|
|
488
|
-
}
|
|
489
|
-
return null;
|
|
490
|
-
}
|
|
491
|
-
const text = String(value).trim();
|
|
492
|
-
const start = text.indexOf("{");
|
|
493
|
-
const end = text.lastIndexOf("}");
|
|
494
|
-
for (const candidate of [
|
|
495
|
-
text,
|
|
496
|
-
text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, ""),
|
|
497
|
-
start >= 0 && end > start ? text.slice(start, end + 1) : "",
|
|
498
|
-
]) {
|
|
499
|
-
if (!candidate) continue;
|
|
500
|
-
try {
|
|
501
|
-
const result = findUnderstanding(JSON.parse(candidate));
|
|
502
|
-
if (result) return result;
|
|
503
|
-
} catch {
|
|
504
|
-
// 尝试下一种包装形式。
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
return null;
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
function csvField(value) {
|
|
511
|
-
const text = String(value ?? "");
|
|
512
|
-
return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
513
|
-
}
|
|
514
|
-
|
|
515
|
-
function help() {
|
|
516
|
-
return {
|
|
517
|
-
usage: [
|
|
518
|
-
"snapshot --workspace-id <id> --output <relative-json> [--values-per-dimension <n>] [--max-dimensions <n>] [--max-cardinality <n>]",
|
|
519
|
-
"generate --workspace-id <id> --input <csv> --output <relative-csv> --question-column <name> [--understanding-column <name>] [--tokens-column <name>] [--token-words-column <name>]",
|
|
520
|
-
],
|
|
521
|
-
options: ["--poll-interval-ms <n>", "--max-wait-ms <n>"],
|
|
522
|
-
};
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
526
|
-
await runCli(() => execute(process.argv.slice(2)));
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import {
|
|
6
|
+
createClient,
|
|
7
|
+
isGlobalError,
|
|
8
|
+
parseArgs,
|
|
9
|
+
required,
|
|
10
|
+
runCli,
|
|
11
|
+
} from "./datarc-client.mjs";
|
|
12
|
+
|
|
13
|
+
const STATUS_COLUMN = "生成_执行状态";
|
|
14
|
+
const ERROR_COLUMN = "生成_错误简述";
|
|
15
|
+
|
|
16
|
+
export function parseCsv(text) {
|
|
17
|
+
const rows = [];
|
|
18
|
+
let row = [];
|
|
19
|
+
let field = "";
|
|
20
|
+
let quoted = false;
|
|
21
|
+
const source = String(text).replace(/^\uFEFF/, "");
|
|
22
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
23
|
+
const character = source[index];
|
|
24
|
+
if (quoted) {
|
|
25
|
+
if (character === '"' && source[index + 1] === '"') {
|
|
26
|
+
field += '"';
|
|
27
|
+
index += 1;
|
|
28
|
+
} else if (character === '"') quoted = false;
|
|
29
|
+
else field += character;
|
|
30
|
+
} else if (character === '"' && field === "") quoted = true;
|
|
31
|
+
else if (character === ",") {
|
|
32
|
+
row.push(field);
|
|
33
|
+
field = "";
|
|
34
|
+
} else if (character === "\n" || character === "\r") {
|
|
35
|
+
if (character === "\r" && source[index + 1] === "\n") index += 1;
|
|
36
|
+
row.push(field);
|
|
37
|
+
rows.push(row);
|
|
38
|
+
row = [];
|
|
39
|
+
field = "";
|
|
40
|
+
} else field += character;
|
|
41
|
+
}
|
|
42
|
+
if (quoted) throw new Error("CSV 存在未闭合的引号");
|
|
43
|
+
if (field !== "" || row.length) rows.push([...row, field]);
|
|
44
|
+
return rows.filter((item, index) => index === 0 || item.some(Boolean));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function stringifyCsv(rows) {
|
|
48
|
+
return `${rows.map((row) => row.map(csvField).join(",")).join("\r\n")}\r\n`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function extractFinalTokens(actions) {
|
|
52
|
+
const candidates = [];
|
|
53
|
+
visit(actions, (value) => {
|
|
54
|
+
if (value?.type === "answer" && Array.isArray(value.data?.tokens))
|
|
55
|
+
candidates.push(value.data.tokens);
|
|
56
|
+
});
|
|
57
|
+
return candidates.at(-1) ?? null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function extractUnderstanding(message) {
|
|
61
|
+
const step = [...(message.history ?? [])].reverse().find(
|
|
62
|
+
(item) =>
|
|
63
|
+
item?.name === "理解问题" || item?.name === "Understand the problem",
|
|
64
|
+
);
|
|
65
|
+
if (!step) throw new Error("DataSeek 消息历史中缺少理解问题步骤");
|
|
66
|
+
const candidates = [
|
|
67
|
+
step.reasoning_content ?? step.reasoningContent,
|
|
68
|
+
Array.isArray(step.reasoning_content)
|
|
69
|
+
? step.reasoning_content.join("")
|
|
70
|
+
: undefined,
|
|
71
|
+
Array.isArray(step.reasoningContent)
|
|
72
|
+
? step.reasoningContent.join("")
|
|
73
|
+
: undefined,
|
|
74
|
+
step.result,
|
|
75
|
+
step.content,
|
|
76
|
+
Array.isArray(step.content) ? step.content.join("") : undefined,
|
|
77
|
+
];
|
|
78
|
+
for (const value of candidates) {
|
|
79
|
+
const result = findUnderstanding(value);
|
|
80
|
+
if (result) return result;
|
|
81
|
+
}
|
|
82
|
+
throw new Error("DataSeek 理解问题步骤没有可解析的结构化 JSON");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function tokensToWords(tokens) {
|
|
86
|
+
const words = [];
|
|
87
|
+
visit(tokens, (value) => {
|
|
88
|
+
if (typeof value?.word === "string" && value.word.trim())
|
|
89
|
+
words.push(value.word.trim());
|
|
90
|
+
});
|
|
91
|
+
return words.join(" ");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function generate(args, options = {}) {
|
|
95
|
+
const inputPath = resolve(process.cwd(), required(args, "input"));
|
|
96
|
+
const outputPath = safeOutputFile(required(args, "output"));
|
|
97
|
+
if (inputPath.toLowerCase() === outputPath.toLowerCase())
|
|
98
|
+
throw new Error("--output 不得覆盖输入 CSV");
|
|
99
|
+
const workspaceId = required(args, "workspace-id");
|
|
100
|
+
const names = {
|
|
101
|
+
question: required(args, "question-column"),
|
|
102
|
+
understanding: args["understanding-column"] ?? "理解JSON",
|
|
103
|
+
tokens: args["tokens-column"] ?? "问题Token",
|
|
104
|
+
tokenWords: args["token-words-column"] ?? "问题TokenWord",
|
|
105
|
+
};
|
|
106
|
+
validateColumnRoles(names);
|
|
107
|
+
const rows = parseCsv(await readFile(inputPath, "utf8"));
|
|
108
|
+
if (!rows.length)
|
|
109
|
+
throw new Error("CSV 为空;请确认输入文件路径、内容和 UTF-8 编码后重试");
|
|
110
|
+
const header = rows[0];
|
|
111
|
+
if (new Set(header).size !== header.length)
|
|
112
|
+
throw new Error("CSV 表头存在重复列名;请将每列改为唯一名称后重试");
|
|
113
|
+
if (!header.includes(names.question))
|
|
114
|
+
throw new Error(`CSV 缺少问题列:${names.question}`);
|
|
115
|
+
const outputHeader = [...header];
|
|
116
|
+
insertColumnAfter(outputHeader, names.understanding, names.question);
|
|
117
|
+
insertColumnAfter(outputHeader, names.tokens, names.understanding);
|
|
118
|
+
insertColumnAfter(outputHeader, names.tokenWords, names.tokens);
|
|
119
|
+
for (const name of [STATUS_COLUMN, ERROR_COLUMN])
|
|
120
|
+
if (!outputHeader.includes(name)) outputHeader.push(name);
|
|
121
|
+
const client = options.client ?? createClient(options);
|
|
122
|
+
const intervalMs = positiveInteger(
|
|
123
|
+
args["poll-interval-ms"] ?? 2000,
|
|
124
|
+
"poll-interval-ms",
|
|
125
|
+
true,
|
|
126
|
+
);
|
|
127
|
+
const maxWaitMs = positiveInteger(
|
|
128
|
+
args["max-wait-ms"] ?? 600000,
|
|
129
|
+
"max-wait-ms",
|
|
130
|
+
);
|
|
131
|
+
const outputRows = [outputHeader];
|
|
132
|
+
await writeNewFile(outputPath, stringifyCsv(outputRows));
|
|
133
|
+
let success = 0;
|
|
134
|
+
let error = 0;
|
|
135
|
+
for (const values of rows.slice(1)) {
|
|
136
|
+
const source = Object.fromEntries(
|
|
137
|
+
header.map((name, index) => [name, values[index] ?? ""]),
|
|
138
|
+
);
|
|
139
|
+
const question = String(source[names.question] ?? "").trim();
|
|
140
|
+
let result;
|
|
141
|
+
try {
|
|
142
|
+
if (!question) throw new Error("原始问题为空");
|
|
143
|
+
result = await collectExpected(client, workspaceId, question, {
|
|
144
|
+
intervalMs,
|
|
145
|
+
maxWaitMs,
|
|
146
|
+
});
|
|
147
|
+
success += 1;
|
|
148
|
+
} catch (caught) {
|
|
149
|
+
if (isGlobalError(caught)) throw caught;
|
|
150
|
+
result = { status: "error", error: caught.message ?? String(caught) };
|
|
151
|
+
error += 1;
|
|
152
|
+
}
|
|
153
|
+
const output = Object.fromEntries(
|
|
154
|
+
outputHeader.map((name) => [name, source[name] ?? ""]),
|
|
155
|
+
);
|
|
156
|
+
output[names.understanding] = jsonCell(result.understanding);
|
|
157
|
+
output[names.tokens] = jsonCell(result.tokens);
|
|
158
|
+
output[names.tokenWords] = result.tokenWords ?? "";
|
|
159
|
+
output[STATUS_COLUMN] = result.status;
|
|
160
|
+
output[ERROR_COLUMN] = result.error ?? "";
|
|
161
|
+
outputRows.push(outputHeader.map((name) => output[name]));
|
|
162
|
+
await atomicWrite(outputPath, stringifyCsv(outputRows));
|
|
163
|
+
}
|
|
164
|
+
return { output: outputPath, total: rows.length - 1, success, error };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function snapshotWorkspace(args, options = {}) {
|
|
168
|
+
const workspaceId = required(args, "workspace-id");
|
|
169
|
+
const outputPath = safeOutputFile(required(args, "output"));
|
|
170
|
+
const valuesPerDimension = boundedInteger(
|
|
171
|
+
args["values-per-dimension"] ?? 3,
|
|
172
|
+
"values-per-dimension",
|
|
173
|
+
1,
|
|
174
|
+
20,
|
|
175
|
+
);
|
|
176
|
+
const maxDimensions = boundedInteger(
|
|
177
|
+
args["max-dimensions"] ?? 30,
|
|
178
|
+
"max-dimensions",
|
|
179
|
+
1,
|
|
180
|
+
200,
|
|
181
|
+
);
|
|
182
|
+
const maxCardinality = boundedInteger(
|
|
183
|
+
args["max-cardinality"] ?? 1000,
|
|
184
|
+
"max-cardinality",
|
|
185
|
+
1,
|
|
186
|
+
100000,
|
|
187
|
+
);
|
|
188
|
+
const client = options.client ?? createClient(options);
|
|
189
|
+
const context = await client.request(
|
|
190
|
+
"GET",
|
|
191
|
+
`/api/v2/account-projects/${workspaceId}/agent-context/`,
|
|
192
|
+
{ query: { format: "json" } },
|
|
193
|
+
);
|
|
194
|
+
const dimensions = uniqueDimensions(context.models ?? []).slice(
|
|
195
|
+
0,
|
|
196
|
+
maxDimensions,
|
|
197
|
+
);
|
|
198
|
+
const samples = [];
|
|
199
|
+
for (const dimension of dimensions) {
|
|
200
|
+
const body = {
|
|
201
|
+
prop: dimension.prop,
|
|
202
|
+
q: "",
|
|
203
|
+
count: 1,
|
|
204
|
+
tuids: dimension.modelUids,
|
|
205
|
+
};
|
|
206
|
+
try {
|
|
207
|
+
const count = await client.request(
|
|
208
|
+
"POST",
|
|
209
|
+
`/api/v2/account-projects/${workspaceId}/dimension-keywords/`,
|
|
210
|
+
{ body },
|
|
211
|
+
);
|
|
212
|
+
if (!Number.isFinite(Number(count)) || Number(count) > maxCardinality) {
|
|
213
|
+
samples.push({
|
|
214
|
+
...dimension,
|
|
215
|
+
count: Number.isFinite(Number(count)) ? Number(count) : null,
|
|
216
|
+
values: [],
|
|
217
|
+
status: "skipped",
|
|
218
|
+
reason: Number.isFinite(Number(count))
|
|
219
|
+
? `维度值数量超过 ${maxCardinality}`
|
|
220
|
+
: "维度值数量无效",
|
|
221
|
+
});
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const tokens = await client.request(
|
|
225
|
+
"POST",
|
|
226
|
+
`/api/v2/account-projects/${workspaceId}/dimension-keywords/`,
|
|
227
|
+
{
|
|
228
|
+
body: {
|
|
229
|
+
...body,
|
|
230
|
+
count: undefined,
|
|
231
|
+
offset: 0,
|
|
232
|
+
limit: valuesPerDimension,
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
);
|
|
236
|
+
samples.push({
|
|
237
|
+
...dimension,
|
|
238
|
+
count: Number(count),
|
|
239
|
+
values: uniqueWords(tokens),
|
|
240
|
+
status: "success",
|
|
241
|
+
});
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (isGlobalError(error)) throw error;
|
|
244
|
+
samples.push({
|
|
245
|
+
...dimension,
|
|
246
|
+
count: null,
|
|
247
|
+
values: [],
|
|
248
|
+
status: "error",
|
|
249
|
+
reason: error.message ?? String(error),
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
const snapshot = {
|
|
254
|
+
schemaVersion: 1,
|
|
255
|
+
workspaceId: String(workspaceId),
|
|
256
|
+
workspace: context.workspace ?? null,
|
|
257
|
+
models: withoutEmbeddedExamples(context.models ?? []),
|
|
258
|
+
dimensionSamples: samples,
|
|
259
|
+
limits: { valuesPerDimension, maxDimensions, maxCardinality },
|
|
260
|
+
sampledAt: new Date().toISOString(),
|
|
261
|
+
};
|
|
262
|
+
await atomicWrite(outputPath, `${JSON.stringify(snapshot, null, 2)}\n`);
|
|
263
|
+
return {
|
|
264
|
+
output: outputPath,
|
|
265
|
+
models: snapshot.models.length,
|
|
266
|
+
dimensions: samples.length,
|
|
267
|
+
sampled: samples.filter((item) => item.status === "success").length,
|
|
268
|
+
skipped: samples.filter((item) => item.status === "skipped").length,
|
|
269
|
+
errors: samples.filter((item) => item.status === "error").length,
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export async function collectExpected(client, workspaceId, question, poll) {
|
|
274
|
+
const thread = await client.request(
|
|
275
|
+
"POST",
|
|
276
|
+
`/api/v3/account-projects/${workspaceId}/threads/`,
|
|
277
|
+
{ body: {} },
|
|
278
|
+
);
|
|
279
|
+
const message = await client.request(
|
|
280
|
+
"POST",
|
|
281
|
+
`/api/v3/account-projects/${workspaceId}/threads/${thread.uid}/messages/`,
|
|
282
|
+
{ body: { message: question } },
|
|
283
|
+
);
|
|
284
|
+
const completed = await waitForMessage(
|
|
285
|
+
client,
|
|
286
|
+
workspaceId,
|
|
287
|
+
thread.uid,
|
|
288
|
+
message.id,
|
|
289
|
+
poll,
|
|
290
|
+
);
|
|
291
|
+
const understanding = extractUnderstanding(completed);
|
|
292
|
+
const unsupportedType = unsupportedQueryType(completed.current?.result);
|
|
293
|
+
if (unsupportedType)
|
|
294
|
+
throw new Error(
|
|
295
|
+
`当前测试集只支持直接单 query,不能保存 ${unsupportedType} 查询;请改写为单个问题后重试`,
|
|
296
|
+
);
|
|
297
|
+
const tokens = extractFinalTokens(completed.current?.result);
|
|
298
|
+
if (!tokens) throw new Error("DataSeek 最终 answer 缺少问题 Token");
|
|
299
|
+
const tokenWords = tokensToWords(tokens);
|
|
300
|
+
if (!tokenWords) throw new Error("DataSeek 最终问题 Token 缺少 word");
|
|
301
|
+
return { status: "success", understanding, tokens, tokenWords };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
export async function execute(argv, options = {}) {
|
|
305
|
+
const args = parseArgs(argv);
|
|
306
|
+
if (args.help === true || args._[0] === "help" || !args._[0]) return help();
|
|
307
|
+
if (args._[0] === "snapshot") return snapshotWorkspace(args, options);
|
|
308
|
+
if (args._[0] === "generate") return generate(args, options);
|
|
309
|
+
throw new Error("命令应为 snapshot 或 generate");
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function waitForMessage(client, workspaceId, threadUid, messageId, options) {
|
|
313
|
+
const started = Date.now();
|
|
314
|
+
while (Date.now() - started <= options.maxWaitMs) {
|
|
315
|
+
const message = await client.request(
|
|
316
|
+
"GET",
|
|
317
|
+
`/api/v3/account-projects/${workspaceId}/threads/${threadUid}/messages/${messageId}/`,
|
|
318
|
+
);
|
|
319
|
+
if (message.current?.error) throw new Error(String(message.current.error));
|
|
320
|
+
if (Array.isArray(message.current?.result) && message.current.result.length)
|
|
321
|
+
return message;
|
|
322
|
+
await client.sleep(options.intervalMs);
|
|
323
|
+
}
|
|
324
|
+
const error = new Error(
|
|
325
|
+
"DataSeek 消息轮询超时;请调大 --max-wait-ms 后重试",
|
|
326
|
+
);
|
|
327
|
+
error.code = "TASK_TIMEOUT";
|
|
328
|
+
throw error;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function safeOutputFile(value) {
|
|
332
|
+
if (typeof value !== "string" || !value || isAbsolute(value))
|
|
333
|
+
throw new Error("--output 必须是当前目录下的相对路径");
|
|
334
|
+
const root = resolve(process.cwd());
|
|
335
|
+
const target = resolve(root, value);
|
|
336
|
+
if (relative(root, target).startsWith(".."))
|
|
337
|
+
throw new Error("--output 不得超出当前目录");
|
|
338
|
+
return target;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function positiveInteger(value, name, allowZero = false) {
|
|
342
|
+
const number = Number(value);
|
|
343
|
+
if (!Number.isInteger(number) || number < (allowZero ? 0 : 1))
|
|
344
|
+
throw new Error(
|
|
345
|
+
`--${name} 必须是${allowZero ? "非负" : "正"}整数(当前值:${value});请修改参数后重试`,
|
|
346
|
+
);
|
|
347
|
+
return number;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function insertColumnAfter(header, name, precedingName) {
|
|
351
|
+
if (header.includes(name)) return;
|
|
352
|
+
const index = header.indexOf(precedingName);
|
|
353
|
+
header.splice(index < 0 ? header.length : index + 1, 0, name);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function validateColumnRoles(names) {
|
|
357
|
+
const roles = {
|
|
358
|
+
question: names.question,
|
|
359
|
+
understanding: names.understanding,
|
|
360
|
+
tokens: names.tokens,
|
|
361
|
+
tokenWords: names.tokenWords,
|
|
362
|
+
status: STATUS_COLUMN,
|
|
363
|
+
error: ERROR_COLUMN,
|
|
364
|
+
};
|
|
365
|
+
const seen = new Map();
|
|
366
|
+
for (const [role, rawName] of Object.entries(roles)) {
|
|
367
|
+
const name = String(rawName ?? "").trim();
|
|
368
|
+
if (!name) throw new Error(`${role} 列名不能为空`);
|
|
369
|
+
if (seen.has(name))
|
|
370
|
+
throw new Error(
|
|
371
|
+
`列名角色冲突:${seen.get(name)} 与 ${role} 均使用“${name}”`,
|
|
372
|
+
);
|
|
373
|
+
seen.set(name, role);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function boundedInteger(value, name, minimum, maximum) {
|
|
378
|
+
const number = Number(value);
|
|
379
|
+
if (!Number.isInteger(number) || number < minimum || number > maximum)
|
|
380
|
+
throw new Error(`--${name} 必须是 ${minimum} 到 ${maximum} 的整数`);
|
|
381
|
+
return number;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function uniqueDimensions(models) {
|
|
385
|
+
const dimensions = new Map();
|
|
386
|
+
for (const model of models) {
|
|
387
|
+
for (const dimension of model.dimensions ?? []) {
|
|
388
|
+
if (!Number.isInteger(Number(dimension.id))) continue;
|
|
389
|
+
const prop = `d${Number(dimension.id)}`;
|
|
390
|
+
const current = dimensions.get(prop) ?? {
|
|
391
|
+
id: Number(dimension.id),
|
|
392
|
+
prop,
|
|
393
|
+
name: dimension.name ?? prop,
|
|
394
|
+
description: dimension.description ?? null,
|
|
395
|
+
examples: [],
|
|
396
|
+
modelUids: [],
|
|
397
|
+
};
|
|
398
|
+
current.examples = [
|
|
399
|
+
...new Set([...current.examples, ...(dimension.examples ?? [])]),
|
|
400
|
+
];
|
|
401
|
+
if (model.uid && !current.modelUids.includes(model.uid))
|
|
402
|
+
current.modelUids.push(model.uid);
|
|
403
|
+
dimensions.set(prop, current);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
return [...dimensions.values()].sort((left, right) => left.id - right.id);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function uniqueWords(tokens) {
|
|
410
|
+
return [
|
|
411
|
+
...new Set(
|
|
412
|
+
(Array.isArray(tokens) ? tokens : [])
|
|
413
|
+
.map((token) => String(token?.word ?? "").trim())
|
|
414
|
+
.filter(Boolean),
|
|
415
|
+
),
|
|
416
|
+
];
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function withoutEmbeddedExamples(models) {
|
|
420
|
+
return models.map((model) => ({
|
|
421
|
+
...model,
|
|
422
|
+
dimensions: (model.dimensions ?? []).map(({ examples: _examples, ...item }) =>
|
|
423
|
+
item,
|
|
424
|
+
),
|
|
425
|
+
}));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
async function atomicWrite(path, content) {
|
|
429
|
+
await mkdir(dirname(path), { recursive: true });
|
|
430
|
+
const temporary = `${path}.tmp-${process.pid}`;
|
|
431
|
+
await writeFile(temporary, content, "utf8");
|
|
432
|
+
await rename(temporary, path);
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
async function writeNewFile(path, content) {
|
|
436
|
+
await mkdir(dirname(path), { recursive: true });
|
|
437
|
+
try {
|
|
438
|
+
await writeFile(path, content, { encoding: "utf8", flag: "wx" });
|
|
439
|
+
} catch (error) {
|
|
440
|
+
if (error?.code === "EEXIST")
|
|
441
|
+
throw new Error(
|
|
442
|
+
`输出文件已存在:${relative(process.cwd(), path)};请指定新的 --output 路径后重试`,
|
|
443
|
+
);
|
|
444
|
+
throw error;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function jsonCell(value) {
|
|
449
|
+
return value === undefined ? "" : JSON.stringify(value);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function visit(value, callback, seen = new Set()) {
|
|
453
|
+
if (!value || typeof value !== "object" || seen.has(value)) return;
|
|
454
|
+
seen.add(value);
|
|
455
|
+
callback(value);
|
|
456
|
+
for (const child of Array.isArray(value) ? value : Object.values(value))
|
|
457
|
+
visit(child, callback, seen);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export function unsupportedQueryType(actions) {
|
|
461
|
+
let result = null;
|
|
462
|
+
visit(actions, (value) => {
|
|
463
|
+
if (!result && ["parallel", "chained"].includes(value?.type))
|
|
464
|
+
result = value.type;
|
|
465
|
+
});
|
|
466
|
+
return result;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function findUnderstanding(value) {
|
|
470
|
+
if (value === null || value === undefined) return null;
|
|
471
|
+
if (Array.isArray(value)) {
|
|
472
|
+
for (const item of [...value].reverse()) {
|
|
473
|
+
const result = findUnderstanding(item);
|
|
474
|
+
if (result) return result;
|
|
475
|
+
}
|
|
476
|
+
return null;
|
|
477
|
+
}
|
|
478
|
+
if (typeof value === "object") {
|
|
479
|
+
if (
|
|
480
|
+
Object.hasOwn(value, "dimensions") &&
|
|
481
|
+
Object.hasOwn(value, "metrics") &&
|
|
482
|
+
Object.hasOwn(value, "time_range")
|
|
483
|
+
)
|
|
484
|
+
return value;
|
|
485
|
+
for (const item of Object.values(value)) {
|
|
486
|
+
const result = findUnderstanding(item);
|
|
487
|
+
if (result) return result;
|
|
488
|
+
}
|
|
489
|
+
return null;
|
|
490
|
+
}
|
|
491
|
+
const text = String(value).trim();
|
|
492
|
+
const start = text.indexOf("{");
|
|
493
|
+
const end = text.lastIndexOf("}");
|
|
494
|
+
for (const candidate of [
|
|
495
|
+
text,
|
|
496
|
+
text.replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, ""),
|
|
497
|
+
start >= 0 && end > start ? text.slice(start, end + 1) : "",
|
|
498
|
+
]) {
|
|
499
|
+
if (!candidate) continue;
|
|
500
|
+
try {
|
|
501
|
+
const result = findUnderstanding(JSON.parse(candidate));
|
|
502
|
+
if (result) return result;
|
|
503
|
+
} catch {
|
|
504
|
+
// 尝试下一种包装形式。
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
return null;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function csvField(value) {
|
|
511
|
+
const text = String(value ?? "");
|
|
512
|
+
return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function help() {
|
|
516
|
+
return {
|
|
517
|
+
usage: [
|
|
518
|
+
"snapshot --workspace-id <id> --output <relative-json> [--values-per-dimension <n>] [--max-dimensions <n>] [--max-cardinality <n>]",
|
|
519
|
+
"generate --workspace-id <id> --input <csv> --output <relative-csv> --question-column <name> [--understanding-column <name>] [--tokens-column <name>] [--token-words-column <name>]",
|
|
520
|
+
],
|
|
521
|
+
options: ["--poll-interval-ms <n>", "--max-wait-ms <n>"],
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
|
526
|
+
await runCli(() => execute(process.argv.slice(2)));
|