Skip to content

Building Interactive Chat Components with Widgets

When your AI peer responds to users, sometimes plain text isn't enough. What if your peer could show a live KPI dashboard, an interactive chart, or a product comparison table right in the chat?

That's where Widgets come in.

Widgets are interactive visual components that AI peers can render within chat conversations to display structured data, visualizations, and actionable content - making conversations more engaging and informative.

What Are Widgets?

Widgets are pre-built, interactive UI components that appear directly in chat messages. Instead of just sending text, your AI peer can:

  • Display charts and graphs (line, bar, pie, donut, radar)
  • Show KPI dashboards with metrics and trends
  • Render data tables and lists with sortable columns
  • Present cards and timelines for structured information
  • Create interactive forms and action buttons

Example conversation:

User: Show me our sales performance this quarter

AI Peer: Here's your Q1 sales overview:
[Revenue Trend Chart Widget]
Revenue is up 24% compared to last quarter, with March showing the strongest growth.

The widget appears inline with the chat message, creating a rich, interactive experience.

Why Use Widgets?

Text-Only Limitations

Traditional chat interfaces face challenges with complex data:

Hard to parse: Large data sets are overwhelming as text
No context: Numbers without visuals lack impact
Poor UX: Users have to mentally process raw data
No interaction: Can't sort, filter, or explore data

Widget Benefits

Visual clarity: Charts and graphs make data instantly understandable
Interactive: Users can explore, sort, and filter information
Professional: Polished UI components enhance credibility
Efficient: Convey complex information quickly
Engaging: Rich media keeps users interested
Accessible: Works in peer conversations, flows, and webchat

How Widgets Work

Three Ways to Use Widgets

1. In Peer Conversations 🤖 Your AI peer can select and render widgets from the gallery as part of its response.

2. In Flows 🔄 Add widgets to flow steps to display data visually at any stage.

3. In Webchat 💬 Widgets work seamlessly in embedded webchat interfaces on your website.

Cognipeer provides a curated gallery of ready-to-use widgets. You can:

  • Browse by category (Analytics, Business, Visualization)
  • Preview widgets with sample data
  • Select widgets for your peers and flows
  • Customize widget appearance and behavior

Getting Started

In the Cognipeer dashboard:

  1. Go to Widgets Gallery
  2. Browse available widgets by category
  3. Click on a widget to see its preview and description
  4. Note the widget's key for use in your peer or flow

2. Use Widgets in Your Peer

Configure your peer to use widgets from the gallery:

javascript
// Your peer can reference widgets in responses
{
  "message": "Here's your sales performance:",
  "widget": {
    "key": "revenue-trend-chart",
    "data": {
      "title": "Q1 2024 Revenue",
      "datasets": [{
        "label": "Revenue",
        "data": [45000, 52000, 61000, 58000]
      }]
    }
  }
}

3. Add Widgets to Flows

In your flow designer:

  1. Add a step where you want to display data
  2. Select "Show Widget" action
  3. Choose a widget from the gallery
  4. Map your data to widget properties
  5. Configure appearance options

Available Widget Types

Charts & Visualizations 📊

Line Charts

  • basic-line-chart: Simple line chart for trends
  • user-growth-line: Track user growth over time
  • revenue-trend-chart: Revenue visualization

Bar Charts

  • basic-bar-chart: Vertical bar comparisons
  • sales-comparison-bar: Compare sales across categories

Pie & Donut Charts

  • basic-pie-chart: Simple pie chart
  • basic-donut-chart: Donut chart with center value
  • market-share-pie: Market share visualization
  • channel-performance-donut: Channel metrics

Area Charts

  • basic-area-chart: Filled area chart for cumulative data

Combo Charts

  • performance-combo-chart: Combine multiple chart types

Specialized Charts

  • skills-comparison-radar: Radar chart for multi-dimensional comparisons

Business & Analytics 📈

KPI Widgets

  • kpi-highlight: Spotlight a key metric with trends
  • kpi-sparkline-mini: Mini KPI with sparkline

Progress & Tracking

  • sales-funnel-progress: Funnel visualization
  • budget-allocation-stacked: Stacked budget view

Lists & Tables

  • essential-list: Clean, organized list display
  • inventory-item-list: Product inventory view
  • support-ticket-overview: Ticket status overview

Interactive Components 🎯

Cards & Details

  • dynamic-object-card: Display object details dynamically
  • shopping-cart-summary: Cart items and total

Timelines

  • activity-timeline: Event and activity timeline

Project Management

  • task-kanban: Kanban board for tasks

Specialized

  • weather-daily-highlight: Weather information display

Widget Configuration

Each widget accepts:

Common Properties:

  • title: Widget headline
  • data: The data to visualize
  • accentColor: Primary color theme
  • layout: Responsive layout options

Example Configuration:

javascript
{
  "widget": {
    "key": "kpi-highlight",
    "data": {
      "label": "Monthly Revenue",
      "value": "$48,921",
      "change": "+11.9%",
      "progress": 64,
      "caption": "vs. last month"
    }
  }
}

