Files
rongtongjin/openspec/changes/archive/2026-01-14-add-llm-trend-analysis/design.md
T
hughhuangandClaude Sonnet 4.5 ccf523543a feat: 实现LLM趋势告警历史上下文判断功能
新增功能:
- 在LLM趋势分析中集成历史告警上下文,提供最近3次已触发告警的记录
- LLM自动判断本次分析是否与历史告警相似,避免重复通知
- 新增shouldNotify和notifyReason字段,支持智能通知决策

技术改进:
- 扩展TrendAnalysisResponse类型,增加通知决策字段
- 数据库服务新增getRecentTriggeredAnalyses()方法
- LLM客户端新增analyzeTrendWithHistory()和相关方法
- 趋势分析服务集成历史上下文获取和通知决策逻辑

测试验证:
- 创建test-db-history-method.ts验证数据库方法
- 创建test-llm-history-context.ts测试历史上下文功能
- 通过TypeScript类型检查和构建验证

这个功能可以有效减少重复告警,提升告警质量,避免通知疲劳。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-15 19:37:28 +08:00

337 lines
11 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# LLM 趋势总结架构设计
## 系统架构概述
```
┌─────────────────────────────────────────────────────────────┐
│ 主程序 (index.ts) │
│ │
│ ┌──────────────────────┐ ┌──────────────────────────┐ │
│ │ 白银基线监控 │ │ LLM 趋势总结(新功能) │ │
│ │ (每分钟执行) │ │ (每 10 分钟执行) │ │
│ └──────────────────────┘ └──────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
└────────────┼─────────────────────────┼──────────────────────┘
│ │
▼ ▼
┌────────────────────┐ ┌──────────────────────────┐
│ SilverBaseline │ │ SilverTrendAnalyzer │
│ Monitor │ │ (新服务) │
│ │ │ │
│ - 基线管理 │ │ - 定时触发 │
│ - 阈值告警 │ │ - 数据准备 │
│ - 飞书告警 │ │ - LLM 调用 │
└────────────────────┘ │ - 结果解析 │
│ - 告警判断 │
└──────────┬───────────────┘
│
▼
┌──────────────────────┐
│ LLMClient │
│ (新工具类) │
│ │
│ - OpenAI API 调用 │
│ - Prompt 构建 │
│ - 响应解析 │
│ - 错误处理 │
└──────────────────────┘
│
▼
┌──────────────────────┐
│ DatabaseService │
│ │
│ - 趋势数据存储 │
│ - 历史查询 │
└──────────────────────┘
```
## 核心组件设计
### 1. SilverTrendAnalyzer Service
**职责**:
- 协调趋势总结的完整流程
- 从数据库获取最近30分钟的价格数据(作为上下文)
- 指导 LLM 重点总结最近10分钟的趋势
- 解析 LLM 响应并判断是否需要告警
- 触发飞书告警通知
- 保存分析记录
**接口设计**:
```typescript
class SilverTrendAnalyzer {
constructor(
db: DatabaseService,
alertService: AlertService,
llmClient: LLMClient,
webhookUrl?: string
)
// 主要方法
async analyzeTrend(): Promise<TrendAnalysisResult | null>
// 内部方法
private async prepareAnalysisData(): Promise<PriceDataPoint[]>
private async callLLM(data: PriceDataPoint[]): Promise<LLMResponse>
private parseLLMResponse(response: LLMResponse): ParsedTrendAnalysis
private shouldAlert(analysis: ParsedTrendAnalysis, previous?: ParsedTrendAnalysis): boolean
private async sendTrendAlert(analysis: ParsedTrendAnalysis): Promise<void>
private async saveAnalysis(analysis: ParsedTrendAnalysis): Promise<void>
}
```
### 2. LLMClient Utility
**职责**:
- 封装 LLM API 调用细节
- 构建趋势总结提示词(Prompt)
- 解析 LLM 的结构化响应
- 处理 API 错误和重试逻辑
**接口设计**:
```typescript
class LLMClient {
constructor(config: LLMConfig)
async analyzeTrend(data: PriceDataPoint[]): Promise<TrendAnalysisResponse>
// 配置接口
private buildPrompt(data: PriceDataPoint[]): string
private parseResponse(response: string): TrendAnalysisResponse
private callAPI(prompt: string): Promise<string>
}
interface LLMConfig {
apiBase: string
apiKey: string
model: string
timeout?: number
maxRetries?: number
}
interface TrendAnalysisResponse {
trend: 'uptrend' | 'downtrend' | 'sideways' | 'volatile'
confidence: number // 0-1
summary: string // 人类可读的趋势总结
signals: string[] // 识别到的关键信号
risk: 'low' | 'medium' | 'high'
}
```
### 3. 数据类型定义
**新增类型**(在 `src/types/index.ts` 中):
```typescript
// 价格数据点(用于 LLM 分析)
interface PriceDataPoint {
price: number
timestamp: string
// 可选:包含更多技术指标
changeFromPrevious?: number
volatility?: number
}
// LLM 趋势分析记录
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 // 原始响应(用于调试)
}
// 趋势分析数据库
interface TrendAnalysisDatabase {
analyses: TrendAnalysisRecord[]
}
```
## Prompt 工程
### Prompt 设计原则
1. **结构化输入**:将价格数据转换为易读的格式
2. **明确任务**:清晰定义 LLM 需要完成的任务(总结趋势,而非预测)
3. **结构化输出**:要求 LLM 返回 JSON 格式的响应
4. **上下文信息**:提供足够的背景信息帮助 LLM 理解数据
### Prompt 模板(示例)
```typescript
const promptTemplate = `
你是一个专业的金融分析师,擅长分析贵金属价格趋势。
以下是白银最近 30 分钟的价格数据(每分钟一次):
{PRICE_DATA}
请重点分析**最近 10 分钟**的价格趋势(同时参考前 20 分钟的走势作为背景),并提供:
1. 趋势判断:uptrend(上涨趋势)/ downtrend(下跌趋势)/ sideways(平稳波动)/ volatile(剧烈波动)
2. 置信度:0-1 之间的数值
3. 趋势总结:用 1-2 句话描述最近 10 分钟的价格走势
4. 关键信号:列出你观察到的 3-5 个关键信号(如价格突破、波动异常、趋势转变等)
5. 风险评估:low/medium/high
**重要**:
- 专注于总结已经发生的趋势,不要预测未来走势
- 重点分析最近 10 分钟的变化,但理解前 20 分钟的背景有助于判断趋势
- 如果检测到趋势反转(从上涨变为下跌或反之),必须在 signals 中明确标注
- 如果检测到价格剧烈波动(波动幅度异常增大),必须将 trend 设为 volatile
- 关注价格变化的幅度、速度和持续性
请以 JSON 格式返回:
{
"trend": "uptrend|downtrend|sideways|volatile",
"confidence": 0.85,
"summary": "...",
"signals": ["...", "...", "..."],
"risk": "low|medium|high"
}
`;
```
### 数据格式化
将价格数据格式化为易读的文本:
```
时间 价格 变化 波动
2026-01-14 16:00 22.24 +0.01 0.5%
2026-01-14 16:01 22.24 0.00 0.0%
...
```
## 告警逻辑
### 告警触发条件
```typescript
function shouldAlert(
current: ParsedTrendAnalysis,
previous?: ParsedTrendAnalysis
): boolean {
// 条件 1:趋势反转
if (previous && isTrendReversal(previous.trend, current.trend)) {
return true
}
// 条件 2:剧烈波动
if (current.trend === 'volatile' && current.confidence > 0.7) {
return true
}
// 条件 3:高风险 + 高置信度
if (current.risk === 'high' && current.confidence > 0.8) {
return true
}
return false
}
```
### 飞书告警卡片设计
使用飞书交互式卡片,包含:
- 标题:白银价格趋势告警
- 趋势标签(上涨📈 / 下跌📉 / 平稳➡️ / 波动📊)
- 趋势总结
- 关键信号列表
- 风险评估(颜色编码)
- 分析时间
- 置信度指示器
## 集成方案
### 主程序集成(`src/index.ts`)
```typescript
class App {
private trendAnalyzer: SilverTrendAnalyzer
constructor() {
// ... 现有初始化代码
// 配置 LLM 客户端
const llmConfig = {
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1',
apiKey: process.env.LLM_API_KEY,
model: process.env.LLM_MODEL || 'gpt-4o-mini',
timeout: 30000
}
const llmClient = new LLMClient(llmConfig)
// 配置趋势总结服务
this.trendAnalyzer = new SilverTrendAnalyzer(
this.db,
this.alertService,
llmClient,
process.env.WEBHOOK_URL
)
}
start() {
// ... 现有白银基线监控代码
// 启动 LLM 趋势总结
const trendAnalysisInterval = Number(process.env.TREND_ANALYSIS_INTERVAL) || 600000 // 默认 10 分钟
const analyzeTrend = async () => {
try {
await this.trendAnalyzer.analyzeTrend()
} catch (error) {
console.error('趋势总结执行出错:', error)
}
}
// 首次延迟 10 分钟执行(等待积累足够数据)
setTimeout(analyzeTrend, 600000)
// 定时执行
setInterval(analyzeTrend, trendAnalysisInterval)
}
}
```
## 错误处理和容错
### LLM API 调用失败处理
- 重试机制:最多重试 2 次,间隔 5 秒
- 超时处理:30 秒超时,避免阻塞主程序
- 降级处理:分析失败时记录日志,不影响基线监控
- 告警抑制:连续失败时暂停告警,避免频繁通知
### 数据不足处理
- 如果历史数据少于 30 个点,跳过本次分析
- 记录警告日志,等待下次执行
## 性能和成本优化
### 成本控制
- 使用 `gpt-4o-mini` 模型(成本较低)
- 控制输入 token 数量(约 1000-2000 tokens)
- 可配置分析间隔,默认 10 分钟
- 仅在检测到重要信号时发送告警
### 性能优化
- 异步执行,不阻塞主程序
- 缓存 LLM 客户端实例
- 数据库查询优化(添加索引)
## 测试策略
### 单元测试
- LLMClient 的 Prompt 构建和响应解析
- 趋势判断逻辑
- 告警触发条件
### 集成测试
- 端到端的分析流程
- 飞书告警发送
- 数据库存储
### 手动测试
- 使用测试数据验证 LLM 响应质量
- 测试不同市场情况(上涨、下跌、波动)
- 验证告警触发逻辑