Telerik blogs

The Blazor PromptBox component helps connect people with AI models, with three input modes, customization and integration with your favorite AI model.

Nowadays, it is increasingly common to see more and more applications that integrate features using AI to make things easier for users. An essential component for this to work is the text box in which the user can write instructions for the AI model to process their request.

Internally, that component can be very simple or incorporate complex features. In this article, we will analyze the Progress Telerik UI for Blazor PromptBox component, designed for communication between people and AI. Let’s see what it is about.

What Is the Telerik PromptBox Component?

The Telerik PromptBox component is built for AI-based applications. One advantage it offers is that it combines text input, speech recognition, file selection and an action button that toggles between send and stop.

Its main features include:

  • Allows specifying the input mode
  • Integrates a button to start speech-to-text recognition
  • Includes a button to select files with built-in validation
  • Has an action button with loading states
  • Among other features

Let’s see some of the most important features in action.

Creating a Project and Configuring It to Use Blazor PromptBox

The first thing you should do to work with the PromptBox component is create a new project using the Telerik pre-created template, or if you already have an existing project, installing the Telerik components into your existing project.

Another important point is to install the packages necessary to use generative AI models. In my case, since I will use Azure OpenAI, I will install the packages:

Microsoft.Extensions.AI
Microsoft.Extensions.AI.OpenAI
Azure.AI.OpenAI

To carry out the configuration of an AI model, it is recommended to register a service of type IChatClient, so it can be injected into any component we want. We will do this by going to Program.cs, reading the key from the configuration:

...
builder.Services.AddTelerikBlazor();

#region AI configuration

var openAiKey = builder.Configuration["OPENAI_API_KEY"];
var azureKey = builder.Configuration["AZURE_OPENAI_API_KEY"];

if (!string.IsNullOrEmpty(openAiKey))
{
    builder.Services.AddChatClient(new OpenAIClient(
            new ApiKeyCredential(openAiKey))
        .GetChatClient("gpt-4o-mini")
        .AsIChatClient());
}
else if (!string.IsNullOrEmpty(azureKey))
{
    builder.Services.AddChatClient(new AzureOpenAIClient(
            new Uri("https://your-endpoint.openai.azure.com/"),
            new ApiKeyCredential(azureKey))
        .GetChatClient("gpt-4.1")
        .AsIChatClient());
}
else
{
    Debug.WriteLine("Warning: no AI key configured.");
}

#endregion


var app = builder.Build();
...

In the code above, we read two possible configuration keys, one to read the OpenAI API Key, and another for Azure OpenAI. Depending on the value found, the method AddChatClient is used to configure the corresponding client with the necessary values.

If no keys are found configured, a warning will be shown. With the model configured, it’s time to try the component.

Using the PromptBox Component in a Blazor Project

Let’s start by creating a component style page called Playground.razor, defining the basic structure of the page:

@page "/playground"

@using Microsoft.Extensions.AI
@inject IChatClient ChatClient

<PageTitle>PromptBox AI Playground</PageTitle>

<h1 class="mb-1">PromptBox AI Playground</h1>
<p class="text-secondary mb-4">
    Compose prompts with the Telerik PromptBox and send them to a real AI model.
    Switch the input mode to see how the component adapts.
</p>

In the previous code section, we make sure to inject the IChatClient instance so we can talk to an LLM model.

Configuring Selection Mode

The PromptBox component allows users to interact in three ways, through the parameter PromptBoxMode:

  1. Auto (default): Starts as a single-line input and transforms into a multi-line area if the content requires it.
  2. SingleLine: A single-line input with horizontal scrolling. Height remains constant.
  3. MultiLine: A multi-line text area that grows vertically.

To see them in action at the same time, I’ll use the fantastic Telerik components TelerikButtonGroup and TelerikChip to create a section that allows me to select between the different modes:

...
<div class="d-flex align-items-center gap-3 flex-wrap mb-3">
    <span class="fw-semibold">Input mode:</span>
    <TelerikButtonGroup>
        <ButtonGroupToggleButton Selected="@(SelectedMode == PromptBoxMode.SingleLine)"
                                 OnClick="@(() => SelectedMode = PromptBoxMode.SingleLine)">
            Single line
        </ButtonGroupToggleButton>
        <ButtonGroupToggleButton Selected="@(SelectedMode == PromptBoxMode.MultiLine)"
                                 OnClick="@(() => SelectedMode = PromptBoxMode.MultiLine)">
            Multi line
        </ButtonGroupToggleButton>
        <ButtonGroupToggleButton Selected="@(SelectedMode == PromptBoxMode.Auto)"
                                 OnClick="@(() => SelectedMode = PromptBoxMode.Auto)">
            Auto
        </ButtonGroupToggleButton>
    </TelerikButtonGroup>
    <TelerikChip Size="@ThemeConstants.Chip.Size.Small"
                 ThemeColor="@ThemeConstants.Chip.ThemeColor.Info"
                 Rounded="@ThemeConstants.Chip.Rounded.Full"
                 Selectable="false"
                 Text="@($"Mode: {SelectedMode}")">
    </TelerikChip>
