> ## Documentation Index
> Fetch the complete documentation index at: https://docs.flowx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat component

> Technical reference for the Chat component - runtime behavior, session management, workflows, and SDK integration.

The Chat component enables interactive AI agent conversations with end-users within FlowX apps. This page covers runtime behavior, session management, and advanced integration patterns.

<Frame>
  <video controls autoPlay muted loop className="w-full aspect-video" src="https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/5.x/chat_comp.mp4" />
</Frame>

<Info>
  For UI configuration, settings, and styling, see the [Chat component in UI Designer](/5.9/docs/building-blocks/ui-designer/ui-component-types/chat).
</Info>

## Key features

<CardGroup cols={2}>
  <Card title="Real-time messaging" icon="bolt">
    Send and receive messages instantly with streaming support
  </Card>

  <Card title="AI agent integration" icon="robot">
    Connect to workflows powered by AI agents
  </Card>

  <Card title="Session management" icon="id-badge">
    Automatic session handling and persistence across page refreshes
  </Card>

  <Card title="Message history" icon="clock-rotate-left">
    Retrieve and display conversation history on refresh
  </Card>

  <Card title="Knowledge Base integration" icon="database">
    Ground AI responses in your organization's data using RAG capabilities
  </Card>

  <Card title="Reasoning transparency" icon="brain">
    Show AI reasoning steps to users for trust and transparency
  </Card>

  <Card title="Flexible display modes" icon="layout">
    Inline, Overlay, FullScreen, and Floating modes with per-mode theming for Web, Android, and iOS
  </Card>
</CardGroup>

***

## Display modes

<Info>
  The Chat component supports four distinct display modes, including mobile chat support.
</Info>

When adding a Chat component, you choose a **display mode** that determines how the chat renders and behaves at runtime.

| Display mode   | Description                                                | Placement                      |
| -------------- | ---------------------------------------------------------- | ------------------------------ |
| **Inline**     | Renders in place within the page layout (default)          | Child of any container or card |
| **Overlay**    | Positioned overlay panel with minimize and expand controls | Child of Page or Root Zone     |
| **FullScreen** | Takes over the full viewport                               | Child of Page or Root Zone     |
| **Floating**   | Floating panel triggered by a FAB (Floating Action Button) | Child of Page or Root Zone     |

<Info>
  You can change the display mode after creation if needed.
</Info>

### Mode details

<Tabs>
  <Tab title="Inline">
    Renders within the parent component, filling the available space. This is the default mode.

    * Can be a child of **any container or card**
    * Embeds directly into the page layout
    * Best for dedicated chat pages or inline chat experiences
    * Width and height follow the parent container; supports **Fill** or **Fixed** sizing
  </Tab>

  <Tab title="Overlay">
    Renders as a positioned panel on top of the page content, with controls to minimize or expand.

    * Must be a child of **Page** or **Root Zone** (global scope)
    * Includes minimize and expand buttons in the chat header
    * Useful when the chat should be accessible without leaving the current page context
  </Tab>

  <Tab title="FullScreen">
    Takes over the full viewport when opened.

    * Must be a child of **Page** or **Root Zone**
    * Provides an immersive, distraction-free chat experience
    * Triggered via the chat header button or a FAB
    * Automatically dismissed when the user closes or navigates away
  </Tab>

  <Tab title="Floating">
    Renders as a floating panel anchored to a corner of the screen. Triggered by a **Floating Action Button (FAB)**.

    * Must be a child of **Page** or **Root Zone**
    * FAB defaults to bottom-right position (`right: 24px`, `bottom: 24px`)
    * FAB dimensions: `56 × 56px` (configurable)
    * Chat panel defaults: `420px` wide, `640px` tall
    * Best for persistent, always-accessible chat without interrupting main content
  </Tab>
</Tabs>

### Sizing defaults

| Display mode   | Default width   | Default height  | Notes                                |
| -------------- | --------------- | --------------- | ------------------------------------ |
| **Inline**     | Fill (parent)   | Fill (parent)   | Supports Fill or Fixed sizing        |
| **Overlay**    | Configurable    | Configurable    | Positioned over content              |
| **FullScreen** | Full viewport   | Full viewport   | No sizing controls                   |
| **Floating**   | `420px` (fixed) | `640px` (fixed) | FAB at `right: 24px`, `bottom: 24px` |

### Theming per display mode

Theme values can be set independently for each display mode and per platform (Web, Android, iOS) through **Design Assets** → **Themes** → **Components** → **Chat**.

| Platform    | Configurable modes           |
| ----------- | ---------------------------- |
| **Web**     | Inline, Floating, FullScreen |
| **Android** | Inline, Floating, FullScreen |
| **iOS**     | Inline, Floating, FullScreen |

