
GraphRAG:基于PolarDB+通義千問api+LangChain的知識圖譜定制實踐
Bearer YOUR_API_KEY
},
body: JSON.stringify({
model: 'gpt-4',
prompt: prompt,
stream: true // 啟用流式響應
})
});
// 檢查響應狀態(tài)
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 獲取響應的可讀流并處理流數(shù)據(jù)
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let done = false;
while (!done) {
// 讀取流中的下一個數(shù)據(jù)塊
const {
value, done: readerDone } = await reader.read();
done = readerDone;
// 將數(shù)據(jù)塊解碼為字符串
const chunk = decoder.decode(value, {
stream: true });
console.log(chunk); // 處理或顯示每一塊數(shù)據(jù)
// ***** 這需要注意,各個大模型的分塊數(shù)據(jù)結構可能不一樣,甚至會有可能出現(xiàn)部分數(shù)據(jù)的情況,要單獨兼容和處理哦
// 以及有些模型內(nèi)容的路徑不一樣,一次性響應在content,但是流式在delta字段下
}
};
當后端返回流式響應時,前端可以逐步接收并更新UI,提供更好的用戶交互體驗。以下是前端處理流式響應的關鍵步驟。
每當接收到一個新的數(shù)據(jù)塊,前端可以立即將其更新到UI上,而不必等待完整的響應。這種實時更新的機制對于聊天機器人、搜索建議等場景尤為重要。例如:
const chatBox = document.getElementById('chat-box');
const updateChat = (text) => {
// 將新數(shù)據(jù)塊追加到界面上
chatBox.innerHTML += `<p>${
text}</p>`;
};
// 在逐塊接收時更新
while (!done) {
const {
value, done: readerDone } = await reader.read();
const chunk = decoder.decode(value, {
stream: true });
updateChat(chunk); // 實時更新聊天框
}
通過這種方式,用戶能夠看到模型生成內(nèi)容的部分結果,即使整個請求尚未完成,提升了用戶體驗。
在流式調(diào)用中,網(wǎng)絡連接可能會中斷,或者服務器可能會返回錯誤。前端應該做好錯誤處理,例如:
if (!response.ok) {
console.error('Error with the request');
return;
}
reader.read().then(processStream).catch(error => {
console.error('Error while reading stream:', error);
});
在中斷時,前端可以選擇顯示錯誤消息,或嘗試重新發(fā)起請求以重新建立連接。
由于流傳輸?shù)臄?shù)據(jù)是分塊發(fā)送的,前端可能需要將這些分段數(shù)據(jù)拼接起來,形成完整的響應。例如:
let fullResponse = '';
while (!done) {
const {
value, done: readerDone } = await reader.read();
const chunk = decoder.decode(value, {
stream: true });
fullResponse += chunk; // 拼接完整響應
}
對于聊天機器人或類似應用,前端可以設置自動滾動,使得用戶在流式數(shù)據(jù)逐步加載時能夠始終看到最新的內(nèi)容。
const scrollToBottom = () => {
chatBox.scrollTop = chatBox.scrollHeight;
};
updateChat(chunk);
scrollToBottom(); // 更新后自動滾動
HTTP API流式調(diào)用為大語言模型的響應提供了更高效和實時的交互方式。通過流式調(diào)用,前端可以逐步接收模型生成的部分數(shù)據(jù),并即時呈現(xiàn),從而提升用戶體驗。前端在實現(xiàn)流式調(diào)用時,需要處理數(shù)據(jù)分塊的拼接、實時更新界面和處理可能的中斷錯誤。通過這種方式,可以在交互密集的應用場景(如聊天機器人、自動化助手等)中大幅改善用戶的使用體驗。
文章轉自微信公眾號@阿里云開發(fā)者