Files
rongtongjin/openspec/changes/archive/2026-01-15-add-llm-alert-history-context/design.md
T
hughhuangandClaude Sonnet 4.5 00d6683bb1 docs: 归档 LLM 趋势告警历史上下文判断变更
将 add-llm-alert-history-context 变更归档到 archive 目录,
并更新 silver-trend-analysis 规格文档。

主要变更:
- 归档变更到 2026-01-15-add-llm-alert-history-context
- 更新规格文档:新增 2 个需求,修改 5 个需求
- 补充 MySQL 数据库配置示例到 .env.example

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-15 23:58:03 +08:00

13 KiB

Design: LLM 趋势告警历史上下文判断

概述

本设计文档描述如何在 LLM 趋势分析流程中增加历史告警上下文,让 LLM 基于历史告警内容判断本次是否需要发送通知,从而避免重复告警和通知疲劳。

架构设计

数据流

1. 获取价格数据 (最近 30 个数据点)
   ↓
2. 获取历史告警记录 (最近 3 次 triggered=true 的记录)
   ↓
3. 构建 LLM Prompt (包含价格数据 + 历史告警上下文)
   ↓
4. 调用 LLM API
   ↓
5. 解析响应 (包含 shouldNotify 和 notifyReason)
   ↓
6. 判断是否触发告警 (现有条件 + shouldNotify)
   ↓
7. 保存分析记录 (包含通知决策)
   ↓
8. 发送或跳过通知 (根据 shouldNotify)

组件交互

SilverTrendAnalyzer
  ├─> DatabaseService.getRecentTriggeredAnalyses(3)  // 获取历史告警
  ├─> DatabaseService.getRecentPricePoints(30)       // 获取价格数据
  ├─> LLMClient.analyzeTrendWithHistory(data, history) // 调用 LLM
  ├─> shouldTriggerAlert(response, previous, dataPoints) // 判断触发条件
  ├─> checkShouldNotify(response)                    // 检查通知决策
  └─> sendTrendAlert(record) or skipAlert(record)    // 发送或跳过

详细设计

1. 数据库服务扩展

新增方法: getRecentTriggeredAnalyses(count: number)

/**
 * 获取最近 N 次已触发告警的分析记录
 * @param count 获取的记录数量
 * @returns 已触发告警的分析记录数组(按时间倒序)
 */
getRecentTriggeredAnalyses(count: number): TrendAnalysisRecord[] {
  return this.trendAnalysisData.analyses
    .filter(record => record.triggered === true)
    .slice(-count)
    .reverse();
}

设计考虑:

  • 只返回 triggered: true 的记录,因为只有这些记录发送了通知
  • 按时间倒序返回,最新的在前
  • 如果历史记录不足 count 个,返回所有可用记录

2. LLM 客户端扩展

新增方法: analyzeTrendWithHistory(data, history)

/**
 * 分析价格趋势(包含历史告警上下文)
 * @param data 价格数据点
 * @param history 历史告警记录
 * @returns 趋势分析结果(包含通知决策)
 */
async analyzeTrendWithHistory(
  data: PriceDataPoint[],
  history: TrendAnalysisRecord[]
): Promise<TrendAnalysisResponse> {
  const prompt = this.buildPromptWithHistory(data, history);
  const response = await this.callAPI(prompt);
  return this.parseResponseWithNotify(response);
}

Prompt 构建策略:

private buildPromptWithHistory(
  data: PriceDataPoint[],
  history: TrendAnalysisRecord[]
): string {
  const dataText = this.formatDataPoints(data);
  const historyText = this.formatHistoryContext(history);

  return `你是一个专业的金融分析师,擅长分析贵金属价格趋势。

**重要:你只需要输出 JSON 格式,不要包含任何其他文字、解释或推理过程。**

以下是白银最近 30 分钟的价格数据(每分钟一次):

${dataText}

${historyText}

请重点分析**最近 10 分钟**的价格趋势,并提供:
1. 趋势判断: uptrend/downtrend/sideways/volatile
2. 置信度: 0-1 之间的数值
3. 趋势总结: 用 1-2 句话描述最近 10 分钟的价格走势
4. 关键信号: 列出你观察到的 3-5 个关键信号
5. 风险评估: low/medium/high
6. **通知决策**: 判断是否应该发送通知(shouldNotify: true/false)
7. **通知原因**: 说明为什么应该或不应该发送通知(notifyReason)

**通知决策标准**:
- 如果本次分析与最近的历史告警**高度相似**(趋势类型相同、总结内容大部分重复、信号列表高度重叠),则 shouldNotify 应为 false
- 如果出现**新的重要变化**(趋势反转、新的风险信号、波动幅度显著变化),则 shouldNotify 应为 true
- 如果没有历史告警记录,则 shouldNotify 应为 true
- 相似度判断应综合考虑:趋势类型、总结内容、信号列表、风险评估

**输出格式:直接输出以下 JSON 结构,不要包含任何其他内容**
{
  "trend": "uptrend|downtrend|sideways|volatile",
  "confidence": 0.85,
  "summary": "...",
  "signals": ["...", "...", "..."],
  "risk": "low|medium|high",
  "shouldNotify": true,
  "notifyReason": "..."
}`;
}

