chd 6 ヶ月 前
コミット
140c171761
7 ファイル変更108 行追加48 行削除
  1. 65 26
      js/ai-service.js
  2. 12 0
      js/background.js
  3. 18 16
      js/chat-ui.js
  4. 2 2
      js/config.js
  5. 10 4
      js/content.js
  6. 0 0
      openis.js
  7. 1 0
      sidebar.html

+ 65 - 26
js/ai-service.js

@@ -12,6 +12,14 @@ class AIService {
     this.apiKey = CONFIG.AI_API.DEFAULT_API_KEY;
     this.controller = null; // 用于中断请求的 AbortController
     this.currentPageInfo = null; // 保存当前页面信息
+    this.openai = new OpenAI(
+      {
+        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
+        apiKey: 'sk-e9855234f47346049809ce23ed3ebe3f',
+        baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
+        dangerouslyAllowBrowser: true,
+      }
+    );
   }
 
   /**
@@ -48,34 +56,65 @@ class AIService {
     try {
       // 创建新的 AbortController
       this.controller = new AbortController();
+      const a = +new Date()
 
-      const response = await fetch(this.apiEndpoint, {
-        method: "POST",
-        headers: {
-          "Content-Type": "application/json",
-          Authorization: `Bearer ${this.apiKey}`,
-        },
-        body: JSON.stringify({
-          model: this.model,
-          messages: this.formatMessages(message),
-          max_tokens: CONFIG.AI_API.MAX_TOKENS,
-          temperature: CONFIG.AI_API.TEMPERATURE,
-        }),
-        signal: this.controller.signal,
+      const response = await this.openai.chat.completions.create({
+        model: "qwen-plus",  //模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
+        messages: this.formatMessages(message),
+        stream:true
       });
-
-      if (!response.ok) {
-        throw new Error(`API request failed: ${response.status}`);
-      }
-
-      const data = await response.json();
-      const aiResponse = data.choices[0]?.message?.content;
-
-      if (!aiResponse) {
-        throw new Error("无效的API响应");
-      }
-
-      return aiResponse;
+      // console.log(completion);
+      const signal = response.controller.signal;
+      let text = ''
+      try {
+        const iterator = response.iterator();
+        for await (const chunk of iterator) {
+          if (chunk) {
+            console.log(chunk);
+            
+            const decodedChunk = chunk.choices[0].delta.content;
+            if (decodedChunk) {
+              text += decodedChunk;
+            }
+          }
+        }
+        console.log(text);
+        
+      } catch (error) {
+        if (signal.aborted) {
+          console.log("Stream reading aborted");
+        } else {
+          console.error("Error reading stream:", error);
+        }
+      } 
+      console.log((+new Date() - a) / 1000)
+      // console.log(completion.choices[0].message.content);
+
+      // const response = await fetch(this.apiEndpoint, {
+      //   method: "POST",
+      //   headers: {
+      //     "Content-Type": "application/json",
+      //     Authorization: `Bearer ${this.apiKey}`,
+      //   },
+      //   body: JSON.stringify({
+      //     model: this.model,
+      //     messages: this.formatMessages(message),
+      //   }),
+      //   signal: this.controller.signal,
+      // });
+
+      // if (!response.ok) {
+      //   throw new Error(`API request failed: ${response.status}`);
+      // }
+
+      // const data = await response.json();
+      // const aiResponse = data.choices[0]?.message?.content;
+      // const aiResponse = completion.choices[0].message.content
+      // if (!aiResponse) {
+      //   throw new Error("无效的API响应");
+      // }
+
+      // return aiResponse;
     } catch (error) {
       if (error.name === "AbortError") {
         throw new Error("REQUEST_ABORTED");

+ 12 - 0
js/background.js

@@ -13,3 +13,15 @@ chrome.action.onClicked.addListener(async (tab) => {
     console.error('发送消息失败:', error);
   }
 });
+
+fetch('http://180.76.147.97:11435/api/chat', {
+  method: 'post',
+  body: JSON.stringify({
+    model: "deepseek-r1:latest",
+    messages: {
+      "role": "user",
+      "content": "why is the sky blue?"
+    },
+    stream: false
+  })
+}).then(res => { console.log(res) })

+ 18 - 16
js/chat-ui.js

@@ -267,6 +267,7 @@ ${this.iframeInfo}`;
       }
 
       const response = await this.aiService.sendMessage(prompt);
+console.log(response);
 
       if (this.loadingDiv) {
         this.loadingDiv.remove();
@@ -807,15 +808,16 @@ ${this.iframeInfo}`;
 
             // 调用AI服务理解数据
             const response = await this.aiService.sendMessage(prompt);
-
+            console.log(response);
+            
             if (this.loadingDiv) {
               this.loadingDiv.remove();
               this.loadingDiv = null;
             }
-            window.parent.postMessage({
+           0 &&  window.parent.postMessage({
               type: "HANDLE_FILL_INPUT", data: {
                 excelData: this.excelData,
-                formData: JSON.parse(response)
+                formData: JSON.parse(response.split('json')[1].split('```')[0])  //根据不同返回修改res
               }
             }, "*");
             // 显示AI的理解结果
@@ -859,17 +861,7 @@ ${this.iframeInfo}`;
 
 文件名:${fileName}
 列标题:${headers.join(", ")}
-数据行数:${rows.length}
-
-示例数据(前2行):
-${sampleRows
-        .map((row, index) => {
-          return `第${index + 1}行: ${row
-            .map((cell, i) => `${headers[i]}=${cell}`)
-            .join(", ")}`;
-        })                                                                                                  
-        .join("\n")}
-  
+
 表单内容:
 ${this.iframeInfo}
              
@@ -879,7 +871,7 @@ ${this.iframeInfo}
 3. 并去除没有匹配到的表单项和excel文件中没有匹配到的列,
 4. 通过type字段告诉我输入项的类型
 5. 如果表单项有label标签,同时返回label,通过label字段告诉我label元素的文本
-5. 仅返回数组类型的数组,不要带换行符,不要返回任何其他内容。`
+5. 仅返回数组,不要返回任何其他内容。`
   }
 
   /**
@@ -921,7 +913,17 @@ ${this.iframeInfo}
     });
   }
 }
-
+// 数据行数:${rows.length}
+
+// 示例数据(前2行):
+// ${sampleRows
+//         .map((row, index) => {
+//           return `第${index + 1}行: ${row
+//             .map((cell, i) => `${headers[i]}=${cell}`)
+//             .join(", ")}`;
+//         })                                                                                                  
+//         .join("\n")}
+  
 // 等待DOM加载完成后再初始化
 document.addEventListener("DOMContentLoaded", () => {
   try {

+ 2 - 2
js/config.js

@@ -3,8 +3,8 @@
  */
 const CONFIG = {
   AI_API: {
-    ENDPOINT: "https://api.deepseek.com/v1/chat/completions", // DeepSeek API端点
-    MODEL: "deepseek-chat", // 使用的模型名称
+    ENDPOINT: "https://dashscope.aliyuncs.com/compatible-mode/v1", // DeepSeek API端点
+    MODEL: "qwen-plus", // 使用的模型名称
     MAX_TOKENS: 2000, // 最大token数
     TEMPERATURE: 0.7, // 温度参数
   },

+ 10 - 4
js/content.js

@@ -166,9 +166,10 @@ class SidebarManager {
           }
           
           if (item.type === 'date') {
+            formatDate
             const input = formChildren.find(child => child.id === item.findByValue)
             if (excelDataA[item.excelColumn][index]) {
-              await simulateCompleteUserAction(input, input, excelDataA[item.excelColumn][index], excelDataA[item.excelColumn][index])
+              await simulateCompleteUserAction(input, input, formatDate(excelDataA[item.excelColumn][index]), formatDate(excelDataA[item.excelColumn][index]))
             }
           }
         } else if (item.findBy === 'placeholder') {
@@ -231,7 +232,7 @@ class SidebarManager {
           );
         }
         if (event.data.type === "ANALYZE_PAGE") {
-          form = document.querySelectorAll("form")[1];
+          form = document.querySelectorAll("form")[0];
           formChildren = [...form.elements]
           // 分析页面并返回结果
           const pageInfo = window.pageAnalyzer.analyzePage();
@@ -524,7 +525,6 @@ const simulateCompleteUserAction = async (clickElement, inputElement, inputText,
   // 2. 模拟键盘输入
   const simulateTyping = async (element, text, delay = 50) => {
     element.focus();
-
     for (let char of text) {
       await new Promise(resolve => setTimeout(resolve, delay));
 
@@ -622,7 +622,13 @@ const simulateCompleteUserAction = async (clickElement, inputElement, inputText,
     throw error;
   }
 };
-
+function formatDate(date) {
+  const d = new Date(date);
+  const year = d.getFullYear();
+  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并确保两位数
+  const day = String(d.getDate()).padStart(2, '0'); // 确保两位数
+  return `${year}-${month}-${day}`;
+}
 
 
 

ファイルの差分が大きいため隠しています
+ 0 - 0
openis.js


+ 1 - 0
sidebar.html

@@ -5,6 +5,7 @@
     <title>派维斯智能体助手</title>
     <link rel="stylesheet" href="css/sidebar.css" />
     <link rel="stylesheet" href="css/chat.css" />
+    <script src="./openis.js" type="module"></script>
   </head>
   <body>
     <div class="sidebar-header">

この差分においてかなりの量のファイルが変更されているため、一部のファイルを表示していません