</div>

@code {
    private PromptBoxMode SelectedMode = PromptBoxMode.Auto;
}

Once the mode selection part is defined, we can implement the PromptBox component in the project using the tag TelerikPromptBox. For this demonstration, we’re going to enable all its features, including the modes parameter, the loading state, voice recognition, file selection and an initial template:

...
<TelerikPromptBox @bind-Value="@Prompt"
                  Mode="@SelectedMode"
                  Rows="4"
                  MaxTextAreaHeight="220px"
                  Width="100%"
                  IsLoading="@IsProcessing"
                  EnableSpeechToText="true"
                  EnableFileSelect="true"
                  Placeholder="Ask anything  type, dictate, or attach a file"
                  OnPromptAction="@OnPromptAction">
    <PromptBoxSettings>
        <PromptBoxFileSelectButtonSettings Multiple="true"
                                           AllowedExtensions="@AllowedExtensions" />
        <PromptBoxSpeechToTextButtonSettings Lang="en-US" />
    </PromptBoxSettings>
    <PromptBoxStartAffixTemplate>
        <TelerikSvgIcon Icon="@SvgIcon.Sparkles" />
    </PromptBoxStartAffixTemplate>
</TelerikPromptBox>
@code {
    ...
    private string Prompt = string.Empty;
    private bool IsProcessing;
    private List<string> AllowedExtensions = new() { ".txt", ".pdf", ".png", ".jpg", ".jpeg" };

    private async Task OnPromptAction(PromptBoxActionButtonEventArgs args)
    {
    }
}

In the previous code, we can notice the usage of some important parameters:

  • Mode is bound to SelectedMode, allowing the mode to change automatically.
  • IsLoading allows showing whether a response is being generated, giving good feedback to the user that their request is being processed.
  • EnableSpeechToText and EnableFileSelect enable the microphone and attach-file buttons.
  • <PromptBoxSettings> is a tag that allows configuring details for each button of the component. For example, PromptBoxFileSelectButtonSettings limits allowed extensions as well as whether multiple file selection is allowed, while PromptBoxSpeechToTextButtonSettings defines the language for voice recognition.
  • <PromptBoxStartAffixTemplate> is a section where we can add adornments to the component. In our example we add an icon at the start of the text box. Here you could add any content, such as buttons or a status indicator.

When running the application, the component already displays correctly, configured as specified:

PromptBox component demo with controls to choose the input mode.

By pressing each of the modes, you can notice how the size of the text box changes to adapt. Now let’s see how to converse with the AI model.

Interacting with an AI Model Using PromptBox

We’ll keep a conversation with the AI model by maintaining a list of messages. To make it more interactive, we’ll display the user’s messages on the right, and those generated by the AI model on the left. Similarly, we’ll implement a loader to show while a response is being generated:

...
<div class="mt-4">
    @if (Messages.Count == 0)
    {
        <div class="text-center text-secondary py-5 border rounded-3 bg-light">
            <TelerikSvgIcon Icon="@SvgIcon.Sparkles" Size="@ThemeConstants.SvgIcon.Size.ExtraLarge" />
            <p class="mt-2 mb-0">Send a prompt to see the model's response here.</p>
        </div>
    }
    else
    {
        @foreach (var message in Messages)
        {
            <div class="d-flex mb-3 @(message.IsUser ? "justify-content-end" : "justify-content-start")">
                <div class="p-3 rounded-3 shadow-sm @(message.IsUser ? "bg-primary text-white" : "bg-white border")"
                     style="max-width: 75%; white-space: pre-wrap;">
                    @message.Text
                    @if (message.Attachments.Count > 0)
                    {
                        <div class="mt-2 d-flex flex-wrap gap-1">
                            @foreach (var fileName in message.Attachments)
                            {
                                <TelerikChip Size="@ThemeConstants.Chip.Size.Small"
                                             Icon="@SvgIcon.Paperclip"
                                             Selectable="false"
                                             Text="@fileName">
                                </TelerikChip>
                            }
                        </div>
                    }
                </div>
            </div>
        }

        @if (IsProcessing)
        {
            <div class="d-flex justify-content-start mb-3">
                <div class="p-3 rounded-3 border bg-white d-flex align-items-center">
                    <TelerikLoader Size="@ThemeConstants.Loader.Size.Small"></TelerikLoader>
                    <span class="ms-2 text-secondary fst-italic">Thinking </span>
                </div>
            </div>
        }
    }
