ai-service.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. try {
  65. const iterator = response.iterator();
  66. for await (const chunk of iterator) {
  67. if (chunk) {
  68. console.log(chunk);
  69. const decodedChunk = chunk.choices[0].delta.content;
  70. if (decodedChunk) {
  71. text += decodedChunk;
  72. paragraph.innerHTML = text
  73. }
  74. }
  75. }
  76. } catch (error) {
  77. if (signal.aborted) {
  78. console.log("Stream reading aborted");
  79. } else {
  80. console.error("Error reading stream:", error);
  81. }
  82. }
  83. console.log((+new Date() - a) / 1000)
  84. // console.log(completion.choices[0].message.content);
  85. // const response = await fetch(this.apiEndpoint, {
  86. // method: "POST",
  87. // headers: {
  88. // "Content-Type": "application/json",
  89. // Authorization: `Bearer ${this.apiKey}`,
  90. // },
  91. // body: JSON.stringify({
  92. // model: this.model,
  93. // messages: this.formatMessages(message),
  94. // }),
  95. // signal: this.controller.signal,
  96. // });
  97. // if (!response.ok) {
  98. // throw new Error(`API request failed: ${response.status}`);
  99. // }
  100. // const data = await response.json();
  101. // const aiResponse = data.choices[0]?.message?.content;
  102. // const aiResponse = completion.choices[0].message.content
  103. // if (!aiResponse) {
  104. // throw new Error("无效的API响应");
  105. // }
  106. // return aiResponse;
  107. } catch (error) {
  108. if (error.name === "AbortError") {
  109. throw new Error("REQUEST_ABORTED");
  110. }
  111. console.error("API call failed:", error);
  112. throw error;
  113. } finally {
  114. this.controller = null;
  115. }
  116. }
  117. /**
  118. * 格式化消息历史
  119. * @param {string} currentMessage 当前消息
  120. * @returns {Array} 格式化后的消息数组
  121. */
  122. formatMessages(currentMessage) {
  123. const messages = this.context.map((msg) => ({
  124. role: msg.role,
  125. content: msg.content,
  126. }));
  127. // 如果存在页面信息,添加到当前消息的上下文
  128. if (this.currentPageInfo) {
  129. currentMessage = `基于之前总结的页面内容(标题:${this.currentPageInfo.title}),${currentMessage}`;
  130. }
  131. messages.push({
  132. role: "user",
  133. content: currentMessage,
  134. });
  135. return messages;
  136. }
  137. /**
  138. * 更新对话上下文
  139. * @param {string} message 新消息
  140. * @param {string} role 消息角色(user/assistant)
  141. */
  142. updateContext(message, role) {
  143. this.context.push({
  144. role,
  145. content: message,
  146. timestamp: new Date().toISOString(),
  147. });
  148. // 保持上下文长度在合理范围内
  149. if (this.context.length > 10) {
  150. this.context = this.context.slice(-10);
  151. }
  152. }
  153. /**
  154. * 清除对话上下文
  155. */
  156. clearContext() {
  157. this.context = [];
  158. }
  159. /**
  160. * 获取当前对话上下文
  161. * @returns {Array} 对话上下文数组
  162. */
  163. getContext() {
  164. return this.context;
  165. }
  166. // 添加中断方法
  167. abortRequest() {
  168. if (this.controller) {
  169. this.controller.abort();
  170. this.controller = null;
  171. }
  172. }
  173. /**
  174. * 获取页面总结提示词
  175. * @param {Object} pageInfo 页面信息
  176. * @returns {string} 提示词
  177. */
  178. // 4. 按重要性排序
  179. // 5. 如果内容是新闻,需要包含时间、地点、人物等关键信息
  180. // 6. 如果内容是教程,需要突出操作步骤和关键提示
  181. // 7. 如果内容是产品介绍,需要包含主要特点和优势
  182. getSummaryPrompt(pageInfo) {
  183. return `请帮我总结以下网页内容的要点:
  184. 页面标题:${pageInfo.title}
  185. 网站:${pageInfo.siteName}
  186. URL:${pageInfo.url}
  187. 主要内容:
  188. ${pageInfo.mainContent}
  189. 要求:
  190. 1. 帮助我分析表单项与上传excel文件中每一列的关系
  191. 2- 将excel文件中每一列的内容与表单项进行匹配,并生成对应的数组,在一个字段内返回
  192. `;
  193. }
  194. /**
  195. * 设置当前Excel数据
  196. * @param {Object} data Excel数据和元信息
  197. */
  198. setExcelData(data) {
  199. this.currentExcelData = data;
  200. }
  201. /**
  202. * 设置当前页面信息
  203. * @param {Object} pageInfo 页面信息
  204. */
  205. setPageInfo(pageInfo) {
  206. this.currentPageInfo = pageInfo;
  207. }
  208. }
  209. // 确保在DOM加载完成后再创建实例
  210. document.addEventListener("DOMContentLoaded", () => {
  211. // 只有在实例不存在时才创建
  212. if (!window.aiService) {
  213. window.aiService = new AIService();
  214. }
  215. });