ChatGPT.js 2.6 KB

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