From 2d301370e262e8533085e586f4e8a43f0a40d7cc Mon Sep 17 00:00:00 2001 From: hugh <1012760428@qq.com> Date: Fri, 20 Feb 2026 11:22:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20Anthropic=20Messag?= =?UTF-8?q?es=20API=20=E6=A0=BC=E5=BC=8F=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 通过 LLM_PROVIDER 环境变量区分 openai 和 anthropic 两种调用方式, LLMClient 根据 provider 分发到不同的 API 调用路径。 Co-Authored-By: Claude Opus 4.6 --- .env.example | 9 ++ src/index.ts | 12 ++- src/types/index.ts | 7 ++ src/utils/llm-client.ts | 178 +++++++++++++++++++++++++--------------- test-anthropic-llm.ts | 100 ++++++++++++++++++++++ 5 files changed, 236 insertions(+), 70 deletions(-) create mode 100644 test-anthropic-llm.ts diff --git a/.env.example b/.env.example index 3b9ac31..aadfb6a 100644 --- a/.env.example +++ b/.env.example @@ -16,6 +16,10 @@ SILVER_BASELINE_THRESHOLD=0.2 GOLD_BASELINE_THRESHOLD=5 # LLM API 配置(用于趋势分析功能) +# LLM 提供商类型:openai(默认)或 anthropic +# LLM_PROVIDER=openai + +# === OpenAI 兼容 API 配置 === # LLM API 基础 URL(可选,默认 OpenAI API) # LLM_API_BASE=https://api.openai.com/v1 # LLM API 密钥(必需,如果未配置则跳过趋势分析功能) @@ -23,5 +27,10 @@ GOLD_BASELINE_THRESHOLD=5 # LLM 模型(可选,默认 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 分钟) # TREND_ANALYSIS_INTERVAL=300000 diff --git a/src/index.ts b/src/index.ts index bd3e605..1f62fbf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -58,10 +58,18 @@ class App { // 配置 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 = { - 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, - model: process.env.LLM_MODEL || 'gpt-4o-mini', + model: process.env.LLM_MODEL || defaultModel, timeout: 120000 }; const llmClient = new LLMClient(llmConfig); diff --git a/src/types/index.ts b/src/types/index.ts index 36f0191..8516b49 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -184,10 +184,17 @@ export interface TrendAnalysisDatabase { analyses: TrendAnalysisRecord[]; } +/** + * LLM 提供商类型 + */ +export type LLMProvider = 'openai' | 'anthropic'; + /** * LLM 配置 */ export interface LLMConfig { + /** API 提供商类型,默认 openai */ + provider?: LLMProvider; /** API 基础 URL */ apiBase: string; /** API 密钥 */ diff --git a/src/utils/llm-client.ts b/src/utils/llm-client.ts index fff0f97..4c3ce44 100644 --- a/src/utils/llm-client.ts +++ b/src/utils/llm-client.ts @@ -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 客户端 - * 用于调用 OpenAI 兼容的 API 进行趋势分析 + * 支持 OpenAI 兼容 API 和 Anthropic Messages API */ export class LLMClient { private config: LLMConfig; + private provider: LLMProvider; constructor(config: LLMConfig) { this.config = { - timeout: 120000, // 增加到 120 秒以适应智谱AI的推理时间 + timeout: 120000, maxRetries: 2, ...config }; + this.provider = config.provider || 'openai'; } /** @@ -253,7 +255,7 @@ ${historyLines} } /** - * 调用 LLM API + * 调用 LLM API(根据 provider 分发) * @param prompt 提示词 * @returns API 响应文本 */ @@ -263,82 +265,21 @@ ${historyLines} 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 字段'); - } - + 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)); } } @@ -346,6 +287,107 @@ ${historyLines} throw lastError || new Error('未知错误'); } + /** + * 调用 OpenAI 兼容 API + */ + private async callOpenAIAPI(prompt: string): Promise { + 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(); + + let content = result.choices?.[0]?.message?.content; + + 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; + } + + /** + * 调用 Anthropic Messages API + */ + private async callAnthropicAPI(prompt: string): Promise { + 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(); + + // 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 内容'); + } + + return textBlock.text; + } + /** * 解析 LLM 响应 * @param response API 响应文本 diff --git a/test-anthropic-llm.ts b/test-anthropic-llm.ts new file mode 100644 index 0000000..5c178d3 --- /dev/null +++ b/test-anthropic-llm.ts @@ -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();