Skip to content

Refatoração da funcionalidade de chatbots (em andamento) #1482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 21, 2025

Conversation

gomessguii
Copy link
Contributor

@gomessguii gomessguii commented May 21, 2025

Summary by Sourcery

Refactor chatbot integrations to remove duplication and centralize common logic.

Enhancements:

  • Introduce BaseChatbotService and BaseChatbotController to consolidate shared chatbot functionality across all integrations
  • Update Openai/Dify/N8n/Evoai services to extend the base service and simplify session, message, and media handling
  • Refactor Openai/Dify/N8n/Evoai controllers to extend the base controller for unified bot management, settings, and event emission
  • Convert chatbot-specific DTOs to extend shared BaseChatbotDto and BaseChatbotSettingDto to standardize configuration fields

…on capabilities

- Introduced a base structure for chatbot integrations, including BaseChatbotController and BaseChatbotService.
- Added common DTOs for chatbot settings and data to streamline integration processes.
- Updated existing chatbot controllers (Dify, Evoai, N8n) to extend from the new base classes, improving code reusability and maintainability.
- Enhanced media message handling across integrations, including audio transcription capabilities using OpenAI's Whisper API.
- Refactored service methods to accommodate new message structures and improve error handling.
… transcription handling

- Updated OpenaiService and related classes to enhance the initialization process by ensuring the correct order of parameters.
- Simplified audio message handling by consolidating transcription logic and improving error handling.
- Refactored the OpenaiController to utilize the new structure, ensuring better integration with the base chatbot framework.
- Enhanced logging for better traceability during audio processing and API interactions.
Copy link
Contributor

sourcery-ai bot commented May 21, 2025

Reviewer's Guide

This PR centralizes duplicated chatbot logic into reusable base classes, refactors each integration’s controllers and services to extend these abstractions, and updates DTOs and channel code to conform to the new unified architecture.

Sequence Diagram for OpenaiService Audio Transcription (speechToText)

sequenceDiagram
    participant CS as ChannelService (e.g., BaileysStartupService)
    participant OS as OpenaiService
    participant ConfS as ConfigService
    participant Axios as HTTP Client (axios)
    participant OAI as OpenAI API

    CS->>OS: speechToText(msgOrBuffer, updateMediaMessage?)
    activate OS
        OS->>OS: getAudioBufferFromMsg(msgOrBuffer, updateMediaMessage?)
        OS-->>OS: audioBuffer
        OS->>OS: processAudioTranscription(audioBuffer)
        activate OS
            alt client already initialized with API key
                note right of OS: Use existing API key from client
            else
                OS->>ConfS: get("OPENAI").API_KEY
                ConfS-->>OS: apiKey
            end
            OS->>Axios: POST /v1/audio/transcriptions (formData with audioBuffer, model, lang)
            activate Axios
                Axios->>OAI: Transcribe Audio Request
                OAI-->>Axios: Transcription Response
            Axios-->>OS: { text: "transcribed_text" }
            deactivate Axios
        OS-->>OS: "transcribed_text"
        deactivate OS
    OS-->>CS: "transcribed_text"
    deactivate OS
Loading

Class Diagram for Chatbot Refactoring

