ai-service.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /**
  2. * AI服务类
  3. * 处理与AI模型的通信和响应
  4. */
  5. class AIService {
  6. constructor() {
  7. this.apiEndpoint = CONFIG.AI_API.ENDPOINT;
  8. this.messageContainer = document.getElementById("chat-messages");
  9. this.model = CONFIG.AI_API.MODEL;
  10. this.context = [];
  11. this.currentExcelData = null; // 保存当前Excel数据
  12. this.response = ''
  13. // 使用默认API密钥
  14. this.apiKey = CONFIG.AI_API.DEFAULT_API_KEY;
  15. this.controller = null; // 用于中断请求的 AbortController
  16. this.currentPageInfo = null; // 保存当前页面信息
  17. this.openai = new OpenAI(
  18. {
  19. // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
  20. apiKey: 'sk-e9855234f47346049809ce23ed3ebe3f',
  21. baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
  22. dangerouslyAllowBrowser: true,
  23. }
  24. );
  25. }
  26. /**
  27. * 初始化AI服务
  28. */
  29. async init() {
  30. try {
  31. // 尝试从storage中获取用户设置的API密钥
  32. const result = await Utils.getStorageData("apiKey");
  33. if (result?.apiKey) {
  34. this.apiKey = result.apiKey;
  35. }
  36. console.log("AI Service initialized");
  37. } catch (error) {
  38. console.error("Failed to initialize AI service:", error);
  39. }
  40. }
  41. /**
  42. * 设置API密钥
  43. * @param {string} apiKey
  44. */
  45. async setApiKey(apiKey) {
  46. this.apiKey = apiKey;
  47. await Utils.setStorageData("apiKey", { apiKey });
  48. }
  49. /**
  50. * 发送消息到DeepSeek API
  51. * @param {string} message 用户消息
  52. * @returns {Promise<string>} AI响应
  53. */
  54. async sendMessage(message) {
  55. try {
  56. // 创建新的 AbortController
  57. this.controller = new AbortController();
  58. const a = +new Date()
  59. const response = await this.openai.chat.completions.create({
  60. model: "qwen-plus", //模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
  61. messages: this.formatMessages(message),
  62. stream: true
  63. });
  64. return response;
  65. // console.log((+new Date() - a) / 1000)
  66. // console.log(completion.choices[0].message.content);
  67. // const response = await fetch(this.apiEndpoint, {
  68. // method: "POST",
  69. // headers: {
  70. // "Content-Type": "application/json",
  71. // Authorization: `Bearer ${this.apiKey}`,
  72. // },
  73. // body: JSON.stringify({
  74. // model: this.model,
  75. // messages: this.formatMessages(message),
  76. // }),
  77. // signal: this.controller.signal,
  78. // });
  79. // if (!response.ok) {
  80. // throw new Error(`API request failed: ${response.status}`);
  81. // }
  82. // const data = await response.json();
  83. // const aiResponse = data.choices[0]?.message?.content;
  84. // const aiResponse = completion.choices[0].message.content
  85. // if (!aiResponse) {
  86. // throw new Error("无效的API响应");
  87. // }
  88. // return aiResponse;
  89. } catch (error) {
  90. // if (error.name === "AbortError") {
  91. // throw new Error("REQUEST_ABORTED");
  92. // }
  93. console.error("API call failed:", error);
  94. // throw error;
  95. return '[FILE]'
  96. } finally {
  97. this.controller = null;
  98. }
  99. }
  100. /**
  101. * 格式化消息历史
  102. * @param {string} currentMessage 当前消息
  103. * @returns {Array} 格式化后的消息数组
  104. */
  105. formatMessages(currentMessage) {
  106. const messages = this.context.map((msg) => ({
  107. role: msg.role,
  108. content: msg.content,
  109. }));
  110. // 如果存在页面信息,添加到当前消息的上下文
  111. if (this.currentPageInfo) {
  112. currentMessage = `基于之前总结的页面内容(标题:${this.currentPageInfo.title}),${currentMessage}`;
  113. }
  114. messages.push({
  115. role: "user",
  116. content: currentMessage,
  117. });
  118. return messages;
  119. }
  120. /**
  121. * 更新对话上下文
  122. * @param {string} message 新消息
  123. * @param {string} role 消息角色(user/assistant)
  124. */
  125. updateContext(message, role) {
  126. this.context.push({
  127. role,
  128. content: message,
  129. timestamp: new Date().toISOString(),
  130. });
  131. // 保持上下文长度在合理范围内
  132. if (this.context.length > 10) {
  133. this.context = this.context.slice(-10);
  134. }
  135. }
  136. /**
  137. * 清除对话上下文
  138. */
  139. clearContext() {
  140. this.context = [];
  141. }
  142. /**
  143. * 获取当前对话上下文
  144. * @returns {Array} 对话上下文数组
  145. */
  146. getContext() {
  147. return this.context;
  148. }
  149. // 添加中断方法
  150. abortRequest() {
  151. if (this.controller) {
  152. this.controller.abort();
  153. this.controller = null;
  154. }
  155. }
  156. /**
  157. * 获取页面总结提示词
  158. * @param {Object} pageInfo 页面信息
  159. * @returns {string} 提示词
  160. */
  161. // 4. 按重要性排序
  162. // 5. 如果内容是新闻,需要包含时间、地点、人物等关键信息
  163. // 6. 如果内容是教程,需要突出操作步骤和关键提示
  164. // 7. 如果内容是产品介绍,需要包含主要特点和优势
  165. getSummaryPrompt(pageInfo) {
  166. return `请帮我总结以下网页内容的要点:
  167. 页面标题:${pageInfo.title}
  168. 网站:${pageInfo.siteName}
  169. URL:${pageInfo.url}
  170. 主要内容:
  171. ${pageInfo.mainContent}
  172. 要求:
  173. 1. 帮助我分析表单项与上传excel文件中每一列的关系
  174. 2- 将excel文件中每一列的内容与表单项进行匹配,并生成对应的数组,在一个字段内返回
  175. `;
  176. }
  177. /**
  178. * 设置当前Excel数据
  179. * @param {Object} data Excel数据和元信息
  180. */
  181. setExcelData(data) {
  182. this.currentExcelData = data;
  183. }
  184. /**
  185. * 设置当前页面信息
  186. * @param {Object} pageInfo 页面信息
  187. */
  188. setPageInfo(pageInfo) {
  189. this.currentPageInfo = pageInfo;
  190. }
  191. }
  192. // 确保在DOM加载完成后再创建实例
  193. document.addEventListener("DOMContentLoaded", () => {
  194. // 只有在实例不存在时才创建
  195. if (!window.aiService) {
  196. window.aiService = new AIService();
  197. }
  198. });