More reliable Cohere stream parsing

9286daaf3fd8e142b5abd5f41c61177f7baa448a

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

1 files changed, +6 -16Ignore whitespace
src/endpoints/backends/chat-completions.js+6 -16
@@ -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();
52+ try {
54- partialData += chunk;
53+ const json = JSON.parse(data.toString());
55- while (true) {
56- let json;
57- try {
58- json = JSON.parse(partialData);
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
@@ -437,7 +427,7 @@ async function sendAI21Request(request, response) {
437427
438428 console.log('AI21 request:', body);
439429
440430 try {
441431 const generateResponse = await fetch(API_AI21 + '/chat/completions', options);
442432 if (request.body.stream) {
443433 forwardFetchResponse(generateResponse, response);