920 lines
38 KiB
TypeScript
920 lines
38 KiB
TypeScript
/**
|
||
* NAC 自主推理问答引擎 (NAC Autonomous Inference Engine)
|
||
*
|
||
* 设计原则:
|
||
* - 零外部 LLM 依赖,完全在 NAC 私有服务器上运行
|
||
* - 基于 CNNL 规则推理 + RAG 知识库检索
|
||
* - 封闭域专业问答:只回答与 NAC 公链相关的问题
|
||
* - 支持七种语言输出(zh/en/ar/ja/ko/fr/ru)
|
||
*
|
||
* 架构:
|
||
* 用户问题 → 意图识别 → 实体提取 → RAG检索 → CNNL推理 → 模板化回答生成
|
||
*/
|
||
|
||
import { retrieveComplianceRules, buildRAGPromptContext, type RAGContext } from "./ragRetrieval";
|
||
|
||
// ─── 类型定义 ─────────────────────────────────────────────────────
|
||
|
||
export interface InferenceRequest {
|
||
question: string;
|
||
language?: string; // zh | en | ar | ja | ko | fr | ru
|
||
jurisdiction?: string; // CN | HK | SG | AE | EU | US
|
||
assetType?: string; // RealEstate | Equity | Bond | Commodity | IP | Fund
|
||
sessionId?: string;
|
||
}
|
||
|
||
export interface InferenceResponse {
|
||
answer: string; // 自然语言回答
|
||
confidence: number; // 置信度 0-1
|
||
intent: QueryIntent; // 识别到的意图
|
||
entities: ExtractedEntities; // 提取的实体
|
||
sources: SourceReference[]; // 引用的知识库条目
|
||
suggestions: string[]; // 后续建议问题
|
||
engineVersion: string; // 引擎版本
|
||
processingMs: number; // 处理耗时
|
||
}
|
||
|
||
export type QueryIntent =
|
||
| "compliance_query" // 合规要求查询
|
||
| "document_checklist" // 文件清单查询
|
||
| "process_guide" // 上链流程指导
|
||
| "technical_query" // 技术概念查询(Charter/CNNL/NVM等)
|
||
| "jurisdiction_compare" // 管辖区对比
|
||
| "asset_type_query" // 资产类型查询
|
||
| "fee_query" // 费用查询
|
||
| "ownership_verification" // 所有权验证查询(新增)
|
||
| "trading_rules" // 贸易规则查询(新增)
|
||
| "general_nac" // 一般性 NAC 公链问题
|
||
| "out_of_scope"; // 超出范围(非 NAC 相关)
|
||
|
||
export interface ExtractedEntities {
|
||
jurisdictions: string[];
|
||
assetTypes: string[];
|
||
technicalTerms: string[];
|
||
documentTypes: string[];
|
||
keywords: string[];
|
||
}
|
||
|
||
export interface SourceReference {
|
||
ruleId: string;
|
||
ruleName: string;
|
||
jurisdiction: string;
|
||
category: string;
|
||
relevance: number;
|
||
}
|
||
|
||
// ─── 意图识别模式 ─────────────────────────────────────────────────
|
||
|
||
const INTENT_PATTERNS: Array<{ intent: QueryIntent; patterns: RegExp[] }> = [
|
||
{
|
||
intent: "document_checklist",
|
||
patterns: [
|
||
/需要(哪些|什么|哪几个)(文件|材料|证明|文档)/,
|
||
/文件(清单|列表|要求)/,
|
||
/what (documents?|materials?|files?) (are|do)/i,
|
||
/document (checklist|requirements?|list)/i,
|
||
/提交(哪些|什么)/,
|
||
],
|
||
},
|
||
{
|
||
intent: "compliance_query",
|
||
patterns: [
|
||
/合规(要求|规定|标准|条件|审查)/,
|
||
/是否合规/,
|
||
/合规(吗|么|吧)/,
|
||
/compliance (requirements?|rules?|standards?)/i,
|
||
/七层合规/,
|
||
/KYC|AML|反洗钱|反恐融资/i,
|
||
],
|
||
},
|
||
{
|
||
intent: "process_guide",
|
||
patterns: [
|
||
/如何(上链|注册|申请|操作|使用)/,
|
||
/怎么(上链|注册|申请|操作)/,
|
||
/(上链|注册|申请)(流程|步骤|过程|方法)/,
|
||
/how to (onboard|register|apply|use)/i,
|
||
/step[s]? (to|for)/i,
|
||
/流程是什么/,
|
||
],
|
||
},
|
||
{
|
||
intent: "technical_query",
|
||
patterns: [
|
||
/Charter|CNNL|NVM|CBPP|CSNP|NRPC|GNACS|ACC-20|XTZH/i,
|
||
/智能合约|虚拟机|共识|区块链/,
|
||
/NAC(公链|链|网络)/,
|
||
/什么是(NAC|Charter|CNNL|NVM|CBPP|XTZH)/,
|
||
/how does .*(work|function)/i,
|
||
],
|
||
},
|
||
{
|
||
intent: "jurisdiction_compare",
|
||
patterns: [
|
||
/(中国|香港|新加坡|迪拜|欧盟|美国).*(和|与|比较|对比).*(中国|香港|新加坡|迪拜|欧盟|美国)/,
|
||
/(CN|HK|SG|AE|EU|US).*(vs?|compare|difference)/i,
|
||
/不同(管辖区|地区|国家)(的|有什么)差异/,
|
||
/哪个(管辖区|地区|国家)更(好|适合|容易)/,
|
||
],
|
||
},
|
||
{
|
||
intent: "asset_type_query",
|
||
patterns: [
|
||
/(房地产|股权|债券|大宗商品|知识产权|基金)(上链|RWA|合规)/,
|
||
/(RealEstate|Equity|Bond|Commodity|IP|Fund)/i,
|
||
/什么类型的资产/,
|
||
/资产类型/,
|
||
],
|
||
},
|
||
{
|
||
intent: "ownership_verification",
|
||
patterns: [
|
||
/所有权(验证|证明|确认|查询)/,
|
||
/产权(证明|验证|文件)/,
|
||
/确权|所有人|所有者/,
|
||
/(谁|如何)(拥有|持有|证明)/,
|
||
/ownership (verification|proof|confirmation)/i,
|
||
/title (deed|verification|transfer)/i,
|
||
/所有权(转移|过户)/,
|
||
/外资(限制|规定|要求)/,
|
||
/登记(机构|机关|要求)/,
|
||
],
|
||
},
|
||
{
|
||
intent: "trading_rules",
|
||
patterns: [
|
||
/贸易(规则|规定|要求|限制)/,
|
||
/交易(规则|规定|要求|限制|条件)/,
|
||
/(买卖|上市|流通)(规则|条件|要求)/,
|
||
/投资者(资质|要求|门槛)/,
|
||
/结算(周期|规则|方式)/,
|
||
/允许(货币|币种)/,
|
||
/trading (rules?|requirements?|restrictions?)/i,
|
||
/settlement (period|rules?)/i,
|
||
/investor (qualification|requirements?)/i,
|
||
/资产(交易|流通)(规则|要求)/,
|
||
],
|
||
},
|
||
{
|
||
intent: "fee_query",
|
||
patterns: [
|
||
/费用|收费|价格|成本|手续费|gas/i,
|
||
/how much|cost|fee|price/i,
|
||
/多少钱|多少费用/,
|
||
],
|
||
},
|
||
];
|
||
|
||
// ─── 实体提取模式 ─────────────────────────────────────────────────
|
||
|
||
const JURISDICTION_MAP: Record<string, string> = {
|
||
"中国": "CN", "中国大陆": "CN", "大陆": "CN", "CN": "CN",
|
||
"香港": "HK", "HK": "HK",
|
||
"新加坡": "SG", "SG": "SG",
|
||
"迪拜": "AE", "阿联酋": "AE", "UAE": "AE", "AE": "AE", "DIFC": "AE",
|
||
"欧盟": "EU", "EU": "EU", "欧洲": "EU",
|
||
"美国": "US", "US": "US", "SEC": "US",
|
||
};
|
||
|
||
const ASSET_TYPE_MAP: Record<string, string> = {
|
||
"房地产": "RealEstate", "房产": "RealEstate", "不动产": "RealEstate", "物业": "RealEstate",
|
||
"股权": "Equity", "股票": "Equity", "股份": "Equity",
|
||
"债券": "Bond", "债权": "Bond",
|
||
"大宗商品": "Commodity", "商品": "Commodity", "黄金": "Commodity", "原油": "Commodity",
|
||
"知识产权": "IP", "专利": "IP", "版权": "IP",
|
||
"基金": "Fund", "信托": "Fund",
|
||
};
|
||
|
||
const TECH_TERMS = [
|
||
"Charter", "CNNL", "NVM", "CBPP", "CSNP", "NRPC", "GNACS", "ACC-20", "XTZH",
|
||
"RWA", "KYC", "AML", "DID", "DNA", "七层合规", "宪法节点", "CBP节点",
|
||
"XTZH", "SDR", "量子浏览器", "流体区块",
|
||
];
|
||
|
||
// ─── NAC 技术知识库(内置,不依赖外部 LLM)─────────────────────────
|
||
|
||
const NAC_KNOWLEDGE_BASE: Record<string, string> = {
|
||
"Charter": `Charter 是 NAC 公链的原生智能合约语言,专为 RWA(真实世界资产)合规场景设计。
|
||
Charter 使用 clause(条款)作为基本单元,而非传统的 contract(合约)。
|
||
语法特点:大写标识符命名、predicate 谓词逻辑、内置合规验证操作码。
|
||
示例:clause ASSET_COMPLIANCE { predicate IS_VALID(value: u64) -> bool { value > 0 } }
|
||
Charter 编译后生成 NVM 字节码,在 NAC 虚拟机上执行。`,
|
||
|
||
"CNNL": `CNNL(宪政神经网络语言)是 NAC 公链的宪法规则描述语言,用于编写链上合规规则。
|
||
CNNL 与 Charter 的区别:CNNL 描述"什么是合规"(规则层),Charter 描述"如何执行"(执行层)。
|
||
CNNL 编译器地址:https://cnnl.newassetchain.io
|
||
三层架构:战略层(宪法条款)→ 战术层(合规规则)→ 操作层(验证逻辑)`,
|
||
|
||
"NVM": `NVM(NAC Virtual Machine)是 NAC 公链的原生虚拟机,专为 RWA 合规执行设计。
|
||
NVM 与 EVM 的区别:NVM 内置 AI 合规验证操作码、支持 GNACS 资产分类、原生支持 ACC-20 协议。
|
||
当前版本:NVM v2.0,支持流体区块模式。`,
|
||
|
||
"CBPP": `CBPP(Constitutional Block Production Protocol)是 NAC 公链的共识协议。
|
||
CBPP 基于宪政节点(CBP 节点)轮流出块,而非 PoS/PoW 挖矿。
|
||
CBP 节点需要:KYC Level 2 + constitutional 节点状态 + 质押 XTZH。
|
||
区块生产流程:提案 → 宪法验证 → 多签确认 → 上链 → 广播。`,
|
||
|
||
"CSNP": `CSNP(Constitutional Sovereign Network Protocol)是 NAC 公链的网络协议,替代传统 P2P。
|
||
CSNP V2.0 六层架构:物理层 → 数据链路层 → 网络层 → 传输层 → 会话层 → 应用层。
|
||
CSNP 与传统 P2P 的区别:节点需要宪法授权才能加入网络,防止女巫攻击。`,
|
||
|
||
"XTZH": `XTZH 是 NAC 公链的原生稳定币,采用 SDR 锚定模型 + 黄金储备双重背书。
|
||
SDR 篮子权重:USD 41.73% + EUR 30.93% + CNY 10.92% + JPY 8.33% + GBP 8.09%。
|
||
黄金储备:每枚 XTZH 背后有等值黄金储备支撑。
|
||
用途:链上 Gas 费用、质押、RWA 资产定价。`,
|
||
|
||
"GNACS": `GNACS(Global NAC Asset Classification System)是 NAC 公链的全球资产分类编码系统。
|
||
GNACS 为每类资产分配唯一的 48 字节 Hash 编码(SHA3-384)。
|
||
支持资产类型:房地产、股权、债券、大宗商品、知识产权、基金。`,
|
||
|
||
"ACC-20": `ACC-20 是 NAC 公链的原生资产协议标准,类似以太坊的 ERC-20 但专为 RWA 设计。
|
||
ACC-20 内置:AI 合规验证、AI 估值、GNACS 分类编码、七层合规验证框架。
|
||
ACC-20 资产上链需要通过七层合规验证才能铸造(mint)。`,
|
||
|
||
"七层合规": `NAC 七层合规验证框架是 RWA 资产上链的核心审查机制:
|
||
第1层:身份验证(KYC/AML)
|
||
第2层:资产真实性验证(实物资产证明)
|
||
第3层:所有权验证(产权证明)
|
||
第4层:估值验证(AI 估值 + 第三方评估)
|
||
第5层:法律合规验证(管辖区法规)
|
||
第6层:技术合规验证(Charter 合约审计)
|
||
第7层:宪法合规验证(CNNL 规则通过)`,
|
||
|
||
"RWA": `RWA(Real World Assets)即真实世界资产,是 NAC 公链的核心应用场景。
|
||
NAC 公链专为 RWA 上链设计,支持:房地产、股权、债券、大宗商品、知识产权、基金。
|
||
RWA 上链流程:资产评估 → KYC 认证 → 七层合规验证 → GNACS 编码 → ACC-20 铸造 → 链上确权。`,
|
||
};
|
||
|
||
// ─── 多语言回答模板 ───────────────────────────────────────────────
|
||
|
||
const ANSWER_TEMPLATES: Record<string, Record<string, string>> = {
|
||
"out_of_scope": {
|
||
zh: "抱歉,我只能回答与 NAC 公链相关的问题,包括:合规要求、上链流程、Charter/CNNL 技术、XTZH 稳定币、RWA 资产上链等。请重新提问。",
|
||
en: "Sorry, I can only answer questions related to the NAC blockchain, including: compliance requirements, onboarding process, Charter/CNNL technology, XTZH stablecoin, and RWA asset onboarding. Please rephrase your question.",
|
||
ar: "آسف، يمكنني فقط الإجابة على الأسئلة المتعلقة بسلسلة كتل NAC.",
|
||
ja: "申し訳ありませんが、NAC公チェーンに関連する質問のみお答えできます。",
|
||
ko: "죄송합니다. NAC 블록체인 관련 질문만 답변할 수 있습니다.",
|
||
fr: "Désolé, je ne peux répondre qu'aux questions relatives à la blockchain NAC.",
|
||
ru: "Извините, я могу отвечать только на вопросы, связанные с блокчейном NAC.",
|
||
},
|
||
"no_rules_found": {
|
||
zh: "在知识库中未找到与您问题直接相关的合规规则。建议您联系 NAC 合规团队获取专业指导:compliance@newassetchain.io",
|
||
en: "No directly relevant compliance rules were found in the knowledge base. Please contact the NAC compliance team: compliance@newassetchain.io",
|
||
ar: "لم يتم العثور على قواعد امتثال ذات صلة مباشرة. يرجى التواصل مع فريق الامتثال: compliance@newassetchain.io",
|
||
ja: "関連するコンプライアンスルールが見つかりませんでした。NACコンプライアンスチームにお問い合わせください。",
|
||
ko: "관련 규정을 찾을 수 없습니다. NAC 컴플라이언스 팀에 문의하세요.",
|
||
fr: "Aucune règle de conformité directement pertinente n'a été trouvée. Veuillez contacter l'équipe de conformité NAC.",
|
||
ru: "Соответствующие правила соответствия не найдены. Обратитесь в команду NAC по соответствию.",
|
||
},
|
||
};
|
||
|
||
// ─── 核心推理引擎 ─────────────────────────────────────────────────
|
||
|
||
/**
|
||
* 识别用户问题的意图
|
||
*/
|
||
function detectIntent(question: string): QueryIntent {
|
||
const q = question.toLowerCase();
|
||
|
||
// 检查是否超出范围(非 NAC 相关)
|
||
const nacRelated = /nac|charter|cnnl|nvm|cbpp|csnp|xtzh|gnacs|acc-20|rwa|合规|上链|区块链|blockchain|公链|newassetchain/i.test(question);
|
||
const generalBlockchain = /比特币|以太坊|bitcoin|ethereum|solana|bnb|defi|nft/i.test(question);
|
||
const nonBlockchain = /天气|新闻|股票|汇率|美食|旅游|娱乐|体育/i.test(question);
|
||
|
||
if (nonBlockchain && !nacRelated) return "out_of_scope";
|
||
if (generalBlockchain && !nacRelated) return "out_of_scope";
|
||
|
||
// 按优先级匹配意图
|
||
for (const { intent, patterns } of INTENT_PATTERNS) {
|
||
if (patterns.some(p => p.test(question))) {
|
||
return intent;
|
||
}
|
||
}
|
||
|
||
// 默认:如果包含 NAC 相关词汇,归为一般性 NAC 问题
|
||
if (nacRelated) return "general_nac";
|
||
|
||
return "out_of_scope";
|
||
}
|
||
|
||
/**
|
||
* 从问题中提取实体
|
||
*/
|
||
function extractEntities(question: string): ExtractedEntities {
|
||
const jurisdictions: string[] = [];
|
||
const assetTypes: string[] = [];
|
||
const technicalTerms: string[] = [];
|
||
const documentTypes: string[] = [];
|
||
const keywords: string[] = [];
|
||
|
||
// 提取管辖区
|
||
for (const [key, code] of Object.entries(JURISDICTION_MAP)) {
|
||
if (question.includes(key) && !jurisdictions.includes(code)) {
|
||
jurisdictions.push(code);
|
||
}
|
||
}
|
||
|
||
// 提取资产类型
|
||
for (const [key, type] of Object.entries(ASSET_TYPE_MAP)) {
|
||
if (question.includes(key) && !assetTypes.includes(type)) {
|
||
assetTypes.push(type);
|
||
}
|
||
}
|
||
|
||
// 提取技术术语
|
||
for (const term of TECH_TERMS) {
|
||
if (question.toLowerCase().includes(term.toLowerCase())) {
|
||
technicalTerms.push(term);
|
||
}
|
||
}
|
||
|
||
// 提取文件类型关键词
|
||
const docPatterns = ["不动产登记证", "营业执照", "KYC", "AML", "评估报告", "产权证", "合规证明"];
|
||
for (const doc of docPatterns) {
|
||
if (question.includes(doc)) documentTypes.push(doc);
|
||
}
|
||
|
||
// 提取通用关键词(中文分词简化版:提取2字以上的词)
|
||
const chineseWords = question.match(/[\u4e00-\u9fa5]{2,6}/g) || [];
|
||
const englishWords = question.match(/[A-Za-z]{3,}/g) || [];
|
||
keywords.push(...chineseWords.slice(0, 5), ...englishWords.slice(0, 3));
|
||
|
||
return { jurisdictions, assetTypes, technicalTerms, documentTypes, keywords };
|
||
}
|
||
|
||
/**
|
||
* 生成技术概念回答(基于内置知识库)
|
||
*/
|
||
function generateTechAnswer(entities: ExtractedEntities, language: string): string | null {
|
||
for (const term of entities.technicalTerms) {
|
||
const knowledge = NAC_KNOWLEDGE_BASE[term];
|
||
if (knowledge) {
|
||
if (language === "en") {
|
||
// 简单英文化处理(实际可扩展多语言版本)
|
||
return `**${term}** - NAC Blockchain Technical Concept:\n\n${knowledge}`;
|
||
}
|
||
return `**${term}** — NAC 公链技术概念:\n\n${knowledge}`;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 基于 RAG 检索结果生成结构化回答
|
||
*/
|
||
function generateAnswerFromRAG(
|
||
intent: QueryIntent,
|
||
entities: ExtractedEntities,
|
||
ragCtx: RAGContext,
|
||
language: string,
|
||
question: string
|
||
): { answer: string; confidence: number; suggestions: string[] } {
|
||
const lang = language || "zh";
|
||
const rules = ragCtx.rules;
|
||
|
||
if (rules.length === 0) {
|
||
return {
|
||
answer: ANSWER_TEMPLATES["no_rules_found"][lang] || ANSWER_TEMPLATES["no_rules_found"]["zh"],
|
||
confidence: 0.1,
|
||
suggestions: [
|
||
lang === "zh" ? "查看 NAC 公链文档" : "View NAC documentation",
|
||
lang === "zh" ? "联系合规团队" : "Contact compliance team",
|
||
],
|
||
};
|
||
}
|
||
|
||
const lines: string[] = [];
|
||
let confidence = 0.7;
|
||
|
||
// 根据意图生成不同格式的回答
|
||
switch (intent) {
|
||
case "document_checklist": {
|
||
const jurisdiction = entities.jurisdictions[0] || "通用";
|
||
const assetType = entities.assetTypes[0] || "RWA资产";
|
||
|
||
lines.push(lang === "zh"
|
||
? `## ${jurisdiction} ${assetType} 上链所需文件清单`
|
||
: `## Document Checklist for ${assetType} in ${jurisdiction}`);
|
||
lines.push("");
|
||
|
||
const requiredRules = rules.filter(r => r.category === "Document" || r.ruleName.includes("证") || r.ruleName.includes("书"));
|
||
const allRules = requiredRules.length > 0 ? requiredRules : rules;
|
||
|
||
allRules.forEach((rule, idx) => {
|
||
const marker = `${idx + 1}. ✅`;
|
||
lines.push(`${marker} **${rule.ruleName}**(${rule.jurisdiction})`);
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(` 📜 法律依据:${ruleExt.legalBasis}`);
|
||
}
|
||
if (rule.content) {
|
||
lines.push(` ${rule.content.slice(0, 400)}`);
|
||
}
|
||
const owReq = ruleExt.ownershipRequirements as Record<string, unknown> | undefined;
|
||
if (owReq) {
|
||
if (owReq.proofDocuments && Array.isArray(owReq.proofDocuments) && (owReq.proofDocuments as string[]).length > 0) {
|
||
lines.push(` 📋 所需文件:${(owReq.proofDocuments as string[]).join("、")}`);
|
||
}
|
||
if (owReq.registrationAuthority) {
|
||
lines.push(` 🏛️ 登记机构:${owReq.registrationAuthority}`);
|
||
}
|
||
if (owReq.chainRecognition) {
|
||
lines.push(` ⛓️ 链上认可:${owReq.chainRecognition}`);
|
||
}
|
||
if (owReq.foreignOwnershipRestriction) {
|
||
lines.push(` ⚠️ 外资限制:${owReq.foreignOwnershipRestriction}`);
|
||
}
|
||
}
|
||
if (ruleExt.sourceUrl) {
|
||
lines.push(` 🔗 官方来源:${ruleExt.sourceUrl}`);
|
||
}
|
||
lines.push("");
|
||
});
|
||
|
||
lines.push("---");
|
||
lines.push(lang === "zh"
|
||
? `> 以上清单基于 NAC 合规知识库(${rules.length} 条规则),如有疑问请联系 compliance@newassetchain.io`
|
||
: `> Based on NAC compliance knowledge base (${rules.length} rules). Contact compliance@newassetchain.io for questions.`);
|
||
|
||
confidence = 0.88;
|
||
break;
|
||
}
|
||
|
||
case "compliance_query": {
|
||
lines.push(lang === "zh" ? "## 合规要求分析" : "## Compliance Requirements Analysis");
|
||
lines.push("");
|
||
|
||
if (entities.jurisdictions.length > 0) {
|
||
lines.push(lang === "zh"
|
||
? `**适用管辖区**:${entities.jurisdictions.join("、")}`
|
||
: `**Applicable Jurisdictions**: ${entities.jurisdictions.join(", ")}`);
|
||
lines.push("");
|
||
}
|
||
|
||
rules.forEach((rule) => {
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
lines.push(`### ${rule.ruleName}`);
|
||
lines.push(`- **${lang === "zh" ? "管辖区" : "Jurisdiction"}**: ${rule.jurisdiction}`);
|
||
lines.push(`- **${lang === "zh" ? "分类" : "Category"}**: ${rule.category}${ruleExt.assetClass ? " / " + ruleExt.assetClass : ""}`);
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(`- **${lang === "zh" ? "法律依据" : "Legal Basis"}**: ${ruleExt.legalBasis}`);
|
||
}
|
||
if (rule.content) {
|
||
lines.push(`- **${lang === "zh" ? "详细内容" : "Content"}**: ${rule.content.slice(0, 500)}`);
|
||
}
|
||
const owReq2 = ruleExt.ownershipRequirements as Record<string, unknown> | undefined;
|
||
if (owReq2) {
|
||
lines.push(`- **${lang === "zh" ? "所有权要求" : "Ownership Requirements"}**:`);
|
||
if (owReq2.proofDocuments && Array.isArray(owReq2.proofDocuments)) {
|
||
lines.push(` - ${lang === "zh" ? "所需文件" : "Required Documents"}: ${(owReq2.proofDocuments as string[]).join("、")}`);
|
||
}
|
||
if (owReq2.registrationAuthority) {
|
||
lines.push(` - ${lang === "zh" ? "登记机构" : "Registration Authority"}: ${owReq2.registrationAuthority}`);
|
||
}
|
||
if (owReq2.foreignOwnershipRestriction) {
|
||
lines.push(` - ${lang === "zh" ? "外资限制" : "Foreign Ownership"}: ${owReq2.foreignOwnershipRestriction}`);
|
||
}
|
||
if (owReq2.chainRecognition) {
|
||
lines.push(` - ${lang === "zh" ? "链上认可" : "Chain Recognition"}: ${owReq2.chainRecognition}`);
|
||
}
|
||
}
|
||
const trReq = ruleExt.tradingRequirements as Record<string, unknown> | undefined;
|
||
if (trReq) {
|
||
lines.push(`- **${lang === "zh" ? "交易要求" : "Trading Requirements"}**:`);
|
||
if (trReq.minimumInvestor) {
|
||
lines.push(` - ${lang === "zh" ? "投资者资质" : "Investor Qualification"}: ${trReq.minimumInvestor}`);
|
||
}
|
||
if (trReq.settlementPeriod) {
|
||
lines.push(` - ${lang === "zh" ? "结算周期" : "Settlement Period"}: ${trReq.settlementPeriod}`);
|
||
}
|
||
if (trReq.allowedCurrencies && Array.isArray(trReq.allowedCurrencies)) {
|
||
lines.push(` - ${lang === "zh" ? "允许货币" : "Allowed Currencies"}: ${(trReq.allowedCurrencies as string[]).join("、")}`);
|
||
}
|
||
}
|
||
if (ruleExt.sourceUrl) {
|
||
lines.push(`- **${lang === "zh" ? "官方来源" : "Official Source"}**: ${ruleExt.sourceUrl}`);
|
||
}
|
||
lines.push("");
|
||
});
|
||
|
||
confidence = 0.85;
|
||
break;
|
||
}
|
||
|
||
case "process_guide": {
|
||
lines.push(lang === "zh" ? "## NAC 公链 RWA 上链流程" : "## NAC Blockchain RWA Onboarding Process");
|
||
lines.push("");
|
||
|
||
const steps = lang === "zh" ? [
|
||
"**第一步:身份认证(KYC)**\n 完成 NAC 注册系统实名认证:https://id.newassetchain.io",
|
||
"**第二步:资产评估**\n 提交资产材料,AI 估值系统自动评估资产价值",
|
||
"**第三步:七层合规验证**\n 系统自动执行七层合规检查,包括身份、所有权、估值、法律、技术、宪法验证",
|
||
"**第四步:GNACS 编码**\n 系统为资产分配全球唯一的 GNACS 分类编码",
|
||
"**第五步:Charter 合约部署**\n 生成并部署资产对应的 Charter 智能合约到 NVM",
|
||
"**第六步:ACC-20 铸造**\n 通过七层验证后,铸造 ACC-20 标准的链上资产代币",
|
||
"**第七步:链上确权**\n 资产 DNA 上链,完成不可篡改的所有权确认",
|
||
] : [
|
||
"**Step 1: Identity Verification (KYC)**\n Complete NAC registration: https://id.newassetchain.io",
|
||
"**Step 2: Asset Valuation**\n Submit asset materials for AI valuation",
|
||
"**Step 3: Seven-Layer Compliance Verification**\n Automated compliance checks",
|
||
"**Step 4: GNACS Classification**\n Assign unique GNACS code to the asset",
|
||
"**Step 5: Charter Contract Deployment**\n Deploy Charter smart contract to NVM",
|
||
"**Step 6: ACC-20 Minting**\n Mint ACC-20 standard tokens after passing all verifications",
|
||
"**Step 7: On-chain Title Registration**\n Asset DNA recorded on-chain",
|
||
];
|
||
|
||
steps.forEach(step => {
|
||
lines.push(step);
|
||
lines.push("");
|
||
});
|
||
|
||
if (rules.length > 0) {
|
||
lines.push("---");
|
||
lines.push(lang === "zh" ? "### 相关合规要求" : "### Related Compliance Requirements");
|
||
rules.slice(0, 4).forEach(rule => {
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
lines.push(`- **${rule.ruleName}**(${rule.jurisdiction})`);
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(` 📜 ${ruleExt.legalBasis}`);
|
||
}
|
||
if (rule.content) {
|
||
lines.push(` ${rule.content.slice(0, 200)}`);
|
||
}
|
||
const owReqP = ruleExt.ownershipRequirements as Record<string, unknown> | undefined;
|
||
if (owReqP?.proofDocuments && Array.isArray(owReqP.proofDocuments)) {
|
||
lines.push(` 📋 所需文件:${(owReqP.proofDocuments as string[]).slice(0, 3).join("、")}`);
|
||
}
|
||
});
|
||
}
|
||
|
||
confidence = 0.92;
|
||
break;
|
||
}
|
||
|
||
case "jurisdiction_compare": {
|
||
lines.push(lang === "zh" ? "## 管辖区合规要求对比" : "## Jurisdiction Compliance Comparison");
|
||
lines.push("");
|
||
|
||
const byJurisdiction: Record<string, typeof rules> = {};
|
||
rules.forEach(rule => {
|
||
if (!byJurisdiction[rule.jurisdiction]) byJurisdiction[rule.jurisdiction] = [];
|
||
byJurisdiction[rule.jurisdiction].push(rule);
|
||
});
|
||
|
||
const jurisdictionNames: Record<string, string> = {
|
||
CN: "中国大陆", HK: "香港", SG: "新加坡", AE: "迪拜/阿联酋", EU: "欧盟", US: "美国",
|
||
GB: "英国", JP: "日本", AU: "澳大利亚", CH: "瑞士", GLOBAL: "全球通用",
|
||
};
|
||
|
||
for (const [jur, jurRules] of Object.entries(byJurisdiction)) {
|
||
lines.push(`### ${jurisdictionNames[jur] || jur}`);
|
||
jurRules.slice(0, 3).forEach(rule => {
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
lines.push(`- **${rule.ruleName}**`);
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(` 📜 ${ruleExt.legalBasis}`);
|
||
}
|
||
if (rule.content) {
|
||
lines.push(` ${rule.content.slice(0, 300)}`);
|
||
}
|
||
const owReqC = ruleExt.ownershipRequirements as Record<string, unknown> | undefined;
|
||
if (owReqC?.foreignOwnershipRestriction) {
|
||
lines.push(` ⚠️ 外资限制:${owReqC.foreignOwnershipRestriction}`);
|
||
}
|
||
if (owReqC?.chainRecognition) {
|
||
lines.push(` ⛓️ 链上认可:${owReqC.chainRecognition}`);
|
||
}
|
||
});
|
||
lines.push("");
|
||
}
|
||
|
||
confidence = 0.82;
|
||
break;
|
||
}
|
||
|
||
case "ownership_verification": {
|
||
const jurOV = entities.jurisdictions[0] || "通用";
|
||
const assetOV = entities.assetTypes[0] || "资产";
|
||
lines.push(lang === "zh"
|
||
? `## ${jurOV} ${assetOV} 所有权验证要求`
|
||
: `## Ownership Verification Requirements for ${assetOV} in ${jurOV}`);
|
||
lines.push("");
|
||
|
||
if (rules.length === 0) {
|
||
lines.push(lang === "zh"
|
||
? "未找到该辖区该资产类别的所有权验证规则,请联系 compliance@newassetchain.io"
|
||
: "No ownership verification rules found. Contact compliance@newassetchain.io");
|
||
} else {
|
||
rules.forEach((rule, idx) => {
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
lines.push(`### ${idx + 1}. ${rule.ruleName}(${rule.jurisdiction})`);
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(`📜 **法律依据**:${ruleExt.legalBasis}`);
|
||
}
|
||
if (rule.content) {
|
||
lines.push(rule.content.slice(0, 600));
|
||
}
|
||
const owReqOV = ruleExt.ownershipRequirements as Record<string, unknown> | undefined;
|
||
if (owReqOV) {
|
||
lines.push("");
|
||
lines.push(lang === "zh" ? "**所有权验证详细要求:**" : "**Ownership Verification Details:**");
|
||
if (owReqOV.proofDocuments && Array.isArray(owReqOV.proofDocuments) && (owReqOV.proofDocuments as string[]).length > 0) {
|
||
lines.push(`- 📋 所需文件:${(owReqOV.proofDocuments as string[]).join("、")}`);
|
||
}
|
||
if (owReqOV.registrationRequired !== undefined) {
|
||
lines.push(`- 🏛️ 强制登记:${owReqOV.registrationRequired ? "是" : "否"}`);
|
||
}
|
||
if (owReqOV.registrationAuthority) {
|
||
lines.push(`- 🏛️ 登记机构:${owReqOV.registrationAuthority}`);
|
||
}
|
||
if (owReqOV.transferMechanism) {
|
||
lines.push(`- 🔄 转移机制:${owReqOV.transferMechanism}`);
|
||
}
|
||
if (owReqOV.chainRecognition) {
|
||
lines.push(`- ⛓️ 链上认可:${owReqOV.chainRecognition}`);
|
||
}
|
||
if (owReqOV.foreignOwnershipRestriction) {
|
||
lines.push(`- ⚠️ 外资限制:${owReqOV.foreignOwnershipRestriction}`);
|
||
}
|
||
if (owReqOV.disputeResolution) {
|
||
lines.push(`- ⚖️ 争议解决:${owReqOV.disputeResolution}`);
|
||
}
|
||
}
|
||
if (ruleExt.sourceUrl) {
|
||
lines.push(`- 🔗 官方来源:${ruleExt.sourceUrl}`);
|
||
}
|
||
lines.push("");
|
||
});
|
||
lines.push("---");
|
||
lines.push(lang === "zh"
|
||
? `> NAC 公链通过七层合规验证框架自动验证所有权,Charter 合约在 NVM 上执行不可篡改的确权记录。`
|
||
: `> NAC blockchain automatically verifies ownership through its seven-layer compliance framework, with Charter contracts executing immutable title records on NVM.`);
|
||
}
|
||
confidence = 0.90;
|
||
break;
|
||
}
|
||
|
||
case "trading_rules": {
|
||
const jurTR = entities.jurisdictions[0] || "通用";
|
||
const assetTR = entities.assetTypes[0] || "资产";
|
||
lines.push(lang === "zh"
|
||
? `## ${jurTR} ${assetTR} 贸易规则`
|
||
: `## Trading Rules for ${assetTR} in ${jurTR}`);
|
||
lines.push("");
|
||
|
||
if (rules.length === 0) {
|
||
lines.push(lang === "zh"
|
||
? "未找到该辖区该资产类别的贸易规则,请联系 compliance@newassetchain.io"
|
||
: "No trading rules found. Contact compliance@newassetchain.io");
|
||
} else {
|
||
rules.forEach((rule, idx) => {
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
lines.push(`### ${idx + 1}. ${rule.ruleName}(${rule.jurisdiction})`);
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(`📜 **法律依据**:${ruleExt.legalBasis}`);
|
||
}
|
||
if (rule.content) {
|
||
lines.push(rule.content.slice(0, 600));
|
||
}
|
||
const trReqTR = ruleExt.tradingRequirements as Record<string, unknown> | undefined;
|
||
if (trReqTR) {
|
||
lines.push("");
|
||
lines.push(lang === "zh" ? "**交易规则详细要求:**" : "**Trading Requirements Details:**");
|
||
if (trReqTR.minimumInvestor) {
|
||
lines.push(`- 👤 投资者资质:${trReqTR.minimumInvestor}`);
|
||
}
|
||
if (trReqTR.settlementPeriod) {
|
||
lines.push(`- ⏱️ 结算周期:${trReqTR.settlementPeriod}`);
|
||
}
|
||
if (trReqTR.allowedCurrencies && Array.isArray(trReqTR.allowedCurrencies)) {
|
||
lines.push(`- 💱 允许货币:${(trReqTR.allowedCurrencies as string[]).join("、")}`);
|
||
}
|
||
}
|
||
if (ruleExt.sourceUrl) {
|
||
lines.push(`- 🔗 官方来源:${ruleExt.sourceUrl}`);
|
||
}
|
||
lines.push("");
|
||
});
|
||
lines.push("---");
|
||
lines.push(lang === "zh"
|
||
? `> NAC 公链的 ACC-20 协议内置贸易规则验证,所有交易在 CBPP 共识下自动合规检查。`
|
||
: `> NAC blockchain's ACC-20 protocol has built-in trading rule verification, with all transactions automatically compliance-checked under CBPP consensus.`);
|
||
}
|
||
confidence = 0.88;
|
||
break;
|
||
}
|
||
|
||
default: {
|
||
lines.push(lang === "zh" ? "## NAC 公链相关信息" : "## NAC Blockchain Information");
|
||
lines.push("");
|
||
|
||
rules.forEach(rule => {
|
||
const ruleExt = rule as Record<string, unknown>;
|
||
lines.push(`### ${rule.ruleName}`);
|
||
if (ruleExt.legalBasis) {
|
||
lines.push(`📜 法律依据:${ruleExt.legalBasis}`);
|
||
}
|
||
lines.push(rule.content.slice(0, 500));
|
||
lines.push(`*${lang === "zh" ? "来源" : "Source"}: ${rule.source}*`);
|
||
lines.push("");
|
||
});
|
||
|
||
confidence = 0.65;
|
||
}
|
||
|
||
}
|
||
|
||
// 生成建议问题
|
||
const suggestions = generateSuggestions(intent, entities, lang);
|
||
|
||
return {
|
||
answer: lines.join("\n"),
|
||
confidence,
|
||
suggestions,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 生成后续建议问题
|
||
*/
|
||
function generateSuggestions(intent: QueryIntent, entities: ExtractedEntities, lang: string): string[] {
|
||
const isZh = lang === "zh";
|
||
|
||
const suggestionMap: Record<QueryIntent, string[]> = {
|
||
document_checklist: isZh ? [
|
||
"七层合规验证框架是什么?",
|
||
"上链流程需要多长时间?",
|
||
"Charter 智能合约如何编写?",
|
||
] : [
|
||
"What is the seven-layer compliance framework?",
|
||
"How long does the onboarding process take?",
|
||
"How to write Charter smart contracts?",
|
||
],
|
||
compliance_query: isZh ? [
|
||
"需要哪些文件?",
|
||
"如何提高合规评分?",
|
||
"七层合规验证流程是什么?",
|
||
] : [
|
||
"What documents are required?",
|
||
"How to improve compliance score?",
|
||
"What is the seven-layer verification process?",
|
||
],
|
||
process_guide: isZh ? [
|
||
"KYC 认证需要什么材料?",
|
||
"GNACS 编码是什么?",
|
||
"ACC-20 和 ERC-20 有什么区别?",
|
||
] : [
|
||
"What materials are needed for KYC?",
|
||
"What is GNACS encoding?",
|
||
"What is the difference between ACC-20 and ERC-20?",
|
||
],
|
||
technical_query: isZh ? [
|
||
"Charter 和 Solidity 有什么区别?",
|
||
"NVM 如何执行智能合约?",
|
||
"CBPP 共识机制是什么?",
|
||
] : [
|
||
"What is the difference between Charter and Solidity?",
|
||
"How does NVM execute smart contracts?",
|
||
"What is the CBPP consensus mechanism?",
|
||
],
|
||
jurisdiction_compare: isZh ? [
|
||
"哪个管辖区的合规要求最简单?",
|
||
"香港 RWA 监管框架是什么?",
|
||
"新加坡 MAS 对 RWA 的要求?",
|
||
] : [
|
||
"Which jurisdiction has the simplest requirements?",
|
||
"What is Hong Kong's RWA regulatory framework?",
|
||
"What are MAS requirements for RWA in Singapore?",
|
||
],
|
||
asset_type_query: isZh ? [
|
||
"房地产上链需要哪些文件?",
|
||
"股权类资产如何上链?",
|
||
"大宗商品 RWA 合规要求?",
|
||
] : [
|
||
"What documents are needed for real estate onboarding?",
|
||
"How to onboard equity assets?",
|
||
"Compliance requirements for commodity RWA?",
|
||
],
|
||
fee_query: isZh ? [
|
||
"XTZH 如何获取?",
|
||
"Gas 费用如何计算?",
|
||
"上链总费用是多少?",
|
||
] : [
|
||
"How to obtain XTZH?",
|
||
"How is gas fee calculated?",
|
||
"What is the total onboarding cost?",
|
||
],
|
||
general_nac: isZh ? [
|
||
"NAC 公链支持哪些资产类型?",
|
||
"如何开始使用 NAC 公链?",
|
||
"Charter 智能合约怎么写?",
|
||
] : [
|
||
"What asset types does NAC blockchain support?",
|
||
"How to get started with NAC blockchain?",
|
||
"How to write Charter smart contracts?",
|
||
],
|
||
out_of_scope: isZh ? [
|
||
"NAC 公链是什么?",
|
||
"RWA 资产如何上链?",
|
||
"Charter 语言介绍",
|
||
] : [
|
||
"What is NAC blockchain?",
|
||
"How to onboard RWA assets?",
|
||
"Introduction to Charter language",
|
||
],
|
||
};
|
||
|
||
return suggestionMap[intent] || suggestionMap["general_nac"];
|
||
}
|
||
|
||
// ─── 主推理函数 ───────────────────────────────────────────────────
|
||
|
||
/**
|
||
* NAC 自主推理问答引擎主入口
|
||
* 完全基于 CNNL + RAG,零外部 LLM 依赖
|
||
*/
|
||
export async function nacInfer(request: InferenceRequest): Promise<InferenceResponse> {
|
||
const startTime = Date.now();
|
||
const { question, language = "zh", jurisdiction, assetType } = request;
|
||
|
||
// 1. 意图识别
|
||
const intent = detectIntent(question);
|
||
|
||
// 2. 实体提取
|
||
const entities = extractEntities(question);
|
||
|
||
// 补充用户明确指定的实体
|
||
if (jurisdiction && !entities.jurisdictions.includes(jurisdiction)) {
|
||
entities.jurisdictions.unshift(jurisdiction);
|
||
}
|
||
if (assetType && !entities.assetTypes.includes(assetType)) {
|
||
entities.assetTypes.unshift(assetType);
|
||
}
|
||
|
||
// 3. 超出范围处理
|
||
if (intent === "out_of_scope") {
|
||
return {
|
||
answer: ANSWER_TEMPLATES["out_of_scope"][language] || ANSWER_TEMPLATES["out_of_scope"]["zh"],
|
||
confidence: 0,
|
||
intent,
|
||
entities,
|
||
sources: [],
|
||
suggestions: generateSuggestions("out_of_scope", entities, language),
|
||
engineVersion: "NAC-Inference-v1.0",
|
||
processingMs: Date.now() - startTime,
|
||
};
|
||
}
|
||
|
||
// 4. 技术概念查询(优先使用内置知识库)
|
||
if (intent === "technical_query") {
|
||
const techAnswer = generateTechAnswer(entities, language);
|
||
if (techAnswer) {
|
||
return {
|
||
answer: techAnswer,
|
||
confidence: 0.95,
|
||
intent,
|
||
entities,
|
||
sources: [],
|
||
suggestions: generateSuggestions(intent, entities, language),
|
||
engineVersion: "NAC-Inference-v1.0",
|
||
processingMs: Date.now() - startTime,
|
||
};
|
||
}
|
||
}
|
||
|
||
// 5. RAG 检索
|
||
const ragCtx = await retrieveComplianceRules(
|
||
String(question),
|
||
{
|
||
language,
|
||
jurisdictions: entities.jurisdictions.length > 0 ? entities.jurisdictions : undefined,
|
||
maxResults: 5,
|
||
}
|
||
);
|
||
|
||
// 6. 基于 RAG 结果生成回答
|
||
const { answer, confidence, suggestions } = generateAnswerFromRAG(
|
||
intent, entities, ragCtx, language, question
|
||
);
|
||
|
||
// 7. 构建来源引用
|
||
const sources: SourceReference[] = ragCtx.rules.map(rule => ({
|
||
ruleId: rule.ruleId,
|
||
ruleName: rule.ruleName,
|
||
jurisdiction: rule.jurisdiction,
|
||
category: rule.category,
|
||
relevance: rule.score,
|
||
}));
|
||
|
||
return {
|
||
answer,
|
||
confidence,
|
||
intent,
|
||
entities,
|
||
sources,
|
||
suggestions,
|
||
engineVersion: "NAC-Inference-v1.0",
|
||
processingMs: Date.now() - startTime,
|
||
};
|
||
}
|