in apps/chat/src/utils/server/index.ts [165:221]
async start(controller) {
const onParse = (event: ParsedEvent | ReconnectInterval) => {
if (isFinished) {
return;
}
if (event.type === 'event') {
try {
if (event.data === '[DONE]') {
controller.close();
isFinished = true;
return;
}
const data = event.data;
const json = JSON.parse(data);
if (json.error) {
throw new DialAIError(
json.error.message,
json.error.type,
json.error.param,
json.error.code,
json.error.display_message,
);
}
if (!idSend) {
appendChunk(controller, { responseId: json.id });
idSend = true;
}
if (json.choices?.[0]?.delta) {
if (json.choices[0].finish_reason === 'content_filter') {
throw new DialAIError(
errorsMessages.contentFiltering,
'',
'',
'content_filter',
);
}
appendChunk(controller, json.choices[0].delta);
}
} catch (e) {
controller.error(e);
}
}
};
const parser = createParser(onParse);
if (res.body) {
for await (const chunk of res.body) {
if (isFinished) {
return;
}
parser.feed(decoder.decode(chunk as Buffer));
}
}
},