Skip to main contentSkip to navigation

AI Assistant

Conversational AI assistant with chat interface, message history, and tool integration

Loading...

Overview

The AI Assistant component provides a complete chat interface for conversational AI interactions. It includes message history, typing indicators, avatar support, and integration with AI tools and function calling.

Features

  • Message History - Scrollable chat history with user and assistant messages
  • Avatar Support - Display avatars for user and AI assistant
  • Timestamps - Optional message timestamps
  • Tool Integration - Support for AI function calling and tool use
  • Typing Indicators - Loading states during AI responses
  • Auto-scroll - Automatically scrolls to latest message
  • Keyboard Shortcuts - Send messages with Enter (Shift+Enter for new line)

Usage

Basic Chat Interface

import { AIAssistant } from "@/components/ui/ai-assistant"

const messages = [
  {
    id: "1",
    role: "user",
    content: "What's the weather like?",
    timestamp: new Date(),
  },
  {
    id: "2",
    role: "assistant",
    content: "I can help you check the weather. What city are you in?",
    timestamp: new Date(),
  },
]

export default function Chat() {
  const handleSendMessage = (message: string) => {
    console.log("Sending:", message)
    // Send to AI API
  }

  return (
    <AIAssistant
      messages={messages}
      onSendMessage={handleSendMessage}
      placeholder="Ask me anything..."
    />
  )
}

With AI Provider Integration

import { useState } from "react"

import { AIAssistant } from "@/components/ui/ai-assistant"

export default function ChatWithAI() {
  const [messages, setMessages] = useState([])
  const [isLoading, setIsLoading] = useState(false)

  const handleSendMessage = async (content: string) => {
    // Add user message
    const userMessage = {
      id: Date.now().toString(),
      role: "user",
      content,
      timestamp: new Date(),
    }
    setMessages((prev) => [...prev, userMessage])
    setIsLoading(true)

    // Call AI API (OpenAI, Anthropic, etc.)
    const response = await fetch("/api/chat", {
      method: "POST",
      body: JSON.stringify({ messages: [...messages, userMessage] }),
    })
    const data = await response.json()

    // Add assistant response
    setMessages((prev) => [
      ...prev,
      {
        id: Date.now().toString(),
        role: "assistant",
        content: data.message,
        timestamp: new Date(),
      },
    ])
    setIsLoading(false)
  }

  return (
    <AIAssistant
      provider="openai"
      model="gpt-4"
      messages={messages}
      onSendMessage={handleSendMessage}
      isLoading={isLoading}
      showAvatar={true}
      showTimestamp={true}
    />
  )
}

With Tool Integration

const tools = [
  {
    name: "get_weather",
    description: "Get current weather for a location",
    parameters: {
      type: "object",
      properties: {
        location: { type: "string" },
        unit: { type: "string", enum: ["celsius", "fahrenheit"] },
      },
    },
  },
  {
    name: "search_web",
    description: "Search the web for information",
    parameters: {
      type: "object",
      properties: {
        query: { type: "string" },
      },
    },
  },
]

<AIAssistant
  tools={tools}
  messages={messages}
  onSendMessage={handleSendMessage}
/>

Props

AIAssistantProps

PropTypeDefaultDescription
providerstring"openai"AI provider name
modelstring"gpt-4"Model identifier
apiKeystring-API key for provider
systemPromptstring-System instruction for AI
messagesMessage[][]Array of chat messages
onSendMessage(message: string) => void-Called when user sends message
isLoadingbooleanfalseShow typing indicator
placeholderstring"Ask the AI assistant anything..."Input placeholder text
showAvatarbooleantrueDisplay user/assistant avatars
showTimestampbooleantrueShow message timestamps
toolsTool[][]Available AI tools
onResponse(response: any) => void-Called when AI responds
onError(error: Error) => void-Called on error

Message Interface

interface Message {
  id: string
  role: "user" | "assistant" | "system"
  content: string
  timestamp: Date
}

Tool Interface

interface Tool {
  name: string
  description: string
  parameters?: any // JSON Schema for parameters
}

Styling

The component uses semantic color tokens and adapts to light/dark mode:

  • Primary: AI assistant messages
  • Secondary: User messages
  • Muted: System messages and timestamps
  • Border: Message dividers

Keyboard Shortcuts

  • Enter - Send message
  • Shift+Enter - New line in input
  • Escape - Clear input (when not empty)

Auto-scrolling Behavior

The component automatically scrolls to the latest message when:

  • New messages are added
  • Initial messages are loaded
  • User sends a message

Users can manually scroll up to view history, and auto-scroll will resume when they scroll to the bottom.

Integration Examples

OpenAI

import OpenAI from "openai"

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY })

const handleSendMessage = async (message: string) => {
  const response = await openai.chat.completions.create({
    model: "gpt-4",
    messages: [{ role: "user", content: message }],
  })
  return response.choices[0].message.content
}

Anthropic Claude

import Anthropic from "@anthropic-ai/sdk"

const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })

const handleSendMessage = async (message: string) => {
  const response = await anthropic.messages.create({
    model: "claude-3-opus-20240229",
    max_tokens: 1024,
    messages: [{ role: "user", content: message }],
  })
  return response.content[0].text
}

Accessibility

  • Semantic HTML with proper ARIA labels
  • Keyboard navigation support
  • Screen reader friendly message announcements
  • High contrast mode support
  • Focus management for input field
  • AI Chat - Full chat application with sidebar
  • AI Actions - Quick action buttons
  • AI Tools - Tool library for function calling