'use strict'; const axios = require('axios'); class AiInspect { /** * 构造函数 * @param {object} config * @param {string} config.apiKey - Dify API Key * @param {string} config.chatflowId - ChatFlow ID * @param {string} [config.baseUrl=https://api.dify.ai/v1] - Dify API 接口地址 */ constructor({ apiKey = 'app-vc7cLDuIRJngvEgQUMBqT3SX', chatflowId = '', baseUrl = 'http://workflow.smartcost.com.cn/v1' }) { if (!apiKey) { throw new Error('apiKey 不能为空'); } this.apiKey = apiKey; this.chatflowId = chatflowId; this.baseUrl = baseUrl; } /** * 向 ChatFlow 发送请求 * @param {string} userInput - 用户输入内容 * @param {string} [userId='user_123'] - 用户 ID * @returns {Promise} - Dify 返回的对象 */ async ask(userInput, userId = 'user_123') { const url = `${this.baseUrl}/chat-messages`; const headers = { 'Authorization': `Bearer ${this.apiKey}`, 'Content-Type': 'application/json', }; const body = { inputs: {}, // 如果你的 ChatFlow 有 schema,可填写 key-value query: userInput, response_mode: 'blocking', user: userId, conversation_id: this.chatflowId, }; try { const res = await axios.post(url, body, { headers }); return res.data; } catch (err) { console.error('Dify 请求失败:', err.response || err.response.data || err.message); throw new Error('Dify 请求失败'); } } } module.exports = AiInspect;