tongyi.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. const axios = require('axios')
  2. const sqlite3 = require('sqlite3')
  3. const db = new sqlite3.Database("./db/data.db")
  4. function getConfigValue(configName) {
  5. return new Promise((resolve, reject) => {
  6. const query = 'SELECT value FROM tongyiconfig WHERE config = ?';
  7. db.get(query, [configName], (err, row) => {
  8. if (err) {
  9. reject(err);
  10. } else {
  11. const configValue = row ? row.value : null;
  12. // 处理字符串 'null',如果是 'null' 则返回 null
  13. resolve(configValue === 'null' ? null : configValue)
  14. }
  15. })
  16. })
  17. }
  18. // 读取配置信息并设置相应的变量
  19. async function loadConfigValues() {
  20. try {
  21. ty_apiKey = await getConfigValue('apiKey')
  22. ty_apiUrl = await getConfigValue('apiUrl')
  23. ty_maxTokensStr = await getConfigValue('max_tokens')
  24. ty_temperatureStr = await getConfigValue('temperature')
  25. ty_model = await getConfigValue('model')
  26. ty_presets = await getConfigValue('presets')
  27. ty_temperature = parseFloat(ty_temperatureStr)
  28. ty_max_tokens = parseInt(ty_maxTokensStr)
  29. } catch (error) {
  30. console.error('加载通义api接口设置失败!', error)
  31. }
  32. }
  33. // 调用函数加载配置信息
  34. loadConfigValues()
  35. async function getTYMessage(message) {
  36. const requestData = {
  37. model: ty_model,
  38. input: {
  39. messages: [
  40. { "role": "user", "content": message }
  41. ],
  42. },
  43. parameters: {
  44. max_tokens: ty_max_tokens,
  45. temperature: ty_temperature
  46. }
  47. }
  48. if (ty_presets) {
  49. requestData.input.messages.unshift({ "role": "system", "content": ty_presets })
  50. }
  51. const token = "Bearer " + ty_apiKey
  52. try {
  53. const responseData = await axios.post(ty_apiUrl, requestData, {
  54. headers: { 'Content-Type': 'application/json', Authorization: token }
  55. });
  56. const apiMessage = responseData.data.output.text;
  57. return apiMessage;
  58. } catch (error) {
  59. console.error("向api接口发送请求时出现错误")
  60. return error;
  61. }
  62. }
  63. // 更新api设置到数据库
  64. function updateTYConfig(configName, configValue) {
  65. const query = 'REPLACE INTO tongyiconfig (config, value) VALUES (?, ?)'
  66. db.run(query, [configName, configValue], (err) => {
  67. if (err) {
  68. console.error('更新数据失败:', err);
  69. }
  70. loadConfigValues()
  71. })
  72. }
  73. module.exports = {
  74. updateTYConfig, getTYMessage
  75. }