More reliable Cohere stream parsing

9286daaf3fd8e142b5abd5f41c61177f7baa448a

Cohee <18619528+Cohee1207@users.noreply.github.com>

1 files changed, +4 -14Showing whitespace changes
src/endpoints/backends/chat-completions.js+4 -14
@@ -48,32 +48,22 @@ function postProcessPrompt(messages, type, charName, userName) {
4848 */
4949async function parseCohereStream(jsonStream, request, response) {
5050 try {
51- let partialData = '';
5251 jsonStream.body.on('data', (data) => {
53- const chunk = data.toString();
54- partialData += chunk;
55- while (true) {
56- let json;
5752 try {
5853 const json = JSON.parse(partialDatadata.toString());
59- } catch (e) {
60- break;
61- }
6254 if (json.message) {
6355 const message = json.message || 'Unknown error';
6456 const chunk = { error: { message: message } };
6557 response.write(`data: ${JSON.stringify(chunk)}\n\n`);
66- partialData = '';
67- break;
6858 } else if (json.event_type === 'text-generation') {
6959 const text = json.text || '';
7060 const chunk = { choices: [{ text }] };
7161 response.write(`data: ${JSON.stringify(chunk)}\n\n`);
72- partialData = '';
7362 } else {
74- partialData = '';
63+ return;
75- break;
7664 }
65+ } catch (e) {
66+ // ignore
7767 }
7868 });
7969