历史上下文格式化:

private formatHistoryContext(history: TrendAnalysisRecord[]): string {
  if (history.length === 0) {
    return '**历史告警记录**: 无(这是首次分析或首次触发告警)';
  }

  const historyLines = history.map((record, index) => {
    const time = new Date(record.timestamp).toLocaleString('zh-CN');
    return `
**历史告警 ${index + 1}** (${time}):
- 趋势: ${record.trend}
- 总结: ${record.summary}
- 信号: ${record.signals.join('; ')}
- 风险: ${record.risk}
- 置信度: ${(record.confidence * 100).toFixed(0)}%`;
  }).join('\n');

  return `**最近 ${history.length} 次历史告警记录**:
${historyLines}

请比较本次分析与上述历史告警的相似度,判断是否需要再次发送通知。`;
}

响应解析扩展:

private parseResponseWithNotify(response: string): TrendAnalysisResponse {
  const parsed = JSON.parse(response);

  // 验证必需字段(包括新增字段)
  const requiredFields = [
    'trend', 'confidence', 'summary',
    'signals', 'risk', 'shouldNotify', 'notifyReason'
  ];

  for (const field of requiredFields) {
    if (!(field in parsed)) {
      // 如果缺少 shouldNotify,默认为 true(保守策略)
      if (field === 'shouldNotify') {
        parsed.shouldNotify = true;
        parsed.notifyReason = '未提供通知决策,默认发送通知';
      } else {
        throw new Error(`响应缺少必需字段: ${field}`);
      }
    }
  }

  return parsed;
}

3. 趋势分析服务调整

修改 analyzeTrend() 方法:

async analyzeTrend(): Promise<TrendAnalysisRecord | null> {
  try {
    console.log('\n========================================');
    console.log('开始 LLM 趋势总结');

    // 准备分析数据
    const dataPoints = this.prepareAnalysisData();

    if (dataPoints.length < 5) {
      console.log(`历史数据不足(${dataPoints.length} 个数据点),跳过趋势总结`);
      return null;
    }

    // 获取历史告警记录
    const historyAlerts = this.db.getRecentTriggeredAnalyses(3);
    console.log(`获取到 ${historyAlerts.length} 条历史告警记录`);

    // 调用 LLM API(包含历史上下文)
    console.log('调用 LLM API(包含历史告警上下文)');
    const llmResponse = await this.llmClient.analyzeTrendWithHistory(
      dataPoints,
      historyAlerts
    );

    console.log(`LLM 响应成功`);
    console.log(`  趋势: ${llmResponse.trend}`);
    console.log(`  置信度: ${(llmResponse.confidence * 100).toFixed(0)}%`);
    console.log(`  风险: ${llmResponse.risk}`);
    console.log(`  通知决策: ${llmResponse.shouldNotify ? '发送' : '跳过'}`);
    console.log(`  决策原因: ${llmResponse.notifyReason}`);

    // 判断是否需要告警(现有逻辑)
    const previousAnalysis = this.db.getLatestTrendAnalysis();
    const shouldAlert = this.shouldTriggerAlert(
      llmResponse,
      previousAnalysis,
      dataPoints
    );

    // 创建分析记录
    const record: TrendAnalysisRecord = {
      id: uuidv4(),
      timestamp: new Date().toISOString(),
      dataPoints,
      trend: llmResponse.trend,
      confidence: llmResponse.confidence,
      summary: llmResponse.summary,
      signals: llmResponse.signals,
      risk: llmResponse.risk,
      triggered: shouldAlert && llmResponse.shouldNotify, // 同时满足两个条件
      llmResponseRaw: JSON.stringify(llmResponse)
    };

    // 保存分析记录
    await this.db.addTrendAnalysis(record);

    // 发送告警(需要同时满足触发条件和通知决策)
    if (shouldAlert) {
      if (llmResponse.shouldNotify) {
        console.log('⚠️ 触发趋势告警!');
        await this.sendTrendAlert(record);
      } else {
        console.log(`⏭️ 满足告警条件但跳过通知: ${llmResponse.notifyReason}`);
      }
    } else {
      console.log(`趋势总结完成: ${llmResponse.trend},置信度 ${(llmResponse.confidence * 100).toFixed(0)}%,风险 ${llmResponse.risk}`);
    }

    console.log('========================================\n');

    return record;
  } catch (error) {
    console.error('趋势总结执行出错:', error);
    return null;
  }
}

4. 类型定义扩展

扩展 TrendAnalysisResponse 接口:

