ChatGPT.js 2.2 KB

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