feat: 支持 Anthropic Messages API 格式调用

通过 LLM_PROVIDER 环境变量区分 openai 和 anthropic 两种调用方式,
LLMClient 根据 provider 分发到不同的 API 调用路径。

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Opus 4.6 committed 2026-02-20 11:22:08 +08:00
1 parent e76a85db97
commit 2d301370e2
5 files changed
+195 -29

No files matched your search

+9
View File
@@ -16,6 +16,10 @@ SILVER_BASELINE_THRESHOLD=0.2
GOLD_BASELINE_THRESHOLD=5 GOLD_BASELINE_THRESHOLD=5
# LLM API 配置(用于趋势分析功能) # LLM API 配置(用于趋势分析功能)
# LLM 提供商类型:openai(默认)或 anthropic
# LLM_PROVIDER=openai
# === OpenAI 兼容 API 配置 ===
# LLM API 基础 URL(可选,默认 OpenAI API) # LLM API 基础 URL(可选,默认 OpenAI API)
# LLM_API_BASE=https://api.openai.com/v1 # LLM_API_BASE=https://api.openai.com/v1
# LLM API 密钥(必需,如果未配置则跳过趋势分析功能) # LLM API 密钥(必需,如果未配置则跳过趋势分析功能)
@@ -23,5 +27,10 @@ GOLD_BASELINE_THRESHOLD=5
# LLM 模型(可选,默认 gpt-4o-mini) # LLM 模型(可选,默认 gpt-4o-mini)
# LLM_MODEL=gpt-4o-mini # LLM_MODEL=gpt-4o-mini
# === Anthropic API 配置(用于测试脚本 test-anthropic-llm.ts) ===
# ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxxxxxxxxxx
# ANTHROPIC_MODEL=claude-sonnet-4-20250514
# ANTHROPIC_API_BASE=https://api.anthropic.com
# 趋势分析间隔(毫秒),默认 300000(5 分钟) # 趋势分析间隔(毫秒),默认 300000(5 分钟)
# TREND_ANALYSIS_INTERVAL=300000 # TREND_ANALYSIS_INTERVAL=300000
+10 -2
View File
@@ -58,10 +58,18 @@ class App {
// 配置 LLM 趋势总结服务(如果配置了 API Key) // 配置 LLM 趋势总结服务(如果配置了 API Key)
if (process.env.LLM_API_KEY) { if (process.env.LLM_API_KEY) {
const provider = (process.env.LLM_PROVIDER as 'openai' | 'anthropic') || 'openai';
const defaultBase = provider === 'anthropic'
? 'https://api.anthropic.com'
: 'https://api.openai.com/v1';
const defaultModel = provider === 'anthropic'
? 'claude-sonnet-4-20250514'
: 'gpt-4o-mini';
const llmConfig = { const llmConfig = {
apiBase: process.env.LLM_API_BASE || 'https://api.openai.com/v1', provider,
apiBase: process.env.LLM_API_BASE || defaultBase,
apiKey: process.env.LLM_API_KEY, apiKey: process.env.LLM_API_KEY,
model: process.env.LLM_MODEL || 'gpt-4o-mini', model: process.env.LLM_MODEL || defaultModel,
timeout: 120000 timeout: 120000
}; };
const llmClient = new LLMClient(llmConfig); const llmClient = new LLMClient(llmConfig);
+7
View File
@@ -184,10 +184,17 @@ export interface TrendAnalysisDatabase {
analyses: TrendAnalysisRecord[]; analyses: TrendAnalysisRecord[];
} }
/**
* LLM 提供商类型
*/
export type LLMProvider = 'openai' | 'anthropic';
/** /**
* LLM 配置 * LLM 配置
*/ */
export interface LLMConfig { export interface LLMConfig {
/** API 提供商类型,默认 openai */
provider?: LLMProvider;
/** API 基础 URL */ /** API 基础 URL */
apiBase: string; apiBase: string;
/** API 密钥 */ /** API 密钥 */
+69 -27
View File
@@ -1,18 +1,20 @@
import type { LLMConfig, TrendAnalysisResponse, PriceDataPoint, TrendAnalysisRecord } from '../types/index.js'; import type { LLMConfig, LLMProvider, TrendAnalysisResponse, PriceDataPoint, TrendAnalysisRecord } from '../types/index.js';
/** /**
* LLM API 客户端 * LLM API 客户端
* 用于调用 OpenAI 兼容的 API 进行趋势分析 * 支持 OpenAI 兼容 API 和 Anthropic Messages API
*/ */
export class LLMClient { export class LLMClient {
private config: LLMConfig; private config: LLMConfig;
private provider: LLMProvider;
constructor(config: LLMConfig) { constructor(config: LLMConfig) {
this.config = { this.config = {
timeout: 120000, // 增加到 120 秒以适应智谱AI的推理时间 timeout: 120000,
maxRetries: 2, maxRetries: 2,
...config ...config
}; };
this.provider = config.provider || 'openai';
} }
/** /**
@@ -253,7 +255,7 @@ ${historyLines}
} }
/** /**
* 调用 LLM API * 调用 LLM API(根据 provider 分发)
* @param prompt 提示词 * @param prompt 提示词
* @returns API 响应文本 * @returns API 响应文本
*/ */
@@ -263,6 +265,32 @@ ${historyLines}
for (let attempt = 0; attempt <= maxRetries; attempt++) { for (let attempt = 0; attempt <= maxRetries; attempt++) {
try { try {
const content = this.provider === 'anthropic'
? await this.callAnthropicAPI(prompt)
: await this.callOpenAIAPI(prompt);
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('未知错误');
}
/**
* 调用 OpenAI 兼容 API
*/
private async callOpenAIAPI(prompt: string): Promise<string> {
const controller = new AbortController(); const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout); const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
@@ -274,12 +302,7 @@ ${historyLines}
}, },
body: JSON.stringify({ body: JSON.stringify({
model: this.config.model, model: this.config.model,
messages: [ messages: [{ role: 'user', content: prompt }],
{
role: 'user',
content: prompt
}
],
temperature: 0.1, temperature: 0.1,
max_tokens: 20000 max_tokens: 20000
}), }),
@@ -295,15 +318,11 @@ ${historyLines}
const result = await response.json(); const result = await response.json();
// 尝试多种可能的响应格式
// 优先检查标准的 content 字段
let content = result.choices?.[0]?.message?.content; let content = result.choices?.[0]?.message?.content;
// 如果没有 content,检查 reasoning_content 字段(智谱AI推理模型)
if (!content) { if (!content) {
content = result.choices?.[0]?.message?.reasoning_content; content = result.choices?.[0]?.message?.reasoning_content;
// 如果还没有,尝试其他可能的格式
if (!content) { if (!content) {
if (result.data?.choices?.[0]?.message?.content) { if (result.data?.choices?.[0]?.message?.content) {
content = result.data.choices[0].message.content; content = result.data.choices[0].message.content;
@@ -325,25 +344,48 @@ ${historyLines}
} }
return 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) { * 调用 Anthropic Messages API
throw new Error(`API 调用失败(已重试 ${maxRetries} 次): ${lastError.message}`); */
private async callAnthropicAPI(prompt: string): Promise<string> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
const response = await fetch(`${this.config.apiBase}/v1/messages`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': this.config.apiKey,
'anthropic-version': '2023-06-01'
},
body: JSON.stringify({
model: this.config.model,
max_tokens: 4096,
messages: [{ role: 'user', content: prompt }],
temperature: 0.1
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Anthropic API 请求失败: ${response.status} ${response.statusText} - ${errorText}`);
} }
// 等待后重试 const result = await response.json();
await new Promise(resolve => setTimeout(resolve, 5000));
} // Anthropic 响应格式: { content: [{ type: "text", text: "..." }] }
const textBlock = result.content?.find((block: { type: string }) => block.type === 'text');
if (!textBlock?.text) {
console.error('Anthropic API 响应原始数据:', JSON.stringify(result, null, 2));
throw new Error('Anthropic API 响应格式错误:未找到 text 内容');
} }
throw lastError || new Error('未知错误'); return textBlock.text;
} }
/** /**
+100
View File
@@ -0,0 +1,100 @@
import 'dotenv/config';
import { LLMClient } from './src/utils/llm-client.js';
import type { PriceDataPoint } from './src/types/index.js';
/**
* 测试 Anthropic API 调用
*/
async function testAnthropicLLM() {
console.log('========================================');
console.log('Anthropic LLM 趋势分析测试');
console.log('========================================\n');
// 检查环境变量
const apiKey = process.env.ANTHROPIC_API_KEY;
if (!apiKey) {
console.error('错误:未配置 ANTHROPIC_API_KEY 环境变量');
console.log('请在 .env 文件中设置:');
console.log(' ANTHROPIC_API_KEY=sk-ant-xxxxxxxxxxxx');
console.log(' ANTHROPIC_MODEL=claude-sonnet-4-20250514 (可选)');
console.log(' ANTHROPIC_API_BASE=https://api.anthropic.com (可选)');
process.exit(1);
}
const config = {
provider: 'anthropic' as const,
apiBase: process.env.ANTHROPIC_API_BASE || 'https://api.anthropic.com',
apiKey,
model: process.env.ANTHROPIC_MODEL || 'claude-sonnet-4-20250514',
timeout: 60000,
maxRetries: 1
};
console.log('配置信息:');
console.log(` Provider: ${config.provider}`);
console.log(` API Base: ${config.apiBase}`);
console.log(` Model: ${config.model}`);
console.log(` Timeout: ${config.timeout}ms\n`);
const llmClient = new LLMClient(config);
// 准备测试数据(模拟 30 分钟价格数据)
const testData: PriceDataPoint[] = [];
const now = Date.now();
const basePrice = 22.0;
for (let i = 30; i >= 0; i--) {
const timestamp = new Date(now - i * 60000).toISOString();
const price = basePrice + (Math.random() * 0.5 - 0.1) + (30 - i) * 0.01;
const changeFromPrevious = i < 30
? price - (basePrice + (Math.random() * 0.5 - 0.1) + (29 - i) * 0.01)
: undefined;
testData.push({
price: parseFloat(price.toFixed(3)),
timestamp,
changeFromPrevious: changeFromPrevious ? parseFloat(changeFromPrevious.toFixed(3)) : undefined,
volatility: Math.random() * 0.01
});
}
console.log(`准备了 ${testData.length} 个测试数据点`);
console.log('最后 5 个数据点:');
testData.slice(-5).forEach(point => {
console.log(` ${new Date(point.timestamp).toLocaleTimeString('zh-CN')} - ${point.price.toFixed(3)}`);
});
console.log();
try {
console.log('开始 Anthropic LLM 分析...\n');
const startTime = Date.now();
const result = await llmClient.analyzeTrend(testData);
const elapsed = Date.now() - startTime;
console.log('========================================');
console.log(`分析结果(耗时 ${elapsed}ms)`);
console.log('========================================');
console.log(`趋势类型: ${result.trend}`);
console.log(`置信度: ${(result.confidence * 100).toFixed(0)}%`);
console.log(`风险评估: ${result.risk}`);
console.log(`\n趋势总结:`);
console.log(` ${result.summary}`);
console.log(`\n关键信号:`);
result.signals.forEach((signal, index) => {
console.log(` ${index + 1}. ${signal}`);
});
console.log('========================================\n');
console.log('完整 JSON 结果:');
console.log(JSON.stringify(result, null, 2));
console.log();
console.log('测试成功!Anthropic API 调用正常。');
} catch (error) {
console.error('\n测试失败:');
console.error(error);
process.exit(1);
}
}
testAnthropicLLM();