Skip to content

DevExpress-Examples/blazor-grid-and-report-viewer-integrate-ai-assistant

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

57 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Blazor Grid and Report Viewer — Incorporate an AI Assistant (Azure OpenAI) in your next DevExpress-powered Blazor app

This example adds a Copilot-inspired chat window (DevExpress DxAIChat component) to a DevExpress-powered Blazor application (using both the DevExpress Report Viewer and Blazor Grid component). Our chat implementation utilizes Azure OpenAI Assistant to answer user questions based on information displayed in the report and/or data grid.

To integrate AI-powered chat capabilities to your next great Blazor application, please follow the steps below:

  1. Register AI Services within the application.
  2. Add the DevExpress Chat component (DxAIChat).
  3. Export component data and pass it to the AI Assistant.

The following DevExpress Blazor Components were used in this sample project:

Open AI Assistant initialization may take time. DxAIChat is ready for use once Microsoft Azure OpenAI completes its source document scan.

Note

We use the following versions of the Microsoft.Extensions.AI.* libraries in our source code:

  • Microsoft.Extensions.AI.Abstractions: 9.5.0
  • Microsoft.Extensions.AI: 9.5.0
  • Microsoft.Extensions.AI.OpenAI: 9.5.0-preview.1.25265.7

We do not guarantee compatibility or correct operation with higher versions.

Implementation Details

Register AI Services

Note

DevExpress AI-powered extensions follow the "bring your own key" principle. DevExpress does not offer a REST API and does not ship any built-in LLMs/SLMs. You need an active Azure/Open AI subscription to obtain the REST API endpoint, key, and model deployment name. These variables must be specified at application startup to register AI clients and enable DevExpress AI-powered Extensions in your application.

Add the following code snippet to the Program.cs file to register AI Services and incorporate an OpenAI Assistant in your application:

using Azure.AI.OpenAI;
using DevExpress.AIIntegration;
using Microsoft.Extensions.AI;
using System.ClientModel;
//...
string azureOpenAIEndpoint = "AZURE_OPENAI_ENDPOINT";
string azureOpenAIKey = "AZURE_OPENAI_API_KEY";
string deploymentName = "YOUR_MODEL_NAME";
//...
var azureOpenAIClient = new AzureOpenAIClient(
    new Uri(azureOpenAIEndpoint),
    new ApiKeyCredential(azureOpenAIKey));

var chatClient = azureOpenAIClient.GetChatClient(deploymentName).AsIChatClient();
builder.Services.AddChatClient(chatClient);
builder.Services.AddDevExpressAI((config) => {
    //Reference the DevExpress.AIIntegration.OpenAI NuGet package to use Open AI Assistants
    config.RegisterOpenAIAssistants(azureOpenAIClient, deploymentName); 
});

For additional information on the use of AI Assistants with DxAIChat and managing messages with custom RAG (Retrieval-Augmented Generation) solutions, refer to the following topic: AI Service Assistants in the DxAIChat component.

Note

The availability of Azure Open AI Assistants depends on region. For additional guidance in this regard, refer to the following document: Azure OpenAI Service models -- Assistants (Preview).

Files to Review:

Use an AI Assistant with the DevExpress Blazor Grid

This example includes a page with both the DevExpress Blazor Grid (DxGrid) and Blazor Chat component (DxAIChat):

Blazor Grid and Integrated AI Assistant

To configure our Blazor Grid (data binding and customizations), review the following code file: Grid.razor.

Add AI Chat to the Grid Page

The following code snippet adds the DxAIChat component to the page:

@using DevExpress.AIIntegration.Blazor.Chat
@using Markdig

<DxGrid @ref="grid" Data="@DataSource" CssClass="my-grid" ShowGroupPanel="true" TextWrapEnabled="false">
    @* ... *@
</DxGrid>
<DxAIChat @ref="chat" CssClass="my-grid-chat">
    <MessageContentTemplate>
        <div class="my-chat-content">
            @ToHtml(context.Content)
        </div>
    </MessageContentTemplate>
</DxAIChat>

@code {
    MarkupString ToHtml(string text) {
        return (MarkupString)Markdown.ToHtml(text);
    }
}

Use the MessageContentTemplate property to display rich-formatted messages. Use a markdown processor to convert response content to HTML code.

Files to Review:

Create an AI Assistant

In this example, the AIAssistantCreator.CreateAssistantAsync method uploads a file to OpenAI, configures tool resources, creates an assistant with specified instructions and tools, initializes a new thread, and returns the assistant and thread IDs.

For information on OpenAI Assistants, refer to the following documents:

In the Program.cs file, add the AIAssistantCreator service to the application's service collection:

// ...
var azureOpenAIClient = new AzureOpenAIClient(
    new Uri(azureOpenAIEndpoint),
    new ApiKeyCredential(azureOpenAIKey));

var assistantCreator = new AIAssistantCreator(azureOpenAIClient, deploymentName);

builder.Services.AddSingleton(assistantCreator);
// ...

Files to Review:

Set Up the AI Assistant

Handle the OnAfterRenderAsync event and call the SetupAssistantAsync method to set up your AI assistant based on the assistant and thread IDs created in the previous step. This example calls our Blazor Grid's ExportToXlsxAsync method to generate data for the AI Assistant.

@using DevExpress.AIIntegration.OpenAI.Services
@inject AIAssistantCreator assistantCreator

