fetch-stream-tool
v1.0.0
Published
一个流式输出接口的访问工具库
Readme
fetch-stream-tool
一个流式输出接口的访问工具库,基于 Vue 3 Composition API 实现。
安装
在你的 Vue 项目中安装此工具库:
npm install fetch-stream-tool注意: 此库依赖于 Vue 3,请确保你的项目已安装 Vue 3.5.0 或更高版本。
使用方式
1. 在 Vue 组件中使用
<template>
<div>
<button @click="startStream">开始流式请求</button>
<button @click="stopStream">停止流式请求</button>
<div>连接状态: {{ isConnecting ? '连接中...' : isContentGenerating ? '生成中...' : '空闲' }}</div>
<div>生成结果: {{ result }}</div>
</div>
</template>
<script setup>
import { useSseListenerMessage } from 'fetch-stream-tool'
const {
createSSEConnection,
closeSSEConnection,
isConnecting,
isContentGenerating,
result
} = useSseListenerMessage()
const startStream = () => {
createSSEConnection("/chat/completions", {
seriesId: 123,
tags: ['tag1', 'tag2']
})
}
const stopStream = () => {
closeSSEConnection()
}
</script>2. 主要功能
- 流式连接管理: 自动处理 HTTP 流式连接
- 事件消息解析: 解析 SSE (Server-Sent Events) 格式的消息
- 响应式状态: 使用 Vue 的 ref 提供响应式状态管理
- 连接控制: 支持启动和关闭流式连接
3. API 说明
useSseListenerMessage()
返回包含以下属性和方法的对象:
createSSEConnection(seriesId: number, tags: string[]): 创建 SSE 连接closeSSEConnection(): 关闭 SSE 连接isConnecting: 连接状态(响应式布尔值)isContentGenerating: 内容生成状态(响应式布尔值)result: 生成的结果内容(响应式字符串)
SseEventMessage 接口
interface SseEventMessage {
event: string; // 事件类型 ('content' | 'complete' 等)
data: string; // 事件数据
id?: string; // 事件ID(可选)
retry?: number; // 重试时间(可选)
}依赖要求
此库需要以下 peer dependencies:
vue>= 3.5.0
在你的项目中安装 Vue:
npm install vue@^3.5.0构建
如果需要从源代码构建:
git clone <repository-url>
cd fetch-stream-tool
npm install
npm run build开发
npm run dev # 监听模式构建注意事项
- 此工具库专为 Vue 3 项目设计
- 使用前请确保后端 API 支持 SSE 流式响应
- 连接会自动处理错误和重连逻辑
- 支持通过
closeSSEConnection()方法手动中断连接
