调用AI接口,流式返回数据如何在前端展示

该文章已生成可运行项目,
import request from "@/utils/request.js";
import { getToken } from "@/utils/auth";
let baseApi = process.env.VUE_APP_BASE_API;

export function callBaiLianAPI(message, onDataReceived, onComplete, onError) {
  let token = "";
  let signHeader = {};
  if (getToken()) {
    signHeader["Authorization"] = `Bearer ${getToken()}`;
  }

  let messages = message
    .slice(0, -1)
    .map(({ role, content }) => ({ role, content }));

  fetch(`${baseApi}/business/bailian/chat`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...signHeader,
    },
    body: JSON.stringify(messages),
  })
    .then((response) => response.body.getReader())
    .then((reader) => {
      const decoder = new TextDecoder();
      let partialReasoningContent = "";
      let partialContent = "";
      let resource = [];
      let pre = "";

      function processStream({ done, value }) {
        if (done) {
          // 流式读取完成
          onComplete({ partialReasoningContent, partialContent });
          return;
        }

        const textChunk = decoder.decode(value, { stream: true });

        let lines = textChunk.split("data:");

        if (!lines[0].startsWith(`{"requestId":`)) {
          lines[0] = pre + lines[0];
          pre = "";
        }
        if (!lines[lines.length - 1].endsWith("\n\n")) {
          pre = lines[lines.length - 1];
          lines.pop();
        }

        for (const line of lines) {
          if (!line.trim()) continue;
          const jsonString = line;
          try {
            const jsonData = JSON.parse(jsonString);
            let res = jsonData.output.thoughts[1].thought;
            let con = jsonData.output.text;
            let source = jsonData.output.thoughts[0].observation;

            if (res != null && res != undefined) {
              partialReasoningContent += res;
            }
            if (con != null && con != undefined) {
              partialContent += con;
            }
            if (source.length > 0) {
              let parsedData = JSON.parse(source);
              if (parsedData.length > 0) {
                parsedData.map((item) => {
                  resource.push({
                    dataId: item.dataId,
                    dataName: item.dataName,
                  });
                });
              }
            }

            resource = resource.filter(
              (value, index, self) =>
                index ===
                self.findIndex(
                  (t) =>
                    t.dataId === value.dataId && t.dataName === value.dataName
                )
            );
          } catch (error) {
            console.error("解析 JSON 失败:", error, "原始数据:", textChunk);
          }
        }

        onDataReceived({ partialReasoningContent, partialContent, resource });
        // 继续读取下一块数据
        reader.read().then(processStream).catch(onError);
      }

      // 开始读取流
      reader.read().then(processStream).catch(onError);
    })
    .catch((error) => {
      console.error("调用 DeepSeek API 出错:", error);
      onError(error);
    });
}

本文章已经生成可运行项目
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值