ai_inspect.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. 'use strict';
  2. const axios = require('axios');
  3. class AiInspect {
  4. /**
  5. * 构造函数
  6. * @param {object} config
  7. * @param {string} config.apiKey - Dify API Key
  8. * @param {string} config.chatflowId - ChatFlow ID
  9. * @param {string} [config.baseUrl=https://api.dify.ai/v1] - Dify API 接口地址
  10. */
  11. constructor({ apiKey = 'app-vc7cLDuIRJngvEgQUMBqT3SX', chatflowId = '', baseUrl = 'http://workflow.smartcost.com.cn/v1' }) {
  12. if (!apiKey) {
  13. throw new Error('apiKey 不能为空');
  14. }
  15. this.apiKey = apiKey;
  16. this.chatflowId = chatflowId;
  17. this.baseUrl = baseUrl;
  18. }
  19. /**
  20. * 向 ChatFlow 发送请求
  21. * @param {string} userInput - 用户输入内容
  22. * @param {string} [userId='user_123'] - 用户 ID
  23. * @returns {Promise<object>} - Dify 返回的对象
  24. */
  25. async ask(userInput, userId = 'user_123') {
  26. const url = `${this.baseUrl}/chat-messages`;
  27. const headers = {
  28. 'Authorization': `Bearer ${this.apiKey}`,
  29. 'Content-Type': 'application/json',
  30. };
  31. const body = {
  32. inputs: {}, // 如果你的 ChatFlow 有 schema,可填写 key-value
  33. query: userInput,
  34. response_mode: 'blocking',
  35. user: userId,
  36. conversation_id: this.chatflowId,
  37. };
  38. try {
  39. const res = await axios.post(url, body, { headers });
  40. return res.data;
  41. } catch (err) {
  42. console.error('Dify 请求失败:', err.response || err.response.data || err.message);
  43. throw new Error('Dify 请求失败');
  44. }
  45. }
  46. }
  47. module.exports = AiInspect;