Skip to content

AI Chat New

The AI Chat element gives you a complete, assistant-style chat interface with a built-in input bar, message grouping, date separators, optional markdown rendering, file attachments, and the streming of responses.

Features

  • Assistant-style chat: Messages have a clear user vs assistant role with grouped bubbles and timestamps
  • Streaming response support: Show partial assistant output via isStreaming and streamingText
  • Markdown rendering: Optional markdown with syntax highlighting in assistant and user messages
  • Attachments: Show image previews, file name and size, and a pending attachments strip before sending
  • Flexible data mapping: Map your own fields to id, content, role, timestamp, and attachments
  • Auto-scroll control: Choose default instant or smooth scrolling; programmatic Scroll to bottom action

Getting started

Using AI

The quickest way to set up AI Chat is by using AI:

  1. Ask AI to add the AI Chat element. Be sure to specify:

    • which array you want to bind to Messages
    • your User Label and Assistant Label
    • whether to enable Allow Attachments
    • styling preferences (message colors, borders, rounded corners)
  2. The AI will create a styled chat bound to your data and set up the basics:

  3. Continue refining by asking for specific updates:

    • "Turn on markdown and make code blocks monospace"
    • "Use smooth auto-scroll on new messages"
    • "Make my messages have a subtle border and 18px radius"

Manual setup

  1. Add the AI Chat element to your page from the Add panel
  2. Bind Messages to your array of chat message objects
  3. In Mapping, set:
    • Message ID (unique id)
    • Message Text
    • Message Role (use user or assistant)
    • Timestamp
    • (optional) Attachments
  4. Set labels in Chat Settings:
    • User Label
    • Assistant Label
  5. (Optional) Toggle Enable Markdown and Allow Attachments
  6. Adjust styling in the Style panel for messages, the input area, and action buttons

Binding messages

Bind Messages to an array. If your field names differ, use the mapping properties.

Click to view example messages data
json
[
  {
    "id": "m-1",
    "content": "Hi there!",
    "role": "assistant",
    "timestamp": "2025-10-02T10:30:00Z"
  },
  {
    "id": "m-2",
    "content": "Can you summarize my notes?",
    "role": "user",
    "timestamp": "2025-10-02T10:31:10Z"
  },
  {
    "id": "m-3",
    "content": "Sure — upload them as a file and I can help.",
    "role": "assistant",
    "timestamp": "2025-10-02T10:31:40Z"
  }
]

Attachment objects

When you include attachments in a message, each attachment is an object:

json
{
  "id": "file-1",
  "name": "notes.pdf",
  "url": "https://example.com/files/notes.pdf",
  "type": "application/pdf",
  "size": 532188
}

The fields of the attachment are used to show previews of the attachment insde the chat.

Sending messages and attachments

Use the On message sent trigger to save messages:

  1. Create a workflow on the chat element using On message sent
  2. Save the core data of the new message to your backend (such as the text of the message input)
  3. After a successful response, refetch or update the data bound to Messages

MESSAGE SENDING LOGIC WALKTHROUGH

For a full, practical walkthrough on setting up the logic to handle the message sending, check out this video:

Sending attachments

The sending of attachments can be fairly complicated, particularly if you are sending the attachments to an LLM, as every LLM will have their own unique way they wish for the messages and attachments to be structured.

However, the base premise of setting up logic to handle attachments is th following:

  1. Looping through all uploaded attachments, and encoding each as a data URL, so that we can send this data URL to external services, such as an LLM for processing or our backend for saving

  2. Saving the the data URL in the attachments field of the new message we save

  3. Re-formatting our list of messages into the format our LLM expects (format differs for each LLM)

  4. Saving the new messages in our backend, along with their respective attachments

ATTACHMENT HANDLING LOGIC WALKTHROUGH

Here is a guide on how to set up attachment handling when using OpenAI:

Click to view javascript used in video to format messages for OpenAI
javascript
function convertToOpenAIFormat(messages) {
  return messages.map(msg => {
    // Start building the content array
    const content = [];

    // If there’s text content, include it
    if (msg.content) {
      content.push({
        type: "text",
        text: msg.content
      });
    }

    // If there are attachments, include them as image_url blocks
    if (msg.attachments && Array.isArray(msg.attachments)) {
      msg.attachments.forEach(att => {
        // only include if it looks like an image
        if (att.mime && att.mime.startsWith("image/")) {
          content.push({
            type: "image_url",
            image_url: {
              url: att.url
            }
          });
        }
      });
    }

    return {
      role: msg.role === "assistant" ? "assistant" : "user",
      content
    };
  });
}

