.NET 如何實現ChatGPT的Stream傳輸
.NET 如何實現ChatGPT的Stream傳輸
ChatGPT是如何實現不適用websocket進行一個一個字返回到前端的?
下面我們會介紹一下EventSource
EventSource
EventSource 接口是 web 內容與服務器發送事件[1]通信的接口。
一個 EventSource 實例會對 HTTP[2] 服務器開啟一個持久化的連接,以 text/event-stream 格式發送事件[3],此連接會一直保持開啟直到通過調用 `EventSource.close()`[4] 關閉。
EventTarget <= EventSource
一旦連接開啟,來自服務端傳入的消息會以事件的形式分發至你代碼中。如果接收消息中有一個 event 字段,觸發的事件與 event 字段的值相同。如果不存在 event 字段,則將觸發通用的 `message`[5] 事件。
與 WebSocket[6] 不同的是,服務器發送事件是單向的。數據消息只能從服務端到發送到客戶端(如用戶的瀏覽器)。這使其成為不需要從客戶端往服務器發送消息的情況下的最佳選擇。例如,對于處理如社交媒體狀態更新、消息來源(news feed)或將數據傳遞到客戶端存儲[7]機制(如 IndexedDB[8] 或 web 存儲[9])之類的,EventSource 無疑是一個有效方案。
- 參考文獻 EventSource[10]
使用場景
- ChatGPT的Stream式對話,可以一個字一個字相應,增加用戶體驗
- 簡單的大數據量的數據進行推送到客戶端
- 耗時并且持續化的數據傳輸
- 等
ASP.NET Core 實現
創建WebApi項目
圖片
在Controllers中新建一個StreamController.cs文件,并且提供一個IAsyncEnumerable<out T>的Demo
- IAsyncEnumerable<out T>
公開對指定類型的值提供異步迭代的枚舉器。
StreamController.cs
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers;
[ApiController]
[Route("[controller]")]
public class StreamController : ControllerBase
{
[HttpPost]
public async IAsyncEnumerable<char> Test()
{
const string value = "這是一個完整的測試數據;為了測試IAsyncEnumerable<T>的使用";
foreach (var v in value)
{
await Task.Delay(500);
yield return v;
}
await Task.CompletedTask;
}
}
上面案例的接口使用了IAsyncEnumerable<char>,作為返回值,將value字符串一個一個字符返回到前端。
每次返回等待500,這是服務端的實現,下面寫客戶端的實現,客戶端也是用.NET
使用js實現調用
首先啟動api服務,然后在打開的swagger的瀏覽器界面中打開開發者工具使用F12打開開發者工具
圖片
在控制臺中添加fetchAsStream方法用于調用IAsyncEnumerable<char>的接口服務,代碼如下
async function fetchAsStream(url,data) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data),
});
if (!response.ok) {
const reader = response.body?.getReader();
const { done, value } = await reader.read();
throw new Error(
`Failed to fetch `
);
}
if (!response.body) {
throw new Error("ReadableStream not supported in this browser.");
}
const reader = response.body.getReader();
return {
[Symbol.asyncIterator]( "Symbol.asyncIterator") {
return {
async next() {
const { done, value } = await reader.read();
if (done) {
return { done: true, value: null };
}
return {
done: false,
value: new TextDecoder("utf-8").decode(value),
};
},
};
},
};
}
圖片
輸入完成按回車鍵會顯示一個undefined
然后下一步就調用這個方法,當執行下面這個代碼會發現控制臺會一個一個字顯示內容。
var stream = await fetchAsStream("http://localhost:5255/stream");
for await(var c of stream){
console.log(c);
}
圖片
看效果控制臺的字在一個一個輸出,請注意不要使用axios,默認是不支持的。
參考資料
[1]服務器發送事件: https://developer.mozilla.org/zh-CN/docs/Web/API/Server-sent_events
[2]HTTP: https://developer.mozilla.org/zh-CN/docs/Web/HTTP
[3]事件: https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Building_blocks/Events
[4]EventSource.close(): https://developer.mozilla.org/zh-CN/docs/Web/API/EventSource/close
[5]message: https://developer.mozilla.org/zh-CN/docs/Web/API/EventSource/message_event
[6]WebSocket: https://developer.mozilla.org/zh-CN/docs/Web/API/WebSockets_API
[7]客戶端存儲: https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Client-side_web_APIs/Client-side_storage
[8]IndexedDB: https://developer.mozilla.org/zh-CN/docs/Web/API/IndexedDB_API
[9]web 存儲: https://developer.mozilla.org/zh-CN/docs/Web/API/Web_Storage_API
[10]EventSource: https://developer.mozilla.org/zh-CN/docs/Web/API/EventSource