To modify the get_compute_stream function to handle a streaming response, you'll need to use the ReadableStream API provided by the fetch method. Generators in JavaScript can be used to yield data chunks as they come in from the stream, but since Response objects from fetch support streams natively, there's no need to use a generator.
Instead, you can consume the stream using an asynchronous iteration over the Response body. Here is an illustration of how the code can be changed:
async function get_compute_stream(model) {
const url = 'https://pandora-s-sandbox-api.onrender.com/llm_compute_stream';
let history = [];
const storedHistory = localStorage.getItem('playground_history');
if (storedHistory) {
JSON.parse(storedHistory).forEach(element => {
history.push({ author: element[0], content: element[1] });
});
}
console.log(history);
const data = {
history: history,
model: model,
key: "Kouti'theBox",
style: "html"
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (response.body) {
const reader = response.body.getReader();
let receivedLength = 0; // length at the moment
let chunks = []; // array of received binary chunks (comprises the body)
while(true) {
const { done, value } = await reader.read();
if (done) {
console.log('Stream complete');
break;
}
chunks.push(value);
receivedLength += value.length;
console.log(`Received ${receivedLength} bytes of data so far`);
// processChunk(value); // (not shown) whatever you want to do with each chunk
// When you are ready to process the entire concatenated result you can do:
// let chunksAll = new Uint8Array(receivedLength); // (not shown) create a new array to hold all the chunks
// Symantically we should concatenate chunks here, but consider processing them one by one as they arrive instead
}
}
// let allData = new TextDecoder('utf-8').decode(chunksAll); // (not shown) convert chunks to a string
// console.log('Success:', allData);
// return allData;
// Note: Instead of accumulating all received chunks, and only then processing them,
// it's often more practical to handle each chunk immediately when it comes in.
} catch (error) {
console.error('Error:', error);
throw error; // Rethrow to allow caller to handle the error appropriately
}
}
In this modified function:
- It checks the
Response.body for a readable stream.
- Uses the reader from the readable stream to read the chunks.
- Loops until the stream is fully read (
done flag is true), accumulating chunks and their lengths to process each part of the stream.
I've left comments where you might convert chunks into strings and concatenate them, as well as placeholders where you might process the chunks incrementally. You could process the stream as it arrives or after you've accumulated all chunks depending on your application's requirements.