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>
This commit is contained in:
commit
ccf523543a
52 files changed
+7763
No files matched your search
@@ -0,0 +1,447 @@
|
||||
import type { LLMConfig, TrendAnalysisResponse, PriceDataPoint, TrendAnalysisRecord } from '../types/index.js';
|
||||
|
||||
/**
|
||||
* LLM API 客户端
|
||||
* 用于调用 OpenAI 兼容的 API 进行趋势分析
|
||||
*/
|
||||
export class LLMClient {
|
||||
private config: LLMConfig;
|
||||
|
||||
constructor(config: LLMConfig) {
|
||||
this.config = {
|
||||
timeout: 120000, // 增加到 120 秒以适应智谱AI的推理时间
|
||||
maxRetries: 2,
|
||||
...config
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析价格趋势
|
||||
* @param data 价格数据点
|
||||
* @returns 趋势分析结果
|
||||
*/
|
||||
async analyzeTrend(data: PriceDataPoint[]): Promise<TrendAnalysisResponse> {
|
||||
const prompt = this.buildPrompt(data);
|
||||
const response = await this.callAPI(prompt);
|
||||
return this.parseResponse(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分析价格趋势(包含历史告警上下文)
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分析提示词
|
||||
* @param data 价格数据点
|
||||
* @returns Prompt 文本
|
||||
*/
|
||||
private buildPrompt(data: PriceDataPoint[]): string {
|
||||
// 将数据格式化为文本表格
|
||||
const dataText = this.formatDataPoints(data);
|
||||
|
||||
return `你是一个专业的金融分析师,擅长分析贵金属价格趋势。
|
||||
|
||||
**重要:你只需要输出 JSON 格式,不要包含任何其他文字、解释或推理过程。**
|
||||
|
||||
以下是白银最近 30 分钟的价格数据(每分钟一次):
|
||||
|
||||
${dataText}
|
||||
|
||||
请重点分析**最近 10 分钟**的价格趋势(同时参考前 20 分钟的走势作为背景),并提供:
|
||||
1. 趋势判断:uptrend(上涨趋势)/ downtrend(下跌趋势)/ sideways(平稳波动)/ volatile(剧烈波动)
|
||||
2. 置信度:0-1 之间的数值
|
||||
3. 趋势总结:用 1-2 句话描述最近 10 分钟的价格走势,**必须包含**:
|
||||
- 当前价格(单位:元)
|
||||
- 总价差(所有 30 分钟数据的最高价 - 最低价,单位:元)
|
||||
- 如果是上涨趋势,说明上涨了多少元
|
||||
- 如果是下跌趋势,说明下跌了多少元
|
||||
4. 关键信号:列出你观察到的 3-5 个关键信号(如价格突破、波动异常、趋势转变等)
|
||||
5. 风险评估:low/medium/high
|
||||
|
||||
**分析要求**:
|
||||
- 专注于总结已经发生的趋势,不要预测未来走势
|
||||
- 重点分析最近 10 分钟的变化,但理解前 20 分钟的背景有助于判断趋势
|
||||
- 如果检测到趋势反转(从上涨变为下跌或反之),必须在 signals 中明确标注
|
||||
- **剧烈波动判定标准**:只有当最近 10 分钟内的价格波动幅度(最高价 - 最低价)大于 0.2 时,才将 trend 设为 volatile
|
||||
- 计算方法:找出最近 10 分钟内的最高价格和最低价格,计算差值
|
||||
- 例如:最高 22.6,最低 22.3,波动幅度 = 0.3(> 0.2,可判定为 volatile)
|
||||
- 例如:最高 22.5,最低 22.4,波动幅度 = 0.1(< 0.2,应判定为 sideways 或其他趋势)
|
||||
- 如果波动幅度小于 0.2,即使价格有所波动,也应优先考虑 uptrend、downtrend 或 sideways,而非 volatile
|
||||
- 关注价格变化的幅度、速度和持续性
|
||||
|
||||
**风险评估标准(必须严格按照以下标准判断)**:
|
||||
|
||||
**high(高风险)**:满足以下**任意一个**条件即可判定为 high
|
||||
- 最近 10 分钟价格波动幅度 > 0.3 元
|
||||
- 出现急剧反转(单分钟价格变化 > 0.3 元)
|
||||
- trend = volatile 且置信度 > 0.8
|
||||
- 最近 10 分钟内有 3 次或更多次波动率 > 0.8%
|
||||
- 价格在创出新高/新低后立即出现大幅回调(幅度 > 0.25 元)
|
||||
|
||||
**medium(中等风险)**:满足以下**任意一个**条件即可判定为 medium
|
||||
- 最近 10 分钟价格波动幅度在 0.15-0.3 元之间
|
||||
- 出现趋势反转信号(从上涨转为下跌或反之)
|
||||
- 检测到明显的阻力位或支撑位测试(价格多次触及同一价位后回调)
|
||||
- 波动率在 0.4%-0.8% 之间,但未达到高风险标准
|
||||
- trend = volatile 但置信度 ≤ 0.8
|
||||
|
||||
**low(低风险)**:同时满足以下条件才可判定为 low
|
||||
- 最近 10 分钟价格波动幅度 < 0.15 元
|
||||
- 趋势明确(uptrend 或 downtrend)且持续,无明显反转
|
||||
- 波动率普遍 < 0.4%
|
||||
- 价格走势平稳,没有异常的急剧变化
|
||||
|
||||
**输出格式:直接输出以下 JSON 结构,不要包含任何其他内容**
|
||||
{
|
||||
"trend": "uptrend|downtrend|sideways|volatile",
|
||||
"confidence": 0.85,
|
||||
"summary": "...",
|
||||
"signals": ["...", "...", "..."],
|
||||
"risk": "low|medium|high"
|
||||
}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建分析提示词(包含历史告警上下文)
|
||||
* @param data 价格数据点
|
||||
* @param history 历史告警记录
|
||||
* @returns Prompt 文本
|
||||
*/
|
||||
private buildPromptWithHistory(data: PriceDataPoint[], history: TrendAnalysisRecord[]): string {
|
||||
// 将数据格式化为文本表格
|
||||
const dataText = this.formatDataPoints(data);
|
||||
// 格式化历史告警上下文
|
||||
const historyText = this.formatHistoryContext(history);
|
||||
|
||||
return `你是一个专业的金融分析师,擅长分析贵金属价格趋势。
|
||||
|
||||
**重要:你只需要输出 JSON 格式,不要包含任何其他文字、解释或推理过程。**
|
||||
|
||||
以下是白银最近 30 分钟的价格数据(每分钟一次):
|
||||
|
||||
${dataText}
|
||||
|
||||
${historyText}
|
||||
|
||||
请重点分析**最近 10 分钟**的价格趋势(同时参考前 20 分钟的走势作为背景),并提供:
|
||||
1. 趋势判断:uptrend(上涨趋势)/ downtrend(下跌趋势)/ sideways(平稳波动)/ volatile(剧烈波动)
|
||||
2. 置信度:0-1 之间的数值
|
||||
3. 趋势总结:用 1-2 句话描述最近 10 分钟的价格走势,**必须包含**:
|
||||
- 当前价格(单位:元)
|
||||
- 总价差(所有 30 分钟数据的最高价 - 最低价,单位:元)
|
||||
- 如果是上涨趋势,说明上涨了多少元
|
||||
- 如果是下跌趋势,说明下跌了多少元
|
||||
4. 关键信号:列出你观察到的 3-5 个关键信号(如价格突破、波动异常、趋势转变等)
|
||||
5. 风险评估:low/medium/high
|
||||
6. **通知决策**:判断是否应该发送通知(shouldNotify: true/false)
|
||||
7. **通知原因**:说明为什么应该或不应该发送通知(notifyReason)
|
||||
|
||||
**分析要求**:
|
||||
- 专注于总结已经发生的趋势,不要预测未来走势
|
||||
- 重点分析最近 10 分钟的变化,但理解前 20 分钟的背景有助于判断趋势
|
||||
- 如果检测到趋势反转(从上涨变为下跌或反之),必须在 signals 中明确标注
|
||||
- **剧烈波动判定标准**:只有当最近 10 分钟内的价格波动幅度(最高价 - 最低价)大于 0.2 时,才将 trend 设为 volatile
|
||||
- 计算方法:找出最近 10 分钟内的最高价格和最低价格,计算差值
|
||||
- 例如:最高 22.6,最低 22.3,波动幅度 = 0.3(> 0.2,可判定为 volatile)
|
||||
- 例如:最高 22.5,最低 22.4,波动幅度 = 0.1(< 0.2,应判定为 sideways 或其他趋势)
|
||||
- 如果波动幅度小于 0.2,即使价格有所波动,也应优先考虑 uptrend、downtrend 或 sideways,而非 volatile
|
||||
- 关注价格变化的幅度、速度和持续性
|
||||
|
||||
**风险评估标准(必须严格按照以下标准判断)**:
|
||||
|
||||
**high(高风险)**:满足以下**任意一个**条件即可判定为 high
|
||||
- 最近 10 分钟价格波动幅度 > 0.3 元
|
||||
- 出现急剧反转(单分钟价格变化 > 0.3 元)
|
||||
- trend = volatile 且置信度 > 0.8
|
||||
- 最近 10 分钟内有 3 次或更多次波动率 > 0.8%
|
||||
- 价格在创出新高/新低后立即出现大幅回调(幅度 > 0.25 元)
|
||||
|
||||
**medium(中等风险)**:满足以下**任意一个**条件即可判定为 medium
|
||||
- 最近 10 分钟价格波动幅度在 0.15-0.3 元之间
|
||||
- 出现趋势反转信号(从上涨转为下跌或反之)
|
||||
- 检测到明显的阻力位或支撑位测试(价格多次触及同一价位后回调)
|
||||
- 波动率在 0.4%-0.8% 之间,但未达到高风险标准
|
||||
- trend = volatile 但置信度 ≤ 0.8
|
||||
|
||||
**low(低风险)**:同时满足以下条件才可判定为 low
|
||||
- 最近 10 分钟价格波动幅度 < 0.15 元
|
||||
- 趋势明确(uptrend 或 downtrend)且持续,无明显反转
|
||||
- 波动率普遍 < 0.4%
|
||||
- 价格走势平稳,没有异常的急剧变化
|
||||
|
||||
**通知决策标准**:
|
||||
- 如果本次分析与最近的历史告警**高度相似**(趋势类型相同、总结内容大部分重复、信号列表高度重叠),则 shouldNotify 应为 false
|
||||
- 如果出现**新的重要变化**(趋势反转、新的风险信号、波动幅度显著变化),则 shouldNotify 应为 true
|
||||
- 如果没有历史告警记录,则 shouldNotify 应为 true
|
||||
- 相似度判断应综合考虑:趋势类型、总结内容、信号列表、风险评估
|
||||
|
||||
**输出格式:直接输出以下 JSON 结构,不要包含任何其他内容**
|
||||
{
|
||||
"trend": "uptrend|downtrend|sideways|volatile",
|
||||
"confidence": 0.85,
|
||||
"summary": "...",
|
||||
"signals": ["...", "...", "..."],
|
||||
"risk": "low|medium|high",
|
||||
"shouldNotify": true,
|
||||
"notifyReason": "..."
|
||||
}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化数据点为文本表格
|
||||
* @param data 价格数据点
|
||||
* @returns 格式化后的文本
|
||||
*/
|
||||
private formatDataPoints(data: PriceDataPoint[]): string {
|
||||
const header = '时间 价格 变化 波动率';
|
||||
const rows = data.map(point => {
|
||||
const time = new Date(point.timestamp).toLocaleString('zh-CN', {
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
const price = point.price.toFixed(3);
|
||||
const change = point.changeFromPrevious !== undefined
|
||||
? (point.changeFromPrevious > 0 ? '+' : '') + point.changeFromPrevious.toFixed(3)
|
||||
: 'N/A';
|
||||
const volatility = point.volatility !== undefined
|
||||
? (point.volatility * 100).toFixed(1) + '%'
|
||||
: 'N/A';
|
||||
return `${time} ${price} ${change} ${volatility}`;
|
||||
});
|
||||
|
||||
return [header, ...rows].join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化历史告警上下文为文本
|
||||
* @param history 历史告警记录
|
||||
* @returns 格式化后的文本
|
||||
*/
|
||||
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}
|
||||
|
||||
请比较本次分析与上述历史告警的相似度,判断是否需要再次发送通知。`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用 LLM API
|
||||
* @param prompt 提示词
|
||||
* @returns API 响应文本
|
||||
*/
|
||||
private async callAPI(prompt: string): Promise<string> {
|
||||
const maxRetries = this.config.maxRetries || 2;
|
||||
let lastError: Error | null = null;
|
||||
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
|
||||
|
||||
const response = await fetch(`${this.config.apiBase}/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${this.config.apiKey}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: this.config.model,
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: prompt
|
||||
}
|
||||
],
|
||||
temperature: 0.1,
|
||||
max_tokens: 20000
|
||||
}),
|
||||
signal: controller.signal
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`API 请求失败: ${response.status} ${response.statusText} - ${errorText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// 尝试多种可能的响应格式
|
||||
// 优先检查标准的 content 字段
|
||||
let content = result.choices?.[0]?.message?.content;
|
||||
|
||||
// 如果没有 content,检查 reasoning_content 字段(智谱AI推理模型)
|
||||
if (!content) {
|
||||
content = result.choices?.[0]?.message?.reasoning_content;
|
||||
|
||||
// 如果还没有,尝试其他可能的格式
|
||||
if (!content) {
|
||||
if (result.data?.choices?.[0]?.message?.content) {
|
||||
content = result.data.choices[0].message.content;
|
||||
} else if (result.data?.choices?.[0]?.message?.reasoning_content) {
|
||||
content = result.data.choices[0].message.reasoning_content;
|
||||
} else if (result.message?.content) {
|
||||
content = result.message.content;
|
||||
} else if (result.message?.reasoning_content) {
|
||||
content = result.message.reasoning_content;
|
||||
} else if (typeof result === 'string') {
|
||||
content = result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!content) {
|
||||
console.error('API 响应原始数据:', JSON.stringify(result, null, 2));
|
||||
throw new Error('API 响应格式错误:未找到 content 字段');
|
||||
}
|
||||
|
||||
return content;
|
||||
} catch (error) {
|
||||
lastError = error as Error;
|
||||
|
||||
// 如果是超时或非重试错误,直接抛出
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw new Error(`API 请求超时(${this.config.timeout}ms)`);
|
||||
}
|
||||
|
||||
// 最后一次尝试失败,抛出错误
|
||||
if (attempt === maxRetries) {
|
||||
throw new Error(`API 调用失败(已重试 ${maxRetries} 次): ${lastError.message}`);
|
||||
}
|
||||
|
||||
// 等待后重试
|
||||
await new Promise(resolve => setTimeout(resolve, 5000));
|
||||
}
|
||||
}
|
||||
|
||||
throw lastError || new Error('未知错误');
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 LLM 响应
|
||||
* @param response API 响应文本
|
||||
* @returns 解析后的趋势分析结果
|
||||
*/
|
||||
private parseResponse(response: string): TrendAnalysisResponse {
|
||||
// 向后兼容:调用新的解析方法,但使用默认值
|
||||
return this.parseResponseWithNotify(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 LLM 响应(包含通知决策)
|
||||
* @param response API 响应文本
|
||||
* @returns 解析后的趋势分析结果
|
||||
*/
|
||||
private parseResponseWithNotify(response: string): TrendAnalysisResponse {
|
||||
try {
|
||||
// 尝试提取 JSON(可能包含在 markdown 代码块中)
|
||||
let jsonStr = response.trim();
|
||||
|
||||
// 尝试查找 JSON 对象的模式(以 { 开头,以 } 结尾)
|
||||
const jsonMatch = response.match(/\{[\s\S]*\}/);
|
||||
if (jsonMatch) {
|
||||
jsonStr = jsonMatch[0];
|
||||
} else if (jsonStr.startsWith('```')) {
|
||||
// 移除可能的 markdown 代码块标记
|
||||
const lines = jsonStr.split('\n');
|
||||
// 移除第一行(```json 或 ```)和最后一行(```)
|
||||
if (lines.length > 2) {
|
||||
jsonStr = lines.slice(1, -1).join('\n').trim();
|
||||
} else {
|
||||
jsonStr = lines[lines.length - 1].trim();
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(jsonStr);
|
||||
|
||||
// 验证必需字段
|
||||
const requiredFields = ['trend', 'confidence', 'summary', 'signals', 'risk'];
|
||||
for (const field of requiredFields) {
|
||||
if (!(field in parsed)) {
|
||||
throw new Error(`响应缺少必需字段: ${field}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 验证趋势类型
|
||||
const validTrends = ['uptrend', 'downtrend', 'sideways', 'volatile'];
|
||||
if (!validTrends.includes(parsed.trend)) {
|
||||
throw new Error(`无效的 trend 值: ${parsed.trend}`);
|
||||
}
|
||||
|
||||
// 验证置信度范围
|
||||
if (typeof parsed.confidence !== 'number' || parsed.confidence < 0 || parsed.confidence > 1) {
|
||||
throw new Error(`无效的 confidence 值: ${parsed.confidence}`);
|
||||
}
|
||||
|
||||
// 验证风险评估
|
||||
const validRisks = ['low', 'medium', 'high'];
|
||||
if (!validRisks.includes(parsed.risk)) {
|
||||
throw new Error(`无效的 risk 值: ${parsed.risk}`);
|
||||
}
|
||||
|
||||
// 验证信号数组
|
||||
if (!Array.isArray(parsed.signals)) {
|
||||
throw new Error('signals 必须是数组');
|
||||
}
|
||||
|
||||
// 处理 shouldNotify 和 notifyReason 字段(可能不存在)
|
||||
let shouldNotify = true;
|
||||
let notifyReason = '未提供通知决策,默认发送通知';
|
||||
|
||||
if ('shouldNotify' in parsed && typeof parsed.shouldNotify === 'boolean') {
|
||||
shouldNotify = parsed.shouldNotify;
|
||||
if ('notifyReason' in parsed && typeof parsed.notifyReason === 'string') {
|
||||
notifyReason = parsed.notifyReason;
|
||||
} else {
|
||||
console.warn('LLM 响应缺少 notifyReason 字段,使用默认值');
|
||||
}
|
||||
} else {
|
||||
console.warn('LLM 响应缺少 shouldNotify 字段,使用默认值 true');
|
||||
}
|
||||
|
||||
return {
|
||||
trend: parsed.trend,
|
||||
confidence: parsed.confidence,
|
||||
summary: parsed.summary,
|
||||
signals: parsed.signals,
|
||||
risk: parsed.risk,
|
||||
shouldNotify,
|
||||
notifyReason
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof SyntaxError) {
|
||||
throw new Error(`JSON 解析失败: ${error.message}\n原始响应: ${response}`);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user