link
Handling Stream API Call in Angular Using ChatGPT API
It is possible to handle stream API calls in Angular using the ChatGPT API. To do this, you can use the fetch
and ReadableStream
. Here is an example of how to use it:
chatStream(url, body, apikey) {
return new Observable<string>(observer => {
fetch(url, {
method: 'POST',
body: body,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apikey}`,
},
}).then(response => {
const reader = response.body?.getReader(); //Create a ReadableStream object from the response
const decoder = new TextDecoder(); //Create a text decoder for decoding the stream data into readable text
if (!response.ok) { //Handle any errors from the response
observer.error();
}
function push() { //This function will read chunks of data from the stream and process them one by one
return reader?.read().then(({ done, value }) => {
if (done) { //If there are no more chunks available in the stream then complete the observable
observer.complete();
return;
}
//Parse text content from response
const events = decoder.decode(value).split('\n\n');
let content="";
for (let i = 0; i < events.length; i++) {
const event = events[i];
if (event === 'data: [DONE]') break; //Check for end of stream chunk
if (event && event.slice(0, 6) === 'data: ') { //Check for valid data chunk
const data = JSON.parse(event.slice(6)); //Parse valid data chunk
content += data.choices[0].delta?.content || '';//Add parsed content to output string
}
}
observer.next(content);//Send parsed content as next value on observable
push();//Process next chunk in stream
});
}
push();//Start processing first chunk in stream
}).catch((err: Error) => {//Handle any errors while processing chunks in stream
observer.error();
});
});
//Subscribe to above created observable like this
let botMessage=""
chatStream().subscribe({
next: (text) => {
botMessage += text
},
complete: () => {
console.log("Completed");
},
error: () => {
console.log("Error occured");
}, });