Copied RSS Feed

Weekly Data Visualization

How to Build an AI-Powered Blazor Chatbot That Turns Conversations into Charts

TL;DR: Traditional data visualization often requires deep technical skills and complex coding. This blog post introduces an innovative solution: an AI-powered Blazor Chatbot that leverages natural language processing to transform plain text requests into dynamic and interactive Blazor Charts, making data insights accessible to everyone without extensive technical know-how.

Welcome to our Weekly Data Visualization blog series!

Tired of wrestling with complex code and tedious configurations to visualize your data? Imagine generating stunning, interactive charts just by describing them in plain English.

This revolutionary approach introduces how to build an AI-powered Blazor Chatbot that makes advanced data visualization as simple as a conversation, democratizing insights for everyone. Leveraging natural language processing and robust Syncfusion® Blazor Charts, you can transform plain text requests into dynamic visualizations with unparalleled ease.

This blog post elevates chart generation to a new level with a fully AI-powered chatbot experience. This solution combines advanced natural language processing with powerful charting frameworks, empowering users to generate interactive visualizations by having a conversation.

Let’s dive in.

From Chat to Chart: Visual insights made simple

Our objective was to develop an intuitive, conversational interface where users can:

  • Engage naturally with an AI assistant to address data visualization needs.
  • Request charts using plain language descriptions.
  • View dynamically generated, professionally styled Blazor Charts directly within the chat.
  • Modify visualizations through follow-up conversations.
  • Maintain a persistent conversation history, similar to popular AI assistants.

The result is an application that feels instantly familiar to users of modern AI tools, now enhanced with specialized chart-generation capabilities powered by the Syncfusion® Blazor Charts component.

AI Chatbot for Chart generation

Why choose Syncfusion® Blazor Charts?

Syncfusion® Blazor Charts offers a comprehensive suite of interactive and customizable charting tools, built for modern web applications developed with Blazor. These charts are visually appealing and optimized for dynamic rendering and real-time data updates, making them ideal for today’s fast-paced, data-driven applications.

Among its many components, the Syncfusion® Blazor Accumulation Chart stands out for its ability to represent data as parts of a whole. Whether you’re displaying market share, budget distribution, or survey results, these charts, such as pie and doughnut, are perfect for highlighting the contribution of individual items to a total.

Both Standard and Accumulation charts are designed to integrate seamlessly into Blazor applications. They support real-time data updates, making them ideal for dashboards, monitoring tools, and live analytics. Whether you’re using Blazor Server or Blazor WebAssembly, these charts adapt smoothly to changing data and screen sizes, ensuring a consistent and responsive user experience. Here are some compelling reasons why:

  1. Rich set of chart types
    • Over 50 chart types, including line, bar, area, scatter, pie, and financial charts.
    • Suitable for everything from simple dashboards to complex, real-time data visualizations.
  1. Interactive features
    • Built-in support for zooming, panning, tooltips, crosshairs, legends, and data labels.
    • Enhances user engagement with real-time updates and smooth animations.
  1. Customization and styling
    • Fully customizable visuals: colors, fonts, borders, gradients, and themes.
    • Responsive and adaptive layouts ensure charts look great on any device.
  1. Comprehensive documentation and support
    • Extensive documentation, live demos, and a strong developer community.
    • Backed by enterprise-grade support for production-ready reliability.

Ready to start building? Check out our Getting Started guide to dive in with Syncfusion® Blazor Charts and  Syncfusion® Blazor Accumulation Chart.

How to begin: Tools and setup

To build your version of this AI-powered Blazor chatbot application, ensure you have the following tools and services in place:

Prerequisites

  • .NET 8 SDK: The core framework for building modern Blazor applications.
  • Visual Studio 2022+ or Visual Studio Code: Your preferred development environment, with Blazor and web development workloads installed.
  • Azure subscription: Required to access Azure services, including OpenAI.
  • Azure OpenAI access: Enables natural language processing and chart configuration generation.
  • Syncfusion® Blazor components: Provides the UI controls and charting libraries to render interactive

Essential NuGet packages needed for this example are,

  1. AI.OpenAI
  2. Extensions.AI
  3. Blazor.Buttons
  4. Blazor.Charts
  5. Blazor.Core
  6. Blazor.Inputs
  7. Blazor.InteractiveChat
  8. Blazor.Navigations
  9. Blazor.Themes

