|
| 1 | +//! LLM 集成模块 |
| 2 | +//! |
| 3 | +//! 支持 DeepSeek 等大语言模型 API |
| 4 | +
|
| 5 | +use reqwest::Client; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use std::sync::Arc; |
| 8 | +use std::time::Duration; |
| 9 | +use tokio::sync::RwLock; |
| 10 | +use std::collections::HashMap; |
| 11 | +use tracing::{error, info}; |
| 12 | + |
| 13 | +use crate::config::LlmConfig; |
| 14 | + |
| 15 | +/// LLM 客户端 |
| 16 | +pub struct LlmClient { |
| 17 | + config: LlmConfig, |
| 18 | + http: Client, |
| 19 | + /// 用户对话历史缓存 (openid -> messages) |
| 20 | + conversations: Arc<RwLock<HashMap<String, Vec<ChatMessage>>>>, |
| 21 | +} |
| 22 | + |
| 23 | +#[derive(Debug, Clone, Serialize, Deserialize)] |
| 24 | +pub struct ChatMessage { |
| 25 | + pub role: String, // "system", "user", "assistant" |
| 26 | + pub content: String, |
| 27 | +} |
| 28 | + |
| 29 | +#[derive(Debug, Serialize)] |
| 30 | +struct ChatRequest { |
| 31 | + model: String, |
| 32 | + messages: Vec<ChatMessage>, |
| 33 | + max_tokens: Option<u32>, |
| 34 | + temperature: Option<f32>, |
| 35 | + stream: bool, |
| 36 | +} |
| 37 | + |
| 38 | +#[derive(Debug, Deserialize)] |
| 39 | +struct ChatResponse { |
| 40 | + choices: Vec<Choice>, |
| 41 | +} |
| 42 | + |
| 43 | +#[derive(Debug, Deserialize)] |
| 44 | +struct Choice { |
| 45 | + message: ChatMessage, |
| 46 | +} |
| 47 | + |
| 48 | +#[derive(Debug, Deserialize)] |
| 49 | +struct ErrorResponse { |
| 50 | + error: ApiError, |
| 51 | +} |
| 52 | + |
| 53 | +#[derive(Debug, Deserialize)] |
| 54 | +struct ApiError { |
| 55 | + message: String, |
| 56 | +} |
| 57 | + |
| 58 | +impl LlmClient { |
| 59 | + pub fn new(config: LlmConfig) -> Self { |
| 60 | + let timeout = config.timeout_secs.unwrap_or(30); |
| 61 | + let http = Client::builder() |
| 62 | + .timeout(Duration::from_secs(timeout)) |
| 63 | + .build() |
| 64 | + .expect("Failed to create HTTP client"); |
| 65 | + |
| 66 | + Self { |
| 67 | + config, |
| 68 | + http, |
| 69 | + conversations: Arc::new(RwLock::new(HashMap::new())), |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + /// 与 LLM 聊天 |
| 74 | + /// |
| 75 | + /// `user_id`: 用户标识(微信 openid),用于维护对话上下文 |
| 76 | + /// `message`: 用户消息 |
| 77 | + pub async fn chat(&self, user_id: &str, message: &str) -> Result<String, String> { |
| 78 | + // 获取或创建对话历史 |
| 79 | + let mut conversations = self.conversations.write().await; |
| 80 | + let history = conversations.entry(user_id.to_string()).or_insert_with(|| { |
| 81 | + vec![ChatMessage { |
| 82 | + role: "system".to_string(), |
| 83 | + content: "你是一个友好的助手,用简洁的中文回复用户问题。回复尽量控制在100字以内。".to_string(), |
| 84 | + }] |
| 85 | + }); |
| 86 | + |
| 87 | + // 添加用户消息 |
| 88 | + history.push(ChatMessage { |
| 89 | + role: "user".to_string(), |
| 90 | + content: message.to_string(), |
| 91 | + }); |
| 92 | + |
| 93 | + // 限制历史长度(保留最近10轮对话) |
| 94 | + if history.len() > 21 { // 1 system + 20 user/assistant |
| 95 | + let system_msg = history[0].clone(); |
| 96 | + let recent: Vec<_> = history.iter().skip(history.len() - 20).cloned().collect(); |
| 97 | + history.clear(); |
| 98 | + history.push(system_msg); |
| 99 | + history.extend(recent); |
| 100 | + } |
| 101 | + |
| 102 | + // 构建请求 |
| 103 | + let base_url = self.config.base_url.as_deref() |
| 104 | + .unwrap_or("https://api.deepseek.com"); |
| 105 | + let model = self.config.model.as_deref() |
| 106 | + .unwrap_or("deepseek-chat"); |
| 107 | + |
| 108 | + let request = ChatRequest { |
| 109 | + model: model.to_string(), |
| 110 | + messages: history.clone(), |
| 111 | + max_tokens: self.config.max_tokens.or(Some(500)), |
| 112 | + temperature: Some(0.7), |
| 113 | + stream: false, |
| 114 | + }; |
| 115 | + |
| 116 | + info!("Calling LLM API for user {}", user_id); |
| 117 | + |
| 118 | + // 发送请求 |
| 119 | + let response = self.http |
| 120 | + .post(format!("{}/v1/chat/completions", base_url)) |
| 121 | + .header("Authorization", format!("Bearer {}", self.config.api_key)) |
| 122 | + .header("Content-Type", "application/json") |
| 123 | + .json(&request) |
| 124 | + .send() |
| 125 | + .await |
| 126 | + .map_err(|e| { |
| 127 | + error!("LLM API request failed: {}", e); |
| 128 | + format!("请求失败: {}", e) |
| 129 | + })?; |
| 130 | + |
| 131 | + let status = response.status(); |
| 132 | + let body = response.text().await.map_err(|e| format!("读取响应失败: {}", e))?; |
| 133 | + |
| 134 | + if !status.is_success() { |
| 135 | + error!("LLM API error: {} - {}", status, body); |
| 136 | + // 尝试解析错误信息 |
| 137 | + if let Ok(err) = serde_json::from_str::<ErrorResponse>(&body) { |
| 138 | + return Err(format!("API错误: {}", err.error.message)); |
| 139 | + } |
| 140 | + return Err(format!("API错误: {}", status)); |
| 141 | + } |
| 142 | + |
| 143 | + // 解析响应 |
| 144 | + let chat_response: ChatResponse = serde_json::from_str(&body) |
| 145 | + .map_err(|e| { |
| 146 | + error!("Failed to parse LLM response: {} - {}", e, body); |
| 147 | + format!("解析响应失败: {}", e) |
| 148 | + })?; |
| 149 | + |
| 150 | + let assistant_message = chat_response.choices |
| 151 | + .first() |
| 152 | + .map(|c| c.message.content.clone()) |
| 153 | + .unwrap_or_else(|| "抱歉,我没有生成回复。".to_string()); |
| 154 | + |
| 155 | + // 保存助手回复到历史 |
| 156 | + history.push(ChatMessage { |
| 157 | + role: "assistant".to_string(), |
| 158 | + content: assistant_message.clone(), |
| 159 | + }); |
| 160 | + |
| 161 | + info!("LLM response for user {}: {} chars", user_id, assistant_message.len()); |
| 162 | + |
| 163 | + Ok(assistant_message) |
| 164 | + } |
| 165 | + |
| 166 | + /// 清除用户对话历史 |
| 167 | + pub async fn clear_history(&self, user_id: &str) { |
| 168 | + let mut conversations = self.conversations.write().await; |
| 169 | + conversations.remove(user_id); |
| 170 | + info!("Cleared conversation history for user {}", user_id); |
| 171 | + } |
| 172 | +} |
0 commit comments