Skip to content

AI 辅助分析(Page Copilot)与受控 BI 2.5 ​

磐台将 AI 能力严格限定在只读、脱敏、可审计、可降级的生产安全边界内,拒绝把未脱敏业务数据或任意写 SQL 暴露给外部大模型。

1. Page Copilot(当前页 AI 辅助分析) ​

1.1 四层安全与工程保障 ​

  1. 入模前强制脱敏(PageCopilotService::sanitizeContext):
    • 自动剥离列键/列标题包含敏感词(password、secret、token、api_key、phone、mobile、email、bank_card、id_card 等)的字段,即使全部声明列都被脱敏也不会回流到行数据;
    • 递归脱敏 filters 与 rows 中的嵌套关联对象(限深 3 层,超限截断);
    • 自动剥离 route 中的 ?query 与 #fragment,防止 URL 中携带的 access_token 泄露。
  2. 确定性统计预分析(computeSignals):
    • 调用 LLM 前先在服务端计算可复核的数学信号:数值列 sum / mean / min / max / std_dev、离群点检测(|z| >= 2.2)、头部集中度检测(Top-1 占比 >= 50%)、以及 summary vs compare_summary 环比变化率;
    • 过滤 INF/NAN 防止数值溢出破坏 JSON 输出。
  3. 双模式与平滑降级:
    • 配置 OpenAiCompatibleLlmProvider 时走 mode = 'llm',模型仅基于脱敏上下文与统计信号输出严格 JSON;
    • 未配置模型或上游调用失败时自动降级为 mode = 'heuristic'(规则引擎分析),返回 fallback_reason = 'LLM_UNAVAILABLE',绝不透传上游错误体或 API Key。
  4. 权限、授权与审计闭环(CopilotHandler):
    • 强制校验 WriteOriginGuard(防跨站 CSRF)、节点级 RBAC(copilot:analyze)、可选 LicenseManager(校验 copilot 模块授权),并写入 AuditLogger(仅记录统计摘要,绝不落盘原始行数据)。

1.2 服务端挂载代码 ​

php
<?php

use Plinth\DeckCore\Core\Analytics\OpenAiCompatibleLlmProvider;
use Plinth\DeckCore\Core\Analytics\PageCopilotService;
use Plinth\DeckCore\Core\Http\CopilotHandler;

$llm = new OpenAiCompatibleLlmProvider([
    'base_url' => getenv('DECKCORE_LLM_BASE_URL'),
    'api_key' => getenv('DECKCORE_LLM_API_KEY'),
    'model' => getenv('DECKCORE_LLM_MODEL') ?: 'gpt-4o-mini',
]);

$copilot = new PageCopilotService($llm, [
    'maxRows' => 100,
    'maxColumns' => 40,
    'fallbackToHeuristic' => true,
]);

$handler = new CopilotHandler(
    $copilot,
    $decisionService,   // 强制校验 copilot:analyze 节点权限
    $auditLogger,       // 写入 copilot.analyze 审计事件
    null,
    null,
    'default',
    $sessionStore,
    $writeGuardOptions,
    $licenseManager,    // 可选:强制校验 Ed25519 License
    $licenseToken
);

$handler->registerRoutes($dispatcher, '/api/deckcore/copilot');

1.3 请求与响应契约示例 ​

POST /api/deckcore/copilot/analyze

json
{
  "intent": "trend",
  "question": "对比上期营收,拆解本期变化最大的渠道",
  "page_context": {
    "page_key": "revenue_daily",
    "page_title": "每日营收汇总",
    "route": "/reports/revenue-daily",
    "filters": { "date_range": ["2026-11-28", "2026-12-04"] },
    "columns": [
      { "key": "channel", "label": "渠道", "type": "string" },
      { "key": "revenue", "label": "营收", "type": "money" }
    ],
    "summary": { "revenue": 150000, "orders": 3200 },
    "compare_summary": { "revenue": 100000, "orders": 3100 },
    "rows": [
      { "channel": "AppStore", "revenue": 120000, "orders": 2100 },
      { "channel": "GooglePlay", "revenue": 8000, "orders": 280 }
    ]
  }
}

成功响应信封(Cache-Control: no-store):

json
{
  "ret": 1,
  "msg": "ok",
  "content": {
    "mode": "llm",
    "llm_used": true,
    "headline": "AppStore 驱动整体营收环比增长 50%",
    "summary": "本期总营收 150,000(上期 100,000),AppStore 单渠道占比达 80%。",
    "anomalies": [
      { "metric": "revenue", "severity": "high", "finding": "总营收环比上升 50%", "evidence": "150000 vs 100000" }
    ],
    "drivers": [
      { "factor": "AppStore", "impact": "单项贡献占比 80%", "evidence": "120000 / 150000" }
    ],
    "recommendations": [
      { "title": "核查 AppStore 活动复购留存", "priority": "high", "action": "按商品档位拆解增量来源" }
    ],
    "context_stats": { "rows_analyzed": 2, "rows_truncated": false, "redacted_fields": [] }
  }
}

2. 受控 AI 取数 2.5 与轻量嵌入式 BI ​

2.1 定义语义目录与只读连接 ​

php
<?php

use Plinth\DeckCore\Core\Analytics\SemanticCatalog;
use Plinth\DeckCore\Core\Host\DeckCoreStarterKit;

$catalog = new SemanticCatalog([[
    'dataset_key' => 'sales',
    'source' => 'sales_daily',
    'time_column' => 'day',
    'dimensions' => [['key' => 'day', 'column' => 'day', 'type' => 'date']],
    'metrics' => [['key' => 'revenue', 'expression' => 'SUM(amount)']],
    'scope_dimensions' => ['orgs' => 'org_id'],
    'allowed_columns' => ['day'],
]]);

$kit = new DeckCoreStarterKit($conn, [
    'biCatalog' => $catalog,
    'biLlmConfig' => [
        'base_url' => $modelBaseUrl,
        'api_key' => $modelApiKey,
        'model' => $modelName,
    ],
    'biQueryConnection' => $readOnlyConn,
    'biPlannerOptions' => ['maxRepairAttempts' => 1],
    'biExecutorOptions' => ['maxLimit' => 1000],
]);

2.2 内置 14 个 BI 端点一览 ​

端点权限与行为
GET /semanticbi:view;返回当前节点合并后的公开语义字典
GET /datasetsbi:manage;当前节点数据集配置列表
POST /datasets/save / POST /datasets/deletebi:manage;校验语义 schema 并写入同事务审计
POST /querybi:query;执行 DSL 或受控自然语言查询,强制注入 C2 dataScope
GET /dashboards / GET /dashboards/detailbi:view;私有看板强制归属权校验
POST /dashboards/save / POST /dashboards/deletebi:manage;支持 expected_revision 乐观锁(冲突 409)
POST /dashboards/runbi:view + bi:query;合并全局筛选与 widget 条件并逐卡片返回
GET /dashboards/sharesbi:share;查询分享元数据(不回显明文 token)
POST /dashboards/share / POST /dashboards/share/revokebi:share;签发一次性明文 token(库内仅存 SHA-256),固化签发者 _scope 上限
GET /shared/view匿名携带有效 share_token;仅运行已保存结构化 widget,禁止扩大范围

磐石工坊(Plinth Lab)· 企业级多框架中后台统一底座