ai-service.js 6.3 KB

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