DxAIChat Class
An AI-powered chat component.
Namespace: DevExpress.AIIntegration.Blazor.Chat
Assembly: DevExpress.AIIntegration.Blazor.Chat.v25.1.dll
NuGet Package: DevExpress.AIIntegration.Blazor.Chat
#Declaration
public class DxAIChat :
DxComponentBase,
IAsyncDisposable,
IAIChat,
INestedSettingsOwner
#Remarks
DevExpress Blazor AI Chat (<DxAIChat>
) is an AI-powered chat component that allows users to interact with AI services.
The DevExpress Blazor AI Chat component is compatible with major cloud AI providers and self-hosted language models. Its architecture also allows you to integrate custom AI providers or implement support for proprietary, in-house LLMs.
For a complete list of supported AI providers and detailed integration instructions, see the following help topic: DevExpress AI-powered Extensions for Blazor.
Note
DevExpress AI-powered extensions operate on a “bring your own key” (BYOK) model. We do not provide a proprietary REST API or bundled language models (LLMs/SLMs).
You can either deploy a self-hosted model or connect to a cloud AI provider and obtain necessary connection parameters (endpoint, API key, language model identifier, and so on). These parameters must be configured at application startup to register an AI client and enable extension functionality.
#Add an AI Chat to a Project
Follow the steps below to add an AI Chat component to an application:
- 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.
- Install NuGet packages and register the AI model in the project’s entry point class.
Add the following markup to a
.razor
file:Razor@using DevExpress.AIIntegration.Blazor.Chat <DxAIChat />
Optional. Configure other options (see sections below).
#API Reference
Refer to the following list for the component API reference: DxAIChat Members.
#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.
<DxAIChat UseStreaming="true" />
#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.
@using Markdig;
<DxAIChat ResponseContentFormat="ResponseContentFormat.Markdown">
<MessageContentTemplate>
@ToHtml(context.Content)
</MessageContentTemplate>
</DxAIChat>
@code {
MarkupString ToHtml(string text) {
return (MarkupString)Markdown.ToHtml(text);
}
}
#File Attachments
<DxAIChat>
allows users to attach files when sending messages to the chat. Set the DxAIChat.FileUploadEnabled property to true
to enable file upload operations.
Once a user attaches files to a message, the AI Chat component validates attached files. To configure validation rules, declare a DxAIChatFileUploadSettings object in AIChatSettings component markup. You can validate file size, extension, and type as well as limit the number of files.
The following code snippet activates the file upload functionality in Blazor AI Chat and configures validation rules for uploaded files:
@using DevExpress.AIIntegration.Blazor.Chat
<DxAIChat CssClass="demo-chat"
FileUploadEnabled="true">
<AIChatSettings>
<DxAIChatFileUploadSettings MaxFileCount="2"
MaxFileSize="20000"
AllowedFileExtensions="@(new List<string> { ".jpg", ".pdf" })"
FileTypeFilter="@(new List<string> { "image/*", "application/pdf"})" />
</AIChatSettings>
</DxAIChat>
You can also use the AIChatUploadFileInfo class to send messages with file attachments in code (via the SendMessage
method) or access and process uploaded files in a MessageSent
event handler.
#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>
#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, List<AIChatUploadFileInfo>) method to send another message to the chat.
<DxAIChat MessageSent="MessageSent" />
@code {
async Task MessageSent(MessageSentEventArgs args) {
await args.Chat.SendMessage($"Processed: {args.Content}", ChatRole.Assistant);
}
}
#Stop Message Generation
Our Blazor AI Chat component allows users to stop chat message generation before it is complete. You can also use the CancellationToken argument property in a MessageSent event handler to process cancellations in code.
#Save and Load Messages
Use SaveMessages and LoadMessages methods to manage chat history.
<DxAIChat Initialized="ChatInitialized" />
@code {
void ChatInitialized(IAIChat chat) {
chat.LoadMessages(new[] {
new BlazorChatMessage(Microsoft.Extensions.AI.ChatRole.Assistant, "Hello, how can I help you?")
});
}
}
#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:
<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),
});
}
}
#Prompt Suggestions
DevExpress Blazor AI Chat supports prompt suggestions – hints that guide users to possible actions. The component displays prompt suggestions (hint bubbles) when the chat area is empty.
Follow the steps below to enable and configure prompt suggestions:
- Populate the component’s PromptSuggestions property with DxAIChatPromptSuggestion objects (hint bubbles).
- Specify bubble content using Title and Text properties.
- Use the PromptMessage property to specify the text to be displayed in the input field after a user clicks the corresponding suggestion.
@using DevExpress.AIIntegration.Blazor.Chat
<DxAIChat Initialized="ChatInitialized">
<PromptSuggestions>
@foreach (var suggestion in PromptSuggestions) {
<DxAIChatPromptSuggestion Title="@suggestion.Title"
Text="@suggestion.Text"
PromptMessage="@suggestion.PromptMessage" />
}
</PromptSuggestions>
</DxAIChat>
@code {
List<PromptSuggestion> PromptSuggestions { get; set; }
void ChatInitialized() {
PromptSuggestions = GetData();
}
}
Additionally, you can use the PromptSuggestionContentTemplate property to specify a template for prompt suggestions.
#AI Service Assistants
The DevExpress AI Chat component supports OpenAI Assistants. You can use a single OpenAI Assistant instance to initiate multiple tasks within a single application. To connect the chat to an existing assistant, pass the asisstant and thread IDs to the SetupAssistantAsync(String, String) method as parameteres.
Note
Availability of Azure Open AI Assistants depends on the region. Refer to the following article for more details: Assistants (Preview).
The following code snippet creates an OpenAI Assistant, obtains the assistant and thread IDs, and connects the Blazor AI Chat to the assistant in a DxAIChat.Initialized event handler:
@using DevExpress.AIIntegration.OpenAI.Services
@using DevExpress.AIIntegration.Blazor.Chat
@using AIIntegration.Services.Chat
@using Markdig
@inject ReportingApp.AIAssistantCreator assistantCreator
<DxAIChat CssClass="my-chat"
Initialized="Initialized"
ResponseContentFormat="ResponseContentFormat.Markdown">
<MessageContentTemplate>
<div class="my-chat-content">
@ToHtml(context.Content)
</div>
</MessageContentTemplate>
</DxAIChat>
@code {
const string DocumentResourceName = "DevExpress.AI.Samples.Blazor.Data.Restaurant Menu.pdf";
const string prompt = "You are an analytics assistant specialized in analyzing PDF files. Your role is to assist users by providing accurate answers to their questions about data contained within these files.\n \n### Tasks:\n- Perform various types of data analyses, including summaries, calculations, data filtering, and trend identification.\n- Clearly explain your analysis process to ensure users understand how you arrived at your answers.\n- Always provide precise and accurate information based on the Excel data.\n- If you cannot find an answer based on the provided data, explicitly state: \"The requested information cannot be found in the data provided.\"\n \n### Examples:\n1. **Summarization:**\n - **User Question:** \"What is the average sales revenue for Q1?\"\n - **Response:** \"The average sales revenue for Q1 is calculated as $45,000, based on the data in Sheet1, Column C.\"\n \n2. **Data Filtering:**\n - **User Question:** \"Which products had sales over $10,000 in June?\"\n - **Response:** \"The products with sales over $10,000 in June are listed in Sheet2, Column D, and they include Product A, Product B, and Product C.\"\n \n3. **Insufficient Data:**\n - **User Question:** \"What is the market trend for Product Z over the past 5 years?\"\n - **Response:** \"The requested information cannot be found in the data provided, as the dataset only includes data for the current year.\"\n \n### Additional Instructions:\n- Format your responses to clearly indicate which sheet and column the data was extracted from when necessary.\n- Avoid providing any answers if the data in the file is insufficient for a reliable response.\n- Ask clarifying questions if the user's query is ambiguous or lacks detail.\n \nRemember, your primary goal is to provide helpful, data-driven insights that directly answer the user's questions. Do not assume or infer information not present in the dataset.";
async Task Initialized(IAIChat chat) {
(string assistantId, string threadId) = await assistantCreator.CreateAssistantAsync(
Assembly.GetExecutingAssembly().GetManifestResourceStream(DocumentResourceName)!,
$"{Guid.NewGuid().ToString("N")}.pdf",
prompt);
await chat.SetupAssistantAsync(assistantId, threadId);
}
MarkupString ToHtml(string text) {
return (MarkupString)Markdown.ToHtml(text);
}
}