Each mode supports independent configuration for padding, margin, and other layout tokens.

### Chat header button and URL synchronization

The chat header includes a state-aware button that adapts based on the current display mode (for example, toggling between fullscreen and overlay views). Chat session state is also synchronized to the browser URL via `popstate`, so navigating back or refreshing the page restores the correct session context.

### Global component

The Chat component can be added as a **Global Component** in UI Flows, making it persist across pages without needing to add it to each page individually.

When configured as a global component:

* The chat appears in the **Global Components** section of the left navigation panel
* It persists as users navigate between pages in the UI Flow
* You can **attach** or **detach** the chat from specific pages to control where it appears
* The chat maintains its conversation state across page navigation

To add Chat as a global component, click **+** in the **Global Components** section of the UI Flow navigation panel, then select **Chat** and configure its display mode.

<Tip>
  Use Global Components when you want the chat to be available throughout the entire app experience without re-adding it to every page.
</Tip>

### Sizing

The Chat component and floating action button support **fixed sizing**, allowing you to set a specific width and/or height value for precise control over the chat container dimensions.

***

## Subcomponents

<Info>
  The Chat component includes specialized subcomponents for reasoning display, error handling, and message regeneration.
</Info>

The Chat component is composed of the following subcomponents:

| Subcomponent          | Description                                                                                                                              |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| **Header**            | Configurable header with avatar, title, subtitle, new chat button, fullscreen toggle, and dock/collapse controls                         |
| **Messages**          | Message display with sender/receiver differentiation, markdown rendering, and avatar support                                             |
| **Chat History**      | Conversation history list showing past chat sessions grouped by time, with the ability to resume previous conversations                  |
| **Suggested Prompts** | Pre-configured prompt suggestions displayed before the user types, allowing quick-start interactions                                     |
| **Reasoning**         | Displays AI reasoning steps (thinking indicators) during response generation                                                             |
| **Input**             | Message input field with configurable placeholder and multiline support. Includes a Stop button to cancel an in-progress agent response. |

### Reasoning display

The reasoning subcomponent shows users how the AI agent is processing their request. When enabled, a thinking indicator appears while the agent works through its reasoning steps.

| Property            | Description                                                      |
| ------------------- | ---------------------------------------------------------------- |
| **reasoning**       | Toggle to show/hide reasoning steps in the chat                  |
| **thinkingMessage** | Custom message to display during reasoning (e.g., "Thinking...") |

### Error handling and regeneration

When a message fails to generate, the chat displays an error state with an option to retry:

| Property            | Description                                     |
| ------------------- | ----------------------------------------------- |
| **errorMessage**    | Custom error message to display on failure      |
| **canRegenerate**   | Enable the regenerate button on failed messages |
| **regenerateLabel** | Custom label for the regenerate button          |

### Chat History

Chat History displays a list of conversations started by the current user, grouped by time period: **Today**, **Yesterday**, **Previous 7 Days**, **Previous 30 Days**, and **Older**.

<Frame>
  ![Chat History panel showing past conversations grouped by time](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/5.6/chat_history.png)
</Frame>

#### Behavior

* The chat history button is always visible in the chat header
* When opened, the list shows each conversation with its title and timestamp (displayed in a tooltip)
* Available actions: **New chat**, **Expand/Minimize**, **Dock** (hide chat)
* Opening a conversation from the list resumes the session:
  * Messages are prefilled with the last exchanged messages
  * Scrolling up loads older replies
  * New messages continue on the same session ID
* Conversations are **per-user** — attempting to access another user's history shows an access denied error and redirects to a new chat session

#### Theming

Chat History adds three new themed elements configurable per display mode (Inline, Floating, FullScreen) and per platform (Web, Android, iOS) through **Design Assets** → **Themes** → **Components** → **Chat**:

| Theme element            | Description                                                                                     |
| ------------------------ | ----------------------------------------------------------------------------------------------- |
| **Chat History**         | Container for the conversation list (padding, empty state font/color, gap)                      |
| **Chat History Section** | Time-group headers like "Today" or "Previous 7 Days" (title font/color, gap)                    |
| **Chat History Item**    | Individual conversation entry with hover state (padding, font, border radius, background color) |

Two new system icons are added: `sys_ChatHistory` and `sys_ChatBack`.

#### Localization

Chat History uses system substitution tags for all labels. Override these in **CMS** → **Substitution Tags** to customize or localize:

| Substitution tag                       | Default (EN)                                              |
| -------------------------------------- | --------------------------------------------------------- |
| `sys_chat_tooltip_chat_history`        | Chat History                                              |
| `sys_chat_tooltip_new_chat`            | New chat                                                  |
| `sys_chat_tooltip_expand`              | Expand                                                    |
| `sys_chat_tooltip_minimize`            | Exit full screen                                          |
| `sys_chat_tooltip_dock`                | Hide chat                                                 |
| `sys_chat_tooltip_back`                | Back                                                      |
| `sys_chat_time_group_today`            | Today                                                     |
| `sys_chat_time_group_yesterday`        | Yesterday                                                 |
| `sys_chat_time_group_previous_7_days`  | Previous 7 Days                                           |
| `sys_chat_time_group_previous_30_days` | Previous 30 Days                                          |
| `sys_chat_time_group_older`            | Older                                                     |
| `sys_chat_conversations_empty_state`   | No Conversations yet                                      |
| `sys_chat_forbidden`                   | Access denied. This chat history belongs to another user. |

***

### Markdown rendering in messages

Agent (receiver) messages support Markdown formatting, allowing AI-generated responses to include structured content. The renderer automatically converts Markdown syntax to styled HTML.

**Supported syntax:**

| Syntax                               | Renders as                     |
| ------------------------------------ | ------------------------------ |
| `**bold**`                           | **Bold** text                  |
| `*italic*`                           | *Italic* text                  |
| `# Heading` through `###### Heading` | Heading levels 1–6             |
| `` `inline code` ``                  | Inline code                    |
| ` ``` code block ``` `               | Fenced code block              |
| `- item` or `1. item`                | Unordered and ordered lists    |
| `[text](url)`                        | Hyperlink (opens in a new tab) |
| Single newline                       | Line break (`<br/>`)           |

<Tip>
  When building AI agent prompts, you can instruct the agent to format responses using Markdown — the chat component renders the output automatically.
</Tip>

***

### Suggested Prompts

The Suggested Prompts subcomponent displays a set of pre-configured prompt suggestions to the user before they begin typing. When a suggestion is clicked, its text is sent as the user's input, starting the conversation immediately.

