| 48 | 48 | */ |
| 49 | 49 | async function parseCohereStream(jsonStream, request, response) { |
| 50 | 50 | try { |
| 51 | | - let partialData = ''; |
| 52 | 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 | 54 | if (json.message) { |
| 63 | 55 | const message = json.message || 'Unknown error'; |
| 64 | 56 | const chunk = { error: { message: message } }; |
| 65 | 57 | response.write(`data: ${JSON.stringify(chunk)}\n\n`); |
| 66 | | - partialData = ''; |
| 67 | | - break; |
| 68 | 58 | } else if (json.event_type === 'text-generation') { |
| 69 | 59 | const text = json.text || ''; |
| 70 | 60 | const chunk = { choices: [{ text }] }; |
| 71 | 61 | response.write(`data: ${JSON.stringify(chunk)}\n\n`); |
| 72 | | - partialData = ''; |
| 73 | 62 | } else { |
| 74 | | - partialData = ''; |
| 63 | + return; |
| 75 | | - break; |
| 76 | 64 | } |
| 65 | + } catch (e) { |
| 66 | + // ignore |
| 77 | 67 | } |
| 78 | 68 | }); |
| 79 | 69 | |