</div>
@code {
    ...
    private List<PromptMessage> Messages = new();
    ...
    private record PromptMessage(bool IsUser, string Text, List<string> Attachments);
}

In the previous code, if the list is empty, a message is shown so the user knows they should send a prompt. Otherwise, if the list has data, it iterates through the list and aligns left or right depending on who sent the message.

For user messages, if any have attached files, they are displayed as a list of TelerikChip. Also, if IsProcessing is true, a TelerikLoader is shown with a message indicating that a response is being generated.

To populate the message list, we need to add the interaction logic with the AI model, which we’ll do next.

Conversing with AI Models Using the PromptBox Component

For everything to work correctly, we must implement the method OnPromptAction. This event handler receives an argument of type PromptBoxActionButtonEventArgs that contains information such as the text, the action to send or stop, as well as attached files. The method is as follows:

private CancellationTokenSource? _cts;

private async Task OnPromptAction(PromptBoxActionButtonEventArgs args)
{
    //1.
    if (args.Action == PromptBoxActionType.Stop)
    {
        _cts?.Cancel();
        IsProcessing = false;
        return;
    }

    //2.
    if (string.IsNullOrWhiteSpace(args.Text) || IsProcessing)
        return;

    //3.
    var attachments = args.Files?.Select(file => file.Name).ToList() ?? new List<string>();
    Messages.Add(new PromptMessage(IsUser: true, Text: args.Text, Attachments: attachments));

    Prompt = string.Empty;
    IsProcessing = true;

    //4.
    var client = ChatClient;
    if (client is null)
    {
        Messages.Add(new PromptMessage(IsUser: false,
            Text: "No AI model is configured. Set the OPENAI_API_KEY (or AZURE_OPENAI_API_KEY) value to receive live responses.",
            Attachments: new List<string>()));
        IsProcessing = false;
        return;
    }

    _cts = new CancellationTokenSource();

    //5.
    try
    {
        var response = await client.GetResponseAsync(args.Text, cancellationToken: _cts.Token);
        Messages.Add(new PromptMessage(IsUser: false, Text: response.Text, Attachments: new List<string>()));
    }    
    catch (OperationCanceledException)
    {
        Messages.Add(new PromptMessage(IsUser: false, Text: "Generation stopped.", Attachments: new List<string>()));
    }
    catch (Exception ex)
    {
        Messages.Add(new PromptMessage(IsUser: false, Text: $"Something went wrong: {ex.Message}", Attachments: new List<string>()));
    }
    finally
    {
        IsProcessing = false;
    }
}

In the previous method, we do the following:

  1. We check whether the received action is Stop, in which case we cancel the CancellationTokenSource to stop message generation.
  2. We verify that the text is not empty and that there is no request in progress.
  3. We add the user’s message to the list, including the names of attached files.
  4. We verify an AI model has been configured beforehand.
  5. In the try block, we invoke GetResponseAsync passing the prompt text and the cancellation token. We also catch possible exceptions, and add either a success message or an error message to the messages list, always resetting IsProcessing at the end of execution.

Once we apply the changes and test the application, this is the result of the execution:

Interacting with an AI model using the PromptBox component.

In the image above, you can see that the AI model generates a response correctly.

Conclusion

Throughout this article, you have seen how the PromptBox component helps connect people with AI models. We saw its three input modes, how to customize it, and how to connect it to an AI model, thanks to Microsoft.Extensions.AI. With just a few lines of code, we achieved a professional experience that would otherwise take a long time to develop.

Try Telerik UI for Blazor

You can experiment with the PromptBox plus 120 other Telerik UI for Blazor components with the free 30-day trial. 

Try Now


About the Author

Héctor Pérez

Héctor Pérez is a Microsoft MVP with more than 10 years of experience in software development. He is an independent consultant, working with business and government clients to achieve their goals. Additionally, he is an author of books and an instructor at El Camino Dev and Devs School.

 

Related Posts

Comments

Comments are disabled in preview mode.