Flowise Embed

repository·main·Indexed 19 days ago

https://github.com/flowiseai/flowisechatembed

A lightweight JavaScript library (v3.1.6) used to embed Flowise chatbots into websites. It supports floating popup widgets and full-page chat interfaces via Chatbot.init() and Chatbot.initFull(). The library includes features for theme customization, lead capture, chat history management via clearChat(), and an experimental Proxy Server to secure API hosts and chatflow IDs through domain-based restrictions.

Tokens
9.3K
Snippets
27
Records
39
Agent score
66%

What's inside flowise-embed

  1. What is the Flowise Embed Proxy Server?

    main

    The Flowise Embed Proxy Server is an experimental intermediary layer designed to enhance the security of your chatbot implementation. Instead of exposing sensitive Flowise instance details (like your API host and chatflow IDs) directly in your frontend code, the proxy server handles these details on the server side.

    Key Security Benefits:

    • Conceals sensitive data: Hides your Flowise API host and chatflow IDs from client-side exposure.
    • Access Control: Implements strict domain-based restrictions, ensuring only authorized websites can embed your chatbots.
    • Secure Communication: Acts as a gateway for all interactions between your website and the Flowise instance.
    • Authentication Management: Securely handles API key authentication away from the client.
  2. Configure responsive height and width for FullPage mode

    main

    The height and width options in initFull accept a number (pixels) or a CSS string.

    Common patterns:

    • 700: Fixed 700px (shrinks on small screens).
    • '700px': Fixed 700px via string.
    • '80dvh': Responsive (80% of viewport height).
    • 'min(700px, 80dvh)': Caps at 700px on large screens, shrinks on small screens.
    • '100%': Relative to the <flowise-fullchatbot> host (requires host to have explicit height).
  3. Use dialogContainer to manage Dialog Portal rendering

    main

    By default, the NodeDetailsDialog renders inside the chatbot's shadow DOM, which can cause it to appear behind other page elements. To fix this, use the dialogContainer property to render the dialog into a host-page element instead. This places the dialog in the document's stacking context so it appears on top.

    Requirements:

    • chatWindow.showAgentMessages must be true for the dialog to render.
    • The target element should be in the DOM at initialization.

    Supported modes: Works with both init (popup) and initFull (full-page).

    <!-- 1. Add a portal target -->
    <div id="flowise-portal"></div>
    
    <script type="module">
      import Chatbot from 'https://cdn.jsdelivr.net/npm/flowise-embed/dist/web.js';
    
      // 2. Pass the selector or element to dialogContainer
      Chatbot.init({
        chatflowid: '<chatflowid>',
        apiHost: 'http://localhost:3000',
        dialogContainer: '#flowise-portal', 
      });
    </script>
  4. Embed a chatbot using the Proxy Server

    main

    Once your proxy server is running, you can embed your chatbots safely by referencing an identifier defined in your .env file instead of the actual chatflowId.

    Important Requirements:

    • The import path must be your-proxy-server-url/web.js.
    • The chatflowid in Chatbot.init() must match an identifier from your .env.
    • The apiHost must match the URL of your proxy server.
    • The domain where you are embedding the script must be whitelisted in the .env file for that specific identifier.
    <script type="module">
      import Chatbot from 'your-proxy-server-url/web.js'; // Must be 'your-proxy-server-url/web.js'
      Chatbot.init({
        chatflowid: 'your-identifier-here', // Must match an identifier from your .env
        apiHost: 'your-proxy-server-url', // Must match the URL of your proxy server
        chatflowConfig: {
          // ...
        },
      });
    </script>
  5. Set up the Flowise Embed Proxy Server

    main

    To set up the proxy server, follow these steps to configure your environment and start the service.

    1. Configure Environment Variables

    Create a .env file (copy from .env.example) and set the following:

    • API_HOST: Your Flowise instance URL (e.g., https://your-flowise-instance.com).
    • FLOWISE_API_KEY: Your Flowise API key.
    • Chatflow Configuration: Define your chatbots using the format [identifier]=[chatflowId],[allowedDomain1],[allowedDomain2],....

    Example .env configuration:

    API_HOST=https://your-flowise-instance.com
    FLOWISE_API_KEY=your-api-key
    
    # identifier=chatflowId,allowedDomain1,allowedDomain2
    support=abc123-def456,https://example.com
    agent1=xyz789-uvw456,https://sales.example.com
    helpdesk=ghi123-jkl456,https://help.example.com,https://support.example.com

    Note: Identifiers are case-insensitive. Wildcard domains (*) are not supported.

    2. Install and Start

    yarn install
    yarn start

    The server will be available at http://localhost:3001 locally or your platform's URL in the cloud.

    # Configure environment
    API_HOST=https://your-flowise-instance.com
    FLOWISE_API_KEY=your-api-key
    
    # Configure chatflows
    support=abc123-def456,https://example.com
    
    # Install and start
    yarn install
    yarn start
  6. Test the Proxy Server locally

    main

    To test the proxy server and your chatbot implementation on your local machine, follow these steps:

    1. Start the Proxy Server: Run yarn start. It will be available at http://localhost:3001.
    2. Configure the Test Page: Update public/index.html to point to your local proxy.
    3. Start the Development Server: In a new terminal, run yarn dev. This serves the test page at http://localhost:5678.

    Note: The development URL http://localhost:5678 is automatically whitelisted in development mode.

    Local Configuration Examples

    For PopUp Chatbot:

    <script type="module">
      import Chatbot from './web.js';
      Chatbot.init({
        chatflowid: 'agent1', // Must match an identifier from your .env
        apiHost: 'http://localhost:3001',
      });
    </script>

    For Full Page Chatbot:

    <flowise-fullchatbot></flowise-fullchatbot>
    <script type="module">
      import Chatbot from './web.js';
      Chatbot.initFull({
        chatflowid: 'agent1', // Must match an identifier from your .env
        apiHost: 'http://localhost:3001',
      });
    </script>
    # 1. Start proxy
    yarn start
    
    # 2. Start dev server (in another terminal)
    yarn dev
  7. Install and develop Flowise Embed locally

    main

    To install the library for local development, use yarn install. To run the development server, use yarn dev. The server will run on http://localhost:5678.

    To connect the development environment directly to your Flowise instance, update public/index.html with your chatflowid and apiHost.

    yarn install
    yarn dev
  8. Handle Text-to-Speech (TTS) streaming chunks

    main

    The client implements a streaming audio playback mechanism using SourceBuffer.

    1. Initialization: When a tts_start event is received, handleTTSStart initializes the ttsStreamingState, including the audioFormat and a new chunkQueue.
    2. Chunk Processing: As tts_data events arrive, the base64 audio data is converted to a Uint8Array and appended to the chunkQueue.
    3. Buffer Management: The processChunkQueue function attempts to append the next chunk from the queue to the SourceBuffer. It monitors the updateend event on the SourceBuffer to trigger the processing of the next chunk in the queue, ensuring smooth playback without overwhelming the buffer.
  9. Configure the Chatbot theme and behavior

    main

    The Chatbot.init() method accepts a large configuration object to customize the UI. Key sections include:

    • pageTitle: Browser tab title.
    • chatflowConfig: Configuration passed to the chatflow.
    • observersConfig: Callbacks for monitoring chatbot signals (observeUserInput, observeMessages, observeLoading).
    • theme: Extensive styling for button, tooltip, disclaimer, form, and chatWindow.
    • chatWindow: Controls visibility of titles, agent messages, welcome messages, error messages, and starter prompts. It also manages height, width, and clearChatOnReload.
    <script type="module">
      import Chatbot from 'https://cdn.jsdelivr.net/npm/flowise-embed/dist/web.js';
      Chatbot.init({
        chatflowid: '91e9c803-5169-4db9-8207-3c0915d71c5f',
        apiHost: 'http://localhost:3000',
        theme: {
          chatWindow: {
            title: 'Flowise Bot',
            welcomeMessage: 'Hello!',
            starterPrompts: ['What is a bot?'],
            // ... other options
          },
          button: {
            backgroundColor: '#3B81F6',
            autoWindowOpen: { autoOpen: true, openDelay: 2 }
          }
        }
      });
    </script>
  10. Configure file uploads for RAG and Full Upload types

    main

    Flowise Embed supports two primary modes for handling file uploads, which are determined by the fullFileUpload configuration:

    1. Full File Upload (file:full)

    When fullFileUpload is enabled, files are sent as FormData to the createAttachmentWithFormData endpoint. The server processes these files and returns extracted content, which is then used in the chat context.

    2. RAG File Upload (file:rag)

    When fullFileUpload is disabled and isRAGFileUploadAllowed is true, files are sent via upsertVectorStoreWithFormData. This mode is intended for uploading documents to a vector store to be used for Retrieval Augmented Generation (RAG). There is a built-in delay (approx. 2.5s) to allow for vector store updates before the next interaction.

    Upload Validation

    Uploads are validated against uploadsConfig:

    • Images: Checked against isImageUploadAllowed and imgUploadSizeAndTypes (which defines maxUploadSize and allowed fileTypes).
    • RAG Files: Checked against isRAGFileUploadAllowed and fileUploadSizeAndTypes (supports specific extensions or * for all).
  11. Understand the EventStream payload events

    main

    The Flowise Embed client uses an EventStream (SSE) to receive real-time updates from the chatflow. The following payload.event types are processed during a streaming session:

    EventDescription
    startInitiates the streaming session and adds an empty apiMessage to the chat history.
    tokenUpdates the current message with a new text token.
    sourceDocumentsUpdates the current message with retrieved source documents.
    usedToolsUpdates the current message with information about tools used by the agent.
    fileAnnotationsUpdates the current message with file annotations.
    agentReasoningUpdates the current message with the agent's reasoning steps.
    thinkingHandles the agent's 'thinking' state, including duration.
    agentFlowEventUpdates the current message with agent flow events.
    agentFlowExecutedDataUpdates the current message with executed data from an agent flow.
    actionUpdates the current message with an available action.
    artifactsUpdates the current message with generated artifacts.
    metadataUpdates the message metadata.
    errorStops streaming and displays an error message.
    abortStops streaming and aborts the current message.
    endFinalizes the message, adds it to the chat history, and closes the response.
    tts_startInitiates Text-to-Speech playback.
    tts_dataReceives a chunk of audio data for TTS.
    tts_endSignals the end of TTS playback.
    tts_abortAborts the current TTS playback.
  12. Embed a PopUp chatbot in your HTML

    main

    Use Chatbot.init() to display a floating chatbot widget (PopUp mode). You must provide the chatflowid and the apiHost of your Flowise instance.

    <script type="module">
      import Chatbot from 'https://cdn.jsdelivr.net/npm/flowise-embed/dist/web.js';
      Chatbot.init({
        chatflowid: '<chatflowid>',
        apiHost: 'http://localhost:3000',
      });
    </script>