ChatGPT.js 2.1 KB

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