410 lines
14 KiB
Plaintext
410 lines
14 KiB
Plaintext
/**
|
||
* NAC Knowledge Engine - AI智能体系统
|
||
*
|
||
* 四类Agent(无Manus依赖,使用OpenAI兼容接口):
|
||
* 1. KnowledgeQAAgent - 知识库问答(基于合规规则库)
|
||
* 2. ComplianceAgent - 合规分析(七层合规验证框架)
|
||
* 3. TranslationAgent - 多语言翻译(七种语言)
|
||
* 4. ApprovalAssistAgent - 审批辅助(案例分析与建议)
|
||
*
|
||
* 使用环境变量:
|
||
* NAC_AI_API_URL - AI接口地址(OpenAI兼容)
|
||
* NAC_AI_API_KEY - AI接口密钥
|
||
* NAC_AI_MODEL - 模型名称(默认 qwen-plus 或 gpt-3.5-turbo)
|
||
*/
|
||
|
||
import { getMongoDb, COLLECTIONS } from "./mongodb";
|
||
import { retrieveRelevantRules, buildRAGPromptContext } from "./ragRetrieval";
|
||
|
||
// ─── 基础类型定义 ─────────────────────────────────────────────────
|
||
|
||
export type AgentType = "knowledge_qa" | "compliance" | "translation" | "approval_assist";
|
||
|
||
export interface AgentMessage {
|
||
role: "system" | "user" | "assistant";
|
||
content: string;
|
||
}
|
||
|
||
export interface AgentRequest {
|
||
agentType: AgentType;
|
||
userMessage: string;
|
||
conversationHistory?: AgentMessage[];
|
||
context?: Record<string, unknown>;
|
||
}
|
||
|
||
export interface AgentResponse {
|
||
agentType: AgentType;
|
||
message: string;
|
||
confidence: number; // 0-1
|
||
sources?: string[]; // 引用的知识库条目
|
||
suggestions?: string[]; // 后续操作建议
|
||
metadata?: Record<string, unknown>;
|
||
}
|
||
|
||
// ─── AI接口调用(OpenAI兼容,无Manus依赖)────────────────────────
|
||
|
||
export function isAgentConfigured(): boolean {
|
||
return !!(process.env.NAC_AI_API_URL && process.env.NAC_AI_API_KEY);
|
||
}
|
||
|
||
async function callAgentLLM(
|
||
messages: AgentMessage[],
|
||
maxTokens = 2048,
|
||
temperature = 0.7
|
||
): Promise<string> {
|
||
const apiUrl = process.env.NAC_AI_API_URL;
|
||
const apiKey = process.env.NAC_AI_API_KEY;
|
||
// 默认使用通义千问plus(国内稳定),也支持gpt-3.5-turbo等
|
||
const model = process.env.NAC_AI_MODEL || "qwen-plus";
|
||
|
||
if (!apiUrl || !apiKey) {
|
||
throw new Error(
|
||
"[AI Agent] 未配置AI接口。请在 .env 文件中设置 NAC_AI_API_URL 和 NAC_AI_API_KEY。\n" +
|
||
"推荐:阿里云通义千问 https://dashscope.aliyuncs.com/compatible-mode"
|
||
);
|
||
}
|
||
|
||
const endpoint = `${apiUrl.replace(/\/$/, "")}/v1/chat/completions`;
|
||
|
||
const response = await fetch(endpoint, {
|
||
method: "POST",
|
||
headers: {
|
||
"content-type": "application/json",
|
||
authorization: `Bearer ${apiKey}`,
|
||
},
|
||
body: JSON.stringify({
|
||
model,
|
||
messages,
|
||
max_tokens: maxTokens,
|
||
temperature,
|
||
stream: false,
|
||
}),
|
||
});
|
||
|
||
if (!response.ok) {
|
||
const errorText = await response.text().catch(() => "");
|
||
throw new Error(`AI接口调用失败: ${response.status} ${response.statusText} – ${errorText.slice(0, 500)}`);
|
||
}
|
||
|
||
const result = await response.json() as {
|
||
choices: Array<{ message: { content: string } }>;
|
||
usage?: { total_tokens: number };
|
||
};
|
||
|
||
const content = result.choices?.[0]?.message?.content;
|
||
if (!content) throw new Error("AI接口返回空内容");
|
||
return content.trim();
|
||
}
|
||
|
||
// ─── 知识库问答Agent ──────────────────────────────────────────────
|
||
|
||
const KNOWLEDGE_QA_SYSTEM_PROMPT = `你是NAC(NewAssetChain)公链的合规知识库专家助手。
|
||
NAC是一条专注于RWA(真实世界资产)的原生公链,使用Charter智能合约语言、NVM虚拟机、CBPP共识协议、CSNP网络。
|
||
|
||
你的职责:
|
||
1. 回答关于NAC合规规则的问题
|
||
2. 解释各司法管辖区(中国CN、香港HK、美国US、欧盟EU、新加坡SG、阿联酋AE)的合规要求
|
||
3. 指导用户了解RWA资产上链的合规流程
|
||
4. 解释七层合规验证框架(L1身份验证→L7最终审批)
|
||
|
||
回答要求:
|
||
- 专业、准确、简洁
|
||
- 引用具体的合规规则名称
|
||
- 对于不确定的内容,明确说明需要进一步核实
|
||
- 保留专有名词(NAC、RWA、Charter、NVM、CBPP、CSNP、CNNL、ACC-20、GNACS、XTZH)不翻译`;
|
||
|
||
async function runKnowledgeQAAgent(
|
||
userMessage: string,
|
||
history: AgentMessage[],
|
||
context?: Record<string, unknown>
|
||
): Promise<AgentResponse> {
|
||
// ── RAG检索增强:从 MongoDB 知识库检索相关规则 ──
|
||
const ragCtx = await retrieveRelevantRules(userMessage, {
|
||
maxResults: 5,
|
||
jurisdictions: context?.jurisdiction ? [String(context.jurisdiction)] : undefined,
|
||
language: String(context?.language || "zh"),
|
||
});
|
||
|
||
const ragPromptSection = buildRAGPromptContext(ragCtx);
|
||
const sources = ragCtx.rules.map(r => r.source);
|
||
|
||
// 计算置信度:检索到相关规则则提高置信度
|
||
const baseConfidence = ragCtx.retrievalMethod === "fulltext"
|
||
? 0.90
|
||
: ragCtx.retrievalMethod === "regex"
|
||
? 0.80
|
||
: ragCtx.retrievalMethod === "sample"
|
||
? 0.65
|
||
: 0.55;
|
||
|
||
const systemPrompt = KNOWLEDGE_QA_SYSTEM_PROMPT +
|
||
(context?.jurisdiction ? `\n\n当前关注的司法管辖区:${context.jurisdiction}` : "") +
|
||
(ragPromptSection ? `\n\n${ragPromptSection}` : "");
|
||
|
||
const messages: AgentMessage[] = [
|
||
{ role: "system", content: systemPrompt },
|
||
...history.slice(-6), // 保留最近6条历史
|
||
{ role: "user", content: userMessage },
|
||
];
|
||
|
||
const reply = await callAgentLLM(messages, 1024, 0.5);
|
||
|
||
return {
|
||
agentType: "knowledge_qa",
|
||
message: reply,
|
||
confidence: baseConfidence,
|
||
sources,
|
||
suggestions: [
|
||
"查看相关司法管辖区的完整合规规则",
|
||
"提交资产上链申请",
|
||
"了解七层合规验证流程",
|
||
],
|
||
metadata: {
|
||
ragMethod: ragCtx.retrievalMethod,
|
||
ragKeywords: ragCtx.queryKeywords,
|
||
ragRulesCount: ragCtx.totalFound,
|
||
},
|
||
};
|
||
}
|
||
|
||
// ─── 合规分析Agent ────────────────────────────────────────────────
|
||
|
||
const COMPLIANCE_ANALYSIS_SYSTEM_PROMPT = `你是NAC公链的七层合规验证分析专家。
|
||
七层合规验证框架:
|
||
L1: 身份验证(KYC/AML)- 基于ACC-20协议
|
||
L2: 资产真实性验证 - 基于Charter智能合约
|
||
L3: 司法管辖合规 - 基于CNNL神经网络语言
|
||
L4: 资产估值合理性 - 基于XTZH稳定机制
|
||
L5: 法律文件完整性 - 基于GNACS分类系统
|
||
L6: 宪政合规审查 - 基于CBPP共识协议
|
||
L7: 最终审批决策 - 管理员人工审批
|
||
|
||
你的职责:
|
||
1. 分析资产上链申请的合规风险
|
||
2. 识别缺失的合规材料
|
||
3. 评估各层验证的通过可能性
|
||
4. 提供具体的改进建议
|
||
|
||
输出格式:
|
||
- 合规评分(0-100)
|
||
- 各层状态(通过/待审/未通过/不适用)
|
||
- 风险点列表
|
||
- 改进建议`;
|
||
|
||
async function runComplianceAgent(
|
||
userMessage: string,
|
||
history: AgentMessage[],
|
||
context?: Record<string, unknown>
|
||
): Promise<AgentResponse> {
|
||
const assetContext = context?.assetType
|
||
? `\n\n待分析资产类型:${context.assetType}\n司法管辖区:${context.jurisdiction || "未指定"}`
|
||
: "";
|
||
|
||
const messages: AgentMessage[] = [
|
||
{ role: "system", content: COMPLIANCE_ANALYSIS_SYSTEM_PROMPT + assetContext },
|
||
...history.slice(-4),
|
||
{ role: "user", content: userMessage },
|
||
];
|
||
|
||
const reply = await callAgentLLM(messages, 1500, 0.3);
|
||
|
||
return {
|
||
agentType: "compliance",
|
||
message: reply,
|
||
confidence: 0.8,
|
||
suggestions: [
|
||
"查看完整的七层合规验证报告",
|
||
"上传缺失的合规文件",
|
||
"联系合规顾问",
|
||
],
|
||
};
|
||
}
|
||
|
||
// ─── 翻译Agent ────────────────────────────────────────────────────
|
||
|
||
const TRANSLATION_SYSTEM_PROMPT = `你是NAC公链的专业法律合规翻译专家。
|
||
支持语言:中文(zh)、英文(en)、阿拉伯文(ar)、日文(ja)、韩文(ko)、法文(fr)、俄文(ru)
|
||
|
||
翻译要求:
|
||
1. 保持法律术语的准确性和专业性
|
||
2. 保留专有名词(NAC、RWA、Charter、NVM、CBPP、CSNP、CNNL、ACC-20、GNACS、XTZH)不翻译
|
||
3. 保留机构名称(SEC、SFC、MAS、ESMA、DFSA、DLD)不翻译
|
||
4. 阿拉伯语使用标准现代阿拉伯语(MSA),文本方向RTL
|
||
5. 只返回翻译结果,不添加解释`;
|
||
|
||
async function runTranslationAgent(
|
||
userMessage: string,
|
||
history: AgentMessage[],
|
||
context?: Record<string, unknown>
|
||
): Promise<AgentResponse> {
|
||
const langContext = context?.targetLang
|
||
? `\n\n目标语言:${context.targetLang}`
|
||
: "";
|
||
|
||
const messages: AgentMessage[] = [
|
||
{ role: "system", content: TRANSLATION_SYSTEM_PROMPT + langContext },
|
||
...history.slice(-4),
|
||
{ role: "user", content: userMessage },
|
||
];
|
||
|
||
const reply = await callAgentLLM(messages, 2048, 0.2);
|
||
|
||
return {
|
||
agentType: "translation",
|
||
message: reply,
|
||
confidence: 0.9,
|
||
metadata: {
|
||
targetLang: context?.targetLang,
|
||
isRTL: context?.targetLang === "ar",
|
||
},
|
||
};
|
||
}
|
||
|
||
// ─── 审批辅助Agent ────────────────────────────────────────────────
|
||
|
||
const APPROVAL_ASSIST_SYSTEM_PROMPT = `你是NAC公链审批工作流的AI辅助助手。
|
||
你的职责:
|
||
1. 分析审批案例的合规评分和风险点
|
||
2. 根据七层合规验证结果提供审批建议
|
||
3. 识别高风险案例并提醒审核员关注
|
||
4. 生成标准化的审批意见模板
|
||
|
||
审批决策依据:
|
||
- 合规评分 ≥ 90:建议自动批准(需管理员确认)
|
||
- 合规评分 70-89:建议人工审核
|
||
- 合规评分 50-69:建议要求补充材料
|
||
- 合规评分 < 50:建议拒绝
|
||
|
||
输出要求:
|
||
- 给出明确的审批建议(批准/拒绝/需补充材料)
|
||
- 列出关键风险点
|
||
- 提供标准化审批意见文本`;
|
||
|
||
async function runApprovalAssistAgent(
|
||
userMessage: string,
|
||
history: AgentMessage[],
|
||
context?: Record<string, unknown>
|
||
): Promise<AgentResponse> {
|
||
const caseContext = context?.caseNumber
|
||
? `\n\n案例编号:${context.caseNumber}\n合规评分:${context.complianceScore || "未知"}\n资产类型:${context.assetType || "未知"}\n司法管辖区:${context.jurisdiction || "未知"}`
|
||
: "";
|
||
|
||
const messages: AgentMessage[] = [
|
||
{ role: "system", content: APPROVAL_ASSIST_SYSTEM_PROMPT + caseContext },
|
||
...history.slice(-4),
|
||
{ role: "user", content: userMessage },
|
||
];
|
||
|
||
const reply = await callAgentLLM(messages, 1200, 0.4);
|
||
|
||
return {
|
||
agentType: "approval_assist",
|
||
message: reply,
|
||
confidence: 0.75,
|
||
suggestions: [
|
||
"查看完整案例详情",
|
||
"添加审核意见",
|
||
"更新审批状态",
|
||
],
|
||
};
|
||
}
|
||
|
||
// ─── Agent调度器 ──────────────────────────────────────────────────
|
||
|
||
/**
|
||
* 运行指定类型的Agent
|
||
*/
|
||
export async function runAgent(request: AgentRequest): Promise<AgentResponse> {
|
||
if (!isAgentConfigured()) {
|
||
return {
|
||
agentType: request.agentType,
|
||
message: "AI智能体服务未配置。请在生产服务器 .env 文件中设置 NAC_AI_API_URL 和 NAC_AI_API_KEY。\n\n推荐接入阿里云通义千问(国内访问稳定):\n- NAC_AI_API_URL=https://dashscope.aliyuncs.com/compatible-mode\n- NAC_AI_API_KEY=sk-xxxxxxxx\n- NAC_AI_MODEL=qwen-plus",
|
||
confidence: 0,
|
||
suggestions: ["配置AI服务后重试"],
|
||
};
|
||
}
|
||
|
||
const { agentType, userMessage, conversationHistory = [], context } = request;
|
||
|
||
try {
|
||
switch (agentType) {
|
||
case "knowledge_qa":
|
||
return await runKnowledgeQAAgent(userMessage, conversationHistory, context);
|
||
case "compliance":
|
||
return await runComplianceAgent(userMessage, conversationHistory, context);
|
||
case "translation":
|
||
return await runTranslationAgent(userMessage, conversationHistory, context);
|
||
case "approval_assist":
|
||
return await runApprovalAssistAgent(userMessage, conversationHistory, context);
|
||
default:
|
||
throw new Error(`未知的Agent类型: ${agentType}`);
|
||
}
|
||
} catch (error) {
|
||
console.error(`[Agent:${agentType}] 执行失败:`, (error as Error).message);
|
||
return {
|
||
agentType,
|
||
message: `Agent执行失败: ${(error as Error).message}`,
|
||
confidence: 0,
|
||
};
|
||
}
|
||
}
|
||
|
||
// ─── Agent元数据 ──────────────────────────────────────────────────
|
||
|
||
export const AGENT_REGISTRY = [
|
||
{
|
||
type: "knowledge_qa" as AgentType,
|
||
name: "知识库问答助手",
|
||
nameEn: "Knowledge QA Agent",
|
||
description: "基于NAC合规规则库回答问题,支持七大司法管辖区的合规查询",
|
||
icon: "BookOpen",
|
||
capabilities: ["合规规则查询", "司法管辖区解读", "上链流程指导"],
|
||
suggestedQuestions: [
|
||
"中国大陆房地产上链需要哪些文件?",
|
||
"香港RWA合规要求是什么?",
|
||
"七层合规验证框架是什么?",
|
||
],
|
||
},
|
||
{
|
||
type: "compliance" as AgentType,
|
||
name: "合规分析专家",
|
||
nameEn: "Compliance Analysis Agent",
|
||
description: "基于七层合规验证框架分析资产上链申请的合规风险",
|
||
icon: "Shield",
|
||
capabilities: ["风险评估", "合规评分", "缺失材料识别", "改进建议"],
|
||
suggestedQuestions: [
|
||
"分析这个房产上链申请的合规风险",
|
||
"我的资产缺少哪些合规文件?",
|
||
"如何提高合规评分?",
|
||
],
|
||
},
|
||
{
|
||
type: "translation" as AgentType,
|
||
name: "多语言翻译专家",
|
||
nameEn: "Translation Agent",
|
||
description: "专业法律合规文本翻译,支持七种语言,保留专有名词",
|
||
icon: "Languages",
|
||
capabilities: ["七语言翻译", "法律术语准确", "专有名词保留", "阿拉伯语RTL"],
|
||
suggestedQuestions: [
|
||
"将这段合规规则翻译成英文",
|
||
"翻译成阿拉伯语",
|
||
"生成七种语言的翻译",
|
||
],
|
||
},
|
||
{
|
||
type: "approval_assist" as AgentType,
|
||
name: "审批辅助助手",
|
||
nameEn: "Approval Assist Agent",
|
||
description: "辅助审核员分析案例、生成审批意见、识别高风险案例",
|
||
icon: "ClipboardCheck",
|
||
capabilities: ["审批建议", "风险识别", "意见模板", "案例分析"],
|
||
suggestedQuestions: [
|
||
"分析这个案例应该批准还是拒绝?",
|
||
"生成标准审批意见",
|
||
"这个案例有哪些风险点?",
|
||
],
|
||
},
|
||
];
|
||
|
||
export type AgentRegistryItem = typeof AGENT_REGISTRY[number];
|