Skip to main content
All docs
V24.2

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

DxAIChat Class

An AI-powered chat component.

Namespace: DevExpress.AIIntegration.Blazor.Chat

Assembly: DevExpress.AIIntegration.Blazor.Chat.v24.2.dll

NuGet Package: DevExpress.AIIntegration.Blazor.Chat

#Declaration

C#
public class DxAIChat :
    DxComponentBase,
    IAsyncDisposable,
    IAIChat

#Remarks

DevExpress Blazor AI Chat (<DxAIChat>) is an AI-powered chat component that allows users to interact with AI services.

AI Chat

Run Demo: AI Chat
View Example: AI Chat for Blazor - How to add DxAIChat component in Blazor, MAUI, WPF, and WinForms applications

#Supported AI Services

DevExpress AI Chat supports integration with the following 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.

Important

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

  • v24.2.6+ | 9.3.0-preview.1.25161.3
  • v24.2.3-v24.2.5 | 9.0.0-preview.9.24556.5

We do not guarantee compatibility or correct operation with higher versions. Refer to the following announcement for additional information: Microsoft.Extensions.AI.Abstractions NuGet Package Version Upgrade in v24.2.6.

#Add an AI Chat to a Project

Follow the steps below to add an AI Chat component to an application:

  1. Create a new Blazor Server or Blazor WebAssembly application with a DevExpress Project Template. For existing Blazor projects or those created with a Microsoft template, configure your project to integrate DevExpress Blazor components.
  2. Install NuGet packages and register the AI service in the application.

    For instance, the following code snippet registers an Azure OpenAI service:

    using Azure;
    using Azure.AI.OpenAI;
    using Microsoft.Extensions.AI;
    ...
    string azureOpenAIEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
    string azureOpenAIKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
    string deploymentName = string.Empty;
    ...
    IChatClient chatClient = new AzureOpenAIClient(
        new Uri(azureOpenAIEndpoint),
        new AzureKeyCredential(azureOpenAIKey)).AsChatClient(deploymentName);
    
    builder.Services.AddDevExpressBlazor();
    builder.Services.AddChatClient(chatClient);
    builder.Services.AddDevExpressAI();
    
  3. Add the following markup to a .razor file:

    razor
    @using DevExpress.AIIntegration.Blazor.Chat
    <DxAIChat />
    
  4. Optional. Configure other options (see sections below).

#Integration into WinForms, WPF, and .NET MAUI Apps

Use Blazor Hybrid technology to integrate DevExpress AI Chat into WinForms, WPF, or .NET MAUI applications. The following GitHub repository includes an implementation example: Blazor AI Chat - How to add the DevExpress Blazor AI Chat component to your next Blazor, MAUI, WPF, and WinForms application.

#AI Model Settings

The DxAIChat component allows you to specify the following AI model settings:

FrequencyPenalty
Specifies how the model penalizes new tokens based on their frequency in the text.
MaxTokens
Limits the maximum number of tokens to generate in a single call to a GPT model.
Temperature
Specifies the response text randomness.

#Streaming Response

Enable the UseStreaming property for a more responsive chat experience. This setting allows the AI client to send parts of the response once they become available, and the chat component will update the display message accordingly.

razor
<DxAIChat UseStreaming="true" />

AI chat streams a response

Run Demo: AI Chat - Overview

#Rich Formatted Response

The AI service uses plain text as the default response format. To display rich formatted responses, set the ResponseContentFormat property to Markdown and use a markdown processor to convert response content to HTML code.

razor
@using Markdig;

<DxAIChat ResponseContentFormat="ResponseContentFormat.Markdown">
    <MessageContentTemplate>
            @ToHtml(context.Content)
    </MessageContentTemplate>
</DxAIChat>

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

Rich formatter content in AI Chat

#Customizable Message Appearance and Empty Message Area

The DxAIChat component includes the following message customization properties:

MessageTemplate
Changes the message bubble rendering, including paddings and inner content alignment.
MessageContentTemplate
Alters message bubble content without affecting layout.
EmptyMessageAreaTemplate
Specifies the template used to display the message area if there are no message bubbles.
<DxAIChat CssClass="demo-chat">
    <MessageContentTemplate>
        <div class="demo-chat-content">
            @context.Content
        </div>
    </MessageContentTemplate>
</DxAIChat>

AI chat with customized messages

Run Demo: AI Chat - Rich Formatted Response

#Manual Message Processing

When a user sends a message to the chat, the MessageSent event fires. Handle the event to manually process this action. You can use the Content event argument to access user input and call the SendMessage(String, ChatRole) method to send another message to the chat.

razor
<DxAIChat MessageSent="MessageSent" />

@code {
    async Task MessageSent(MessageSentEventArgs args) {
        await args.Chat.SendMessage($"Processed: {args.Content}", ChatRole.Assistant);
    }
}

Run Demo: AI Chat - Manual Message Processing

#Save and Load Messages

Use SaveMessages and LoadMessages methods to manage chat history.

razor
<DxAIChat Initialized="ChatInitialized" />

@code {
    void ChatInitialized(IAIChat chat) {
        chat.LoadMessages(new[] {
            new BlazorChatMessage(Microsoft.Extensions.AI.ChatRole.Assistant, "Hello, how can I help you?")
        });
    }
}

Chat with a loaded message

#Add a System Prompt

DevExpress Blazor AI Chat allows you to create a system prompt that provides the AI model with initial role context and specific instructions. The following code snippet adds a system prompt to the chat using the LoadMessages method in the DxAIChat.Initialized event handler:

razor
<DxAIChat Initialized="ChatInitialized" />

@code {
    async Task ChatInitialized(IAIChat chat) {
        var prompt = @"
            You are a friendly hiking enthusiast who helps people discover fun hikes in their area.
            You introduce yourself when first saying hello.
            When helping people out, you always ask them for this information
            to inform the hiking recommendation you provide:

            1. The location where they would like to hike
            2. What hiking intensity they are looking for

            You will then provide three suggestions for nearby hikes that vary in length
            after you get that information. You will also share an interesting fact about
            local nature on the hikes when making a recommendation. At the end of your
            response, ask if there is anything else you can help with.
        ";
        chat.LoadMessages(new[] {
            new BlazorChatMessage(Microsoft.Extensions.AI.ChatRole.System, prompt),
        });
    }
}

#AI Service Assistants

The DevExpress AI Chat component supports OpenAI Assistants. To use them, specify a model and provide supplementary documents (external knowledge). OpenAI uses these documents to retrieve content for user queries.

Note

Availability of Azure Open AI Assistants depends on the region. Refer to the following article for more details: Assistants (Preview).

Add the following code to the Program.cs file to register the AI Assistant service in the application:

using System.ClientModel;
using DevExpress.AIIntegration;

builder.Services.AddDevExpressAI((config) => {
    //Reference the DevExpress.AIIntegration.OpenAI NuGet package to use Open AI Asisstants
    config.RegisterOpenAIAssistants(azureClient, "gpt4o"); 
});

Include supplementary documents in the project as EmbeddedResource:

<EmbeddedResource Include="Data\Restaurant Menu.pdf" />

Handle the Initialized event and call the SetupAssistantAsync method to supply a file to the OpenAI Assistant.

razor
<DxAIChat CssClass="my-chat" Initialized="Initialized" />

@code {
    const string DocumentResourceName = "DevExpress.AI.Samples.Blazor.Data.Restaurant Menu.pdf";
    const string prompt = "...";

    async Task Initialized(IAIChat chat) {
        await chat.SetupAssistantAsync("Menu", new OpenAIAssistantOptions(
            $"{Guid.NewGuid().ToString("N")}.pdf",
            Assembly.GetExecutingAssembly().GetManifestResourceStream(DocumentResourceName),
            prompt)
        );
    }
}
See Also