Real-World Examples

Example 1: Sales Dashboard Peer

Scenario: A sales manager asks their AI peer for quarterly performance.

Implementation:

javascript
// System Prompt for Sales Peer
`You are a sales analytics assistant. When users ask for performance data:
1. Query the sales database
2. Display results using appropriate widgets
3. Provide context and insights`

// Peer Response with Widget
{
  "message": "Here's your Q1 2024 sales performance:",
  "widget": {
    "key": "revenue-trend-chart",
    "data": {
      "title": "Quarterly Revenue Trend",
      "datasets": [{
        "label": "Revenue ($)",
        "data": [125000, 138000, 142000, 156000],
        "labels": ["Jan", "Feb", "Mar", "Apr"]
      }]
    }
  },
  "additionalMessage": "Revenue grew 24.8% over the quarter, with April showing strongest performance at $156K."
}

Result: The chart widget displays inline, making trends instantly visible.

Example 2: Inventory Management Flow

Scenario: An automated flow checks stock levels and displays alerts.

Flow Configuration:

javascript
{
  "steps": [
    {
      "type": "query-database",
      "query": "SELECT * FROM inventory WHERE stock < reorder_point"
    },
    {
      "type": "show-widget",
      "widget": {
        "key": "inventory-item-list",
        "data": {
          "items": "{{previousStep.results}}",
          "title": "Low Stock Alert",
          "highlightCritical": true
        }
      }
    },
    {
      "type": "send-notification",
      "message": "{{count}} items need reordering"
    }
  ]
}

Result: The flow displays an interactive list widget showing which items need attention.

Example 3: Customer Support with KPIs

Scenario: Support team dashboard showing real-time metrics.

Peer Response:

javascript
{
  "message": "Current support metrics:",
  "widgets": [
    {
      "key": "kpi-highlight",
      "data": {
        "label": "Open Tickets",
        "value": "42",
        "change": "-12%",
        "progress": 85,
        "caption": "vs. yesterday"
      }
    },
    {
      "key": "support-ticket-overview",
      "data": {
        "tickets": [
          { "id": "T-1234", "status": "Open", "priority": "High" },
          { "id": "T-1235", "status": "In Progress", "priority": "Medium" }
        ]
      }
    }
  ],
  "additionalMessage": "Great job! Ticket resolution time is down 18% this week."
}

Result: Multiple widgets display together, providing a comprehensive dashboard view.

Using Widgets in Different Contexts

1. In Peer Conversations

Your AI peer automatically has access to the widget gallery. Configure it to use widgets:

javascript
// Peer System Prompt
`When displaying data or metrics, use appropriate widgets:
- Use 'revenue-trend-chart' for revenue over time
- Use 'kpi-highlight' for single key metrics
- Use 'sales-comparison-bar' for category comparisons
- Use 'support-ticket-overview' for ticket lists

Always provide context with the widget.`

The peer will intelligently select and render widgets based on the data it needs to display.

2. In Flows

Add widget steps to your flow:

javascript
{
  "steps": [
    {
      "id": "step-1",
      "type": "query-data",
      "query": "SELECT * FROM sales WHERE month = current_month"
    },
    {
      "id": "step-2", 
      "type": "show-widget",
      "widgetKey": "revenue-trend-chart",
      "data": {
        "title": "Monthly Sales",
        "datasets": "{{step-1.results}}"
      }
    }
  ]
}

3. In Webchat

Widgets work seamlessly in webchat embeds. When your peer responds with a widget, it renders automatically:

html
<!-- Webchat Embed -->
<script src="https://app.cognipeer.com/scripts/cognipeer.sdk.js"></script>
<script>
  cognipeerChat({
    hookId: 'your-webhook-id',
    contact: {
      name: 'John Doe',
      email: 'john@example.com'
    }
  });
</script>

The webchat interface will display any widgets your peer includes in its responses.

Widget Data Formatting

Chart Widget Data Structure

javascript
// Line/Bar/Area Charts
{
  "title": "Chart Title",
  "datasets": [{
    "label": "Series Name",
    "data": [10, 20, 30, 40],
    "labels": ["Jan", "Feb", "Mar", "Apr"]
  }],
  "yAxisLabel": "Revenue ($)",
  "xAxisLabel": "Month"
}

// Pie/Donut Charts
{
  "title": "Market Share",
  "data": [30, 25, 20, 15, 10],
  "labels": ["Product A", "Product B", "Product C", "Product D", "Other"],
  "showPercentages": true
}

// KPI Widgets
{
  "label": "Monthly Active Users",
  "value": "12,842",
  "change": "+4.2%",
  "progress": 72,
  "caption": "vs. last month target"
}

// List Widgets
{
  "title": "Active Projects",
  "items": [
    { "id": 1, "name": "Project Alpha", "status": "On Track" },
    { "id": 2, "name": "Project Beta", "status": "At Risk" }
  ],
  "sortable": true,
  "searchable": true
}

Best Practices

1. Choose the Right Widget

Match widgets to your data type:

Data TypeRecommended Widget
Time series trendsbasic-line-chart, revenue-trend-chart
Comparisonsbasic-bar-chart, sales-comparison-bar
Distributionsbasic-pie-chart, market-share-pie
Single metricskpi-highlight, kpi-sparkline-mini
Lists of itemsessential-list, inventory-item-list
Task managementtask-kanban, activity-timeline

2. Provide Context

Always accompany widgets with explanatory text:

javascript
{
  "message": "Here's your Q1 performance:",
  "widget": { /* widget config */ },
  "additionalMessage": "Revenue is up 24% vs. last quarter. March was your strongest month with $156K in sales."
}

3. Keep Data Fresh

Update widget data in real-time or at appropriate intervals:

javascript
// In Flow: Refresh every hour
{
  "schedule": "0 * * * *",
  "steps": [
    { "type": "query-data" },
    { "type": "update-widget" }
  ]
}

4. Responsive Design

Widgets automatically adapt to screen size, but test on:

  • Desktop (large screens)
  • Tablets (medium screens)
  • Mobile (small screens)
  • Webchat embeds (constrained width)

5. Accessibility

Widgets are built with accessibility in mind:

  • Keyboard navigation support
  • Screen reader compatible
  • High contrast mode support
  • ARIA labels and roles

Performance Considerations

Widget Rendering

Widgets are lightweight and optimized:

  • Lazy loading: Widgets load only when needed
  • Virtual scrolling: Large lists render efficiently
  • Memoization: Prevents unnecessary re-renders
  • Bundle size: Each widget is ~5-15KB gzipped

Data Volume

For large datasets:

  • Pagination: Lists auto-paginate beyond 50 items
  • Aggregation: Pre-aggregate data before sending
  • Sampling: Use representative samples for visualizations
  • Caching: Widget states cache for 5 minutes by default

Troubleshooting

Widget Not Displaying

Check your peer's response format:

javascript
// ✅ Correct format
{
  "message": "Here's your data:",
  "widget": {
    "key": "kpi-highlight",
    "data": { /* valid data */ }
  }
}

// ❌ Wrong format
{
  "message": "Here's your data:",
  "widgetKey": "kpi-highlight"  // Missing 'widget' wrapper
}

Data Not Showing

Verify data structure matches widget schema:

javascript
// Check widget's initialStateSchema in gallery
// Ensure all required properties are provided
// Match data types (strings vs numbers)

Styling Issues

Widgets inherit theme from platform:

  • Light/dark mode automatically applied
  • Accent colors match organization settings
  • Fonts use platform defaults

Advanced: Creating Custom Widgets

While the gallery provides many ready-to-use widgets, you can create custom widgets for specialized needs.

Custom Widget Structure

json
{
  "key": "my-custom-widget",
  "name": "Custom Widget",
  "shortDescription": "Brief description",
  "description": "Detailed description",
  "icon": "IconName",
  "categories": ["analytics"],
  "tags": ["custom", "specialized"],
  "accentColor": "blue",
  "previewState": {
    // Sample data for preview
  },
  "initialStateSchema": {
    // JSON Schema defining accepted data structure
    "type": "object",
    "properties": {
      "title": { "type": "string" },
      "value": { "type": "number" }
    }
  }
}
  1. Create your widget JSON definition
  2. Test thoroughly with sample data
  3. Document usage examples
  4. Submit for review via the dashboard

Integration with Other Features

Widgets + Tools

Combine widgets with tool outputs:

javascript
// Tool returns structured data
{
  "toolName": "get-sales-data",
  "output": {
    "revenue": [45000, 52000, 61000],
    "months": ["Jan", "Feb", "Mar"]
  }
}

// Peer formats as widget
{
  "widget": {
    "key": "revenue-trend-chart",
    "data": {
      "datasets": [{
        "data": "{{tool.output.revenue}}",
        "labels": "{{tool.output.months}}"
      }]
    }
  }
}

Widgets + Datasources

Query datasources and visualize results:

javascript
// Peer queries datasource
{
  "datasourceQuery": "user_growth_monthly",
  "visualize": true
}

// System automatically selects appropriate widget
// based on data structure and type

Resources

Conclusion

Widgets transform conversational AI from text-only interactions into rich, visual experiences. By rendering charts, dashboards, and interactive components directly in chat, you make data more accessible and actionable.

Key Takeaways:

Gallery access: Choose from 20+ pre-built widgets
Multiple contexts: Works in peers, flows, and webchat
Data visualization: Turn numbers into insights with charts
Interactive components: Lists, cards, timelines, and more
Easy integration: No coding required for basic usage
Extensible: Create custom widgets for specialized needs

Whether you're building a sales dashboard, customer support system, or analytics platform, widgets help you deliver information in the most effective format.


Next Steps:

  1. Browse the Widget Gallery
  2. Configure your first peer to use widgets
  3. Test widgets in your flows
  4. Embed webchat with widget support on your site

Questions? Check out our community forum or contact support.

Related Reading:

Built with VitePress