2
0

🐛 (difyAi) Fix chunk parsing

Closes #1370
This commit is contained in:
Baptiste Arnaud
2024-03-18 18:05:35 +01:00
parent a797fc074c
commit e035a54cfc

View File

@@ -82,15 +82,17 @@ export const createChatMessage = createAction({
stream.on('data', (chunk) => { stream.on('data', (chunk) => {
const lines = chunk.toString().split('\n') as string[] const lines = chunk.toString().split('\n') as string[]
lines lines
.filter((line) => line.length > 0) .filter((line) => line.length > 0 && line !== '\n')
.forEach((line) => { .forEach((line) => {
try { jsonChunk += line
const data = JSON.parse( if (jsonChunk.startsWith('event: ')) {
(jsonChunk.length > 0 ? jsonChunk : line).replace( jsonChunk = ''
/^data: /, return
'' }
) if (!jsonChunk.startsWith('data: ') || !jsonChunk.endsWith('}'))
) as Chunk return
const data = JSON.parse(jsonChunk.slice(6)) as Chunk
jsonChunk = '' jsonChunk = ''
if ( if (
data.event === 'message' || data.event === 'message' ||
@@ -102,10 +104,6 @@ export const createChatMessage = createAction({
totalTokens = data.metadata.usage.total_tokens totalTokens = data.metadata.usage.total_tokens
conversationId = data.conversation_id conversationId = data.conversation_id
} }
} catch (error) {
if (line.includes('event: ')) return
jsonChunk += line
}
}) })
}) })