Skip to content

Commit

Permalink
Merge pull request #1192 from tonimoreiraa/fix-dify-truncated-messages
Browse files Browse the repository at this point in the history
fix(dify-service): Truncated messages (agent bot)
  • Loading branch information
DavidsonGomes authored Feb 1, 2025
2 parents ff5a8ad + fc84e0f commit 9109b14
Showing 1 changed file with 23 additions and 43 deletions.
66 changes: 23 additions & 43 deletions src/api/integrations/chatbot/dify/services/dify.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,63 +224,43 @@ export class DifyService {
headers: {
Authorization: `Bearer ${dify.apiKey}`,
},
responseType: 'stream',
});

let conversationId;
let answer = '';

const stream = response.data;
const reader = new Readable().wrap(stream);
const data = response.data.replaceAll('data: ', '');

reader.on('data', (chunk) => {
const data = chunk.toString().replace(/data:\s*/g, '');
const events = data.split('\n').filter((line) => line.trim() !== '');

if (data.trim() === '' || !data.startsWith('{')) {
return;
}

try {
const events = data.split('\n').filter((line) => line.trim() !== '');
for (const eventString of events) {
if (eventString.trim().startsWith('{')) {
const event = JSON.parse(eventString);

for (const eventString of events) {
if (eventString.trim().startsWith('{')) {
const event = JSON.parse(eventString);

if (event?.event === 'agent_message') {
console.log('event:', event);
conversationId = conversationId ?? event?.conversation_id;
answer += event?.answer;
}
}
if (event?.event === 'agent_message') {
console.log('event:', event);
conversationId = conversationId ?? event?.conversation_id;
answer += event?.answer;
}
} catch (error) {
console.error('Error parsing stream data:', error);
}
});

reader.on('end', async () => {
if (instance.integration === Integration.WHATSAPP_BAILEYS)
await instance.client.sendPresenceUpdate('paused', remoteJid);
}

const message = answer;
if (instance.integration === Integration.WHATSAPP_BAILEYS)
await instance.client.sendPresenceUpdate('paused', remoteJid);

await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
const message = answer;

await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
sessionId: conversationId,
},
});
});
await this.sendMessageWhatsApp(instance, remoteJid, message, settings);

reader.on('error', (error) => {
console.error('Error reading stream:', error);
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
sessionId: conversationId,
},
});

return;
Expand Down

0 comments on commit 9109b14

Please sign in to comment.