tongyi.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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": "system", "content": ty_presets },
  41. { "role": "user", "content": message }
  42. ],
  43. },
  44. parameters: {
  45. max_tokens: ty_max_tokens,
  46. temperature: ty_temperature
  47. }
  48. }
  49. const token = "Bearer " + ty_apiKey
  50. try {
  51. const responseData = await axios.post(ty_apiUrl, requestData, {
  52. headers: { 'Content-Type': 'application/json', Authorization: token }
  53. })
  54. const apiMessage = responseData.data.output.text
  55. return apiMessage
  56. } catch (error) {
  57. console.error("向api接口发送请求时出现错误")
  58. return error
  59. }
  60. }
  61. // 更新api设置到数据库
  62. function updateTYConfig(configName, configValue) {
  63. const query = 'REPLACE INTO tongyiconfig (config, value) VALUES (?, ?)';
  64. db.run(query, [configName, configValue], (err) => {
  65. if (err) {
  66. console.error('更新数据失败:', err);
  67. }
  68. loadConfigValues()
  69. })
  70. }
  71. module.exports = {
  72. updateTYConfig, getTYMessage
  73. }