1002 lines
44 KiB
TypeScript
1002 lines
44 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";
|
||
import { invokeLLM } from "./_core/llm";
|
||
|
||
// ─── 类型定义 ─────────────────────────────────────────────────────
|
||
|
||
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 公链的原生共识协议。
|
||
核心宪法原则(四句):
|
||
① 约法即是治法:宪法条款直接编码为共识规则,无需外部执法机构。
|
||
② 宪法即是规则:所有节点行为受宪法约束,违反宪法的区块自动无效。
|
||
③ 参与即是共识:合格节点的参与行为本身构成共识,无需额外投票或挖矿。
|
||
④ 节点产生区块,交易扩展区块大小:区块由宪政节点(CBP 节点)产生;区块大小不固定,随交易量动态扩展。
|
||
|
||
CBPP 不是 PoS/PoW/DPoS 的变种,其出块权来自宪法赋予的资格,而非财富或算力。
|
||
CBP 节点资格:KYC Level 2+ + 宪法法院审核通过 + 质押 XTZH + 在线率 ≥ 90%。
|
||
出块时间目标:≤ 0.3 秒,最终确认 < 3 秒。初始宪政节点数:21 个(测试网 V1.0)。`,
|
||
|
||
"CSNP": `CSNP(Constitutional Sovereign Network Protocol)是 NAC 公链的网络协议,替代传统 P2P。
|
||
CSNP V2.0 六层架构:物理层 → 数据链路层 → 网络层 → 传输层 → 会话层 → 应用层。
|
||
CSNP 与传统 P2P 的区别:节点需要宪法授权才能加入网络,防止女巫攻击。`,
|
||
|
||
"XTZH": `XTZH(XIN TZU HUANG,新子黄)是 NAC 公链的核心稳定价值尺度系统,定位为 "RWA 结算凭证 + 价值锚"。
|
||
锚定物:SDR 资产组合(50% 黄金 + 30% 法币 + 20% 大宗商品)。
|
||
黄金储备:每铸造 1 XTZH,需 0.625 美元实物黄金储备(1.25 倍安全边际)。
|
||
铸造方式:① RWA 资产质押铸造(七步精炼流程);② 跨链资产质押铸造(八步流程)。
|
||
铸造条件:资产须通过七层合规 + 合规评分 ≥ 85 分 + 持有足够 XIC 作为能耗准备金。
|
||
可铸造量公式:M_max = V_xtzh × L(V_xtzh=AI估值,L=动态质押率30%-90%)。
|
||
资金分配:80% 配置 SDR 资产组合,20% 风险准备金。
|
||
用途:RWA 资产结算、借贷清算、估值基准(NAC 生态唯一法定结算货币)。
|
||
赎回:销毁 XTZH → 释放质押资产 + 平仓黄金储备 → 返还等值资产。`,
|
||
|
||
"GNACS": `GNACS Pro V2.0(Global Native Asset Chain Standard)是 NAC 公链的全球原生资产链统一分类标准,采用 48 位编码。
|
||
编码结构:物理属性(1-6位) + 法律属性(7-12位) + 经济属性(13-18位) + 技术实现(19-24位) + 合规属性(25-30位) + 风险属性(31-36位) + 流动性属性(37-42位) + 实例序列号+校验码(43-48位)。
|
||
整合国际标准:HS海关编码、巴塞尔协议、IPSAS/IFRS、ISO、FATF。
|
||
编码示例:010121=纯种繁殖用马,990101=封装比特币(nBTC),900201=XIC治理代币。
|
||
GNACS 编码规则已宪法化(条款 GNACS_GENERATION_RULE),修改需 66% XIC 投票。`,
|
||
|
||
"ACC-20": `ACC-20 是 NAC 公链的原生同质化资产协议,对应以太坊 ERC-20,但具有原生合规能力。
|
||
ACC 协议家族:ACC-20(同质化)、ACC-721(唯一资产)、ACC-1155(多资产)、ACC-20C(跨链)、ACC-REALESTATE(不动产)、ACC-CARBON(碳信用)。
|
||
ACC-20 与 ERC-20 的核心区别:内置 CHECK_COMPLIANCE 操作码(NVM 层面拒绝不合规操作)、绑定 OwnerDID、使用 SHA3-384(48字节)而非 Keccak-256。
|
||
核心接口:mint(to, amount, assetDNA)—须通过七层合规;transfer(to, amount)—自动合规检查;burn(amount)—触发资产解质押。`,
|
||
|
||
"七层合规": `NAC 七层合规验证框架是 RWA 资产上链的核心审查机制(所有资产操作均须通过全部七层):
|
||
第1层:身份合规(KYC Level ≥ 2 + AML 黑名单筛查 + OwnerDID 验证)
|
||
第2层:资产合规(GNACS 编码合法性 + 资产类别白名单)
|
||
第3层:主权合规(主权类型验证 + 《NAC 原生资产主权规则法典》)
|
||
第4层:估值合规(AI 多模型协同估值 + 白名单预言机数据源)
|
||
第5层:交易合规(单次/日累计限额 + 交易对手方合规状态)
|
||
第6层:监管合规(40+ 司法辖区监管规则 + 实时监管预言机更新)
|
||
第7层:技术合规(DNA 完整性验证 + 合约代码合规 + XIC Gas 充足性)`,
|
||
|
||
"RWA": `RWA(Real World Assets)即真实世界资产,是 NAC 公链的核心应用场景。
|
||
NAC 公链专为 RWA 上链设计,支持:不动产、股权、债券、大宗商品、知识产权、基金、碳信用、跨链数字资产等。
|
||
RWA 上链完整流程(十三步宪法闭环):
|
||
① 资产申请 → ② AI合规审查(七层)→ ③ AI审批 → ④ AI估值 → ⑤ 法律意见书 → ⑥ 确权+DNA生成 → ⑦ 资产托管 → ⑧ TOKEN发行(ACC-20/721/1155) → ⑨ 链上权证凭证 → ⑩ 衍生权益化 → ⑪ XTZH铸造(可选)→ ⑫ 装入钱包 → ⑬ 交易所上线。
|
||
一键上链:AI 自动完成 GNACS 编码、DNA 生成、七层合规、AI 估值、确权、TOKEN 发行全流程。`,
|
||
|
||
"XIC": `XIC(XIN I CHAIN)是 NAC 公链的原生治理代币,承担双重职能:治理代币 + 能量(Gas)代币。
|
||
治理职能:XIC 持有者投票参与 NAC 公链所有重大决策,投票权重按持有量加权。治理范围:宪法修订(75%)、协议参数调整(66%)、常规提案(51%)。
|
||
能量职能:所有 AI 算力操作(资产上链、铸造 XTZH、AI 估值、合规审查)均需消耗 XIC 作为能耗费用。
|
||
发行信息:XIC 已在 BSC(币安智能链)发行,总量 1000 亿枚,永不增发(合约级别限制)。
|
||
BSC 与原生公链锚定:NAC 原生公链主网上线后,BSC XIC 与 NAC 原生 XIC 1:1 完全锚定,可通过官方跨链桥迁移。
|
||
XIC 与 XTZH 的关系:XIC 是铸造 XTZH 的"门票"(能耗费用),XTZH 是 XIC 治理的"对象"(储备参数由 XIC 投票决定)。两者构成 NAC 双代币经济飞轮。`,
|
||
};
|
||
|
||
// ─── 多语言回答模板 ───────────────────────────────────────────────
|
||
|
||
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 结果生成结构化回答(模板,作为 LLM 润色的上下文)
|
||
const { answer: rawAnswer, confidence, suggestions } = generateAnswerFromRAG(
|
||
intent, entities, ragCtx, language, question
|
||
);
|
||
|
||
// 6.5 LLM 润色:将结构化内容转化为思维化、段落化的自然语言
|
||
let answer = rawAnswer;
|
||
try {
|
||
// 构建知识库上下文(最多 5 条规则,每条 300 字)
|
||
const rulesContext = ragCtx.rules.slice(0, 5).map(r => {
|
||
const ruleContent = r.content ? r.content.slice(0, 300) : "";
|
||
return `[${r.ruleName}(${r.jurisdiction})] ${ruleContent}`;
|
||
}).join("\n\n");
|
||
|
||
const isZh = language === "zh" || !language;
|
||
|
||
const systemPrompt = isZh
|
||
? `你是 NAC公链AI,专注于 NAC 公链(NewAssetChain)的专业 AI 助手。NAC 公链是一条 RWA(真实世界资产)专用公链,使用 Charter 智能合约语言、NVM 虚拟机、CBPP 共识协议、CSNP 网络。
|
||
|
||
回答风格要求:
|
||
- 用流畅的段落表达,像一位有思想的专家在向用户解释,而不是列出数据库条目
|
||
- 先给出核心观点,再展开解释,最后简短总结
|
||
- 不要输出原始 Markdown 标题符号(## ###),不要用机械列表(- 字段: 值)
|
||
- 可以适当加粗关键词,但整体是段落文章风格
|
||
- 语气专业、清晰、易懂`
|
||
: `You are NAC公链AI, a professional AI assistant for NAC blockchain (NewAssetChain), an RWA-dedicated blockchain using Charter smart contracts, NVM virtual machine, CBPP consensus, and CSNP network.
|
||
|
||
Response style:
|
||
- Use flowing paragraphs like a thoughtful expert explaining to a user, not database entries
|
||
- Lead with the core insight, elaborate, then briefly summarize
|
||
- No raw Markdown headers (## ###), no mechanical lists (- field: value)
|
||
- Bold key terms sparingly; overall article-paragraph style
|
||
- Professional, clear, accessible tone`;
|
||
|
||
const userPrompt = isZh
|
||
? `用户问题:${question}
|
||
|
||
相关知识库内容:
|
||
${rulesContext || rawAnswer}
|
||
|
||
请用自然、流畅的段落语言回答这个问题,像专家在解释一样,不要列字段。`
|
||
: `User question: ${question}
|
||
|
||
Relevant knowledge:
|
||
${rulesContext || rawAnswer}
|
||
|
||
Please answer in natural, flowing paragraphs like an expert explaining, not listing fields.`;
|
||
|
||
const llmResult = await invokeLLM({
|
||
messages: [
|
||
{ role: "system", content: systemPrompt },
|
||
{ role: "user", content: userPrompt },
|
||
],
|
||
});
|
||
const llmAnswer = llmResult?.choices?.[0]?.message?.content;
|
||
if (llmAnswer && llmAnswer.trim().length > 20) {
|
||
answer = llmAnswer.trim();
|
||
}
|
||
} catch (e) {
|
||
// LLM 润色失败时回退到模板回答,保证服务可用
|
||
console.warn("[nacInfer] LLM polish failed, using template answer:", (e as Error).message);
|
||
}
|
||
|
||
// 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,
|
||
};
|
||
}
|