Now, let’s explore the step-by-step implementation process for converting the chat into charts.

Implementation architecture in Blazor

For developers exploring the internal structure, the application follows a clean and modular architecture, like Model, View, and Service, promoting maintainability and scalability across components.

Core architectural components

  • Models: Data structures like ChatHistoryModel and ChartConfig define the application’s chat sessions and chart rendering data.
  • Services: A service class like AzureAIService interfaces with Azure OpenAI to generate chart configurations, and ChatHistoryService handles persistent storage and retrieves chat history.
  • Views: Razor-defined UI components, including MainPage and SideBarPage, host the main chat interface, render chart visualizations, and display archived conversations and navigation options.
  • Behaviors: Custom interaction logic, such as AssistViewBehavior, enhances the chat interface with extended functionality.
public class Program
{
    var builder = WebApplication.CreateBuilder(args);
    // …
    // Add Syncfusion Blazor service
    builder.Services.AddSyncfusionBlazor();
    // Register custom services
    builder.Services.AddScoped<AzureAIService>();
    builder.Services.AddScoped<ChatHistoryService>();
    Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("YOUR_SYNCFUSION_LICENSE_KEY");
}

Key implementation classes

  • ChatTemplateSelector: Dynamically selects the appropriate UI template based on the type of response returned by the AI.
  • CartesianCategory and CircularCategory: Custom rendering components are responsible for displaying Cartesian and Circular charts using Syncfusion® Blazor Charts.
  • ChatHistoryService: Manages persistent chat history using JSON serialization and cross-platform file handling.
  • AzureAIService: Handles communication with Azure OpenAI, transforming user prompts into structured chat configurations.

Installation Steps:

Follow these steps to set up the chatbot and start converting conversations into charts.

Step 1: Establishing the core: Syncfusion’s Blazor AI AssistView in action

Syncfusion’s Blazor AI AssistView component is the core of our application, which provides a conversational interface like ChatGPT chat experiences. This control is designed to handle:

  • Threaded message flow for maintaining coherent, multi-turn conversations.

<SfAIAssistView @ref="sfAIAssistView" ID="aiAssistView" PromptSuggestions="@SuggestionMessages" PromptRequested="@PromptRequest" ShowHeader="false">
    <AssistViews>
        <AssistView>
            <BannerTemplate>
                @{
                    if (isBannerTemplate)
                    {
                        <div class="banner-content">
                            <div class="e-icons e-assistview-icon"></div>
                            <h3>@HeaderText</h3>
                            <i>To get started, provide input or choose a suggestion.</i>
                        </div>
                    }
                }
            </BannerTemplate>
        </AssistView>
    </AssistViews>
</SfAIAssistView>
  • User input processing and validation to ensure accurate and meaningful interactions.
  • Dynamic response rendering tailored to various content types.
  • Comprehensive chat history management for persistent, context-aware discussions.

To further enhance the user experience, we’ve extended this foundation with custom-built features, including:

  • A dedicated sidebar for navigating and managing previous conversations.
  • Custom response templates optimized for different data visualization outputs.
  • A streamlined New Chat button to initiate fresh interactions effortlessly.
AI AssistView control

Step 2: The AI-Powered chart generation workflow in Blazor

When a user initiates a chart request, a series of intelligent systems work in harmony to deliver a seamless, interactive visualization experience. Here’s how the pipeline unfolds:

  • Capture: The user’s natural language input is collected through the conversational UI, powered by Blazor AI AssistView.
  • Structure: This input is transformed into a structure prompt tailored for the Azure OpenAI service, ensuring accurate interpretation.
  • Process: Azure OpenAI processes the prompt and returns a JSON-formatted chart specification.
  • Deserialize: The application parses this JSON into a strongly typed ChartConfig object, ready for rendering.
  • Select the appropriate chart: A custom responsive template selector evaluates the configuration and determines the appropriate chart type, such as Cartesian or Circular.
  • Display the chart: Finally, Syncfusion’s Blazor chart components render the chart dynamically within the chat interface, providing a polished, interactive visualization.

This tightly integrated pipeline ensures a fluid user experience. For example, the intelligent chart selector dynamically chooses the best visualization type, like a bar chart for categorical data or a pie chart for proportions, based on the AI-generated configuration.