classDiagram
    class BaseChatbotDto {
      +enabled: boolean
      +description: string
      +expire: number
      +keywordFinish: string[]
      +delayMessage: number
      +unknownMessage: string
      +listeningFromMe: boolean
      +stopBotFromMe: boolean
      +keepOpen: boolean
      +debounceTime: number
      +triggerType: TriggerType
      +triggerOperator: TriggerOperator
      +triggerValue: string
      +ignoreJids: string[]
      +splitMessages: boolean
      +timePerChar: number
    }
    class OpenaiDto {
      +openaiCredsId: string
      +botType: string
      +assistantId: string
      +functionUrl: string
      +model: string
      +systemMessages: string[]
      +assistantMessages: string[]
      +userMessages: string[]
      +maxTokens: number
    }
    class DifyDto {
      +botType: $Enums.DifyBotType
      +apiUrl: string
      +apiKey: string
    }
    BaseChatbotDto <|-- OpenaiDto
    BaseChatbotDto <|-- DifyDto

    class BaseChatbotSettingDto {
      +expire: number
      +keywordFinish: string[]
      +delayMessage: number
      +unknownMessage: string
      +listeningFromMe: boolean
      +stopBotFromMe: boolean
      +keepOpen: boolean
      +debounceTime: number
      +ignoreJids: string[]
      +splitMessages: boolean
      +timePerChar: number
      +fallbackId: string
    }
    class OpenaiSettingDto {
      +openaiCredsId: string
      +openaiIdFallback: string
      +speechToText: boolean
    }
    BaseChatbotSettingDto <|-- OpenaiSettingDto

    class BaseChatbotService {
        <<abstract>>
        #prismaRepository: PrismaRepository
        #configService: ConfigService
        #logger: Logger
        +constructor(waMonitor, prismaRepository, loggerName, configService)
        #getBotType(): string
        +createNewSession(instance, data, type)
        #initClient(apiKey: string)
        +sendMessageWhatsApp(instance, remoteJid, message, settings)
        +speechToText(msgOrBuffer, updateMediaMessage) : Promise~string~
        #getAudioBufferFromMsg(msg, updateMediaMessage) : Promise~Buffer~
        #processAudioTranscription(audioBuffer: Buffer) : Promise~string~
    }
    class OpenaiService {
        #client: OpenAI
        +constructor(waMonitor, prismaRepository, configService)
        #getBotType(): string
        +createNewSession(instance, data)
        #initClient(apiKey: string) : OpenAI
        +process(instance, remoteJid, bot, session, settings, content, pushName, msg) : Promise~void~
        #sendMessageToBot(instance, session, settings, bot, remoteJid, pushName, content, msg) : Promise~void~
        #processAssistantMessage(instance, session, openaiBot, remoteJid, pushName, fromMe, content, msg) : Promise~string~
        #processChatCompletionMessage(instance, openaiBot, remoteJid, content, msg) : Promise~string~
        +speechToText(msgOrBuffer, updateMediaMessage) : Promise~string~
    }
    BaseChatbotService <|-- OpenaiService

    class BaseChatbotController {
        <<abstract>>
        #service: BaseChatbotService
        #prismaRepository: PrismaRepository
        #integrationName: string
        +constructor(service, prismaRepository, waMonitor, integrationName)
        #getFallbackBotId(settings: any): string
        #getIntegrationType(): string
        #getAdditionalBotData(data: BaseChatbotDto): Record~string, any~
        #getAdditionalUpdateFields(data: BaseChatbotDto): Record~string, any~
        +createBot(instance, data: BaseChatbotDto)
        +updateBot(instance, botId, data: BaseChatbotDto)
        +emit(data: any)
        #processBot(instance, remoteJid, bot, session, settings, content, pushName, msg) : Promise~void~
    }
    class OpenaiController {
        #openaiService: OpenaiService
        +constructor(openaiService, prismaRepository, waMonitor)
        #getIntegrationType(): string
        #getAdditionalBotData(data: OpenaiDto): Record~string, any~
        #processBot(instance, remoteJid, bot, session, settings, content, pushName, msg) : Promise~void~
        +createOpenaiCreds(instance, data: OpenaiCredsDto)
        +getModels(instance)
    }
    class DifyController {
        #difyService: DifyService
        +constructor(difyService, prismaRepository, waMonitor)
        #getIntegrationType(): string
        #getAdditionalBotData(data: DifyDto): Record~string, any~
        #processBot(instance, remoteJid, bot, session, settings, content, pushName, msg) : Promise~void~
    }
    BaseChatbotController <|-- OpenaiController
    BaseChatbotController <|-- DifyController

    class ChannelStartupService {
        +openaiService: OpenaiService
    }
    class BaileysStartupService {
        +onMessage(received)
    }
    ChannelStartupService <|-- BaileysStartupService
    BaileysStartupService ..> OpenaiService : uses speechToText()
Loading

File-Level Changes

Change Details Files
Introduce BaseChatbotController abstraction
  • Extract common CRUD, settings, session and emit logic into an abstract controller base
  • Define abstract hooks for integration-specific bot data, validation, and processing
  • Standardize fallbacks, trigger handling, and ignore-jid logic across integrations
src/api/integrations/chatbot/base-chatbot.controller.ts
Introduce BaseChatbotService abstraction
  • Extract shared session management, speech-to-text (Whisper), media handling, and WhatsApp response formatting
  • Provide template methods for integration-specific bot types and API calls
  • Unify sendMessageWhatsApp and initNewSession workflows
src/api/integrations/chatbot/base-chatbot.service.ts
Refactor integration controllers to extend BaseChatbotController
  • Openai, Dify, N8n and Evoai controllers now subclass the base controller
  • Remove duplicated methods (createBot, updateBot, settings, sessions, emit)
  • Implement only integration-specific hooks and validation
src/api/integrations/chatbot/openai/controllers/openai.controller.ts
src/api/integrations/chatbot/dify/controllers/dify.controller.ts
src/api/integrations/chatbot/n8n/controllers/n8n.controller.ts
src/api/integrations/chatbot/evoai/controllers/evoai.controller.ts
Refactor integration services to extend BaseChatbotService
  • Openai, Dify, N8n and Evoai services now subclass the base service
  • Remove duplicated sendMessage, session and transcription code
  • Override getBotType, sendMessageToBot and process methods only
src/api/integrations/chatbot/openai/services/openai.service.ts
src/api/integrations/chatbot/dify/services/dify.service.ts
src/api/integrations/chatbot/n8n/services/n8n.service.ts
src/api/integrations/chatbot/evoai/services/evoai.service.ts
Unify DTO definitions via BaseChatbotDto and BaseChatbotSettingDto
  • All integration DTOs now extend common base DTOs
  • Removed per-integration settings fields and duplicated definitions
  • Added placeholder comments for integration-specific properties
src/api/integrations/chatbot/base-chatbot.dto.ts
src/api/integrations/chatbot/openai/dto/openai.dto.ts
src/api/integrations/chatbot/dify/dto/dify.dto.ts
src/api/integrations/chatbot/n8n/dto/n8n.dto.ts
src/api/integrations/chatbot/evoai/dto/evoai.dto.ts
Update channel services and dependency injection
  • Altered speechToText signature to accept a single argument
  • Updated WhatsApp Business, Baileys and Evolution channel code to call new method signature
  • Reordered constructor parameters in server.module.ts and channel.service.ts
src/api/integrations/channel/meta/whatsapp.business.service.ts
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/integrations/channel/evolution/evolution.channel.service.ts
src/api/server.module.ts
src/api/services/channel.service.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@DavidsonGomes DavidsonGomes merged commit 09120aa into EvolutionAPI:develop May 21, 2025
1 check failed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants