ChatGPT.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. } catch (error) {
  28. console.error('加载GPT接口设置失败!', error)
  29. }
  30. }
  31. // 调用函数加载配置信息
  32. loadConfigValues()
  33. async function getGPTMessage(message) {
  34. const requestData = {
  35. app_code: gpt_app_code,
  36. messages: [{ "role": "user", "content": message }],
  37. model: gpt_model
  38. }
  39. if(gpt_presets) {
  40. requestData.messages.unshift({ "role": "system", "content": gpt_presets })
  41. }
  42. const token = "Bearer " + gpt_apiKey
  43. try {
  44. const responseData = await axios.post(gpt_apiUrl, requestData, {
  45. headers: { 'Content-Type': 'application/json', Authorization: token }
  46. })
  47. const apiMessage = responseData.data.choices[0].message.content
  48. return apiMessage
  49. } catch (error) {
  50. console.error("向api接口发送请求时出现错误")
  51. return error
  52. }
  53. }
  54. // 更新api设置到数据库
  55. function updateGPTConfig(configName, configValue) {
  56. const query = 'REPLACE INTO gptconfig (config, value) VALUES (?, ?)';
  57. db.run(query, [configName, configValue], (err) => {
  58. if (err) {
  59. console.error('更新数据失败:', err);
  60. }
  61. loadConfigValues()
  62. })
  63. }
  64. module.exports = { updateGPTConfig, getGPTMessage }