<SfAIAssistView @ref="sfAIAssistView" ID="aiAssistView" PromptSuggestions="@SuggestionMessages" PromptRequested="@PromptRequest" ShowHeader="false">
    <AssistViews>
        <AssistView>
            <ResponseItemTemplate>
                @{
                    var message = context;
                    if (message != null)
                    {
                        <div class="response-item">
                            @if (IsChartMessage(message))
                            {
                                var chartConfig = GetChartConfig(message);
                                if (chartConfig != null)
                                {
                                    <div class="chart-response">
                                        <div class="charttext">@GetDisplayText(message)</div>
                                        @if (chartConfig.ChartType == ChartTypeEnum.Cartesian)
                                        {
                                            <CartesianChart ChartConfig="@chartConfig" />
                                        }
                                        else if(chartConfig.ChartType==ChartTypeEnum.Circular)
                                        {
                                            <CircularChart ChartConfig="@chartConfig" />
                                        }
                                    </div>
                                }
                            }
                        </div>
                    }
                }
            </ResponseItemTemplate>
        </AssistView>
    </AssistViews>
</SfAIAssistView>

Step 3: Implement intelligent prompt engineering

Our approach to prompt engineering ensures that the AI returns precisely the chart configuration required, accurate, structured, and ready for rendering. By crafting context-aware prompts that guide the AI’s understanding, we consistently generate reliable outputs that align with Syncfusion’s Blazor charting schema.

private string GetChartUserPrompt(string userPrompt)
{
    var basePrompt = """
        You are a data visualization assistant. Convert user inputs into structured JSON for chart generation.
        Supported Chart Types:
        - cartesian or circular
        - Series: Line, Column, Spline, Area, Pie, Doughnut
        Output Format:
        {
            "chartType": "cartesian | circular",
            "title": "<Chart Title>",
            "showLegend": true,
            "sideBySidePlacement": true | false,
            "xAxis": [{“type": "category | numerical | datetime | logarithmic", "title": "<X Axis Title> “}],
            "yAxis": [{“type": "numerical | logarithmic", "title": "<Y Axis Title>", "min": 0}],
            "series": [{
            "type": "<SeriesType>",
            "name": "<Series Name>",
            "dataSource": [{“xvalue": "<X>", "yvalue": <Y>}],
            "tooltip": true | false
          }]
        }
        Rules:
        1. Infer chart type from keywords.
        2. Derive a meaningful title.
        3. Cartesian charts require X and Y axes; circular charts do not.
        4. Use only supported series types.
        5. Always include xvalue and yvalue.
        6. Default showLegend to true.
        7. Set sideBySidePlacement based on series layout.
        Now generate the JSON for:
        User Request: 
        """;
    return basePrompt + userPrompt;
}

Step 4: Comprehensive visualization capabilities with Syncfusion® Blazor Charts

Our application leverages the full power of Syncfusion’s Blazor chart components to deliver a wide range of rich, interactive visualizations tailored to diverse data storytelling needs.

Simplifying chart setup with ChartConfig

The ChartConfig class is designed to simplify the process of rendering a wide variety of charts in your application. It provides a flexible structure for defining chart types, axes, series, and layout options in one place.

public class ChartConfig
{
    public string Title { get; set; }
    public bool ShowLegend { get; set; }
    public ChartTypeEnum ChartType { get; set; }
    public ObservableCollection<AxisConfig> XAxis { get; set; } = new();
    public ObservableCollection<AxisConfig> YAxis { get; set; } = new();
    public ObservableCollection<SeriesConfig> Series { get; set; } = new();
    public bool SideBySidePlacement { get; set; } = true;
}

Extensive chart type support

When working with data visualization in Blazor, Syncfusion’s Blazor Chart components offer a powerful and flexible way to render interactive charts.

  • Cartesian Charts: A Cartesian Chart uses X and Y axes to plot data points, making it ideal for comparing trends, categories, and time-series data. It supports various chart types such as line, area, column, spline, and more. The CartesianChart.razor component takes a ChartConfig object as a parameter and renders the chart dynamically based on the provided configuration.
@using Syncfusion.Blazor.Charts
@using BlazorChartAssistView.Models

