AML 模板管理文档

AML 模板管理文档

一、模板存储

1.1 数据库表

文件位置/app/lib/db/index.ts

// AML模板表
database.exec(`
  CREATE TABLE IF NOT EXISTS "AmlTemplate" (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT UNIQUE NOT NULL,
    type TEXT NOT NULL,
    item_type TEXT NOT NULL,
    template TEXT NOT NULL,
    description TEXT,
    parameters TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT DEFAULT CURRENT_TIMESTAMP
  )
`);

// AML对象表
database.exec(`
  CREATE TABLE IF NOT EXISTS "AmlObject" (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    item_type TEXT NOT NULL,
    name TEXT,
    aml TEXT NOT NULL,
    schema TEXT,
    created_at TEXT DEFAULT CURRENT_TIMESTAMP,
    updated_at TEXT DEFAULT CURRENT_TIMESTAMP
  )
`);

1.2 表结构

AmlTemplate表

| 字段 | 类型 | 说明 |

|------|------|------|

| id | INTEGER | 主键 |

| name | TEXT | 模板名称 |

| type | TEXT | 操作类型 (get/add/edit/delete) |

| item_type | TEXT | 对象类型 |

| template | TEXT | AML模板 |

| description | TEXT | 描述 |

| parameters | TEXT | 参数定义 (JSON) |

AmlObject表

| 字段 | 类型 | 说明 |

|------|------|------|

| id | INTEGER | 主键 |

| item_type | TEXT | 对象类型 |

| name | TEXT | 对象名称 |

| aml | TEXT | AML内容 |

| schema | TEXT | 对象Schema (JSON) |

二、模板API

2.1 管理API

文件位置/app/api/aml/templates/route.ts

import { NextRequest, NextResponse } from 'next/server';
import { getDatabase } from '@/app/lib/db';

// GET /api/aml/templates?type=get&item_type=ECR
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const type = searchParams.get('type');
  const itemType = searchParams.get('item_type');

  const db = getDatabase();
  let sql = 'SELECT * FROM "AmlTemplate" WHERE 1=1';
  const params: any[] = [];

  if (type) {
    sql += ' AND type = ?';
    params.push(type);
  }
  if (itemType) {
    sql += ' AND item_type = ?';
    params.push(itemType);
  }

  const templates = db.prepare(sql).all(...params);

  return NextResponse.json({
    success: true,
    data: templates
  });
}

// POST /api/aml/templates
export async function POST(request: NextRequest) {
  const { name, type, item_type, template, description, parameters } = await request.json();

  if (!name || !type || !item_type || !template) {
    return NextResponse.json(
      { success: false, message: 'Missing required fields' },
      { status: 400 }
    );
  }

  const db = getDatabase();

  const result = db.prepare(`
    INSERT INTO "AmlTemplate" (name, type, item_type, template, description, parameters)
    VALUES (?, ?, ?, ?, ?, ?)
  `).run(name, type, item_type, template, description || '', parameters || '{}');

  return NextResponse.json({
    success: true,
    data: { id: result.lastInsertRowid }
  });
}

2.2 对象API

文件位置/app/api/aml/objects/route.ts

import { NextRequest, NextResponse } from 'next/server';
import { getDatabase } from '@/app/lib/db';

// GET /api/aml/objects
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const itemType = searchParams.get('item_type');

  const db = getDatabase();
  let sql = 'SELECT * FROM "AmlObject"';
  const params: any[] = [];

  if (itemType) {
    sql += ' WHERE item_type = ?';
    params.push(itemType);
  }

  const objects = db.prepare(sql).all(...params);

  return NextResponse.json({
    success: true,
    data: objects
  });
}

// POST /api/aml/objects (批量导入)
export async function POST(request: NextRequest) {
  const { items } = await request.json();

  if (!items || !Array.isArray(items)) {
    return NextResponse.json(
      { success: false, message: 'Invalid items' },
      { status: 400 }
    );
  }

  const db = getDatabase();
  let imported = 0;
  let updated = 0;

  const insert = db.prepare(`
    INSERT OR REPLACE INTO "AmlObject" (item_type, name, aml, schema)
    VALUES (?, ?, ?, ?)
  `);

  for (const item of items) {
    const result = insert.run(item.item_type, item.name || '', item.aml, item.schema || '{}');
    if (result.changes > 0) {
      imported++;
    }
  }

  return NextResponse.json({
    success: true,
    data: { imported, updated }
  });
}

三、模板使用

3.1 模板渲染

// 文件位置:/app/lib/aml/render.ts

export function renderTemplate(template: string, params: Record<string, any>): string {
  let result = template;

  // 替换简单变量 {name}
  Object.keys(params).forEach(key => {
    const value = params[key];
    if (value !== undefined && value !== null) {
      result = result.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
    }
  });

  // 替换条件变量 {condition?<true>:<false>}
  result = result.replace(/\{(\w+)\?([^:]+):([^}]+)\}/g, (match, condition, truePart, falsePart) => {
    return params[condition] ? truePart : falsePart;
  });

  return result;
}

// 使用示例
const template = '<AML><Item type="ECR" action="get">{status?<status>{status}</status>:}</Item></AML>';
const rendered = renderTemplate(template, { status: 'pending_approval' });
// 结果: <AML><Item type="ECR" action="get"><status>pending_approval</status></Item></AML>

3.2 模板执行

// 文件位置:/app/lib/aml/execute.ts

import { renderTemplate } from './render';
import { executeAmlWithFallback } from '../SCSAI/fallback';

export async function executeTemplate(
  templateId: number,
  params: Record<string, any>
): Promise<any> {
  const db = getDatabase();
  const template = db.prepare('SELECT * FROM "AmlTemplate" WHERE id = ?').get(templateId) as any;

  if (!template) {
    throw new Error('Template not found');
  }

  const renderedAml = renderTemplate(template.template, params);
  return await executeAmlWithFallback(renderedAml, template.item_type);
}

四、快速创建示例

4.1 创建Part对象类

// 通过大模型生成AML
const prompt = `生成创建汽车Part的AML:
对象类型:Part
字段:
- part_number: PART-CAR-001
- name: 汽车
- description: 一辆完整的汽车
- vehicle_type: SUV
- brand: 奔驰
- model: GLC-300
- color: 黑色
- price: 500000`;

const result = await fetch('/api/ai-proxy', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ messages: [{ role: 'user', content: prompt }] })
});

// 解析AML并保存
const aml = parseAmlResult(result.data);
await saveAmlObject('Part', aml, {
  name: '汽车',
  schema: { fields: [...] }
});

4.2 保存到数据库

// 保存对象定义
db.prepare(`
  INSERT INTO "AmlObject" (item_type, name, aml, schema)
  VALUES (?, ?, ?, ?)
`).run('Part', '汽车', aml, JSON.stringify(schema));

五、文件位置总结

| 功能 | 文件位置 |

|------|----------|

| 数据库初始化 | /app/lib/db/index.ts |

| 模板API | /app/api/aml/templates/route.ts |

| 对象API | /app/api/aml/objects/route.ts |

| 模板渲染 | /app/lib/aml/render.ts |

| 模板执行 | /app/lib/aml/execute.ts |

← 返回案例列表
分享:
🤖 Try Now →
🤖
🎁