首页 > 其他分享 >前端如何接收SSE流式数据传输(大模型网站常用)

前端如何接收SSE流式数据传输(大模型网站常用)

时间:2024-09-25 14:11:53浏览次数:1  
标签:const string successCallback 流式 event SSE 数据传输 ev response

使用fetchEventSource
参考:https://blog.csdn.net/qq_43750656/article/details/131591198
https://zhuanlan.zhihu.com/p/686618062

首先安装:

npm install --save @microsoft/fetch-event-source

我参考各个资料写的函数:

// 流式传输处理函数
export function sseRequest(url: string, data: object, successCallback: Function, closeCallback?: Function, errCallback?: Function) {
  const abortController = new AbortController()
  fetchEventSource(import.meta.env.VITE_APP_BASE_API + url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      'Accept': '*/*',
      'token': localStorage.getItem('token')!
    },
    body: JSON.stringify(data),
    openWhenHidden: true, // 取消visibilityChange事件
    signal: abortController.signal, // AbortSignal
    // 按需添加此函数,不用就不添加
    async onopen(response) {
        if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
            return; // everything's good
        } else if (response.status >= 400 && response.status < 500 && response.status !== 429) {
            // client-side errors are usually non-retriable:
            throw new FatalError();
        } else {
            throw new RetriableError();
        }
    },
    onmessage(ev) {
      // 每当消息推送过来时,就调用处理函数处理消息
      successCallback(ev)
    },
    one rror(err) {
      abortController.abort()
      if (errCallback) { errCallback(err) }
      throw err
    },
    onclose() {
      abortController.abort()
      if (closeCallback) { closeCallback() }
    }
  })
}

// 调用sseRequest示例:
export const beginWrite = (topic: string, styleId: string, style: string) => {
  const writeStore = useWriteStore()
  function successCallback(ev: { data: string, event: string, id: string, retry: number }) {
    if (ev.event === 'message') {
      const newStr = ev.data.replace(/_::_/g, '\n\n').replace(/_:_/g, '\n').replace(/_._/g, ' ')
      writeStore.sseInput += newStr
    }
    if (ev.event === 'message_end') {
      writeStore.sseInput = ''
    }
  }
  sseRequest('/knowledge/know_write', { topic, styleId, style }, successCallback)
}

 

标签:const,string,successCallback,流式,event,SSE,数据传输,ev,response
From: https://www.cnblogs.com/sexintercourse/p/18431250

相关文章

  • List Comprehensions, Classe Data
    Assignment#2-ListComprehensions,Classes,CSV,TabularDataThisassignmentconsistsofthreeparts:1.HighestandLowestPotentiallyaffectedvehicles.2.nelta.py3.nelta.pyandRecallswithPotentiallyaffectedvehicles>500,000Clickonthis......
  • 限流式保护器在低压配电系统中电气火灾的重要性
    随着人类进入现代文明社会,电气的普及深入千家万户,广泛应用于社会的各个领域但是每年因电气而导致的火灾却给国家和人民的生命财产带来巨大的损失,据统计,因低压配电系统中的短路发的火灾几乎达到了电气火灾总数的60%以上,因此加强低压配电系统管理,防止短路故障的发分析掌握短路的......
  • 使用SBP打AssetBundle时脚本引用丢失
    1)使用SBP打AssetBundle时脚本引用丢失2)在UE5.3中连接Power节点为何10的3次幂等于10093)如何在Widget中倾斜一张纹理贴图4)如何在打开关卡蓝图时更改游戏模式这是第401篇UWA技术知识分享的推送,精选了UWA社区的热门话题,涵盖了UWA问答、社区帖子等技术知识点,助力大家更全面地掌握和......
  • WPF ListView GridViewColumn DisplayMemeberBinding SystemDateTime sys:clr-namespa
    <Windowx:Class="WpfApp395.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • CSSE2002 Programming in the Large
    Programming in the Large (CSSE2002)Assignment 2 — Semester 2, 2024Overview This assignment provides experience working with an existing software project. You are provided with a small extension to the Farming game application......
  • Assembly.CreateInstance 方法和Activator.CreateInstance 方法(C#)
    1.Assembly.CreateInstance从程序集中查找某个类型,然后使用系统激活器创建它的实例,有以下三种方式实现:CreateInstance(String)使用区分大小写的搜索,从此程序集中查找指定的类型,然后使用系统激活器创建它的实例。CreateInstance(String,Boolean)使用可选的区分大小写......
  • 4CM5084CM508 Assessment Brief
    ComputerSystems,DataStructuresandDataManagement4CM5084CM508AssessmentBrief–Coursework1DrMuhammadRizwanComputersystems,datastructuresanddatamanagement(4CM508)ContentssessmentType:  IndividualAssessmentweighting:  50%LearningOu......
  • 使用 Rust 和 wasm-pack 开发 WebAssembly 应用
    一、什么是WebAssembly?WebAssembly是一种运行在现代Web浏览器中的新型二进制指令格式。它是一种低级别的字节码,可以被多种语言编译,并在浏览器中高效运行。1.1WebAssembly的背景与概念高性能计算:WebAssembly旨在提高Web应用的性能,接近原生速度,适合计算密集型任务......
  • CSSE4630 Rust-Inspired Analyses
    CSSE4630AssignmentOne:Rust-InspiredAnalyses2024version1.01IntroductionThisassignmentisfocusedonseveralkindsofanalysisinspiredbytheRustprogramminglanguage.Rustisastronglytypedlanguagethatusesasophisticatedtypesystemtop......
  • ChatGPT流式数据传输探索
    文章目录背景介绍目标技术细节1、客户端2、服务端总结背景介绍用过GPT类语言模型的同学都知道,其在返回数据时都是一个字或几个字的显示,你是否思考过它是怎么传输的?经过一番查询学习,了解到了SSE,GPT就是通过SSE流式传输方式进行传输的。SSE全称为Server-sent-even......