- tests/test-import-buildformdata.ts: 证明 dacli 可 import web 端 buildFormData (替换 #/ alias + @jnpf/utils → uuid.ts + lodash-es → structuredClone) - tests/test-direct-ai-call.ts: 验证直接调 AI API 可用 - tests/test-direct-ai-jnpf-prompt.ts: JNPF 原版 GEN_MODEL_QUETION prompt + Anthropic 格式 + 简单/主子表 2 个测试 - data/buildformdata-contract.md: buildFormData 契约清单(16+50+23 keys) 验证结论: - buildFormData 100% 注入 formId/renderKey/isSubTable (BS-51 根因) - buildFormData 自动为 select/options 注入 (BS-54 根因) - JNPF 原版 prompt 可直接用于直连 AI, 不需 JNPF backend - 后续 _ai.ts 改造为双路径 (env 直连 / JNPF backend fallback)
161 lines
6.0 KiB
TypeScript
161 lines
6.0 KiB
TypeScript
// 测试:dacli _ai.ts 改造为 model-agnostic + 真实 API 调用
|
||
// 凭据通过环境变量注入,不入文件
|
||
|
||
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
|
||
import { tmpdir } from 'os';
|
||
import { resolve, dirname } from 'path';
|
||
import { pathToFileURL } from 'url';
|
||
|
||
const BASE_URL = process.env.DACLI_AI_BASE_URL;
|
||
const AUTH_TOKEN = process.env.DACLI_AI_AUTH_TOKEN;
|
||
const MODEL = process.env.DACLI_AI_MODEL;
|
||
|
||
if (!BASE_URL || !AUTH_TOKEN || !MODEL) {
|
||
console.error('❌ 需要设置环境变量:');
|
||
console.error(' DACLI_AI_BASE_URL, DACLI_AI_AUTH_TOKEN, DACLI_AI_MODEL');
|
||
process.exit(1);
|
||
}
|
||
|
||
console.log('=== 配置 ===');
|
||
console.log(' BASE_URL:', BASE_URL);
|
||
console.log(' AUTH_TOKEN:', AUTH_TOKEN.slice(0, 10) + '...' + AUTH_TOKEN.slice(-4));
|
||
console.log(' MODEL:', MODEL);
|
||
console.log();
|
||
|
||
// 1. 复用测试 1 的 import 机制拿 buildFormData
|
||
const WEB_SRC = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src';
|
||
let buildFormDataSrc = readFileSync(`${WEB_SRC}/components/FormGenerator/src/helper/formUtils.ts`, 'utf-8');
|
||
const JNPF_UTILS_UUID = '/home/ubuntu/ccWorkDir/web/packages/jnpf/utils/src/helpers/uuid.ts';
|
||
buildFormDataSrc = buildFormDataSrc
|
||
.replace(/from\s+['"]#\/(.+?)['"]/g, (_, p) => `from '${WEB_SRC}/${p}'`)
|
||
.replace(/from\s+['"]@jnpf\/utils['"]/g, `from '${JNPF_UTILS_UUID}'`)
|
||
.replace(/import\s*\{\s*cloneDeep\s*\}\s*from\s+['"]lodash-es['"];?/g,
|
||
`const cloneDeep = (x) => structuredClone(x);`);
|
||
|
||
const tmpDir = `${tmpdir()}/dacli-ai-test-${Date.now()}`;
|
||
mkdirSync(tmpDir, { recursive: true });
|
||
const tmpBuildFormData = `${tmpDir}/formUtils.ts`;
|
||
writeFileSync(tmpBuildFormData, buildFormDataSrc);
|
||
const { buildFormData } = await import(pathToFileURL(tmpBuildFormData).href);
|
||
console.log('✅ buildFormData 加载成功\n');
|
||
|
||
// 2. 调 AI 拿 form 描述(Anthropic Messages API 格式)
|
||
const url = `${BASE_URL}/v1/messages`;
|
||
const prompt = `设计一个简单的客户管理表单。包含字段:客户姓名(单行文本)、联系电话(单行文本)、客户类型(单选:个人/企业)、备注(多行文本)。
|
||
请严格按以下 JSON 格式返回(不要其他任何内容):
|
||
[{
|
||
"tableTitle": "客户",
|
||
"tableName": "customer",
|
||
"fields": [
|
||
{"fieldTitle": "客户姓名", "fieldName": "f_name", "fieldComponent": "input"},
|
||
...
|
||
]
|
||
}]`;
|
||
|
||
console.log('=== POST', url, '===');
|
||
const aiStart = Date.now();
|
||
const resp = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'x-api-key': AUTH_TOKEN,
|
||
'anthropic-version': '2023-06-01',
|
||
'content-type': 'application/json',
|
||
},
|
||
body: JSON.stringify({
|
||
model: MODEL,
|
||
max_tokens: 2000,
|
||
messages: [{ role: 'user', content: prompt }],
|
||
}),
|
||
});
|
||
const aiMs = Date.now() - aiStart;
|
||
console.log(` HTTP ${resp.status} ${aiMs}ms`);
|
||
|
||
if (!resp.ok) {
|
||
const errText = await resp.text();
|
||
console.error('❌ AI 调用失败:');
|
||
console.error(errText.slice(0, 500));
|
||
process.exit(1);
|
||
}
|
||
|
||
const aiResp = await resp.json();
|
||
console.log('\n=== AI 响应原始结构 ===');
|
||
console.log(' keys:', Object.keys(aiResp));
|
||
if (aiResp.usage) console.log(' usage:', JSON.stringify(aiResp.usage));
|
||
if (aiResp.model) console.log(' model:', aiResp.model);
|
||
if (aiResp.stop_reason) console.log(' stop_reason:', aiResp.stop_reason);
|
||
|
||
// 3. 提取 text content
|
||
const textContent = aiResp.content
|
||
?.filter((b: any) => b.type === 'text')
|
||
.map((b: any) => b.text)
|
||
.join('\n');
|
||
if (!textContent) {
|
||
console.error('❌ 响应中没有 text content');
|
||
console.error('content:', JSON.stringify(aiResp.content));
|
||
process.exit(1);
|
||
}
|
||
|
||
console.log('\n=== AI 返回文本(前 500 字)===');
|
||
console.log(textContent.slice(0, 500));
|
||
console.log('...');
|
||
|
||
// 4. 解析 JSON
|
||
const jsonStart = textContent.indexOf('[');
|
||
const jsonEnd = textContent.lastIndexOf(']');
|
||
if (jsonStart === -1 || jsonEnd === -1) {
|
||
console.error('❌ 响应中没有 JSON 数组');
|
||
process.exit(1);
|
||
}
|
||
const jsonStr = textContent.slice(jsonStart, jsonEnd + 1);
|
||
let aiModelList;
|
||
try {
|
||
aiModelList = JSON.parse(jsonStr);
|
||
} catch (e: any) {
|
||
console.error('❌ JSON 解析失败:', e.message);
|
||
console.error('JSON 字符串(前 500):', jsonStr.slice(0, 500));
|
||
process.exit(1);
|
||
}
|
||
console.log('\n=== 解析后的 aiModelList ===');
|
||
console.log(' 表数:', aiModelList.length);
|
||
for (const t of aiModelList) {
|
||
console.log(` - [${t.isMain ? '主' : '子'}] ${t.tableName}: ${t.tableTitle} (${t.fields?.length || 0} 字段)`);
|
||
for (const f of t.fields || []) {
|
||
console.log(` ${f.fieldName} ${f.fieldComponent} "${f.fieldTitle}"`);
|
||
}
|
||
}
|
||
|
||
// 5. 喂给 buildFormData
|
||
console.log('\n=== 喂给 buildFormData ===');
|
||
const aiModelListWithMain = aiModelList.map((t: any, i: number) => ({ ...t, isMain: i === 0 }));
|
||
const formDataResult = buildFormData(aiModelListWithMain);
|
||
const formData = JSON.parse(formDataResult.formData);
|
||
|
||
console.log(' formData.fields 数:', formData.fields.length);
|
||
console.log(' formConf 顶层 keys 数:', Object.keys(formData).length);
|
||
console.log(' defaultDataForm 顶层 keys:', Object.keys(formDataResult).filter((k: string) => k !== 'formData'));
|
||
|
||
console.log('\n=== 第一个 field 详细 ===');
|
||
const f0 = formData.fields[0];
|
||
console.log(' __vModel__:', f0.__vModel__);
|
||
console.log(' __config__ keys (', Object.keys(f0.__config__).length, '个)');
|
||
console.log(' ⭐ formId:', f0.__config__.formId);
|
||
console.log(' ⭐ renderKey:', f0.__config__.renderKey);
|
||
console.log(' ⭐ tag:', f0.__config__.tag);
|
||
console.log(' ⭐ isSubTable:', f0.__config__.isSubTable);
|
||
|
||
console.log('\n=== select 字段(如果有)===');
|
||
const selectField = formData.fields.find((f: any) => f.options);
|
||
if (selectField) {
|
||
console.log(' 字段:', selectField.__vModel__);
|
||
console.log(' options:', JSON.stringify(selectField.options));
|
||
} else {
|
||
console.log(' (本例无 select)');
|
||
}
|
||
|
||
console.log('\n✅ 完整链路验证通过:');
|
||
console.log(' 1. AI API 调到 ✅');
|
||
console.log(' 2. AI 理解 JNPF schema 格式 ✅');
|
||
console.log(' 3. JSON 解析 ✅');
|
||
console.log(' 4. 喂给 buildFormData ✅');
|
||
console.log(' 5. schema 完整(含 formId/renderKey/isSubTable)✅');
|