const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
async function createCollection() {
try {
const db = wx.cloud.database()
const result = await db.collection('deepseek_tasks').add({
data: {
_id: 'test_collection_creation',
test: true,
createdAt: new Date()
}
})
console.log('集合测试成功,已存在或创建成功')
wx.showToast({ title: '集合正常', icon: 'success' })
} catch (error) {
console.error('集合检查失败:', error)
wx.showModal({
title: '集合不存在',
content: 'deepseek_tasks集合不存在,请在云开发控制台创建',
showCancel: false,
success: () => {
wx.navigateTo({
url: '/pages/cloud/cloud'
})
}
})
}
}
async function processTaskAsync(taskId, prompt) {
console.log(`开始异步处理任务: ${taskId}`)
try {
await db.collection('deepseek_tasks').doc(taskId).update({
data: {
status: 'processing',
updatedAt: db.serverDate()
}
})
console.log(`任务 ${taskId} 状态更新为处理中`)
const apiKey = process.env.DEEPSEEK_API_KEY
console.log('API密钥长度:', apiKey ? apiKey.length : 0)
if (!apiKey || apiKey === 'your-api-key-here') {
throw new Error('API密钥未配置,请在云函数环境变量中设置DEEPSEEK_API_KEY')
}
console.log('开始调用DeepSeek API...')
const response = await cloud.openapi.cloudbase.httpRequest({
url: 'https://api.deepseek.com/v1/chat/completions',
method: 'POST',
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
data: {
model: 'deepseek-chat',
messages: [
{
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 1000
},
dataType: 'json',
timeout: 30000
})
console.log('DeepSeek API调用成功,状态码:', response.statusCode)
const result = response.data?.choices?.[0]?.message?.content || '无回复内容'
await db.collection('deepseek_tasks').doc(taskId).update({
data: {
status: 'completed',
result: result,
usage: response.data?.usage,
completedAt: db.serverDate(),
updatedAt: db.serverDate()
}
})
console.log(`任务 ${taskId} 处理完成`)
} catch (error) {
console.error(`处理任务 ${taskId} 失败:`, error)
await db.collection('deepseek_tasks').doc(taskId).update({
data: {
status: 'failed',
error: error.message,
errorDetail: error.toString(),
updatedAt: db.serverDate()
}
})
}
}
exports.main = async (event, context) => {
const wxContext = cloud.getWXContext()
const { prompt } = event
console.log('收到请求:', {
prompt: prompt?.substring(0, 50),
openid: wxContext.OPENID
})
if (!prompt || prompt.trim() === '') {
return {
code: 400,
message: '请输入有效的问题',
timestamp: Date.now()
}
}
const taskId = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
try {
console.log(`创建任务记录: ${taskId}`)
await db.collection('deepseek_tasks').add({
data: {
_id: taskId,
prompt: prompt,
openid: wxContext.OPENID,
status: 'pending',
createdAt: db.serverDate(),
updatedAt: db.serverDate(),
env: cloud.DYNAMIC_CURRENT_ENV
}
})
console.log(`任务记录创建成功: ${taskId}`)
const immediateResponse = {
success: true,
taskId: taskId,
message: '任务已提交,请稍后查询结果',
timestamp: new Date().toISOString()
}
console.log('立即返回响应:', immediateResponse)
setTimeout(async () => {
console.log(`开始异步处理任务 ${taskId}`)
try {
await processTaskAsync(taskId, prompt)
} catch (asyncError) {
console.error(`异步处理异常: ${asyncError}`)
}
}, 100)
return immediateResponse
} catch (error) {
console.error('创建任务失败:', error)
return {
success: false,
message: '创建任务失败',
error: error.message,
timestamp: Date.now()
}
}
}
/index/index/index.js // pages/index/index.js "use strict"; Page({ data: { // 输入数据 prompt: '', // 输入的提示词 aiResponse: '', // AI返回的结果 isLoading: false, // 加载状态 showResult: false, // 是否显示结果 name: '', gender: '', birthYear: '', birthMonth: '', birthDay: '', timeIndex: 0, // 时辰选项 timeOptions: [ '子时 (23-1)', '丑时 (1-3)', '寅时 (3-5)', '卯时 (5-7)', '辰时 (7-9)', '巳时 (9-11)', '午时 (11-13)', '未时 (13-15)', '申时 (15-17)', '酉时 (17-19)', '戌时 (19-21)', '亥时 (21-23)' ], // 八个圆形按钮的文字 buttonsRow1: ['兴', '衰', '终', '存'], buttonsRow2: ['运', '八', '字', '详'], // 当前日期 currentDate: '', // 对话消息 messages: [], // 输入文本 inputText: '', // 滚动位置 scrollTop: 0, // 自动聚焦 autoFocus: false, // 快捷提示 quickPrompts: [ '用Python写一个快速排序算法', '解释什么是机器学习', '帮我写一封辞职信', '推荐几个学习AI的网站' ] }, onLoad: function() { // this.initCloud() }, onNameInput: function(e) { const value = e.detail.value; this.setData({ name: value }); }, selectGender: function(e) { const gender = e.currentTarget.dataset.gender; this.setData({ gender: gender }); }, // 年份选择 onYearChange: function(e) { const date = e.detail.value; const year = date.split('-')[0]; this.setData({ birthYear: year + '年' }); }, // 月份选择 onMonthChange: function(e) { const date = e.detail.value; const month = date.split('-')[1]; this.setData({ birthMonth: month + '月' }); }, // 日期选择 onDayChange: function(e) { const date = e.detail.value; const day = date.split('-')[2]; this.setData({ birthDay: day + '日' }); }, // 时辰选择 onTimeChange: function(e) { this.setData({ timeIndex: e.detail.value }); }, onBaziDetail: function() { if (!this.data.name) { wx.showToast({ title: '请输入姓名', icon: 'none' }); return; } if (!this.data.gender) { wx.showToast({ title: '请选择性别', icon: 'none' }); return; } if (!this.data.birthYear) { wx.showToast({ title: '请输入年份', icon: 'none' }); return; } if (!this.data.birthMonth) { wx.showToast({ title: '请输入月份', icon: 'none' }); return; } if (!this.data.birthDay) { wx.showToast({ title: '请输入日期', icon: 'none' }); return; } // 收集用户数据 const userData = { name: this.data.name, gender: this.data.gender, birthYear: this.data.birthYear, birthMonth: this.data.birthMonth, birthDay: this.data.birthDay, birthTime: this.data.timeOptions[this.data.timeIndex], aiprt: '' } let info = `我是一位资深的中国命理师,精通八字排盘和解读。请根据以下信息为我进行八字分析。 出生信息:姓名:${userData.name} , 性别:${userData.gender} , 出生信息:公历:${userData.birthYear}${userData.birthMonth}${userData.birthDay},时辰: ${userData.birthTime}任务: 1. 排出我的四柱八字(含天干地支)。 2. 列出我的十神。 3. 分析我的日主强弱和喜用神。 4. 简要分析整体运势特点。 要求: 1. 请严格按照JSON格式返回 2. JSON结构必须包含以下字段: - "八字排盘":字符串,包含四柱八字 - "十神":数组,列出十神关系 - "日主分析":对象,包含{日主, 强弱, 喜用神} - "运势特点":字符串,简要分析 - "温馨提示":字符串,加入"本结果由AI生成,仅供娱乐参考"的提醒 示例格式: { "八字排盘": "年柱:庚午 月柱:辛巳 日柱:乙酉 时柱:辛巳", "十神": ["正官", "偏印", ...], "日主分析": {"日主": "乙木", "强弱": "偏弱", "喜用神": "水、木"}, "运势特点": "整体运势分析...", "温馨提示": "本结果由AI生成,仅供娱乐参考 `; // 使用showModal弹窗显示 wx.showModal({ title: '八字命理详情', content: `${info}\n`, showCancel: false, confirmText: '知道了' }), wx.cloud.callFunction({ name: 'addDeepSeek', data: { prompt: "什么是AI?" } }).then(result => { console.log('结果:', result); if (result.success) { console.log('AI回复:', result.data.reply) // 更新UI显示 } }); } });1.完整的接口调用失败日志(包含fail报错内容及错误代码)
rep:没有报错日志,日志显示是正常的。
2.任务处理过程中云函数的完整日志输出
日志内容 Request ID: d101c0af-4e34-4fad-9fc8-1e7fe6413cde
执行时间: 178ms内存使用: 23.44 MB
返回结果
{"success":true,"taskId":"task_1769658439982_n4mijuiiy","message":"任务已提交,请稍后查询结果","timestamp":"2026-01-29T03:47:20.153Z"}
日志
START RequestId: d101c0af-4e34-4fad-9fc8-1e7fe6413cde
Event RequestId: d101c0af-4e34-4fad-9fc8-1e7fe6413cde
2026-01-29T03:47:19.979Z 收到请求: { prompt: '什么是AI?', openid: 'oJ9iE18EGtmENGIs6GC2J3gD9CaE' }
2026-01-29T03:47:19.982Z 创建任务记录: task_1769658439982_n4mijuiiy
2026-01-29T03:47:20.152Z 任务记录创建成功: task_1769658439982_n4mijuiiy
2026-01-29T03:47:20.153Z 立即返回响应: {
success: true,
taskId: 'task_1769658439982_n4mijuiiy',
message: '任务已提交,请稍后查询结果',
timestamp: '2026-01-29T03:47:20.153Z'
}
Response RequestId: d101c0af-4e34-4fad-9fc8-1e7fe6413cde RetMsg: {"success":true,"taskId":"task_1769658439982_n4mijuiiy","message":"任务已提交,请稍后查询结果","timestamp":"2026-01-29T03:47:20.153Z"}
END RequestId: d101c0af-4e34-4fad-9fc8-1e7fe6413cde
Report RequestId: d101c0af-4e34-4fad-9fc8-1e7fe6413cde Duration: 178ms Memory: 256MB MemUsage: 23.437500MB
3.当前使用的微信基础库版本和操作系统版本
REP:基础库版本:3.14.0
操作系统版本:windows 10 22H2,内核版本:19045.6456
请通过官方代码片段工具提供最小化可复现代码:https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html
注:提供信息时请注意对敏感信息(如appid)进行脱敏处理
云函数运行在微信云服务器端,不支持
wx开头的客户端 API