@if (ChartConfig != null)
{
    <SfChart Title="@ChartConfig.Title" EnableSideBySidePlacement="@ChartConfig.SideBySidePlacement">
        <ChartPrimaryXAxis Title="@GetXAxisTitle()" ValueType="@GetXAxisType()" LabelRotation="@GetXAxisRotation()" />
        <ChartPrimaryYAxis Title="@GetYAxisTitle()" ValueType="@GetYAxisType()" />
        <ChartLegendSettings Visible="@ChartConfig.ShowLegend" Position="LegendPosition.Bottom" />
        <ChartSeriesCollection>
            @foreach (var series in ChartConfig.Series)
            {
                <ChartSeries DataSource="@series.DataSource"
                             Name="@series.Name"
                             XName="@series.XBindingPath"
                             YName="@series.YBindingPath"
                             Type="@(GetSeriesType(series.Type))"
                             Fill="@GetSeriesColor(series)"
                             EnableTooltip="@series.EnableTooltip" />
            }
        </ChartSeriesCollection>
        <ChartTooltipSettings Enable="true" Format="${point.x} : ${point.y}" />
    </SfChart>
}

@code {
    [Parameter] public ChartConfig? ChartConfig { get; set; }
}
  • Circular Charts: An Accumulation Chart displays data as slices of a circle, making it ideal for visualizing proportions. Chart types like Pie and Doughnut are perfect for showing parts of a whole and can be rendered dynamically using a configuration-driven approach. The CircularChart.razor component takes a ChartConfig object as a parameter and renders the chart accordingly.
@using Syncfusion.Blazor.Charts
@using BlazorChartAssistView.Models

@if (ChartConfig != null)
{
    <SfAccumulationChart Title="@ChartConfig.Title" Theme="@Theme.Bootstrap">
        <AccumulationChartLegendSettings Visible="@ChartConfig.ShowLegend"
                                         Position="LegendPosition.Right"
                                         ToggleVisibility="true" />
        <AccumulationChartSeriesCollection>
            @foreach (var series in ChartConfig.Series)
            {
                <AccumulationChartSeries DataSource="@series.DataSource"
                                         Name="@series.Name"
                                         XName="@series.XBindingPath"
                                         YName="@series.YBindingPath"
                                         Type="AccumulationType.Pie"
                                         Radius="80%"
                                         InnerRadius="@(series.Type == SeriesType.Doughnut ? "40%" : null)"
                                         StartAngle="0"
                                         EndAngle="360"
                                         Explode="false"
                                         ExplodeOffset="10%"
                                         EnableTooltip="@series.EnableTooltip">
                    <AccumulationChartAnimation Enable="true" />
                    <AccumulationDataLabelSettings Visible="true"
                                                   Name="XValue"
                                                   Position="AccumulationLabelPosition.Outside">
                        <AccumulationChartConnector Type="ConnectorType.Line" Length="30px" />
                    </AccumulationDataLabelSettings>
                </AccumulationChartSeries>
            }
        </AccumulationChartSeriesCollection>
        <AccumulationChartTooltipSettings Enable="true" Format="${point.x} : ${point.y}%" />
    </SfAccumulationChart>
}

@code {
    [Parameter] public ChartConfig? ChartConfig { get; set; }
}

Advanced Customization Features

Each chart is fully customizable, offering developers and users fine-grained control over:

  • Color palettes for brand consistency and visual clarity
  • Axes and legends with configurable titles, labels, and positioning
  • Interactive tooltips for enhanced data exploration
  • Smooth animations and transitions to improve user engagement

These capabilities ensure that every chart conveys insights effectively and aligns with the visual and functional expectations of modern web applications.

Step 5: Implementing persistent chat history in Blazor

To deliver a seamless and context-aware user experience, our Blazor application includes a robust system for managing and persisting chat history. This ensures that users can revisit previous conversations, maintain continuity, and interact with the chatbot across sessions without losing context.

Key features include:

  • Chat histories are saved using JSON serialization for structured and readable storage.
  • Asynchronous operations ensure smooth performance and a responsive user interface.
  • File paths are resolved using IWebHostEnvironment for cross-platform compatibility.

The ChatHistoryService class handles the persistence logic:

public class ChatHistoryService
{
    private readonly string _dataPath;
    private readonly ILogger<ChatHistoryService> _logger;
    public ChatHistoryService(IWebHostEnvironment environment, ILogger<ChatHistoryService> logger)
    {
        _dataPath = Path.Combine(environment.ContentRootPath, "Data", "ChatHistory.json");
        _logger = logger;
        Directory.CreateDirectory(Path.GetDirectoryName(_dataPath)!);
    }
    public async Task<ObservableCollection<ChatHistoryModel>> LoadChatHistoriesAsync()
    {
        // Implementation
    }
    public async Task SaveChatHistoriesAsync(ObservableCollection<ChatHistoryModel> chatHistories)
    {
        // Implementation
    }
}

After integrating all the code discussed above, the resulting output of the application will be as shown below.

Chat history feature in the Blazor Chatbot

Future possibilities & enhancement opportunities

The foundation of this AI-powered Blazor chatbot opens up exciting opportunities to transform users’ interactions with data across industries and use cases.

Potential applications

  • Enterprise dashboards: Empower non-technical users to generate and customize business visualizations through natural language.
  • Data analysis: Enable conversational exploration of complex datasets, making insights more accessible and intuitive.
  • Educational tools: These tools simplify data visualization for students and educators, fostering data literacy in classrooms and online learning platforms.
  • Reporting systems: Streamline the creation of dynamic, interactive reports with minimal manual effort.

Enhancement opportunities

  • Advanced customization: Introduce more granular controls for users to fine-tune chart appearance, layout, and behavior.
  • Real-Time data integration: Connect to live data sources (e.g., APIs, databases) for continuously updated visualizations.
  • Collaborative features:  Allow teams to co-create, comment on, and share real-time visualizations.
  • Export capabilities: Support exporting charts in various formats (PDF, PNG, Excel, etc.) for reporting presentations or offline use.
AI-powered smart Chatbot with Syncfusion® Blazor Charts

GitHub reference

You can explore the complete source code on GitHub.

FAQs

Q1: How does the chatbot handle ambiguous or incomplete user inputs?

The chatbot employs a fallback mechanism to manage unclear or incomplete prompts. When the input lacks sufficient context, it responds with a guiding message such as:

Include the keyword ‘chart’ or any other term commonly associated with data visualization in the prompt.

This approach ensures a smooth user experience and lays the groundwork for future enhancements, including more advanced clarification and contextual understanding.

Q2: What happens if Azure OpenAI API limits are reached?

When API limits are reached, the system automatically switches to a local response mode. In this mode, it provides predefined responses such as:

Apologies, an error occurred while processing your request. Please try again later or check your API configuration and usage limits.

It may also display sample visualizations. Once the service is restored, the system seamlessly resumes full AI capabilities.

Q3: How customizable is the chart styling via chat?

Users can customize chart types and properties using natural language commands. Supported features include setting titles, axis labels, legend visibility, and selecting chart types to enhance data visualization.

As this is a direct chat-to-chart conversion model, the current implementation focuses on essential chart features. Future enhancements will introduce theme and color customization for more personalized and visually engaging charts.

Q4: Is the chatbot extensible for other Syncfusion® components beyond charts?

Yes, in this example, the AI is configured with the AI AssistView component, and the prompts are specifically tailored for Blazor Charts. However, with additional implementation, it can be extended to support other Blazor UI components such as grids, calendars, and maps.

Syncfusion Blazor components can be transformed into stunning and efficient web apps.

Conclusion

Thank you for reading! This blog demonstrates a paradigm shift in data interaction, showcasing how conversational AI seamlessly integrates with Syncfusion® Blazor Charts to revolutionize data visualization. By combining the power of natural language processing with the flexibility of the Blazor framework, our AI-powered Blazor Chatbot truly democratizes insights, empowering users of all technical backgrounds to gain an actionable understanding from their data in real-time.

Ready to build your own intuitive data assistant?  Unlock the full potential of Syncfusion® Blazor Charts with a 30-day free trial today! Existing Syncfusion® customers can download the latest version of Essential Studio® from the license and downloads page.

If you have any questions or feedback, feel free to reach out via our support forum, support portal, or feedback portal. We’re always here to help!

Meet the Author

Abubucker Sittiq

Abubucker Sittiq R is a passionate .NET developer at Syncfusion who builds web apps using Blazor. He enjoys crafting clean, interactive UIs and making sure every app runs smoothly and efficiently.