ai-service.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. } finally {
  96. this.controller = null;
  97. }
  98. }
  99. /**
  100. * 格式化消息历史
  101. * @param {string} currentMessage 当前消息
  102. * @returns {Array} 格式化后的消息数组
  103. */
  104. formatMessages(currentMessage) {
  105. const messages = this.context.map((msg) => ({
  106. role: msg.role,
  107. content: msg.content,
  108. }));
  109. // 如果存在页面信息,添加到当前消息的上下文
  110. if (this.currentPageInfo) {
  111. currentMessage = `基于之前总结的页面内容(标题:${this.currentPageInfo.title}),${currentMessage}`;
  112. }
  113. messages.push({
  114. role: "user",
  115. content: currentMessage,
  116. });
  117. return messages;
  118. }
  119. /**
  120. * 更新对话上下文
  121. * @param {string} message 新消息
  122. * @param {string} role 消息角色(user/assistant)
  123. */
  124. updateContext(message, role) {
  125. this.context.push({
  126. role,
  127. content: message,
  128. timestamp: new Date().toISOString(),
  129. });
  130. // 保持上下文长度在合理范围内
  131. if (this.context.length > 10) {
  132. this.context = this.context.slice(-10);
  133. }
  134. }
  135. /**
  136. * 清除对话上下文
  137. */
  138. clearContext() {
  139. this.context = [];
  140. }
  141. /**
  142. * 获取当前对话上下文
  143. * @returns {Array} 对话上下文数组
  144. */
  145. getContext() {
  146. return this.context;
  147. }
  148. // 添加中断方法
  149. abortRequest() {
  150. if (this.controller) {
  151. this.controller.abort();
  152. this.controller = null;
  153. }
  154. }
  155. /**
  156. * 获取页面总结提示词
  157. * @param {Object} pageInfo 页面信息
  158. * @returns {string} 提示词
  159. */
  160. // 4. 按重要性排序
  161. // 5. 如果内容是新闻,需要包含时间、地点、人物等关键信息
  162. // 6. 如果内容是教程,需要突出操作步骤和关键提示
  163. // 7. 如果内容是产品介绍,需要包含主要特点和优势
  164. getSummaryPrompt(pageInfo) {
  165. return `请帮我总结以下网页内容的要点:
  166. 页面标题:${pageInfo.title}
  167. 网站:${pageInfo.siteName}
  168. URL:${pageInfo.url}
  169. 主要内容:
  170. ${pageInfo.mainContent}
  171. 要求:
  172. 1. 帮助我分析表单项与上传excel文件中每一列的关系
  173. 2- 将excel文件中每一列的内容与表单项进行匹配,并生成对应的数组,在一个字段内返回
  174. `;
  175. }
  176. /**
  177. * 设置当前Excel数据
  178. * @param {Object} data Excel数据和元信息
  179. */
  180. setExcelData(data) {
  181. this.currentExcelData = data;
  182. }
  183. /**
  184. * 设置当前页面信息
  185. * @param {Object} pageInfo 页面信息
  186. */
  187. setPageInfo(pageInfo) {
  188. this.currentPageInfo = pageInfo;
  189. }
  190. }
  191. // 确保在DOM加载完成后再创建实例
  192. document.addEventListener("DOMContentLoaded", () => {
  193. // 只有在实例不存在时才创建
  194. if (!window.aiService) {
  195. window.aiService = new AIService();
  196. }
  197. });