| 48 | */ | 48 | */ |
| 49 | async function parseCohereStream(jsonStream, request, response) { | 49 | async 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 | }); |
| 79 | | 69 | |