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) {
48 */48 */
49async function parseCohereStream(jsonStream, request, response) {49async function parseCohereStream(jsonStream, request, response) {
50 try {50 try {
51 let partialData = '';
52 jsonStream.body.on('data', (data) => {51 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 }
62 if (json.message) {54 if (json.message) {
63 const message = json.message || 'Unknown error';55 const message = json.message || 'Unknown error';
64 const chunk = { error: { message: message } };56 const chunk = { error: { message: message } };
65 response.write(`data: ${JSON.stringify(chunk)}\n\n`);57 response.write(`data: ${JSON.stringify(chunk)}\n\n`);
66 partialData = '';
67 break;
68 } else if (json.event_type === 'text-generation') {58 } else if (json.event_type === 'text-generation') {
69 const text = json.text || '';59 const text = json.text || '';
70 const chunk = { choices: [{ text }] };60 const chunk = { choices: [{ text }] };
71 response.write(`data: ${JSON.stringify(chunk)}\n\n`);61 response.write(`data: ${JSON.stringify(chunk)}\n\n`);
72 partialData = '';
73 } else {62 } else {
74 partialData = '';63 return;
75 break;
76 }64 }
65 } catch (e) {
66 // ignore
77 }67 }
78 });68 });
7969
@@ -437,7 +427,7 @@ async function sendAI21Request(request, response) {
437427
438 console.log('AI21 request:', body);428 console.log('AI21 request:', body);
439429
440 try{430 try {
441 const generateResponse = await fetch(API_AI21 + '/chat/completions', options);431 const generateResponse = await fetch(API_AI21 + '/chat/completions', options);
442 if (request.body.stream) {432 if (request.body.stream) {
443 forwardFetchResponse(generateResponse, response);433 forwardFetchResponse(generateResponse, response);