Getting Started with Telerik.AI.SmartComponents.ExtensionsPremium
Overview
The Telerik.AI.SmartComponents.Extensions library provides AI-powered functionality for grid operations, enabling natural language processing for filtering, sorting, grouping, highlighting, selection, pagination, column operations, and data export. This library integrates seamlessly with Microsoft.Extensions.AI and Azure OpenAI to provide intelligent grid interactions.
Prerequisites
- .NET 8.0 or later
- Microsoft.Extensions.AI package
- Azure OpenAI or OpenAI API access, or local LLM
- ASP.NET Core (for web API scenarios)
Installation
Add the Telerik.AI.SmartComponents.Extensions package to your project:
dotnet add package Telerik.AI.SmartComponents.Extensions
Add required dependencies:
dotnet add package Microsoft.Extensions.AI
dotnet add package Azure.AI.OpenAI
Configuration
1. Configure AI Services in Program.cs
using Microsoft.Extensions.AI;
using Azure.AI.OpenAI;
var builder = WebApplication.CreateBuilder(args);
// Configure Azure OpenAI Chat Client
builder.Services.AddSingleton<IChatClient>(serviceProvider =>
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
var endpoint = configuration["AI:AzureOpenAI:Endpoint"];
var apiKey = configuration["AI:AzureOpenAI:Key"];
var modelId = configuration["AI:AzureOpenAI:Chat:ModelId"];
var client = new AzureOpenAIClient(new Uri(endpoint), new Azure.AzureKeyCredential(apiKey));
return client.AsChatClient(modelId);
});
builder.Services.AddControllers();
var app = builder.Build();
2. Configure appsettings.json
{
"AI": {
"AzureOpenAI": {
"Endpoint": "https://your-openai-resource.openai.azure.com/",
"Key": "your-api-key-here",
"Chat": {
"ModelId": "gpt-4"
}
}
}
}
Basic Usage
1. Create a Grid Controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.AI;
using Telerik.AI.SmartComponents.Extensions;
[ApiController]
[Route("[controller]/[action]")]
public class GridController : Controller
{
private readonly IChatClient _chatClient;
public GridController(IChatClient chatClient)
{
_chatClient = chatClient;
}
[HttpPost]
[Route("/grid/smart-state")]
public async Task<IActionResult> SmartState([FromBody] GridAIRequest request)
{
// Create chat options
var options = new ChatOptions();
// Add grid-specific chat tools for AI processing
options.AddGridChatTools(request.Columns);
// Convert request contents to chat messages
var conversationMessages = request.Contents
.Select(m => new ChatMessage(ChatRole.User, m.Text))
.ToList();
// Process the request
ChatResponse completion = await _chatClient.GetResponseAsync(conversationMessages, options);
// Extract grid response from AI response
GridAIResponse response = completion.ExtractGridResponse();
return Json(response);
}
}
2. Define Your Data Model
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Department { get; set; }
public decimal Salary { get; set; }
public string City { get; set; }
public string Gender { get; set; }
}
3. Create Grid AI Request
var request = new GridAIRequest
{
Columns = new List<GridAIColumn>
{
new() { Id = "1", Field = "FirstName" },
new() { Id = "2", Field = "LastName" },
new() { Id = "3", Field = "Age" },
new() { Id = "4", Field = "Department", Values = new[] { "IT", "HR", "Finance", "Marketing" } },
new() { Id = "5", Field = "Salary" },
new() { Id = "6", Field = "City", Values = new[] { "New York", "London", "Paris", "Tokyo" } },
new() { Id = "7", Field = "Gender", Values = new[] { "Male", "Female" } }
},
Contents = new List<GridAIRequestContent>
{
new() { Type = "text", Text = "Show me all employees in IT department" }
}
};
Advanced Features
1. Filtering Operations
The library supports various natural language filtering queries:
// Example queries that work with the AI:
"Show me employees older than 30"
"Filter people in IT department"
"Get employees whose name starts with J"
"Show me men with salary greater than 60000"
"Clear the filter" // Removes all filters
2. Sorting Operations
// Natural language sorting examples:
"Sort by age descending"
"Order by salary ascending"
"Sort by department, then by name"
"Clear sort" // Removes all sorts
3. Grouping Operations
// Grouping examples:
"Group by department"
"Group by city, then by age"
"Group employees by gender descending"
"Clear grouping" // Removes all grouping
4. Highlighting Operations
The library supports row and cell-level highlighting:
// Row highlighting examples:
"Highlight employees whose name starts with A"
"Mark rows of people older than 30"
"Highlight IT employees"
// Cell highlighting examples:
"Highlight lastname cells of IT employees"
"Mark salary cells where salary is greater than 60000"
// Clear highlighting
"Clear highlight" // Removes all highlighting
5. Selection Operations
The library supports row and cell-level selection:
// Row selection examples:
"Select all employees from IT department"
"Select people older than 30"
// Cell selection examples:
"Select the name cells of IT employees"
"Select age cells where age is greater than 30"
// Clear selection
"Clear selection" // Removes all selections
6. Pagination Operations
Control grid pagination through natural language:
// Page navigation examples:
"Go to page 3"
"Show page 1"
"Navigate to the second page"
// Page size examples:
"Show 20 items per page"
"Change page size to 50"
"Display 10 rows per page"
7. Column Operations
The library supports various column manipulation operations:
// Column visibility examples:
"Hide the Age column"
"Show the Department column"
// Column locking examples:
"Lock the Name column"
"Unlock the Salary column"
// Column resizing examples:
"Resize the Name column to 200px"
"Set the Age column width to 100px"
// Column reordering examples:
"Move the Age column to position 1"
"Reposition the Department column to the third position"
Note: Column operations require the Id property to be set on GridAIColumn objects.
8. Export Operations
Export grid data to various formats:
// Export examples:
"Export to Excel"
"Export the grid data to Excel as employee_data"
"Export to PDF"
"Export to CSV as report"
Working with Grid Responses
The AI service returns a GridAIResponse object containing a list of commands that represent the operations:
public class GridAIResponse
{
// Collection of commands representing the AI-interpreted operations
public List<ICommand> Commands { get; set; }
// Optional message providing status or information
public string? Message { get; set; }
}
public async Task<GridAIResponse> ProcessGridRequest(GridAIRequest request)
{
var options = new ChatOptions();
options.AddGridChatTools(request.Columns);
var messages = request.Contents.Select(m => new ChatMessage(ChatRole.User, m.Text)).ToList();
var completion = await _chatClient.GetResponseAsync(conversationMessages, options);
GridAIResponse response = completion.ExtractGridResponse();
// The response contains:
// - response.Commands: A list of commands, containing information about the type of operation, and parameters associated with it.
// - response.Message: Status/info message
return response;
}
Command Types
Each command has a type property and relevant data. Common command types include:
Data Operations:
GridFilterCommand- ContainsFilterwith field, operator, and valueGridSortCommand- ContainsSortwith field and directionGridGroupCommand- ContainsGroupwith field and directionGridHighlightCommand- ContainsHighlightwith filters and cells to highlightGridSelectCommand- ContainsSelectwith filters and cells to select
Pagination:
GridPageCommand- ContainsPagenumberGridPageSizeCommand- ContainsPageSizevalue
Column Operations:
GridColumnShowCommand/GridColumnHideCommand- Contains columnIdGridColumnLockCommand/GridColumnUnlockCommand- Contains columnIdGridColumnResizeCommand- Contains columnIdandWidthGridColumnReorderCommand- Contains columnIdandPosition
Export:
GridExportExcelCommand/GridExportPDFCommand/GridExportCSVCommand- ContainsFileName
Clear Operations:
GridClearFilterCommand/GridClearSortCommand/GridClearGroupCommand/GridClearHighlightCommand/GridClearSelectCommand- No additional data needed
Filter Types
The library supports various filter operators:
equalto: Exact matchcontains: Contains substringstartswith: Starts with textendswith: Ends with textgreaterthan: Greater than (numeric)lessthan: Less than (numeric)greaterthanorequal: Greater than or equallessthanorequal: Less than or equal
Best Practices
1. Column Configuration
When the options for the column are of Enum type provide meaningful column values to help the AI understand your data:
new GridAIColumn
{
Field = "Status",
// only when only a set of values are used
Values = new[] { "Active", "Inactive", "Pending" }
}
2. Error Handling
try
{
var completion = await _chatClient.GetResponseAsync(conversationMessages, options);
var response = completion.ExtractGridResponse();
return Json(response);
}
catch (Exception ex)
{
return StatusCode(500, $"AI processing failed: {ex.Message}");
}
3. Input Validation
if (request?.Columns == null || !request.Columns.Any())
{
return BadRequest("Columns are required");
}
if (request.Contents == null || !request.Contents.Any())
{
return BadRequest("Content is required");
}
Testing
The library includes comprehensive test coverage. You can run tests to verify functionality:
cd tests
dotnet test
For integration testing with your specific data model, create test cases that verify AI responses match expected grid operations.
Example Client Usage
JavaScript/TypeScript Frontend
interface GridAIRequest {
columns: GridAIColumn[];
contents: GridAIRequestContent[];
role?: string;
}
interface GridAIColumn {
field: string;
values: string[];
}
interface GridAIRequestContent {
$type: string;
text: string;
}
async function processGridQuery(query: string, columns: GridAIColumn[]) {
const request: GridAIRequest = {
columns: columns,
contents: [{ $type: 'text', text: query }],
role: 'user'
};
const response = await fetch('/grid/smart-state', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request)
});
return await response.json();
}
// Usage
const columns = [
{ field: 'Name', values: ['John', 'Jane', 'Bob'] },
{ field: 'Age', values: ['25', '30', '35'] },
{ field: 'Department', values: ['IT', 'HR', 'Finance'] }
];
const result = await processGridQuery('Show me IT employees', columns);
Troubleshooting
Common Issues
- Invalid URI Format: Ensure your Azure OpenAI endpoint is correctly formatted in configuration
- API Key Issues: Verify your API key has proper permissions and is not expired
- Model Availability: Ensure the specified model ID is deployed in your Azure OpenAI resource
- Token Limits: Be mindful of token limits when processing large datasets