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,29 +82,27 @@ 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(
/^data: /,
''
)
) as Chunk
jsonChunk = '' jsonChunk = ''
if ( return
data.event === 'message' || }
data.event === 'agent_message' if (!jsonChunk.startsWith('data: ') || !jsonChunk.endsWith('}'))
) { return
answer += data.answer
} const data = JSON.parse(jsonChunk.slice(6)) as Chunk
if (data.event === 'message_end') { jsonChunk = ''
totalTokens = data.metadata.usage.total_tokens if (
conversationId = data.conversation_id data.event === 'message' ||
} data.event === 'agent_message'
} catch (error) { ) {
if (line.includes('event: ')) return answer += data.answer
jsonChunk += line }
if (data.event === 'message_end') {
totalTokens = data.metadata.usage.total_tokens
conversationId = data.conversation_id
} }
}) })
}) })