@* ... *@
@code {
    protected override async Task OnAfterRenderAsync(bool firstRender) {
        if(firstRender) {
            using(MemoryStream ms = new MemoryStream()) {
                grid.BeginUpdate();
                grid.ShowGroupedColumns = true;
                await grid.ExportToXlsxAsync(ms, new GridXlExportOptions() {
                        ExportDisplayText = true
                    });
                (string assistantId, string threadId) = await assistantCreator.CreateAssistantAsync(
                    ms,
                    "grid_data.xlsx",
                    AssistantHelper.GetAIAssistantInstructions("xlsx"),
                    false
                );
                await chat.SetupAssistantAsync(assistantId, threadId);
                grid.ShowGroupedColumns = false;
                grid.EndUpdate();
            }
        }
        await base.OnAfterRenderAsync(firstRender);
    }
}

You can review and tailor AI assistant instructions in the following file: Instructions.cs.

Files to Review:

Add an AI Assistant to the DevExpress Blazor Report Viewer

As you can see in the following image, this sample uses our Blazor Report Viewer alongside the DevExpress Chat component (the AI Assistant tab uses the DxAIChat component to display requests and responses):

Blazor Report Viewer and Integrated AI Assistant

Add New Tab for Your AI Assistant

Use the OnCustomizeTabs event to add a new tab:

@using DevExpress.AI.Samples.Blazor.Components.Reporting
@using DevExpress.AI.Samples.Blazor.Models
@using DevExpress.Blazor.Reporting.Models

@* ... *@
<DxReportViewer @ref="Viewer" CssClass="my-report" OnCustomizeTabs="OnCustomizeTabs">
</DxReportViewer>
@* ... *@

@code {
    // ...
    void OnCustomizeTabs(List<TabModel> tabs) {
        tabs.Add(new TabModel(new UserAssistantTabContentModel(() => CurrentReport), "AI", "AI Assistant") {
            TabTemplate = (tabModel) => {
                return (builder) => {
                    builder.OpenComponent<AITabRenderer>(0);
                    builder.AddComponentParameter(1, "Model", tabModel.ContentModel);
                    builder.CloseComponent();
                };
            }
        });
    }
}

A new TabModel object is added to the tab list. The UserAssistantTabContentModel class implements the ITabContentModel interface that specifies AI Assistant tab visibility. The tab is only visible when the report is initialized and contains at least one page.

The TabTemplate property specifies tab content. It dynamically renders the DxAIChat component inside the tab and passes ContentModel as a parameter to control tab content.

The content for the AI Assistant tab is defined in the following file: AITabRenderer.razor.

@using DevExpress.AI.Samples.Blazor.Models
@using DevExpress.AIIntegration.Blazor.Chat
@using System.Text.RegularExpressions
@using Markdig

<DxAIChat CssClass="my-report-chat">
    <MessageContentTemplate>
        <div class="my-chat-content">
            @ToHtml(context.Content)
        </div>
    </MessageContentTemplate>
</DxAIChat>

@code {
    [Parameter] public UserAssistantTabContentModel Model { get; set; }
    string ClearAnnotations(string text) {
    //To clear out annotations in a response from the assistant.
        return Regex.Replace(text, @"\【.*?】", "");
    }
    
    MarkupString ToHtml(string text) {
        text = ClearAnnotations(text);
        return (MarkupString)Markdown.ToHtml(text);
    }
}

Use the MessageContentTemplate property to display rich-formatted messages. Use a markdown processor to convert response content to HTML code.

Files to Review:

Create an AI Assistant

In this example, the AIAssistantCreator.CreateAssistantAsync method uploads a file to OpenAI, configures tool resources, creates an assistant with specified instructions and tools, initializes a new thread, and returns the assistant and thread IDs.

For information on OpenAI Assistants, refer to the following documents:

In the Program.cs file, add the AIAssistantCreator service to the application's service collection:

// ...
var azureOpenAIClient = new AzureOpenAIClient(
    new Uri(azureOpenAIEndpoint),
    new ApiKeyCredential(azureOpenAIKey));

var assistantCreator = new AIAssistantCreator(azureOpenAIClient, deploymentName);

builder.Services.AddSingleton(assistantCreator);
// ...

Files to Review:

Set Up the AI Assistant

Handle the Initialized event and call the SetupAssistantAsync method to set up your AI assistant based on the assistant and thread IDs created in the previous step. This example calls the ExportToPdf method to generate data for the AI Assistant:

@using DevExpress.AIIntegration.Blazor.Chat
@using DevExpress.AIIntegration.OpenAI.Services
// ...
@inject AIAssistantCreator assistantCreator

<DxAIChat CssClass="my-report-chat" Initialized="ChatInitialized">
    @* ... *@
</DxAIChat>

@code {
    // ...
    async Task ChatInitialized(IAIChat aIChat) {
        using (MemoryStream ms = Model.GetReportData()) {
            (string assistantId, string threadId) = await assistantCreator.CreateAssistantAsync(
                ms, 
                "report.pdf", 
                AssistantHelper.GetAIAssistantInstructions("pdf")
            );
            await aIChat.SetupAssistantAsync(assistantId, threadId);
        }
    }
}

You can review and tailor AI assistant instructions in the following file: Instructions.cs.

Files to Review:

Files to Review

Documentation

More Examples

Does this example address your development requirements/objectives?

(you will be redirected to DevExpress.com to submit your response)

About

Integrate an AI Assistant to DevExpress Blazor Components.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 5