// Example usage:
const rawMessages = variables['5a4d2704-186d-46c5-bf54-1f3a437b8bde']; 
const openaiMessages = convertToOpenAIFormat(rawMessages);

return((openaiMessages));

Streaming assistant responses

Use streaming for token-by-token assistant output:

  1. Set isStreaming to true while streaming is in progress
  2. Update streamingText as new characters arrive
  3. When done, set isStreaming to false and append the final assistant message to your Messages

PRINCIPLES OF STREAMING

If it is your first time streaming a response, here is a video walking through the fundamentals of streaming responses in WeWeb:

Dates and timestamps

  • Messages show per-day date separators and per-message timestamps (you can toggle visibility per role in styling)
  • The time label uses a configurable time format internally; map your timestamp in ISO format for the best results

Auto-scrolling

  • New messages scroll to the bottom automatically
  • Choose your default with Auto Scroll Behavior: Instant or Smooth
  • Use the action Scroll to bottom. Passing no argument uses the default; pass true or false to force smooth/instant

Example use cases

In-app support assistant

  1. Bind Messages to the current conversation
  2. Toggle Enable Markdown for richer replies
  3. Use On message sent to save user messages and call your AI assistant for responses

Image Q&A bot

  1. Toggle Allow Attachments so users can add images
  2. On On message sent, upload files and pass image context to your AI endpoint
  3. Stream the assistant reply using isStreaming and streamingText

Content drafting helper

  1. Enable markdown for formatted output and code blocks
  2. Provide quick-start prompt buttons outside the chat
  3. Use Scroll to bottom after inserting system-generated tips

Best practices

Do:

  • set Message Role mapping to exactly user or assistant
  • save messages in your backend on On message sent, do not rely on only saving new messages into variables on the frontend
  • enable markdown only when you want rich text or code highlighting

Don't:

  • send very large files without size checks
  • rely on only front-end variables for persistence; always save to your backend

Forking

While the AI Chat element offers extensive built-in customization options, there may be cases where you need functionality beyond what's natively available. In these situations, you can fork the element and modify it to meet your specific requirements.

If you are unsure how to fork an element, you can learn more in the dedicated documentation.

Properties reference

Settings

PropertyTypeDescription
User LabelTextDisplay name used for the current user
Assistant LabelTextDisplay name used for assistant messages
DisabledToggleDisable the input and actions
Enable MarkdownToggleRender message text as markdown with syntax highlighting
Allow AttachmentsToggleAllow users to add files when sending messages
Auto Scroll BehaviorSelectDefault: Instant or Smooth when new messages appear

Chat Data

PropertyTypeDescription
MessagesArrayCollection of messages to display
Message IDPath/FormulaField to use as message ID
Message TextPath/FormulaField to use as message content (maps to content)
Message RolePath/FormulaField to use as the message role (user or assistant)
TimestampPath/FormulaField to use as the message timestamp (ISO recommended)
AttachmentsPath/FormulaField to use as attachments (array)

Attachments Data

PropertyTypeDescription
IDPath/FormulaField to use as attachment ID
NamePath/FormulaField to use as attachment name
URLPath/FormulaField to use as attachment URL
MIME TypePath/FormulaField to use as MIME type
Size (bytes)Path/FormulaField to use as size in bytes

Styling

General

PropertyDescription
Font FamilyGlobal font for the chat interface

Messages area

PropertyDescription
Background ColorBackground color of the message list
PaddingInner padding for the message list
Empty Message TextText shown when there are no messages
Empty Message ColorColor for the empty message text

Assistant messages

PropertyDescription
Show TimestampShow/hide timestamps on assistant messages
Background ColorBackground color
Text ColorText color
Font SizeFont size
Font WeightFont weight
Font FamilyFont family
BorderBorder
Border RadiusBubble radius

Your messages

PropertyDescription
Show TimestampShow/hide timestamps on your messages
Background ColorBackground color
Text ColorText color
Font SizeFont size
Font WeightFont weight
Font FamilyFont family
BorderBorder
Border RadiusBubble radius

Input area

PropertyDescription
Background ColorBackground color of the input container
Area Border TopTop border of the input container
BorderTextarea border
Border (Hover)Textarea border on hover
Border (Focus)Textarea border on focus
Text ColorInput text color
Font SizeInput font size
Font WeightInput font weight
Font FamilyInput font family
Placeholder ColorPlaceholder text color
HeightFixed height of the textarea
Border RadiusTextarea radius
PlaceholderPlaceholder text
Action AlignmentAlign action buttons Start or End

