Documentation
Components
Chat

Chat Component

The Chat component is the main container that orchestrates the entire chat interface. It combines messages, input, and configuration into a complete chat experience.

Import

import { Chat } from 'aichatkit'

Usage

Basic Example

basic-chat.tsx
import { Chat } from 'aichatkit'
import { useState } from 'react'
 
function BasicChat() {
  const [messages, setMessages] = useState([
    {
      id: '1',
      role: 'assistant',
      content: 'Hello! How can I help you today?',
      timestamp: new Date()
    }
  ])
 
  const handleSendMessage = (content: string) => {
    const newMessage = {
      id: Date.now().toString(),
      content,
      role: 'user' as const,
      timestamp: new Date()
    }
    setMessages(prev => [...prev, newMessage])
  }
 
  return (
    <Chat 
      messages={messages}
      onSendMessage={handleSendMessage}
    />
  )
}

With Configuration

configured-chat.tsx
<Chat 
  messages={messages}
  onSendMessage={handleSendMessage}
  config={{
    placeholder: "Type your message...",
    enableFileUpload: true,
    enableRetry: true,
    enableEdit: true,
    enableCopy: true,
    maxLength: 2000,
    showTimestamps: true,
    showAvatars: true
  }}
  isThinking={false}
  className="custom-chat"
/>

Streaming Messages

streaming-chat.tsx
function StreamingChat() {
  const [messages, setMessages] = useState([])
  const [isThinking, setIsThinking] = useState(false)
  const [streamingMessageId, setStreamingMessageId] = useState(null)
 
  const handleSendMessage = async (content: string) => {
    // Add user message
    const userMessage = {
      id: Date.now().toString(),
      content,
      role: 'user' as const,
      timestamp: new Date()
    }
    setMessages(prev => [...prev, userMessage])
    setIsThinking(true)
 
    // Create streaming assistant message
    const assistantId = (Date.now() + 1).toString()
    const assistantMessage = {
      id: assistantId,
      content: '',
      role: 'assistant' as const,
      timestamp: new Date()
    }
    setMessages(prev => [...prev, assistantMessage])
    setStreamingMessageId(assistantId)
 
    // Simulate streaming response
    const response = await streamAIResponse(content)
    for await (const chunk of response) {
      setMessages(prev => 
        prev.map(msg => 
          msg.id === assistantId 
            ? { ...msg, content: msg.content + chunk }
            : msg
        )
      )
    }
 
    setIsThinking(false)
    setStreamingMessageId(null)
  }
 
  return (
    <Chat 
      messages={messages}
      onSendMessage={handleSendMessage}
      isThinking={isThinking}
      streamingMessageId={streamingMessageId}
    />
  )
}

API Reference

Props

PropTypeDefaultDescription
messagesMessage[][]Array of message objects to display
onSendMessage(content: string) => void-Callback when user sends a message
configChatConfig{}Configuration options for the chat
isThinkingbooleanfalseShows thinking indicator when AI is processing
streamingMessageIdstring-ID of message currently being streamed
classNamestring-Additional CSS classes
styleCSSProperties-Inline styles

Message Type

interface Message {
  id: string
  role: 'user' | 'assistant' | 'system' | 'error'
  content: string
  timestamp: Date
  metadata?: {
    tokens?: number
    model?: string
    cost?: number
    attachments?: Attachment[]
  }
}

ChatConfig Type

interface ChatConfig {
  // Input configuration
  placeholder?: string
  maxLength?: number
  enableFileUpload?: boolean
  acceptedFileTypes?: string[]
  maxFileSize?: number
  
  // Message configuration
  enableRetry?: boolean
  enableEdit?: boolean
  enableCopy?: boolean
  enableDelete?: boolean
  
  // Display configuration
  showTimestamps?: boolean
  showAvatars?: boolean
  showTokenCount?: boolean
  
  // Behavior configuration
  autoFocus?: boolean
  submitOnEnter?: boolean
  clearOnSubmit?: boolean
}

Message Actions

The Chat component automatically handles message actions based on configuration:

Copy Messages

config={{
  enableCopy: true // Adds copy button to messages
}}

Retry Failed Messages

config={{
  enableRetry: true // Adds retry button to failed messages
}}

Edit User Messages

config={{
  enableEdit: true // Allows editing user messages
}}

File Upload

Enable file upload functionality:

file-upload-chat.tsx
<Chat 
  messages={messages}
  onSendMessage={handleSendMessage}
  config={{
    enableFileUpload: true,
    acceptedFileTypes: ['image/*', '.pdf', '.txt'],
    maxFileSize: 10 * 1024 * 1024 // 10MB
  }}
  onFileUpload={(files) => {
    console.log('Files uploaded:', files)
  }}
/>

Customization

CSS Variables

The Chat component can be customized using CSS variables:

custom-chat.css
.chat {
  --ai-chat-height: 600px;
  --ai-chat-background: #ffffff;
  --ai-chat-border: #e5e7eb;
  --ai-chat-border-radius: 12px;
  --ai-chat-padding: 16px;
  --ai-chat-gap: 16px;
}

Custom Styling

styled-chat.tsx
<Chat 
  className="custom-chat"
  style={{
    height: '500px',
    border: '2px solid #e5e7eb',
    borderRadius: '12px'
  }}
  messages={messages}
  onSendMessage={handleSendMessage}
/>

Accessibility

The Chat component includes comprehensive accessibility features:

  • Keyboard Navigation: Full keyboard support for all interactions
  • ARIA Labels: Proper labeling for screen readers
  • Focus Management: Logical focus flow through components
  • Live Regions: Announces new messages to screen readers

ARIA Attributes

// Automatically applied
aria-label="Chat interface"
aria-live="polite" // For message announcements
role="log" // For message history

Performance

Message Virtualization

For large message lists, consider implementing virtualization:

virtualized-chat.tsx
import { FixedSizeList as List } from 'react-window'
 
function VirtualizedChat({ messages }) {
  const renderMessage = ({ index, style }) => (
    <div style={style}>
      <Message message={messages[index]} />
    </div>
  )
 
  return (
    <Chat 
      messages={messages}
      onSendMessage={handleSendMessage}
      renderMessageList={({ messages }) => (
        <List
          height={400}
          itemCount={messages.length}
          itemSize={80}
        >
          {renderMessage}
        </List>
      )}
    />
  )
}

Error Handling

Handle errors gracefully:

error-handling-chat.tsx
function ErrorHandlingChat() {
  const [messages, setMessages] = useState([])
  const [error, setError] = useState(null)
 
  const handleSendMessage = async (content: string) => {
    try {
      setError(null)
      // ... send message logic
    } catch (err) {
      setError(err.message)
      
      // Add error message
      const errorMessage = {
        id: Date.now().toString(),
        role: 'error' as const,
        content: 'Failed to send message. Please try again.',
        timestamp: new Date()
      }
      setMessages(prev => [...prev, errorMessage])
    }
  }
 
  return (
    <Chat 
      messages={messages}
      onSendMessage={handleSendMessage}
      error={error}
      config={{ enableRetry: true }}
    />
  )
}

The Chat component automatically handles scrolling, message rendering, and user interactions. You only need to manage the message state and send logic.

Examples