UNPKG

langflow-chatbot

Version:

Add a Langflow-powered chatbot to your website.

125 lines (124 loc) 6.26 kB
/** * ChatMessageProcessor is responsible for the core logic of processing user input, * managing the interaction with the LangflowChatClient (for sending messages and handling stream events), * and coordinating UI updates through callbacks. * * Its main responsibilities include: * - Receiving raw message text from the user. * - Determining whether to use streaming or non-streaming mode based on configuration. * - Interacting with `LangflowChatClient` to send the message and receive responses (either full or streamed chunks). * - Handling various stream events (`token`, `error`, `end`, `stream_started`, `add_message`) to update the UI progressively. * - Managing the display of "thinking" indicators during bot processing. * - Updating the session ID based on responses from the Langflow backend. * - Relaying UI changes (like adding messages, updating content, disabling/enabling input) to the main ChatWidget or other UI controller via the `MessageProcessorUICallbacks`. * - Encapsulating the logic for both successful message exchanges and error handling during communication. */ import { LangflowChatClient } from '../clients/LangflowChatClient'; import { Logger } from '../utils/logger'; import { SenderConfig } from '../types'; import { IMessageParser } from './messageParsers/IMessageParser'; export interface MessageProcessorUICallbacks { addMessage: (sender: string, message: string, isThinking?: boolean, datetime?: string) => HTMLElement | null; updateMessageContent: (element: HTMLElement, htmlOrText: string) => void; removeMessage: (element: HTMLElement) => void; getBotMessageElement: () => HTMLElement | null; setBotMessageElement: (element: HTMLElement | null) => void; scrollChatToBottom: () => void; updateSessionId: (sessionId: string, notify?: boolean) => void; setInputDisabled: (disabled: boolean) => void; } export declare class ChatMessageProcessor { private chatClient; private config; private logger; private ui; private messageParser; private getEnableStream; private getCurrentSessionId; /** * Constructs a ChatMessageProcessor. * @param chatClient The client for interacting with the Langflow API. * @param config Configuration defining the sender names/roles (e.g., user, bot, error, system). * @param logger Logger instance for logging messages. * @param ui Callbacks for UI interactions related to message processing. * @param messageParser The message parser for parsing messages. * @param getEnableStream Function to dynamically get the current stream enabled status. * @param getCurrentSessionId Function to dynamically get the current session ID. */ constructor(chatClient: LangflowChatClient, config: SenderConfig, logger: Logger, ui: MessageProcessorUICallbacks, messageParser: IMessageParser, getEnableStream: () => boolean, getCurrentSessionId: () => string | null); /** * Displays the initial "thinking" indicator in the UI. */ private displayInitialThinkingIndicator; /** * Main public method to process a user's message. * It disables input, determines streaming vs. non-streaming, calls the appropriate handler, * and re-enables input. * @param messageText The text of the message from the user. */ process(messageText: string): Promise<void>; /** * Attempts to update an existing "thinking" message bubble to display an error. * @param baseErrorMessage The main error message text. * @param detailErrorMessage Optional additional details for the error. * @returns True if a thinking bubble was successfully updated to an error, false otherwise. */ private tryUpdateThinkingToError; /** * Handles the message processing logic when streaming is enabled. * Iterates through stream events, updates UI progressively, and handles errors/completion. * @param messageText The user's message text. * @param sessionIdToSend The session ID to use for the request. */ private handleStreamingResponse; /** * Clears the "thinking" indicator from a message element if conditions are met * (e.g., content starts streaming, or an error/end event occurs). * @param event The current stream event. * @param currentBotElement The current bot message HTML element. * @param accumulatedResponse The accumulated response text so far. */ private clearThinkingIndicatorIfNeeded; /** * Processes an individual stream event by dispatching to event-specific handlers. * @param event The stream event to process. * @param accumulatedResponse The accumulated response string before this event. * @returns The updated accumulated response string. */ private processStreamEvent; /** * Handles a 'token' event from the stream. * Appends the token to the accumulated response and updates the UI. * @param data The data associated with the token event. * @param accumulatedResponse The response accumulated so far. * @returns The new accumulated response. */ private handleStreamTokenEvent; /** * Handles an 'error' event from the stream. * Updates the UI to display the error. * @param data The data associated with the error event. */ private handleStreamErrorEvent; /** * Handles an 'add_message' event from the stream (e.g. for auxiliary messages). * Currently, it only logs the event. * @param data The data associated with the add_message event. */ private handleStreamAddMessageEvent; /** * Handles an 'end' event from the stream. * Finalizes the message content in the UI and updates the session ID. * @param data The data associated with the end event. * @param accumulatedResponse The total response accumulated from tokens. */ private handleStreamEndEvent; /** * Handles the message processing logic when streaming is disabled. * Sends the message, waits for a full response, and updates the UI. * @param messageText The user's message text. * @param sessionIdToSend The session ID to use for the request. */ private handleNonStreamingResponse; }