Skip to content

egarim/devexpress-ai-chat-samples

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Blazor AI Chat - How to add the DevExpress Blazor AI Chat component to your next Blazor, MAUI, WPF, and WinForms application

The DevExpress Blazor AI Chat component (DxAIChat) allows you to incorporate AI-powered interactions into any Blazor/MAUI/WPF/WinForms application. Our AI Chat component ships with a variety of high impact features, including:

Implementation Details

This example adds a DxAIChat to a Blazor application, customizes its settings, and integrates it into WinForms, WPF, and .NET MAUI applications.

Register AI Service

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

using DevExpress.AIIntegration;

string azureOpenAIEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");
string azureOpenAIKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");
...
builder.Services.AddDevExpressAI((config) => {
    var client = new AzureOpenAIClient(
        new Uri(azureOpenAIEndpoint),
        new AzureKeyCredential(azureOpenAIKey));
    config.RegisterChatClientOpenAIService(client, "gpt4o");
});

File to review: Program.cs

Add DxAIChat component to a Blazor Application

Add a <DxAIChat>…</DxAIChat> markup to a .razor file:

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

<DxAIChat CssClass="my-chat" />
.my-chat {
    width: 700px;
    margin: 20px;
}

AIChat

File to review: Chat.razor

Customize message appearance and empty message area

DxAIChat component includes the following message customization properties:

  • MessageTemplate - specifies the template used for message bubbles.
  • MessageContentTemplate - specifies the template used for message bubble content.
  • EmptyMessageAreaTemplate - specifies the template used for the empty message area.
<DxAIChat CssClass="my-chat">
    <EmptyMessageAreaTemplate>
        <div class="my-chat-ui-description">
            AI Assistant is ready to answer your questions.
        </div>
    </EmptyMessageAreaTemplate>
    <MessageTemplate>
        <div class="@GetMessageClasses(context)">
            @if(context.Typing) {
                <span>Loading...</span>
            } else {
                <div class="my-chat-content">
                    @context.Content
                </div>
            }
        </div>
    </MessageTemplate>
</DxAIChat>

File to review: Chat-CustomMessage.razor, Chat-CustomEmptyState.razor

Text or markdown response

The AI service uses plain text as the default response format.

To display rich formatted messages, set the RenderMode property to Markdown. Use a markdown processor to convert response content to HTML code.

@using Markdig;

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

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

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 method to send another message to the chat.

<DxAIChat CssClass="my-chat" MessageSent="MessageSent" />

@code {
    void MessageSent(MessageSentEventArgs args) {
        var message = new Message(MessageRole.Assistant, $"Processed: {args.Content}");
        args.SendMessage(message);
    }
}

File to review: Chat-MessageSent.razor

Streaming response

After a user sends a request, the AI client generates and sends the entire response back. This operation may be time consuming. To make the chat appear more responsive, set the UseStreaming property to true. In this instance, the AI client transmits parts of the response as it becomes available and the chat component adds these parts to the display message.

<DxAIChat CssClass="my-chat" UseStreaming="true" />

File to review: Chat-Streaming.razor

Compatibility with OpenAI assistants

The DevExpress AI Chat (DxAIChat) component supports OpenAI Assistants. This allows you to specify a model and supply supplementary documents (external knowledge). OpenAI parses these documents and searches through them to retrieve relevant content to answer user queries.

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

builder.Services.AddDevExpressAI((config) => {
    ...
    config.RegisterOpenAIAssistants(client, "gpt4o");
});

Include a supplementary document in the project file as an EmbeddedResource:

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

Handle the Initialized event and call the UseAssistantAsync method to supply a file to the Open AI Assistant.

<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.UseAssistantAsync(new OpenAIAssistantOptions(
            $"{Guid.NewGuid().ToString("N")}.pdf",
            Assembly.GetExecutingAssembly().GetManifestResourceStream(DocumentResourceName),
            prompt)
        );
    }
}

File to review: Chat-Assistant.razor

Integrate AI Chat into WinForms, WPF and .NET MAUI Apps

Thanks to both Blazor Hybrid technology and the BlazorWebView component, you can integrate DevExpress AI Chat (DxAIChat) into your next great WinForms, WPF, and .NET MAUI application.

Keys to implementation are as follows:

  • The ISelfEncapsulationService interface allows you to work directly with the DxAIChat component instance/properties from your desktop or mobile app.
  • Built-in DxAIChat wrappers initialize required Blazor Theme scripts.
  • Custom CSS classes hide the built-in input field and the Send button (see index.htm).

Folders to review: DevExpress.AI.Samples.MAUIBlazor, DevExpress.AI.Samples.WinBlazor, DevExpress.AI.Samples.WPFBlazor

Files to Review

Folders 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 AI-driven interactions into your applications.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 62.3%
  • HTML 36.9%
  • JavaScript 0.8%