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.
Our objective was to develop an intuitive, conversational interface where users can:
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.
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:
Ready to start building? Check out our Getting Started guide to dive in with Syncfusion® Blazor Charts and Syncfusion® Blazor Accumulation Chart.
To build your version of this AI-powered Blazor chatbot application, ensure you have the following tools and services in place:
Essential NuGet packages needed for this example are,
Now, let’s explore the step-by-step implementation process for converting the chat into charts.
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.
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");
}
AzureAIService: Handles communication with Azure OpenAI, transforming user prompts into structured chat configurations.
Follow these steps to set up the chatbot and start converting conversations into charts.
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>
To further enhance the user experience, we’ve extended this foundation with custom-built features, including:
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:
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>
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;
}
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.
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;
}
When working with data visualization in Blazor, Syncfusion’s Blazor Chart components offer a powerful and flexible way to render interactive charts.
@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; }
}
@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; }
}
Each chart is fully customizable, offering developers and users fine-grained control over:
These capabilities ensure that every chart conveys insights effectively and aligns with the visual and functional expectations of modern web applications.
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:
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.
The foundation of this AI-powered Blazor chatbot opens up exciting opportunities to transform users’ interactions with data across industries and use cases.
You can explore the complete source code on GitHub.
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.
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!