export interface TrendAnalysisResponse {
  trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
  confidence: number;
  summary: string;
  signals: string[];
  risk: 'low' | 'medium' | 'high';
  shouldNotify: boolean;  // 新增:是否应该发送通知
  notifyReason: string;   // 新增:通知或跳过的原因
}

扩展 TrendAnalysisRecord 接口(可选,用于记录通知决策):

export interface TrendAnalysisRecord {
  id: string;
  timestamp: string;
  dataPoints: PriceDataPoint[];
  trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile';
  confidence: number;
  summary: string;
  signals: string[];
  risk: 'low' | 'medium' | 'high';
  triggered: boolean;
  llmResponseRaw: string;
  shouldNotify?: boolean;  // 新增(可选):LLM 的通知决策
  notifyReason?: string;   // 新增(可选):通知决策原因
}

边界情况处理

1. 历史记录不足

场景: 系统刚启动,还没有历史告警记录

处理:

  • getRecentTriggeredAnalyses(3) 返回空数组
  • Prompt 中说明"无历史告警记录"
  • LLM 应返回 shouldNotify: true(首次告警应该发送)

2. LLM 未返回通知决策

场景: LLM 响应中缺少 shouldNotify 或 notifyReason 字段

处理:

  • 默认 shouldNotify: true(保守策略,避免漏发重要告警)
  • 默认 notifyReason: "未提供通知决策,默认发送通知"
  • 记录警告日志

3. 告警触发条件不满足

场景: 现有的告警触发条件(趋势反转、剧烈波动、高风险)不满足

处理:

  • 即使 shouldNotify: true,也不发送告警
  • 保持现有的告警触发逻辑优先级
  • 只有在满足触发条件后,才进一步检查 shouldNotify

4. 相似度判断失误

场景: LLM 错误地判断为相似,导致漏发重要告警

缓解措施:

  • 在 Prompt 中明确定义"高度相似"的标准
  • 强调"新的重要变化"应该发送通知
  • 保留完整的分析记录,便于事后审计
  • 可通过调整 Prompt 或增加规则来优化判断

性能和成本

Token 消耗估算

  • 价格数据(30 个点): ~500 tokens

  • 历史告警上下文(3 条): ~300 tokens

  • Prompt 指令: ~800 tokens

  • 总输入: ~1600 tokens (增加约 300 tokens)

  • LLM 响应: ~200 tokens

成本影响:

  • 使用 gpt-4o-mini: 输入 $0.15/1M tokens, 输出 $0.60/1M tokens
  • 每次分析成本: ~$0.0004 (增加约 $0.0001)
  • 每天成本(10分钟间隔): ~$0.06 (增加约 $0.01)

成本优化:

  • 通过减少重复告警,可能降低整体通知成本
  • 历史上下文数量可配置(1-5 条),允许用户权衡成本和效果

测试策略

单元测试

  1. 数据库服务测试:

    • 测试 getRecentTriggeredAnalyses() 正确过滤和排序
    • 测试历史记录不足时的行为
  2. LLM 客户端测试:

    • 测试历史上下文格式化
    • 测试响应解析(包含新字段)
    • 测试缺少 shouldNotify 时的默认行为
  3. 趋势分析服务测试:

    • 测试告警触发逻辑(现有条件 + shouldNotify)
    • 测试跳过通知的日志输出

集成测试

  1. 端到端测试:

    • 模拟连续多次分析,验证历史上下文传递
    • 验证相似告警被正确跳过
    • 验证新变化触发通知
  2. 边界情况测试:

    • 首次分析(无历史记录)
    • LLM 响应异常(缺少字段)
    • 历史记录数量不足 3 条

向后兼容性

数据兼容性

  • 新增字段为可选(shouldNotify?, notifyReason?)
  • 现有数据记录不受影响
  • 旧版本分析记录可以正常读取

API 兼容性

  • 保留原有的 analyzeTrend() 方法签名
  • 内部实现调整,外部接口不变
  • 现有的告警触发逻辑保持优先级

监控和调试

日志输出

开始 LLM 趋势总结
获取到 3 条历史告警记录
调用 LLM API(包含历史告警上下文)
LLM 响应成功
  趋势: uptrend
  置信度: 85%
  风险: medium
  通知决策: 跳过
  决策原因: 本次分析与最近一次告警高度相似,趋势类型相同,总结内容重复度高
⏭️ 满足告警条件但跳过通知: 本次分析与最近一次告警高度相似,趋势类型相同,总结内容重复度高

调试信息

  • 在 llmResponseRaw 中保存完整的 LLM 响应
  • 记录历史告警上下文的内容
  • 记录通知决策的原因

总结

本设计通过在 LLM 分析流程中增加历史告警上下文,让 LLM 基于历史内容判断是否需要发送通知,从而有效避免重复告警和通知疲劳。设计保持了向后兼容性,并提供了完善的边界情况处理和调试支持。