ai.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. const config = require('./config');
  2. const REQUEST_TIMEOUT_MS = 120000;
  3. const REQUEST_TIMEOUT_IMG_MS = 180000;
  4. module.exports.REQUEST_TIMEOUT_MS = REQUEST_TIMEOUT_MS;
  5. module.exports.REQUEST_TIMEOUT_IMG_MS = REQUEST_TIMEOUT_IMG_MS;
  6. function request(path, body, timeoutMs) {
  7. const baseUrl = (config.BASE_URL || '').replace(/\/$/, '');
  8. const url = path.startsWith('http') ? path : `${baseUrl}/${path.replace(/^\//, '')}`;
  9. const controller = new AbortController();
  10. const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  11. return fetch(url, {
  12. method: 'POST',
  13. headers: {
  14. 'Content-Type': 'application/json',
  15. 'Authorization': `Bearer ${config.API_KEY || ''}`
  16. },
  17. body: JSON.stringify(body),
  18. signal: controller.signal
  19. })
  20. .then((res) => {
  21. clearTimeout(timeoutId);
  22. return res.json().catch(() => ({})).then((data) => {
  23. if (!res.ok) throw new Error(data.error?.message || data.error || `HTTP ${res.status}`);
  24. return data;
  25. });
  26. })
  27. .catch((e) => {
  28. clearTimeout(timeoutId);
  29. if (e.name === 'AbortError') throw new Error(`请求超时 (${timeoutMs / 1000} 秒)`);
  30. throw e;
  31. });
  32. }
  33. function doubaoRequest(path, body, timeoutMs) {
  34. const baseUrl = (config.DOUBAO_BASE_URL || '').replace(/\/$/, '');
  35. const url = path.startsWith('http') ? path : `${baseUrl}/${path.replace(/^\//, '')}`;
  36. const controller = new AbortController();
  37. const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  38. return fetch(url, {
  39. method: 'POST',
  40. headers: {
  41. 'Content-Type': 'application/json',
  42. 'Authorization': `Bearer ${config.DOUBAO_API_KEY || ''}`
  43. },
  44. body: JSON.stringify(body),
  45. signal: controller.signal
  46. })
  47. .then((res) => {
  48. clearTimeout(timeoutId);
  49. return res.json().catch(() => ({})).then((data) => {
  50. if (!res.ok) throw new Error(data.error?.message || data.error || `HTTP ${res.status}`);
  51. return data;
  52. });
  53. })
  54. .catch((e) => {
  55. clearTimeout(timeoutId);
  56. if (e.name === 'AbortError') throw new Error(`请求超时 (${timeoutMs / 1000} 秒)`);
  57. throw e;
  58. });
  59. }
  60. const text2text = require('./request/text2text');
  61. const img2text = require('./request/img2text');
  62. const text2img = require('./request/text2img');
  63. const img2img = require('./request/img2img');
  64. const REQ = { text2text, img2text, text2img, img2img };
  65. async function run(action, ...args) {
  66. if (action.startsWith('doubao_')) {
  67. return await doRequest(action.substring(7), true, args);
  68. }
  69. return await doRequest(action, false, args);
  70. }
  71. /** 从 request 模块取参数,在 ai.js 内发请求 */
  72. async function doRequest(action, isDoubao, args) {
  73. const req = REQ[action];
  74. if (!req) return { success: false, error: 'Unknown action: ' + action };
  75. if (isDoubao && (!config.DOUBAO_MODEL || !config.DOUBAO_MODEL.trim())) {
  76. return { success: false, error: '豆包未配置:请在 nodejs/ai/config.js 中设置 DOUBAO_MODEL 为你在火山引擎控制台创建的模型接入点 ID(endpoint ID),或设置环境变量 DOUBAO_MODEL' };
  77. }
  78. const path = req.path;
  79. const timeoutMs = req.timeoutMs;
  80. const body = action === 'text2text'
  81. ? (isDoubao ? req.getDoubaoBody(args[0]) : req.getBody(args[0]))
  82. : (isDoubao ? req.getDoubaoBody(args[0], args[1]) : req.getBody(args[0], args[1]));
  83. try {
  84. const data = isDoubao
  85. ? await doubaoRequest(path, body, timeoutMs)
  86. : await request(path, body, timeoutMs);
  87. return { success: true, data };
  88. } catch (e) {
  89. return { success: false, error: e && (e.message || String(e)) };
  90. }
  91. }
  92. module.exports.run = run;
  93. module.exports.request = request;
  94. module.exports.REQUEST_TIMEOUT_MS = REQUEST_TIMEOUT_MS;
  95. module.exports.REQUEST_TIMEOUT_IMG_MS = REQUEST_TIMEOUT_IMG_MS;