3.7 KiB
3.7 KiB
AI 服务配置说明
环境变量配置
AI 服务需要通过环境变量进行配置,支持阿里云 DashScope API。
必需的环境变量
在 .env 文件或系统环境变量中配置以下参数:
# AI API 密钥(阿里云 DashScope API Key)
AI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxx
# AI API 基础 URL(阿里云 DashScope 兼容 OpenAI 格式接口)
AI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
# AI 模型名称
# 可选值:
# - qwen-turbo(快速,推荐日常使用)
# - qwen-plus(增强,平衡性能和成本)
# - qwen-max(最强,高质量输出)
# - qwen-long(长文本,支持超长上下文)
AI_MODEL=qwen-turbo
配置示例
1. 开发环境配置 (.env)
# 阿里云 DashScope 配置
AI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
AI_MODEL=qwen-turbo
2. 生产环境配置 (.env.production)
# 阿里云 DashScope 配置(生产环境使用增强版)
AI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
AI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
AI_MODEL=qwen-plus
阿里云模型对比
| 模型 | 速度 | 质量 | 成本 | 适用场景 |
|---|---|---|---|---|
| qwen-turbo | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | 日常对话、简单分析 |
| qwen-plus | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | 复杂分析、专业任务 |
| qwen-max | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | 高质量输出、关键任务 |
| qwen-long | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | 长文本处理、文档分析 |
代码中使用
// 使用默认配置(从环境变量读取)
const AIService = require('./services/ai_service.js');
const aiService = AIService.getInstance();
// 使用自定义配置
const aiService = AIService.createInstance({
apiKey: 'sk-custom-key',
baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
model: 'qwen-plus',
timeout: 60000
});
API 认证格式
阿里云 DashScope API 使用标准的 Bearer Token 认证:
Authorization: Bearer sk-xxxxxxxxxxxxxxxxxxxxx
注意事项
-
API Key 安全:
- 不要将 API Key 硬编码在代码中
- 不要将
.env文件提交到版本控制 - 生产环境使用独立的 API Key
-
模型选择建议:
- 开发/测试:使用
qwen-turbo(成本低) - 生产环境:使用
qwen-plus(性能平衡) - 关键业务:使用
qwen-max(质量最高)
- 开发/测试:使用
-
速率限制:
- 注意 API 的 QPM(每分钟请求数)限制
- 根据套餐调整并发数量
- 实现重试和错误处理机制
-
成本控制:
- 监控 Token 使用量
- 设置合理的
max_tokens限制 - 定期查看账单和用量统计
获取 API Key
- 访问阿里云控制台:https://dashscope.console.aliyun.com/
- 进入 API-KEY 管理
- 创建新的 API Key
- 复制 API Key 并保存到环境变量
故障排查
问题 1:Authentication Fails
错误:auth header format should be Bearer sk-...
解决:检查 AI_API_KEY 是否正确配置
问题 2:连接超时
错误:timeout of 30000ms exceeded
解决:
1. 检查网络连接
2. 增加 timeout 配置
3. 检查 AI_BASE_URL 是否正确
问题 3:模型不存在
错误:model not found
解决:检查 AI_MODEL 配置,确保使用支持的模型名称
迁移指南
如果之前使用其他 AI 服务(如 DeepSeek),迁移步骤:
- 更新环境变量配置
- 修改 API_BASE_URL
- 更新模型名称
- 测试 AI 调用功能
- 验证响应格式
配置更新时间: 2025-12-27 维护者: 系统管理员