Icons

PropertyDescription
Send IconIcon name for send
Send Icon ColorColor of send icon
Send Icon SizeSize of send icon
Attachment IconIcon name for attachment
Attachment Icon ColorColor of attachment icon
Attachment Icon SizeSize of attachment icon
Remove Attachment IconIcon for removing a pending attachment
Remove Icon ColorColor of remove icon
Remove Icon SizeSize of remove icon

Buttons

PropertyDescription
Send Button BackgroundBackground/gradient of send button
Send Button Hover BackgroundBackground/gradient on hover
Send Button BorderBorder
Send Button Border RadiusRadius
Send Button SizeWidth/height
Send Button Box ShadowShadow
Attachment Button BackgroundBackground of attachment button
Attachment Button Hover BackgroundHover background
Attachment Button BorderBorder
Attachment Button Border RadiusRadius
Attachment Button SizeWidth/height
Attachment Button Box ShadowShadow

Attachment previews (inside messages)

PropertyDescription
Attachment Max WidthMax width for image attachment previews
Attachment Max HeightMax height for image attachment previews
Attachment Min WidthMin width for image previews (useful for SVGs without intrinsic size)
Attachment Min HeightMin height for image previews (useful for SVGs without intrinsic size)
Attachment Border RadiusCorner radius for image previews

Component actions

ActionDescriptionParameters
Scroll to bottomScrolls to the latest messagesmooth (Boolean, optional). If omitted, uses Auto Scroll Behavior.
Add messageAdds a message programmaticallymessage object with { content, role, timestamp?, id? }

Exposed variables

VariableTypeDescription
chatStateObjectComplete chat state including messages and utils

Example variable values

chatState

javascript
{
  "messages": [
    {
      "id": "msg-101",
      "content": "Welcome!",
      "role": "assistant",
      "userName": "Assistant",
      "timestamp": "2025-10-02T10:30:00.000Z",
      "attachments": []
    }
  ],
  "utils": { "messageCount": 1, "isDisabled": false }
}

Event triggers

EventDescriptionPayload
messageSentFired when the user sends a message{ message }
messageReceivedFired when a new assistant message appears in Messages{ message }
messageRightClickFired on right-click on a message{ message, position: { elementX, elementY, viewportX, viewportY } }
attachmentClickFired when an attachment is clicked{ attachment }
pendingAttachmentClickFired when a pending (unsent) attachment is clicked{ attachment: File, index }

Example event payloads

messageSent

javascript
{
  "message": {
    "id": "msg-7f3a",
    "content": "Got it, thanks!",
    "role": "user",
    "timestamp": "2025-10-02T10:35:00.000Z",
    "attachments": [
      { "id": "file-1", "name": "notes.pdf", "type": "application/pdf", "size": 532188, "url": "blob:https://..." }
    ]
  }
}

messageReceived

javascript
{
  "message": {
    "id": "msg-7f3b",
    "content": "Here is the summary...",
    "role": "assistant",
    "timestamp": "2025-10-02T10:35:05.000Z",
    "attachments": []
  }
}

messageRightClick

javascript
{
  "message": {
    "id": "msg-7f3a",
    "content": "Got it, thanks!",
    "role": "user",
    "timestamp": "2025-10-02T10:35:00.000Z"
  },
  "position": { "elementX": 120, "elementY": 24, "viewportX": 320, "viewportY": 480 }
}

attachmentClick

javascript
{
  "attachment": {
    "id": "file-9",
    "name": "guide.pdf",
    "url": "https://...",
    "type": "application/pdf",
    "size": 532188
  }
}

pendingAttachmentClick

javascript
{
  "attachment": File,
  "index": 0
}

Frequently asked questions

How do I save messages?

Use the On message sent event. Send event.message to your backend, then refetch or update the data bound to Messages so the UI reflects the latest conversation.

For an in-depth guide on saving messages, see this video:

How do I implement streaming?

While your backend is generating a reply, set isStreaming = true and update streamingText as output arrives. When done, set isStreaming = false and append the final assistant message to Messages.

How do attachments work?

When Allow Attachments is enabled, users can add files before sending. The On message sent payload includes attachment metadata. If you need the underlying File object before sending, listen to On pending attachment click.

For an in-depth guide on handling attachments, see this video: