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

35 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:

Note

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

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 azureClient = new AzureOpenAIClient(
    new Uri(azureOpenAIEndpoint),
    new ApiKeyCredential(azureOpenAIKey));
builder.Services.AddChatClient(config => 
    config.Use(azureClient.AsChatClient(deploymentName))
);
builder.Services.AddDevExpressAI((config) => {
    config.RegisterOpenAIAssistants(azureClient, 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:

Set Up the AI Assistant

Handle the OnAfterRenderAsync event and call the SetupAssistantAsync method to create your AI assistant and provide it with data and instructions. This example calls our Blazor Grid's ExportToXlsxAsync method to generate data for the AI Assistant.

@using DevExpress.AIIntegration.OpenAI.Services

@* ... *@
@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
                    });
                await chat.SetupAssistantAsync(new OpenAIAssistantOptions("grid_data.xlsx", ms) {
                    Instructions = AssistantHelper.GetAIAssistantInstructions("xlsx"),
                    UseFileSearchTool = false
                });
                grid.ShowGroupedColumns = false;
                grid.EndUpdate();
            }
        }
        await base.OnAfterRenderAsync(firstRender);
    }
}

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

For information on OpenAI Assistants, refer to the following document: Assistants API overview.

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:

Set Up the AI Assistant

Handle the Initialized event and call the SetupAssistantAsync method to create your AI assistant and provide it with data and instructions. This example calls the ExportToPdf method to generate data for the AI Assistant:

@using DevExpress.AIIntegration.Blazor.Chat
@using DevExpress.AIIntegration.OpenAI.Services

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

@code {
    // ...
    async Task ChatInitialized(IAIChat aIChat) {
        using (MemoryStream ms = Model.GetReportData()) {
            await aIChat.SetupAssistantAsync(new OpenAIAssistantOptions("report.pdf", ms) {
                Instructions = AssistantHelper.GetAIAssistantInstructions("pdf")
            });
        }
    }
}

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

For information on OpenAI Assistants, refer to the following article: Assistants API overview.

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)