More reliable Cohere stream parsing

This commit is contained in:
Cohee 2024-08-26 20:35:23 +03:00
parent 00ff2875ab
commit 9286daaf3f

View File

@ -48,32 +48,22 @@ function postProcessPrompt(messages, type, charName, userName) {
*/
async function parseCohereStream(jsonStream, request, response) {
try {
let partialData = '';
jsonStream.body.on('data', (data) => {
const chunk = data.toString();
partialData += chunk;
while (true) {
let json;
try {
json = JSON.parse(partialData);
} catch (e) {
break;
}
const json = JSON.parse(data.toString());
if (json.message) {
const message = json.message || 'Unknown error';
const chunk = { error: { message: message } };
response.write(`data: ${JSON.stringify(chunk)}\n\n`);
partialData = '';
break;
} else if (json.event_type === 'text-generation') {
const text = json.text || '';
const chunk = { choices: [{ text }] };
response.write(`data: ${JSON.stringify(chunk)}\n\n`);
partialData = '';
} else {
partialData = '';
break;
return;
}
} catch (e) {
// ignore
}
});