364 lines
11 KiB
Markdown
364 lines
11 KiB
Markdown
我将为你提供一份完整的、基于Python 3.14.2和DeepSeek-V3.2的实验性版本,将AI能力接入微信个人账号的部署方案文档。
|
||
|
||
## 🚀 项目概述
|
||
本方案使用`chatgpt-on-wechat`开源框架,通过模拟微信网页版登录,让你的个人微信号成为DeepSeek-V3.2智能助手。
|
||
|
||
> **⚠️ 版本兼容性说明**:你提到的Python 3.14.2可能是一个超前版本。目前主流稳定版本是3.8-3.12。本方案已适配3.10+,建议你确认版本或使用虚拟环境。若遇到兼容性问题,可考虑使用Docker方案。
|
||
|
||
---
|
||
|
||
## 📋 一、环境准备与配置
|
||
|
||
### 1.1 获取必要的密钥
|
||
1. **DeepSeek API Key**
|
||
- 访问 [DeepSeek平台](https://platform.deepseek.com/)
|
||
- 注册登录后,在「API Keys」页面创建新密钥并妥善保存
|
||
|
||
2. **微信账号**
|
||
- **强烈建议使用微信小号**,避免主号因违反微信协议被封
|
||
|
||
### 1.2 服务器准备(二选一)
|
||
- **方案A:本地电脑/开发机**(适合测试)
|
||
- **方案B:云服务器**(推荐长期使用)
|
||
- 配置:1核2GB内存,Ubuntu 20.04+/CentOS 7+
|
||
- 确保服务器可访问外网(用于连接微信和DeepSeek API)
|
||
|
||
---
|
||
|
||
## 🛠️ 二、核心部署方案
|
||
|
||
### 2.1 基础Python环境搭建
|
||
```bash
|
||
# 1. 克隆项目(使用支持DeepSeek的分支)
|
||
git clone https://github.com/zhayujie/chatgpt-on-wechat.git
|
||
cd chatgpt-on-wechat
|
||
|
||
# 2. 创建并激活虚拟环境(如使用Python 3.10)
|
||
python3.10 -m venv venv
|
||
source venv/bin/activate # Linux/Mac
|
||
# 或 venv\Scripts\activate # Windows
|
||
|
||
# 3. 安装依赖(项目要求Python 3.7-3.11,若你是3.14.2可尝试)
|
||
pip install -r requirements.txt
|
||
# 如有兼容问题,尝试:
|
||
# pip install --upgrade pip
|
||
# pip install wechaty==0.9.23 wechaty-puppet-service==0.9.14 openai==1.12.0
|
||
```
|
||
|
||
### 2.2 配置文件设置
|
||
在项目根目录创建/修改 `config.json`:
|
||
|
||
```json
|
||
{
|
||
"model": "deepseek-chat",
|
||
"open_ai_api_key": "你的DeepSeek_API_Key",
|
||
"open_ai_api_base": "https://api.deepseek.com",
|
||
"proxy": "",
|
||
"single_chat_prefix": ["", "@bot"],
|
||
"single_chat_reply_prefix": "[AI] ",
|
||
"group_chat_prefix": ["@bot"],
|
||
"group_name_white_list": ["测试群", "ALL_GROUP"],
|
||
"image_create_prefix": ["画", "看", "找"],
|
||
"speech_recognition": false,
|
||
"character_desc": "你是DeepSeek助手,由微信用户部署的个人AI助手。",
|
||
"conversation_max_tokens": 4000,
|
||
"expires_in_seconds": 3600,
|
||
"rate_limit_chatgpt": 20,
|
||
"rate_limit_dalle": 50,
|
||
"hot_reload": false,
|
||
|
||
// DeepSeek-V3.2 实验版特定配置
|
||
"model_version": "deepseek-chat",
|
||
"temperature": 0.7,
|
||
"max_tokens": 2000,
|
||
"enable_stream": true
|
||
}
|
||
```
|
||
|
||
**关键配置说明**:
|
||
- `single_chat_prefix`: 私聊触发前缀,`[""]`表示回复所有消息,`["@bot"]`表示只有@bot才回复
|
||
- `group_name_white_list`: 可响应的群聊,`["ALL_GROUP"]`表示所有群
|
||
- `model_version`: 确保使用DeepSeek最新模型
|
||
|
||
### 2.3 创建DeepSeek适配器
|
||
由于原项目主要支持OpenAI格式,需创建DeepSeek专用适配文件 `deepseek_adapter.py`:
|
||
|
||
```python
|
||
import json
|
||
import time
|
||
from typing import Dict, Any, List
|
||
import requests
|
||
from config import conf
|
||
|
||
class DeepSeekAdapter:
|
||
"""DeepSeek-V3.2 API适配器"""
|
||
|
||
def __init__(self):
|
||
self.api_key = conf().get("open_ai_api_key")
|
||
self.api_base = conf().get("open_ai_api_base", "https://api.deepseek.com")
|
||
self.model = conf().get("model_version", "deepseek-chat")
|
||
self.max_tokens = conf().get("max_tokens", 2000)
|
||
self.temperature = conf().get("temperature", 0.7)
|
||
|
||
def create_completion(self, messages: List[Dict], stream: bool = True) -> str:
|
||
"""调用DeepSeek-V3.2 API"""
|
||
headers = {
|
||
"Authorization": f"Bearer {self.api_key}",
|
||
"Content-Type": "application/json"
|
||
}
|
||
|
||
payload = {
|
||
"model": self.model,
|
||
"messages": messages,
|
||
"temperature": self.temperature,
|
||
"max_tokens": self.max_tokens,
|
||
"stream": stream
|
||
}
|
||
|
||
try:
|
||
if stream:
|
||
return self._handle_stream_response(headers, payload)
|
||
else:
|
||
return self._handle_normal_response(headers, payload)
|
||
except Exception as e:
|
||
return f"请求DeepSeek API时出错: {str(e)}"
|
||
|
||
def _handle_normal_response(self, headers: Dict, payload: Dict) -> str:
|
||
"""处理非流式响应"""
|
||
response = requests.post(
|
||
f"{self.api_base}/chat/completions",
|
||
headers=headers,
|
||
json=payload,
|
||
timeout=60
|
||
)
|
||
response.raise_for_status()
|
||
result = response.json()
|
||
return result["choices"][0]["message"]["content"]
|
||
|
||
def _handle_stream_response(self, headers: Dict, payload: Dict) -> str:
|
||
"""处理流式响应(推荐,体验更好)"""
|
||
full_response = []
|
||
response = requests.post(
|
||
f"{self.api_base}/chat/completions",
|
||
headers=headers,
|
||
json=payload,
|
||
stream=True,
|
||
timeout=60
|
||
)
|
||
|
||
for line in response.iter_lines():
|
||
if line:
|
||
line_text = line.decode('utf-8')
|
||
if line_text.startswith('data: '):
|
||
data = line_text[6:]
|
||
if data == '[DONE]':
|
||
break
|
||
try:
|
||
json_data = json.loads(data)
|
||
if 'choices' in json_data and json_data['choices']:
|
||
delta = json_data['choices'][0].get('delta', {})
|
||
if 'content' in delta:
|
||
content = delta['content']
|
||
full_response.append(content)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
|
||
return ''.join(full_response)
|
||
```
|
||
|
||
### 2.4 修改项目主逻辑
|
||
修改 `bot/chatgpt_bot.py` 中的回复函数,使用DeepSeek适配器:
|
||
|
||
```python
|
||
# 在文件顶部添加
|
||
from deepseek_adapter import DeepSeekAdapter
|
||
|
||
# 在合适的位置初始化适配器
|
||
deepseek_adapter = DeepSeekAdapter()
|
||
|
||
# 修改回复函数
|
||
def reply_text(self, query: str, context: dict) -> str:
|
||
"""使用DeepSeek-V3.2回复"""
|
||
session_id = context.get('session_id')
|
||
|
||
# 构建对话消息
|
||
messages = self._build_messages(query, session_id)
|
||
|
||
# 调用DeepSeek
|
||
response = deepseek_adapter.create_completion(messages)
|
||
|
||
# 保存上下文
|
||
self._save_context(query, response, session_id)
|
||
|
||
return response
|
||
```
|
||
|
||
---
|
||
|
||
## 🐳 三、Docker部署方案(推荐)
|
||
如果Python版本兼容有问题,使用Docker是最稳妥的方式:
|
||
|
||
### 3.1 创建Docker配置
|
||
创建 `docker-compose.yml`:
|
||
|
||
```yaml
|
||
version: '3.8'
|
||
|
||
services:
|
||
wechat-bot:
|
||
build: .
|
||
container_name: deepseek-wechat-bot
|
||
restart: unless-stopped
|
||
environment:
|
||
- OPEN_AI_API_KEY=${DEEPSEEK_API_KEY}
|
||
- MODEL=deepseek-chat
|
||
- OPEN_AI_API_BASE=https://api.deepseek.com
|
||
- SINGLE_CHAT_PREFIX=["", "@bot"]
|
||
- GROUP_CHAT_PREFIX=["@bot"]
|
||
volumes:
|
||
- ./data:/app/data
|
||
- ./config.json:/app/config.json
|
||
network_mode: host # 微信登录需要
|
||
```
|
||
|
||
创建 `Dockerfile`:
|
||
|
||
```dockerfile
|
||
FROM python:3.10-slim
|
||
|
||
WORKDIR /app
|
||
|
||
# 安装系统依赖
|
||
RUN apt-get update && apt-get install -y \
|
||
gcc \
|
||
g++ \
|
||
&& rm -rf /var/lib/apt/lists/*
|
||
|
||
# 复制项目文件
|
||
COPY requirements.txt .
|
||
RUN pip install --no-cache-dir -r requirements.txt
|
||
|
||
# 复制代码
|
||
COPY . .
|
||
|
||
# 创建数据目录
|
||
RUN mkdir -p /app/data
|
||
|
||
CMD ["python3", "app.py"]
|
||
```
|
||
|
||
### 3.2 构建并运行
|
||
```bash
|
||
# 1. 设置环境变量(在终端执行,不要提交到代码)
|
||
export DEEPSEEK_API_KEY="你的实际API密钥"
|
||
|
||
# 2. 构建Docker镜像
|
||
docker-compose build
|
||
|
||
# 3. 启动服务
|
||
docker-compose up -d
|
||
|
||
# 4. 查看日志和二维码
|
||
docker-compose logs -f
|
||
```
|
||
|
||
---
|
||
|
||
## 🔧 四、运行与测试
|
||
|
||
### 4.1 启动机器人
|
||
```bash
|
||
# 直接运行(确保在虚拟环境中)
|
||
python app.py
|
||
|
||
# 或使用Docker
|
||
docker-compose up -d
|
||
```
|
||
|
||
### 4.2 登录微信
|
||
1. 程序启动后,控制台会显示**微信登录二维码**
|
||
2. 使用你的**微信小号**扫码登录
|
||
3. 登录成功后,控制台会显示"Login successfully"
|
||
|
||
### 4.3 功能测试
|
||
1. **私聊测试**:向机器人微信号发送消息,观察回复
|
||
2. **群聊测试**:在配置的群中@机器人发送消息
|
||
3. **命令测试**:
|
||
- `#清除上下文` - 清除对话历史
|
||
- `#帮助` - 查看帮助信息
|
||
|
||
### 4.4 监控与日志
|
||
- 查看实时日志:`docker-compose logs -f`
|
||
- 对话记录保存在 `data/conversations/` 目录
|
||
- API调用统计可在DeepSeek平台仪表板查看
|
||
|
||
---
|
||
|
||
## ⚠️ 五、重要注意事项
|
||
|
||
### 5.1 安全与风险控制
|
||
1. **账号安全**
|
||
- 必须使用微信小号,避免主号被封
|
||
- 不要频繁发送相同消息
|
||
- 避免加入过多群聊(建议<10个)
|
||
|
||
2. **API密钥保护**
|
||
```bash
|
||
# 永远不要将API密钥提交到Git
|
||
echo "config.json" >> .gitignore
|
||
echo "data/" >> .gitignore
|
||
```
|
||
|
||
3. **成本控制**
|
||
- 在DeepSeek平台设置每月预算提醒
|
||
- 监控Token使用情况
|
||
- 利用V3.2的缓存机制优化问题设计
|
||
|
||
### 5.2 性能优化建议
|
||
1. **上下文管理**:对话窗口不要过大(建议<4000 Tokens)
|
||
2. **响应超时**:设置合理的超时时间(30-60秒)
|
||
3. **错误重试**:实现API调用失败时的指数退避重试
|
||
4. **消息队列**:高频使用时添加消息队列缓冲
|
||
|
||
### 5.3 故障排查
|
||
| 问题 | 可能原因 | 解决方案 |
|
||
|------|----------|----------|
|
||
| 扫码后无法登录 | 微信风控 | 更换网络环境,等待24小时重试 |
|
||
| 收不到回复 | API密钥错误 | 检查密钥和API地址配置 |
|
||
| 回复速度慢 | 网络延迟 | 检查服务器到api.deepseek.com的网络 |
|
||
| 频繁断连 | 微信网页版限制 | 减少操作频率,保持在线 |
|
||
|
||
---
|
||
|
||
## 📈 六、后续优化方向
|
||
|
||
### 6.1 功能增强
|
||
1. **多模态支持**:集成DeepSeek-V3的视觉理解能力
|
||
2. **文件处理**:添加PDF、Word文档解析功能
|
||
3. **长期记忆**:实现向量数据库存储重要信息
|
||
4. **插件系统**:支持天气查询、日历管理等插件
|
||
|
||
### 6.2 性能提升
|
||
1. **缓存优化**:实现本地对话缓存,减少API调用
|
||
2. **并发处理**:支持多个用户同时对话
|
||
3. **流式响应优化**:改进微信中的流式消息体验
|
||
|
||
### 6.3 运维完善
|
||
1. **健康检查**:添加/health端点监控服务状态
|
||
2. **自动备份**:定期备份对话数据和配置
|
||
3. **报警系统**:Token余额不足或服务异常时发送通知
|
||
|
||
---
|
||
|
||
## 💰 成本估算示例
|
||
以典型使用场景估算:
|
||
- 每天50条消息,平均每条100字输入+200字输出
|
||
- 约消耗:50 × (200+400) = 30,000 Tokens/天
|
||
- 使用V3.2(缓存未命中):(30,000/1,000,000)×2 + (60,000/1,000,000)×3 = 0.24元/天
|
||
- **月成本约:7-8元人民币**
|
||
|
||
> **提示**:实际成本会根据使用频率、对话长度和缓存命中率变化。建议在DeepSeek平台设置每月预算提醒。
|
||
|
||
---
|
||
|
||
这份方案提供了从零开始的完整部署指南。如果你在实施过程中遇到具体问题(如Python版本兼容、微信登录失败等),可以告诉我具体情况,我会提供更针对性的解决方案。是否需要我对某个部分(如故障排查或成本优化)做更详细的说明? |