Spaces:
Runtime error
Runtime error
File size: 22,365 Bytes
5e518ea |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 |
import { PrismaRepository } from '@api/repository/repository.service';
import { WAMonitoringService } from '@api/services/monitor.service';
import { Integration } from '@api/types/wa.types';
import { ConfigService, Language, Openai as OpenaiConfig } from '@config/env.config';
import { IntegrationSession, OpenaiBot, OpenaiSetting } from '@prisma/client';
import { sendTelemetry } from '@utils/sendTelemetry';
import axios from 'axios';
import { downloadMediaMessage } from 'baileys';
import FormData from 'form-data';
import OpenAI from 'openai';
import P from 'pino';
import { BaseChatbotService } from '../../base-chatbot.service';
/**
* OpenAI service that extends the common BaseChatbotService
* Handles both Assistant API and ChatCompletion API
*/
export class OpenaiService extends BaseChatbotService<OpenaiBot, OpenaiSetting> {
protected client: OpenAI;
constructor(waMonitor: WAMonitoringService, prismaRepository: PrismaRepository, configService: ConfigService) {
super(waMonitor, prismaRepository, 'OpenaiService', configService);
}
/**
* Return the bot type for OpenAI
*/
protected getBotType(): string {
return 'openai';
}
/**
* Initialize the OpenAI client with the provided API key
*/
protected initClient(apiKey: string) {
this.client = new OpenAI({ apiKey });
return this.client;
}
/**
* Process a message based on the bot type (assistant or chat completion)
*/
public async process(
instance: any,
remoteJid: string,
openaiBot: OpenaiBot,
session: IntegrationSession,
settings: OpenaiSetting,
content: string,
pushName?: string,
msg?: any,
): Promise<void> {
try {
this.logger.log(`Starting process for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`);
// Handle audio message transcription
if (content.startsWith('audioMessage|') && msg) {
this.logger.log('Detected audio message, attempting to transcribe');
// Get OpenAI credentials for transcription
const creds = await this.prismaRepository.openaiCreds.findUnique({
where: { id: openaiBot.openaiCredsId },
});
if (!creds) {
this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`);
return;
}
// Initialize OpenAI client for transcription
this.initClient(creds.apiKey);
// Transcribe the audio
const transcription = await this.speechToText(msg, instance);
if (transcription) {
this.logger.log(`Audio transcribed: ${transcription}`);
// Replace the audio message identifier with the transcription
content = transcription;
} else {
this.logger.error('Failed to transcribe audio');
await this.sendMessageWhatsApp(
instance,
remoteJid,
"Sorry, I couldn't transcribe your audio message. Could you please type your message instead?",
settings,
);
return;
}
} else {
// Get the OpenAI credentials
const creds = await this.prismaRepository.openaiCreds.findUnique({
where: { id: openaiBot.openaiCredsId },
});
if (!creds) {
this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`);
return;
}
// Initialize OpenAI client
this.initClient(creds.apiKey);
}
// Handle keyword finish
const keywordFinish = settings?.keywordFinish || '';
const normalizedContent = content.toLowerCase().trim();
if (keywordFinish.length > 0 && normalizedContent === keywordFinish.toLowerCase()) {
if (settings?.keepOpen) {
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'closed',
},
});
} else {
await this.prismaRepository.integrationSession.delete({
where: {
id: session.id,
},
});
}
await sendTelemetry('/openai/session/finish');
return;
}
// If session is new or doesn't exist
if (!session) {
const data = {
remoteJid,
pushName,
botId: openaiBot.id,
};
const createSession = await this.createNewSession(
{ instanceName: instance.instanceName, instanceId: instance.instanceId },
data,
this.getBotType(),
);
await this.initNewSession(
instance,
remoteJid,
openaiBot,
settings,
createSession.session,
content,
pushName,
msg,
);
await sendTelemetry('/openai/session/start');
return;
}
// If session exists but is paused
if (session.status === 'paused') {
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
},
});
return;
}
// Process with the appropriate API based on bot type
await this.sendMessageToBot(instance, session, settings, openaiBot, remoteJid, pushName || '', content);
} catch (error) {
this.logger.error(`Error in process: ${error.message || JSON.stringify(error)}`);
return;
}
}
/**
* Send message to OpenAI - this handles both Assistant API and ChatCompletion API
*/
protected async sendMessageToBot(
instance: any,
session: IntegrationSession,
settings: OpenaiSetting,
openaiBot: OpenaiBot,
remoteJid: string,
pushName: string,
content: string,
): Promise<void> {
this.logger.log(`Sending message to bot for remoteJid: ${remoteJid}, bot type: ${openaiBot.botType}`);
if (!this.client) {
this.logger.log('Client not initialized, initializing now');
const creds = await this.prismaRepository.openaiCreds.findUnique({
where: { id: openaiBot.openaiCredsId },
});
if (!creds) {
this.logger.error(`OpenAI credentials not found in sendMessageToBot. CredsId: ${openaiBot.openaiCredsId}`);
return;
}
this.initClient(creds.apiKey);
}
try {
let message: string;
// Handle different bot types
if (openaiBot.botType === 'assistant') {
this.logger.log('Processing with Assistant API');
message = await this.processAssistantMessage(
instance,
session,
openaiBot,
remoteJid,
pushName,
false, // Not fromMe
content,
);
} else {
this.logger.log('Processing with ChatCompletion API');
message = await this.processChatCompletionMessage(instance, openaiBot, remoteJid, content);
}
this.logger.log(`Got response from OpenAI: ${message?.substring(0, 50)}${message?.length > 50 ? '...' : ''}`);
// Send the response
if (message) {
this.logger.log('Sending message to WhatsApp');
await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
} else {
this.logger.error('No message to send to WhatsApp');
}
// Update session status
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
},
});
} catch (error) {
this.logger.error(`Error in sendMessageToBot: ${error.message || JSON.stringify(error)}`);
if (error.response) {
this.logger.error(`API Response data: ${JSON.stringify(error.response.data || {})}`);
}
return;
}
}
/**
* Process message using the OpenAI Assistant API
*/
private async processAssistantMessage(
instance: any,
session: IntegrationSession,
openaiBot: OpenaiBot,
remoteJid: string,
pushName: string,
fromMe: boolean,
content: string,
): Promise<string> {
const messageData: any = {
role: fromMe ? 'assistant' : 'user',
content: [{ type: 'text', text: content }],
};
// Handle image messages
if (this.isImageMessage(content)) {
const contentSplit = content.split('|');
const url = contentSplit[1].split('?')[0];
messageData.content = [
{ type: 'text', text: contentSplit[2] || content },
{
type: 'image_url',
image_url: {
url: url,
},
},
];
}
// Get thread ID from session or create new thread
let threadId = session.sessionId;
// Create a new thread if one doesn't exist or invalid format
if (!threadId || threadId === remoteJid) {
const newThread = await this.client.beta.threads.create();
threadId = newThread.id;
// Save the new thread ID to the session
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
sessionId: threadId,
},
});
this.logger.log(`Created new thread ID: ${threadId} for session: ${session.id}`);
}
// Add message to thread
await this.client.beta.threads.messages.create(threadId, messageData);
if (fromMe) {
sendTelemetry('/message/sendText');
return '';
}
// Run the assistant
const runAssistant = await this.client.beta.threads.runs.create(threadId, {
assistant_id: openaiBot.assistantId,
});
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
await instance.client.presenceSubscribe(remoteJid);
await instance.client.sendPresenceUpdate('composing', remoteJid);
}
// Wait for the assistant to complete
const response = await this.getAIResponse(threadId, runAssistant.id, openaiBot.functionUrl, remoteJid, pushName);
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
await instance.client.sendPresenceUpdate('paused', remoteJid);
}
// Extract the response text safely with type checking
let responseText = "I couldn't generate a proper response. Please try again.";
try {
const messages = response?.data || [];
if (messages.length > 0) {
const messageContent = messages[0]?.content || [];
if (messageContent.length > 0) {
const textContent = messageContent[0];
if (textContent && 'text' in textContent && textContent.text && 'value' in textContent.text) {
responseText = textContent.text.value;
}
}
}
} catch (error) {
this.logger.error(`Error extracting response text: ${error}`);
}
// Update session with the thread ID to ensure continuity
await this.prismaRepository.integrationSession.update({
where: {
id: session.id,
},
data: {
status: 'opened',
awaitUser: true,
sessionId: threadId, // Ensure thread ID is saved consistently
},
});
// Return fallback message if unable to extract text
return responseText;
}
/**
* Process message using the OpenAI ChatCompletion API
*/
private async processChatCompletionMessage(
instance: any,
openaiBot: OpenaiBot,
remoteJid: string,
content: string,
): Promise<string> {
this.logger.log('Starting processChatCompletionMessage');
// Check if client is initialized
if (!this.client) {
this.logger.log('Client not initialized in processChatCompletionMessage, initializing now');
const creds = await this.prismaRepository.openaiCreds.findUnique({
where: { id: openaiBot.openaiCredsId },
});
if (!creds) {
this.logger.error(`OpenAI credentials not found. CredsId: ${openaiBot.openaiCredsId}`);
return 'Error: OpenAI credentials not found';
}
this.initClient(creds.apiKey);
}
// Check if model is defined
if (!openaiBot.model) {
this.logger.error('OpenAI model not defined');
return 'Error: OpenAI model not configured';
}
this.logger.log(`Using model: ${openaiBot.model}, max tokens: ${openaiBot.maxTokens || 500}`);
// Get existing conversation history from the session
const session = await this.prismaRepository.integrationSession.findFirst({
where: {
remoteJid,
botId: openaiBot.id,
status: 'opened',
},
});
let conversationHistory = [];
if (session && session.context) {
try {
const sessionData =
typeof session.context === 'string' ? JSON.parse(session.context as string) : session.context;
conversationHistory = sessionData.history || [];
this.logger.log(`Retrieved conversation history from session, ${conversationHistory.length} messages`);
} catch (error) {
this.logger.error(`Error parsing session context: ${error.message}`);
// Continue with empty history if we can't parse the session data
conversationHistory = [];
}
}
// Log bot data
this.logger.log(`Bot data - systemMessages: ${JSON.stringify(openaiBot.systemMessages || [])}`);
this.logger.log(`Bot data - assistantMessages: ${JSON.stringify(openaiBot.assistantMessages || [])}`);
this.logger.log(`Bot data - userMessages: ${JSON.stringify(openaiBot.userMessages || [])}`);
// Prepare system messages
const systemMessages: any = openaiBot.systemMessages || [];
const messagesSystem: any[] = systemMessages.map((message) => {
return {
role: 'system',
content: message,
};
});
// Prepare assistant messages
const assistantMessages: any = openaiBot.assistantMessages || [];
const messagesAssistant: any[] = assistantMessages.map((message) => {
return {
role: 'assistant',
content: message,
};
});
// Prepare user messages
const userMessages: any = openaiBot.userMessages || [];
const messagesUser: any[] = userMessages.map((message) => {
return {
role: 'user',
content: message,
};
});
// Prepare current message
const messageData: any = {
role: 'user',
content: [{ type: 'text', text: content }],
};
// Handle image messages
if (this.isImageMessage(content)) {
this.logger.log('Found image message');
const contentSplit = content.split('|');
const url = contentSplit[1].split('?')[0];
messageData.content = [
{ type: 'text', text: contentSplit[2] || content },
{
type: 'image_url',
image_url: {
url: url,
},
},
];
}
// Combine all messages: system messages, pre-defined messages, conversation history, and current message
const messages: any[] = [
...messagesSystem,
...messagesAssistant,
...messagesUser,
...conversationHistory,
messageData,
];
this.logger.log(`Final messages payload: ${JSON.stringify(messages)}`);
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
this.logger.log('Setting typing indicator');
await instance.client.presenceSubscribe(remoteJid);
await instance.client.sendPresenceUpdate('composing', remoteJid);
}
// Send the request to OpenAI
try {
this.logger.log('Sending request to OpenAI API');
const completions = await this.client.chat.completions.create({
model: openaiBot.model,
messages: messages,
max_tokens: openaiBot.maxTokens || 500, // Add default if maxTokens is missing
});
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
await instance.client.sendPresenceUpdate('paused', remoteJid);
}
const responseContent = completions.choices[0].message.content;
this.logger.log(`Received response from OpenAI: ${JSON.stringify(completions.choices[0])}`);
// Add the current exchange to the conversation history and update the session
conversationHistory.push(messageData);
conversationHistory.push({
role: 'assistant',
content: responseContent,
});
// Limit history length to avoid token limits (keep last 10 messages)
if (conversationHistory.length > 10) {
conversationHistory = conversationHistory.slice(conversationHistory.length - 10);
}
// Save the updated conversation history to the session
if (session) {
await this.prismaRepository.integrationSession.update({
where: { id: session.id },
data: {
context: JSON.stringify({
history: conversationHistory,
}),
},
});
this.logger.log(`Updated session with conversation history, now ${conversationHistory.length} messages`);
}
return responseContent;
} catch (error) {
this.logger.error(`Error calling OpenAI: ${error.message || JSON.stringify(error)}`);
if (error.response) {
this.logger.error(`API Response status: ${error.response.status}`);
this.logger.error(`API Response data: ${JSON.stringify(error.response.data || {})}`);
}
return `Sorry, there was an error: ${error.message || 'Unknown error'}`;
}
}
/**
* Wait for and retrieve the AI response
*/
private async getAIResponse(
threadId: string,
runId: string,
functionUrl: string | null,
remoteJid: string,
pushName: string,
) {
let status = await this.client.beta.threads.runs.retrieve(threadId, runId);
let maxRetries = 60; // 1 minute with 1s intervals
const checkInterval = 1000; // 1 second
while (
status.status !== 'completed' &&
status.status !== 'failed' &&
status.status !== 'cancelled' &&
status.status !== 'expired' &&
maxRetries > 0
) {
await new Promise((resolve) => setTimeout(resolve, checkInterval));
status = await this.client.beta.threads.runs.retrieve(threadId, runId);
// Handle tool calls
if (status.status === 'requires_action' && status.required_action?.type === 'submit_tool_outputs') {
const toolCalls = status.required_action.submit_tool_outputs.tool_calls;
const toolOutputs = [];
for (const toolCall of toolCalls) {
if (functionUrl) {
try {
const payloadData = JSON.parse(toolCall.function.arguments);
// Add context
payloadData.remoteJid = remoteJid;
payloadData.pushName = pushName;
const response = await axios.post(functionUrl, {
functionName: toolCall.function.name,
functionArguments: payloadData,
});
toolOutputs.push({
tool_call_id: toolCall.id,
output: JSON.stringify(response.data),
});
} catch (error) {
this.logger.error(`Error calling function: ${error}`);
toolOutputs.push({
tool_call_id: toolCall.id,
output: JSON.stringify({ error: 'Function call failed' }),
});
}
} else {
toolOutputs.push({
tool_call_id: toolCall.id,
output: JSON.stringify({ error: 'No function URL configured' }),
});
}
}
await this.client.beta.threads.runs.submitToolOutputs(threadId, runId, {
tool_outputs: toolOutputs,
});
}
maxRetries--;
}
if (status.status === 'completed') {
const messages = await this.client.beta.threads.messages.list(threadId);
return messages;
} else {
this.logger.error(`Assistant run failed with status: ${status.status}`);
return { data: [{ content: [{ text: { value: 'Failed to get a response from the assistant.' } }] }] };
}
}
protected isImageMessage(content: string): boolean {
return content.includes('imageMessage');
}
/**
* Implementation of speech-to-text transcription for audio messages
*/
public async speechToText(msg: any, instance: any): Promise<string | null> {
const settings = await this.prismaRepository.openaiSetting.findFirst({
where: {
instanceId: instance.instanceId,
},
});
if (!settings) {
this.logger.error(`OpenAI settings not found. InstanceId: ${instance.instanceId}`);
return null;
}
const creds = await this.prismaRepository.openaiCreds.findUnique({
where: { id: settings.openaiCredsId },
});
if (!creds) {
this.logger.error(`OpenAI credentials not found. CredsId: ${settings.openaiCredsId}`);
return null;
}
let audio: Buffer;
if (msg.message.mediaUrl) {
audio = await axios.get(msg.message.mediaUrl, { responseType: 'arraybuffer' }).then((response) => {
return Buffer.from(response.data, 'binary');
});
} else if (msg.message.base64) {
audio = Buffer.from(msg.message.base64, 'base64');
} else {
// Fallback for raw WhatsApp audio messages that need downloadMediaMessage
audio = await downloadMediaMessage(
{ key: msg.key, message: msg?.message },
'buffer',
{},
{
logger: P({
customLevels: {
verbose: 15,
debug: 20,
info: 30,
warn: 40,
error: 50,
fatal: 60,
},
level: 'error',
useOnlyCustomLevels: true,
}) as any,
reuploadRequest: instance,
},
);
}
const lang = this.configService.get<Language>('LANGUAGE').includes('pt')
? 'pt'
: this.configService.get<Language>('LANGUAGE');
const formData = new FormData();
formData.append('file', audio, 'audio.ogg');
formData.append('model', 'whisper-1');
formData.append('language', lang);
const apiKey = creds?.apiKey || this.configService.get<OpenaiConfig>('OPENAI').API_KEY_GLOBAL;
const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${apiKey}`,
},
});
return response?.data?.text;
}
}
|