Grid AI Chat Assistant
The Blazor Grid can be enhanced with an AI-powered chat assistant that allows users to interact with Grid data using natural language commands. By integrating the Chat component with the Grid's built-in AI helper methods, you can create an intuitive conversational interface where users can perform Smart Grid operations through simple text commands instead of navigating through multiple UI controls.
Overview
The AI Chat Assistant provides a conversational interface for Grid operations. Users can:
- Apply data operations (sort, filter, group, page) through natural language
- Manage columns (show, hide, resize, reorder, lock)
- Export data to Excel, PDF, or CSV
- Receive confirmation messages for each operation
The integration leverages two key Grid methods:
GetAIRequest()—Generates a properly formatted request containing the user's prompt and Grid column information to send to your AI service.ProcessAIResponseAsync()—Processes the AI service response and automatically applies all returned commands to the Grid.
The example in this article uses a Telerik-hosted AI service for demonstration purposes only. For production applications, you should implement your own AI service that understands your specific domain, data, and business requirements.
Setup Steps
To implement an AI Chat Assistant for your Grid, follow the steps below:
-
Add the Grid
Configure the desired features in the Grid. You can control Grid features through the state, even if their UI is not enabled explicitly in the declaration of the component.
RAZOR<TelerikGrid @ref="@GridRef" Data="@GridData" FilterMode="GridFilterMode.FilterMenu" Groupable="true" Pageable="true" Reorderable="true" Resizable="true" ShowColumnMenu="true" Sortable="true"> <GridSettings> <GridPdfExport PageOrientation="@GridPdfExportPageOrientation.Landscape" /> </GridSettings> <GridColumns> <!-- Define columns --> </GridColumns> </TelerikGrid> -
Set Up the Chat Component
Add a Chat component to collect user prompts. Handle the
OnSendMessageevent to process user input. Use the Chat'sSuggestionsparameter to provide helpful prompt examples:RAZOR<TelerikChat @ref="@ChatRef" AuthorId="@CurrentUser.Id" Data="@ChatData" OnSendMessage="@OnChatSendMessage" Suggestions="@ChatSuggestions" Placeholder="Ask me to sort, filter, or analyze your data."> </TelerikChat> @code { private TelerikChat<Message> ChatRef { get; set; } private List<Message> ChatData { get; set; } = new(); private List<string> ChatSuggestions = new() { "Sort by Bookings descending", "Group by Sales Person", "Export to PDF", "Filter by North America" }; private Author CurrentUser = new() { Id = "user", Name = "Grid User" }; } -
Process User Prompts
Implement the Chat
OnSendMessageevent handler to process user prompts and send them to your AI service. Use the Grid'sGetAIRequest()method to generate a properly formatted request:C#private async Task OnChatSendMessage(ChatSendMessageEventArgs args) { // Add user message to Chat Message userMessage = new Message() { AuthorId = CurrentUser.Id, AuthorName = CurrentUser.Name, Text = args.Message }; ChatData.Add(userMessage); // Add AI response placeholder with typing indicator Message aiResponse = new Message() { AuthorId = "ai", AuthorName = "AI Assistant", IsTyping = true }; ChatData.Add(aiResponse); ChatRef.Refresh(); try { // Generate AI request from Grid GridAIRequestDescriptor aiRequest = GridRef.GetAIRequest(args.Message); // Send to AI service HttpResponseMessage requestResult = await HttpClientInstance.PostAsJsonAsync( "https://your-ai-service.com/api/grid/smart-state", aiRequest); string aiResultContent = await requestResult.Content.ReadAsStringAsync(); // Process AI response and apply to Grid await GridRef.ProcessAIResponseAsync(aiResultContent); // Extract messages from response GridAIResponse gridAIResponse = JsonSerializer.Deserialize<GridAIResponse>(aiResultContent); string commandMessages = string.Join(" ", gridAIResponse.Commands.Select(x => x.Message)); // Update AI response message aiResponse.IsTyping = false; aiResponse.Text = commandMessages ?? "Grid updated successfully."; } catch (Exception) { aiResponse.IsTyping = false; aiResponse.Text = "The request failed. Please try another request."; } ChatRef.Refresh(); } -
Display AI Responses
Extract messages from the AI service response to display in the Chat. The
GridAIResponseobject contains aCommandscollection where each command has aMessageproperty describing what operation was performed:C#// Deserialize the AI response GridAIResponse gridAIResponse = JsonSerializer.Deserialize<GridAIResponse>(aiResultContent); // Extract messages from each command string commandMessages = string.Join(" ", gridAIResponse.Commands.Select(x => x.Message)); // Update the Chat message aiResponse.Text = commandMessages ?? "Grid updated successfully."; -
Optional: Add Layout Components
For a better user experience, consider using layout components like the Drawer to show/hide the Chat interface:
RAZOR<TelerikDrawer @ref="@DrawerRef" Expanded="@DrawerExpanded" Mode="@DrawerMode.Push" Position="@DrawerPosition.End" Width="360px"> <Template> <TelerikChat @ref="@ChatRef" ...> </TelerikChat> </Template> <DrawerContent> <TelerikGrid @ref="@GridRef" ...> <GridToolBar> <GridToolBarCustomTool> <TelerikToggleButton OnClick="@ToggleChat" Selected="@DrawerExpanded"> AI Assistant </TelerikToggleButton> </GridToolBarCustomTool> </GridToolBar> </TelerikGrid> </DrawerContent> </TelerikDrawer> @code { private bool DrawerExpanded { get; set; } private async Task ToggleChat() { await DrawerRef.ToggleAsync(); } }
View the complete live demo.
Best Practices
Provide Initial Guidance
Add a welcome message to the Chat when it initializes to guide users on what they can ask:
protected override void OnInitialized()
{
ChatData.Add(new Message()
{
AuthorId = "ai",
AuthorName = "AI Assistant",
Text = "👋 Hi! I'm your AI Grid Assistant. I can help you:\n\n• Sort, filter, or group data\n• Manage columns\n• Export to Excel, PDF, or CSV\n\nTry one of the suggestions below!"
});
}
Use Chat Suggestions
Provide common prompts as suggestions to help users understand the AI's capabilities:
private List<string> ChatSuggestions = new() {
"Sort by sales descending",
"Filter orders from last month",
"Group by region",
"Export to Excel",
"Hide the discount column"
};
Handle Errors
When using the Chat OnSendMessage event, consider wrapping the AI service calls in try-catch blocks and provide helpful error messages:
try
{
// AI processing logic
}
catch (Exception ex)
{
aiResponse.Text = "I couldn't process that request. Please try rephrasing or use one of the suggestions.";
Console.WriteLine($"AI request failed: {ex.Message}");
}
Show Typing Indicators
Use the Message's IsTyping property to indicate when the AI is processing:
Message aiResponse = new Message()
{
AuthorId = "ai",
IsTyping = true // Shows typing indicator
};
ChatData.Add(aiResponse);
ChatRef.Refresh();
// After processing...
aiResponse.IsTyping = false;
aiResponse.Text = "Operation completed!";
ChatRef.Refresh();