fengchuanyu 3 months ago
parent
commit
e0d77e920b
1 changed files with 38 additions and 28 deletions
  1. 38 28
      12_vuecli/mediaapp/src/views/talk/TalkPage.vue

+ 38 - 28
12_vuecli/mediaapp/src/views/talk/TalkPage.vue

@@ -64,47 +64,57 @@ export default {
   methods: {
     // 发送消息
     async sendMessage() {
-      let res = await fetch("/doubao/chat/completions",{
+
+      // 将问题展示到页面当中
+      this.talkList.push({
+        ask:this.askInp,
+        answer:"",
+      })
+
+      let res = await fetch("/doubao/chat/completions", {
         method: "POST",
         headers: {
           "Content-Type": "application/json",
-          "Authorization": "Bearer 自己的api-key" 
+          Authorization: "Bearer 1841e844-275f-4d8f-811b-2b4077e8108f",
         },
         body: JSON.stringify({
-          stream:true,
-          model:"doubao-1-5-pro-32k-250115",
-          messages:[
+          stream: true,
+          model: "doubao-1-5-pro-32k-250115",
+          messages: [
             {
-              role:"system",
-              content:"You are a helpful assistant."
+              role: "system",
+              content: "You are a helpful assistant.",
             },
             {
-              role:"user",
-              content:this.askInp
-            }
-          ]
-        })
-      })
+              role: "user",
+              content: this.askInp,
+            },
+          ],
+        }),
+      });
       // 获取getReader 用作解析返回的数据编码
       let reader = res.body.getReader();
       // 解析数据 使用utf-8字符集
       let coder = new TextDecoder("utf-8");
-      // 读取数据
-      let result = await reader.read();
-      // console.log(result);
-      // 解析数据
-      let data = coder.decode(result.value,{
-        stream:true
-      });
-      console.log(1,data)
 
-      result = await reader.read();
-      // 解析数据
-      data = coder.decode(result.value,{
-        stream:true
-      });
-      console.log(2,data)
-      // console.log(JSON.parse(data.slice(5)) );
+      let isContinue = true;
+      while (isContinue) {
+        // 读取数据
+        let result = await reader.read();
+        isContinue = !result.done;
+        // 解析数据
+        let data = coder.decode(result.value, {
+          stream: true,
+        });
+        let dataArr = data.split("data:").slice(1);
+        dataArr.forEach((val)=>{
+          if(!val.includes("[DONE]")){
+            // console.log(JSON.parse(val).choices[0].delta.content);
+            this.talkList[this.talkList.length-1].answer += JSON.parse(val).choices[0].delta.content;
+          }
+        })
+        this.askInp = "";
+      }
     },
   },
   mounted() {