2024-08-24

使用前端 JS 接收 Ollama 回應的 Ndjson 格式

使用前端 JS 接收 Ollama 回應的 Ndjson 格式

基本上就是使用 fetch API 來處理串流資料,利用 async/await 就可以使用無窮迴圈來處理。

<input type="text" id="chat" value="台灣位於哪裡?" /> <button onclick="startAsk()">開始</button> <div id="result_div"></div>
const chat = document.querySelector("#chat"); const result_div = document.querySelector("#result_div"); const model = "mistral-nemo"; // ollama 使用的 LLM 模型名稱 const startAsk = async () => { const response = await fetch(`http://localhost:11434/api/generate`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ model, prompt: chat.value }), }); if (!response.ok) { console.log("回應發生錯誤!!!"); return; } // ['content-type', 'application/x-ndjson'] console.log(...response.headers); const reader = response.body.getReader(); // 讀取器 const decoder = new TextDecoder("utf8"); // 解碼器 while (true) { const { value, done } = await reader.read(); const json = decoder.decode(value); // 基本上每一行都是 json console.log(json); try { const obj = JSON.parse(json); result_div.innerText += obj.response; } catch (ex) { console.log(ex); console.log("不是 JSON:", `---${json}---`); } if (done) { result_div.innerText += "\n\n"; break; } } };

沒有留言:

FB 留言