<Frame>
  ![Suggested Prompts displayed in chat empty state](https://s3.eu-west-1.amazonaws.com/docx.flowx.ai/5.6/chat_suggested_prompts.png)
</Frame>

#### Props

| Property  | Type      | Default               | Description                                       |
| --------- | --------- | --------------------- | ------------------------------------------------- |
| `title`   | string    | `"Suggested Prompts"` | Section heading displayed above the prompt list   |
| `prompts` | string\[] | —                     | Array of prompt strings to display as suggestions |

#### Behavior

* The subcomponent only renders when at least one prompt is provided in the `prompts` array. If the array is empty or not set, the section is hidden entirely.
* Clicking a suggestion sends that prompt text as the user's input, triggering the chat workflow as if the user typed and submitted the message.
* Long prompt strings that exceed the display area are truncated and shown in full via a **tooltip** on hover.

#### Theming

Full theming support is available in both Angular and React SDKs. Styles can be configured per display mode (Inline, Floating, FullScreen) and per platform (Web, Android, iOS) through Theme Admin (**Design Assets** → **Themes** → **Components** → **Chat** → **Suggested Prompts**).

<Tip>
  Use suggested prompts to guide users toward the most common questions or actions in your chat experience. Keep individual prompts short and action-oriented so they remain readable without truncation.
</Tip>

#### AI-generated prompt suggestions

In addition to the static suggested prompts configured above, the chat component can display **AI-generated prompt suggestions** that are dynamically created by Custom Agent nodes in conversational workflows.

When a Custom Agent node has **Prompt Suggestions** enabled (via its satellite panel), the agent generates contextual follow-up suggestions alongside each reply. These appear as clickable chips below the agent's message, similar to static suggested prompts but tailored to the conversation context.

**Key differences from static suggested prompts:**

|                   | Static suggested prompts         | AI-generated suggestions                         |
| ----------------- | -------------------------------- | ------------------------------------------------ |
| **Source**        | Configured on the chat component | Generated by Custom Agent node per reply         |
| **When shown**    | Empty state or as configured     | After each agent reply that includes suggestions |
| **Content**       | Fixed text                       | Dynamic, context-aware                           |
| **Configuration** | Chat component settings          | Custom Agent node satellite panel                |

When a user clicks an AI-generated suggestion, the chip's `label` is displayed as the user's message while the full `content` is sent as input to the next workflow run.

For configuration details, see the [Custom Agent node documentation](/5.9/docs/platform-deep-dive/integrations/custom-agent-node#prompt-suggestions).

***

### Voice input

Users can send voice messages in addition to typed text. When voice input is enabled, a microphone button appears in the chat input. Clicking it records audio in the browser; the recording is uploaded and sent as the user's next message, appearing in the chat history as an audio player alongside text messages.

#### Enabling voice input

Voice input is configured on the **Chat Input** sub-component in UI Designer:

| Property               | Description                                    | Default |
| ---------------------- | ---------------------------------------------- | ------- |
| **Enable Voice Input** | Toggle the microphone button in the chat input | `Off`   |

When enabled, the microphone button is shown by default, the SDK handles recording, upload, and playback, and the agent receives the audio file as part of the message payload. To transcribe incoming audio or generate spoken replies from the agent side, combine voice input with the [Speech to Text node](/5.9/ai-platform/agent-builder/speech-to-text).

#### Runtime behavior

* **Recording limit:** 2 minutes per message. Longer recordings stop automatically.
* **Blocked during replies:** The microphone is disabled while the agent is streaming a response (SSE in progress) to prevent interleaved turns.
* **Single player:** Only one audio message can play at a time — starting a new playback pauses any other voice message.
* **History:** Voice messages are persisted with the rest of the conversation and replayed with a progress bar when the user scrolls back.

***

### Stop agent response

When the user presses Stop:

* The running conversational workflow is cancelled. If cancellation happens before any AI node executes, the user prompt is persisted as cancelled and no AI call is made. If it happens while an AI node is executing, the in-flight AI call is stopped and any partial response is discarded.
* The chat receives a `chatCancelled` SSE event on the `CHAT_WORKFLOW_RESPONSE` channel, signalling the UI to exit the streaming state.
* The user message is stored with a `cancelled: true` flag on the chat message record.

Stop is supported on Web (Standard, Floating, Full Screen), iOS, and Android.

For details on the underlying workflow cancel API and pre-AI vs during-AI behavior, see [Cancelling a running workflow](/5.9/ai-platform/conversational-workflows#cancelling-a-running-workflow).

#### Theming

The Stop button uses a system icon registered as `stopResponseIcon` under each chat input area. Defaults preloaded by `cms-core`:

| Theme content                                                             | Property           | Default value          |
| ------------------------------------------------------------------------- | ------------------ | ---------------------- |
| `chatInputArea`, `chatInputAreaFloating`, `chatInputAreaFullScreen` (Web) | `stopResponseIcon` | `sys_ChatStopResponse` |
| `chatInputArea` (iOS)                                                     | `stopResponseIcon` | `sys_ChatStopResponse` |
| `chatInputArea` (Android)                                                 | `stopResponseIcon` | `sys_ChatStopResponse` |

Override `stopResponseIcon` in the active theme to swap the icon, the same way you would override `sendMessageIcon` or `voiceInputIcon`.

#### Localization

The chat input action labels are configurable via system substitution tags. The `a11y` variants are used as accessibility labels (screen reader text); the non-`a11y` variants are used as visible labels and tooltips.

| Substitution tag               | Purpose                         | Default English value    |
| ------------------------------ | ------------------------------- | ------------------------ |
| `sys_chat_cancel_request`      | Stop button label               | Stop generating response |
| `sys_a11y_chat_cancel_request` | Stop button accessibility label | Stop generating response |
| `sys_chat_submit_message`      | Send button label               | Send message             |
| `sys_a11y_chat_submit_message` | Send button accessibility label | Send message             |

***

### Chat configuration

The `chatConfig` object controls the behavior and appearance of the chat:

| Property           | Type    | Description                                    |
| ------------------ | ------- | ---------------------------------------------- |
| `welcomeMessage`   | string  | Initial message shown when the chat opens      |
| `thinkingMessage`  | string  | Message displayed during AI reasoning          |
| `title`            | string  | Header title text                              |
| `subtitle`         | string  | Header subtitle text                           |
| `showChatIcon`     | boolean | Show/hide the chat icon                        |
| `showSeparator`    | boolean | Show/hide the separator between messages       |
| `newChatLabel`     | string  | Label for the new chat button                  |
| `errorMessage`     | string  | Message shown on errors                        |
| `canRegenerate`    | boolean | Enable message regeneration on failure         |
| `regenerateLabel`  | string  | Label for the regenerate button                |
| `inputPlaceholder` | string  | Placeholder text for the input field           |
| `maxInputRows`     | number  | Maximum number of rows for multiline input     |
| `historyTitle`     | string  | Title text displayed on the chat history panel |

***

## Runtime behavior

### Starting a chat

<Steps>
  <Step title="User initiates chat">
    User opens the chat from the UI Flow
  </Step>

  <Step title="API call">
    System calls the start chat API with the configured workflow
  </Step>

  <Step title="Session created">
    API returns a `chatSessionId` that is persisted for the user
  </Step>

  <Step title="Initial message">
    First message typically comes from the AI agent as a greeting or conversation starter
  </Step>
</Steps>

<Info>
  The initial system message can be configured in the workflow to provide a customized greeting or conversation starter.
</Info>

### Message exchange

<Tabs>
  <Tab title="Sending messages">
    1. User types message in input field
    2. Message is sent to the workflow via Chat Input node
    3. Workflow processes the message through AI nodes
    4. Response is returned to the chat interface
  </Tab>

  <Tab title="Receiving messages">
    * Messages appear in real-time with streaming support
    * User messages aligned to one side
    * Agent messages aligned to the other side
    * Timestamps displayed (configurable)
  </Tab>
</Tabs>

### Session management

<CardGroup cols={2}>
  <Card title="Session persistence" icon="database">
    * `sessionId` stored in browser session/local storage
    * Enables conversation continuity across page refreshes
    * Session data includes message history
  </Card>

  <Card title="Message history retrieval" icon="rotate">
    * On page refresh, system loads existing `sessionId`
    * Retrieves and displays previous messages
    * Restores conversation state automatically
  </Card>
</CardGroup>

### Data storage

Chat sessions are persisted in the **FlowX Database**:

<Info>
  Each chat session is stored as a **document** containing the complete chat history. The chat component works with the FlowX Database to save chat sessions, where each session document contains the full conversation record.
</Info>

| Data Element         | Storage Location           | Description                                             |
| -------------------- | -------------------------- | ------------------------------------------------------- |
| **Session ID**       | Browser storage + Database | Unique identifier linking client to server-side session |
| **Message history**  | FlowX Database             | Complete record of all messages in the conversation     |
| **Session metadata** | FlowX Database             | Timestamps, workflow reference, user information        |

<Tip>
  **Transparent persistence**: Message persistence to the database is handled transparently by the platform. No additional configuration is required to enable chat history storage.
</Tip>

***

## Conversation history API

FlowX provides REST API endpoints for retrieving conversation history programmatically. These are useful for building custom dashboards, analytics, or integrating conversation data into external systems.

### List conversations

Retrieve all conversations for the current authenticated user within a workspace and app.

```bash theme={"system"}
GET /api/runtime/wks/{workspaceId}/app/{appId}/conversations
```

**Path parameters:**

| Parameter     | Type | Description              |
| ------------- | ---- | ------------------------ |
| `workspaceId` | UUID | The workspace identifier |
| `appId`       | UUID | The app identifier       |

**Query parameters (optional):**

| Parameter        | Type               | Description                                   |
| ---------------- | ------------------ | --------------------------------------------- |
| `startDate`      | ISO 8601 timestamp | Filter conversations created after this date  |
| `endDate`        | ISO 8601 timestamp | Filter conversations created before this date |
| `businessCaseId` | UUID               | Filter by business case identifier            |
| `page`           | integer            | Page number for pagination                    |
| `size`           | integer            | Number of conversations per page              |

**Response:**

```json theme={"system"}
{
  "conversations": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "state": "ACTIVE",
      "createdAt": "2026-03-10T14:30:00Z",
      "summary": "Customer asked about account verification process",
      "messageCount": 12
    }
  ],
  "total": 1
}
```

### Fetch a single conversation

Retrieve a single conversation with its full message history.

```bash theme={"system"}
GET /api/runtime/wks/{workspaceId}/app/{appId}/conversations/{conversationId}
```

**Path parameters:**

| Parameter        | Type | Description                                |
| ---------------- | ---- | ------------------------------------------ |
| `workspaceId`    | UUID | The workspace identifier                   |
| `appId`          | UUID | The app identifier                         |
| `conversationId` | UUID | The conversation (chat session) identifier |

**Query parameters (optional):**

| Parameter | Type    | Description                        |
| --------- | ------- | ---------------------------------- |
| `page`    | integer | Page number for message pagination |
| `size`    | integer | Number of messages per page        |

**Response:**

```json theme={"system"}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "state": "ACTIVE",
  "summary": "Customer asked about account verification process",
  "createdAt": "2026-03-10T14:30:00Z",
  "userEmail": "user@example.com",
  "messages": [
    {
      "actor": "human",
      "message": "How do I verify my account?",
      "timestamp": "2026-03-10T14:30:05Z",
      "messageId": "msg-001"
    },
    {
      "actor": "agent",
      "message": "To verify your account, navigate to **Settings** → **Verification**...",
      "timestamp": "2026-03-10T14:30:08Z",
      "messageId": "msg-002"
    }
  ],
  "total": 2
}
```

**Error responses:**

| Status | Description                                    |
| ------ | ---------------------------------------------- |
| `404`  | Conversation not found                         |
| `403`  | User does not have access to this conversation |

<Info>
  These endpoints return conversations owned by the authenticated user only. The workspace must belong to the user's organization.
</Info>

***

## Custom chat persistence workflow

For advanced use cases where you need full control over chat session storage, you can build a custom workflow that manages chat persistence using FlowX Database. This approach allows you to:

* Customize the chat data model
* Add additional metadata to chat sessions
* Integrate with external systems
* Implement custom session management logic

### Workflow overview

The chat persistence workflow handles two main scenarios:

1. **Loading chat history** - When a user returns to an existing chat session
2. **Processing new messages** - When a user sends a new message

```mermaid theme={"system"}
flowchart TD
    A[Start] --> B[Get chat session]
    B --> C{Action type?}
    C -->|LOAD_HISTORY| D[Return chat history]
    C -->|NEW_MESSAGE| E{Session exists?}
    E -->|No| F[Create new session]
    E -->|Yes| G[Update session history]
    F --> H[Return response]
    G --> I[Update chat session]
    I --> H
```

### Setting up the FlowX database data source

<Steps>
  <Step title="Create the data source">
    Navigate to **Integrations** → **Data Sources** → **Add New Data Source** and select **FlowX Database**.
  </Step>

  <Step title="Configure the collection">
    Name the collection (e.g., `chat`) and define the schema based on your data model.
  </Step>

  <Step title="Define the data model">
    Create a data model with the following structure:

    | Field               | Type   | Description                            |
    | ------------------- | ------ | -------------------------------------- |
    | `chatSessionId`     | string | Unique identifier for the chat session |
    | `history`           | array  | List of message objects                |
    | `history[].actor`   | string | Message sender (`human` or `agent`)    |
    | `history[].message` | string | The message content                    |
  </Step>
</Steps>

### Building the workflow

<Steps>
  <Step title="Create the workflow">
    Create a new workflow in Integration Designer with the following input parameters:

    ```json theme={"system"}
    {
      "humanMessage": "",
      "action": "",
      "chatSessionId": ""
    }
    ```

    The `action` parameter determines whether to load history (`LOAD_HISTORY`) or process a new message.
  </Step>

  <Step title="Add Get chat session node">
    Add a **Database Operation** node to retrieve the existing session:

    | Property                     | Value                |
    | ---------------------------- | -------------------- |
    | **Operation**                | `db.chat.findOne`    |
    | **Description**              | Chat session history |
    | **Parameter: chatSessionId** | `${chatSessionId}`   |
    | **Response Key**             | `chatSession`        |
  </Step>

  <Step title="Add action type condition">
    Add a **Condition** node to check the action type:

    ```javascript theme={"system"}
    input.action == "LOAD_HISTORY"
    ```

    * **If true**: Route to the "Return chat history" end node
    * **Else**: Continue to message processing
  </Step>

  <Step title="Add Return chat history end node">
    For the `LOAD_HISTORY` branch, add an **End Flow** node that returns the chat history:

    ```json theme={"system"}
    {
      "history": "${chatSession.data.history}"
    }
    ```
  </Step>

  <Step title="Add session exists condition">
    For new messages, add another **Condition** node to check if the session exists:

    ```javascript theme={"system"}
    input.chatSession.data == null
    ```
  </Step>

  <Step title="Add Create chat session node">
    If the session doesn't exist, add a **Database Operation** node to create it:

    | Property                     | Value                                                  |
    | ---------------------------- | ------------------------------------------------------ |
    | **Operation**                | `db.chat.insertOne`                                    |
    | **Description**              | Create chat session                                    |
    | **Parameter: chatSessionId** | `${chatSessionId}`                                     |
    | **Parameter: history**       | `[{ "actor": "human", "message": "${humanMessage}" }]` |
    | **Response Key**             | `responseKey`                                          |
  </Step>

  <Step title="Add Update history script node">
    If the session exists, add a **Script** node to append the new messages:

    ```javascript theme={"system"}
    const history = input.chatSession.data.history;

    const updatedHistory = [
      ...history,
      { actor: "human", message: input.humanMessage },
      { actor: "agent", message: input.agentMessage }
    ];

    output.put("updatedHistory", updatedHistory);
    ```
  </Step>

  <Step title="Add Update chat session node">
    Add a **Database Operation** node to save the updated history:

    | Property                     | Value               |
    | ---------------------------- | ------------------- |
    | **Operation**                | `db.chat.updateOne` |
    | **Description**              | Update chat session |
    | **Parameter: chatSessionId** | `${chatSessionId}`  |
    | **Parameter: history**       | `${updatedHistory}` |
    | **Response Key**             | `responseKey`       |
  </Step>

  <Step title="Add Return response end node">
    Add an **End Flow** node that returns the response:

    ```json theme={"system"}
    {
      "message": {
        "chatSessionId": "${chatSessionId}",
        "agentMessage": "${agentMessage}"
      }
    }
    ```
  </Step>
</Steps>

### Chat session data model example

```json theme={"system"}
{
  "chatSessionId": "session-abc-123",
  "history": [
    {
      "actor": "human",
      "message": "Hello, I need help with my account"
    },
    {
      "actor": "agent",
      "message": "Hello! I'd be happy to help you with your account. What do you need assistance with?"
    }
  ]
}
```

***

## UI Flow integration

The Chat component integrates with UI Flows:

**Chat Component Wrapper**

* Chat component is embedded within UI Flow structure
* Follows UI template hierarchy
* Shares session context with other components

**Communication with Other Components**

<AccordionGroup>
  <Accordion title="Event-based communication" icon="broadcast-tower">
    * Components emit and listen for custom events
    * Enables loosely coupled interactions
    * Example: Chat triggers process start event
  </Accordion>

  <Accordion title="On-demand communication" icon="link">
    * Direct component-to-component calls
    * For tightly integrated features
    * Example: Chat updates task management state
  </Accordion>
</AccordionGroup>

***

## Audit and debugging

### UI Flows audit

<CardGroup cols={2}>
  <Card title="Chat sessions tracking" icon="chart-line">
    All chat sessions are logged in UI Flow audit:

    * Track when chats are started
    * Monitor active and completed sessions
    * View session duration and message count
  </Card>

  <Card title="Console logging" icon="terminal">
    Access detailed execution information:

    * View workflow execution logs
    * Debug conversation flow
  </Card>
</CardGroup>

### Debug interface

**UI Flow Sessions Console**

Access comprehensive debugging tools through the **UI Flow Sessions** panel:

<Tabs>
  <Tab title="Nodes">
    Track workflow execution with node-by-node timing:

    | Node                | Typical Duration |
    | ------------------- | ---------------- |
    | Start               | 0 ms             |
    | Get chat session    | \~133 ms         |
    | Check action type   | \~52 ms          |
    | Return chat history | \~60 ms          |
  </Tab>

  <Tab title="Logs">
    View detailed execution logs:

    * Workflow Run ID and timestamps
    * Triggered from: AUTOMATIC
    * Node execution start/finish events
    * Data Source operations (FlowX Database)
    * Collection: `chat`
    * Operations: `db.chat.findOne` - Chat session history
    * Status, Time, and Size metrics
  </Tab>

  <Tab title="Input/Output">
    Inspect workflow data:

    * Input parameters passed to the workflow
    * Output data returned from nodes
    * Session state changes
  </Tab>
</Tabs>

***

## SDK integration

The Chat component is available through the FlowX SDKs for both Angular and React applications.

<CardGroup cols={2}>
  <Card title="Angular SDK" icon="angular" href="../../sdks/angular-renderer#chat-component">
    Use the `FlxChatRendererComponent` in Angular applications

    ```ts theme={"system"}
    import { FlxChatRendererComponent } from '@flowx/angular-sdk';
    ```
  </Card>

  <Card title="React SDK" icon="react" href="../../sdks/react-renderer#chat-component">
    Use the `FlxChatRenderer` component in React applications

    ```tsx theme={"system"}
    import { FlxChatRenderer } from '@flowx/react-sdk';
    ```
  </Card>
</CardGroup>

### Key SDK parameters

| Parameter     | Description                                              | Required |
| ------------- | -------------------------------------------------------- | -------- |
| `apiUrl`      | Your base FlowX API URL                                  | ✅        |
| `authToken`   | Authorization token from auth provider                   | ✅        |
| `projectId`   | The FlowX project ID                                     | ✅        |
| `workspaceId` | The workspace ID                                         | ✅        |
| `source`      | Source object with workflow type and ID                  | ✅        |
| `chatConfig`  | Chat configuration object (welcome message, title, etc.) | ❌        |
| `themeId`     | Theme identifier for styling                             | ❌        |
| `language`    | Language for localization                                | ❌        |

<Info>
  For the complete list of parameters and usage examples, see the respective SDK documentation pages linked above.
</Info>

***

## Best practices

### Workflow design

<CardGroup cols={2}>
  <Card title="Do" icon="circle-check">
    * Keep chat workflows focused on a single use case
    * Use clear, natural language prompts
    * Test with various user inputs
    * Handle errors gracefully with helpful messages
  </Card>

  <Card title="Don't" icon="circle-xmark">
    * Don't create overly complex conversation flows
    * Don't send responses from multiple Custom Agent nodes
  </Card>
</CardGroup>

### User experience

<CardGroup cols={2}>
  <Card title="Do" icon="circle-check">
    * Provide clear initial greeting messages
    * Show typing indicators during processing
    * Display helpful error messages
    * Allow users to restart conversations
  </Card>

  <Card title="Don't" icon="circle-xmark">
    * Don't make users wait too long for responses
    * Don't use technical jargon in agent messages
    * Don't lose conversation context
  </Card>
</CardGroup>

### Performance

<CardGroup cols={2}>
  <Card title="Do" icon="circle-check">
    * Optimize workflow execution time
    * Cache frequently accessed data
    * Limit message history retrieval
  </Card>

  <Card title="Don't" icon="circle-xmark">
    * Don't load entire conversation history every time
    * Don't make unnecessary API calls
  </Card>
</CardGroup>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Chat not loading" icon="circle-exclamation">
    **Possible causes:**

    * Workflow is not properly configured
    * Workflow is not published
    * UI Flow has incorrect agent ID/workflow name

    **Solutions:**

    * Verify the workflow is properly configured
    * Check that the workflow is published and active
    * Ensure UI Flow has correct agent ID/workflow name
  </Accordion>

  <Accordion title="Messages not sending" icon="circle-exclamation">
    **Possible causes:**

    * Network connectivity issues
    * Workflow is in error state
    * Configuration errors

    **Solutions:**

    * Check network connectivity
    * Verify workflow is not in error state
    * Review workflow console logs for errors
  </Accordion>

  <Accordion title="Session lost on refresh" icon="circle-exclamation">
    **Possible causes:**

    * sessionId is not persisted in storage
    * Browser storage permissions issues

    **Solutions:**

    * Ensure sessionId is persisted in storage
    * Check browser storage permissions
    * Verify session management configuration
  </Accordion>
</AccordionGroup>

***

## Knowledge Base integration

The Chat component can use **Knowledge Bases** to provide contextual, grounded AI responses.

### How it works

<Steps>
  <Step title="Create Knowledge Base">
    Set up a Knowledge Base as a Data Source in Integration Designer and upload relevant content
  </Step>

  <Step title="Content processing">
    Documents are automatically split into "chunks" and indexed for semantic search
  </Step>

  <Step title="Link to Custom Agent">
    Connect the Knowledge Base to Custom Agent nodes in your workflow
  </Step>

  <Step title="Context retrieval">
    When a user sends a message, relevant chunks are retrieved based on semantic similarity
  </Step>
</Steps>

### Supported file formats

| Format         | Description                        |
| -------------- | ---------------------------------- |
| **PDF**        | Standard PDF documents             |
| **Markdown**   | `.md` files with formatted text    |
| **Word**       | Microsoft Word documents (`.docx`) |
| **Excel**      | Spreadsheet data (`.xlsx`)         |
| **PowerPoint** | Presentation files (`.pptx`)       |
| **Images**     | Image files with text content      |

### Configuration options

| Option                  | Description                                                     |
| ----------------------- | --------------------------------------------------------------- |
| **Minimum relevance**   | Threshold for chunk relevance scores (0-1)                      |
| **Number of responses** | Limit how many relevant chunks are returned to the LLM          |
| **Content updates**     | Use workflows to dynamically append, update, or replace content |

<Info>
  Knowledge Bases provide **Retrieval-Augmented Generation (RAG)** capabilities, ensuring AI responses are grounded in your organization's actual data.
</Info>

<Card title="Knowledge Base Documentation" icon="book" href="../docs/platform-deep-dive/integrations/knowledge-base-integration/knowledge-base-overview">
  See the complete Knowledge Base documentation for setup guides and best practices.
</Card>

***

## Platform availability

<Tabs>
  <Tab title="Web">
    * All four display modes: Inline, Overlay, FullScreen, Floating
    * Complete feature set including Suggested Prompts, Markdown rendering, and voice input
    * Angular and React renderer support
  </Tab>

  <Tab title="Mobile">
    * iOS and Android support via native renderers
    * Inline, Floating, and FullScreen display modes
    * Native chat experience optimized for mobile
    * Per-platform theme configuration (padding, margin per mode)
  </Tab>
</Tabs>

***

## Related resources

<CardGroup cols={2}>
  <Card title="Chat UI configuration" href="../docs/building-blocks/ui-designer/ui-component-types/chat" icon="palette">
    Settings, styling, and theme configuration
  </Card>

  <Card title="Chat interface concepts" href="./using-agents/chat-interface" icon="comments">
    High-level integration patterns
  </Card>

  <Card title="Custom Agent Node" href="../docs/platform-deep-dive/integrations/custom-agent-node" icon="robot">
    Custom Agent nodes in Integration Designer
  </Card>

  <Card title="Knowledge Base" href="../docs/platform-deep-dive/integrations/knowledge-base-integration/knowledge-base-overview" icon="database">
    Configure knowledge bases for grounded AI responses
  </Card>

  <Card title="Conversational workflows" href="./conversational-workflows" icon="messages">
    Build multi-turn chat experiences with session memory and intent routing
  </Card>
</CardGroup>
