# Blazor AI Prompt Component

URL: https://flexcoreui.com/demo/ai-prompt  
Section: Components  
Controls: AIPromptControl  
Keywords: AI prompt, AI assistant UI, LLM prompt box, smart components

Add a text-generation feature to a Blazor app: prompt box, suggestions, command buttons, response card and history; you plug in the model.

## Documentation

### Prompt

| Name | Type | Default | Description |
|---|---|---|---|
| Prompt | string | "" | The prompt, in a multi-line TextBoxControl that updates on every keystroke; a suggestion click replaces it. The control writes its own copy, so bind it with @bind-Prompt; otherwise the parent's value can replace the typed text when the parent re-renders. |
| Generate | Func<AIPromptRequest, CancellationToken, Task<string>>? | null | Your provider. Called with an AIPromptRequest and a token that Cancel and disposal cancel; returns the response text. While it is null the Generate and command buttons stay disabled and a status line asks for a provider. |
| Suggestions | IReadOnlyList<string> | Array.Empty<string>() | One button per string under the prompt. A click replaces the prompt and raises PromptChanged; it does not generate. |
| Commands | IReadOnlyList<AIPromptCommand> | Array.Empty<AIPromptCommand>() | One button per command after Generate, captioned with its Text. A click generates with the command in the request, and the card's badge shows its Text. |
| MaxHistory | int | 10 | Most responses kept in History, newest first. Below 1 keeps one. |
| Rows | int | 4 | Height of the prompt box in lines. |
| AriaLabel | string | "AI prompt" | aria-label of the section and of the prompt box. |
| Placeholder | string | "Enter a prompt…" | Placeholder of the prompt box. |
| ApplyLabel | string | "Use response" | Caption of the card's apply button. The button is drawn whether or not Apply has a handler. |
| FooterContent | RenderFragment? | null | Rendered last inside the section, after the history row, such as the second example's note. |
| Enabled (base) | bool | true | False disables the prompt box, the suggestions, Generate and the commands, and makes the apply button do nothing. The history buttons and Dismiss still work. |
| Visible (base) | bool | true | False adds display:none to the section. |
| Id / CssClass / Style (base) | string? | null | On the section.fx-ai-prompt. |
| Title / Tag / Data / Parent (base) |  | null | Accepted but not rendered. A written title binds to Title, so it does not reach the section. |
| (unmatched attributes) | Dictionary<string,object> |  | Written on the section after its own attributes, so a class or aria-label given here replaces the control's own. |

### Prompt events

| Name | Type | Description |
|---|---|---|
| PromptChanged | string | After every keystroke in the prompt box and after a suggestion click. |
| Generated | AIPromptResult | After a response has arrived and joined the front of History as the response on show. Not raised for a canceled or failed request. |
| Apply | AIPromptResult | When the card's apply button is clicked, with the response on show: the newest, or the one picked in the history row. Ignored while busy or disabled. |

### Prompt methods

| Name | Type | Description |
|---|---|---|
| GenerateAsync(AIPromptCommand? command = null) | Task | What Generate (no command) and the command buttons call. Does nothing unless the control is enabled and idle, Generate is set and the prompt is not blank. Otherwise hides the current response, sets IsBusy, awaits Generate, and on success puts the result at the front of History, shows it and raises Generated. Any exception other than the cancellation sets ErrorMessage to its Message. |
| CancelAsync() | Task | Cancels the running request's token and clears IsBusy at once, as the second example's Stop does; it works even while the control is disabled. A response that still arrives afterward is dropped. |
| Dispose() | void | Cancels a running request. |
| IsBusy | bool | Read-only. True from the start of a request until it finishes or is canceled. |
| ErrorMessage | string? | Read-only. The message of the exception Generate threw, shown in the card's red box, or null; cleared when the next request starts, or by Dismiss. A canceled request sets none. |
| History | IReadOnlyList<AIPromptResult> | Read-only. The responses, newest first, at most MaxHistory. |

### Request

| Name | Type | Description |
|---|---|---|
| Prompt | string | The prompt as it was when the request started. |
| Command | AIPromptCommand? | The command that was clicked, or null for Generate. |

### Command

| Name | Type | Description |
|---|---|---|
| Key | string | Your identifier, passed through in the request; the control does not read it. |
| Text | string | Button caption; also the result's Command and the card's badge. |
| Instruction | string | Text for your provider, for example to add to the prompt; the control does not read it. |

### Result

| Name | Type | Description |
|---|---|---|
| Prompt | string | The request's prompt: the card shows it under Original text, and a history button shows its first 60 characters. |
| Output | string | The text Generate returned; the card's body. |
| Command | string? | The command's Text, or null for Generate, when the card's badge reads Response. |
| CreatedAt | DateTimeOffset | When the response arrived, in UTC. A history button shows it with ToLocalTime() in short-time format, which on Blazor Server is the server's time zone. |

### Card

| Name | Type | Default | Description |
|---|---|---|---|
| OperationLabel | string? | null | Badge at the start of the header. AIPromptControl passes the command's Text, or "Response". |
| ModelDisplayName | string? | null | Pill after the badge, for a model name. |
| IsBusy | bool | false | Adds a spinner row with BusyMessage. A body set at the same time still renders. |
| BusyMessage | string? | null | Spinner text; "Generating…" when null. |
| ErrorMessage | string? | null | Shown in a red fx-alert box. |
| OutputText | string? | null | The body, line breaks kept, with the action row under it. Blank means no body and no actions, unless Variants or ImageBase64 is set. |
| OriginalText | string? | null | Collapsed under a summary at the bottom of the card. AIPromptControl passes the prompt. |
| OriginalLabel | string? | null | Text of that summary; "Original text" when null. |
| Variants | IReadOnlyList<Variant>? | null | A non-empty list draws a tab per variant and the active one's text as the body, in place of OutputText; only Actions are drawn under it. |
| ActiveVariantIndex | int | 0 | Index of the visible tab; out of range shows the first. |
| ActiveVariantIndexChanged | EventCallback<int> |  | Raised when the user picks another tab. |
| ImageBase64 | string? | null | Image bytes in base64, without the data: prefix. Drawn in place of the text, with OutputText, else OriginalText, else "Generated image" as its alt text; only Actions are drawn under it. |
| ImageMime | string? | null | Media type of the image; "image/png" when null. |
| Actions | IReadOnlyList<ResultAction>? | null | Buttons for the action row. A non-empty list replaces the Apply and Dismiss pair. |
| OnApply | EventCallback |  | With a handler, draws the primary apply button under a text body. |
| OnDismiss | EventCallback |  | With a handler, draws Dismiss under a text body; the × button calls it too. |
| ApplyLabel | string? | null | "Apply" when null. |
| DismissLabel | string? | null | "Dismiss" when null. |
| ShowCloseButton | bool | false | Adds a × button to the header that calls OnDismiss. |
| CssClass | string? | null | Added to fx-result-card. The card takes no Id, Style or extra attributes. |
| EchoCompareTo | string? | null | Text to compare with OutputText. When the two start with the same text for at least EchoMinChars characters, a banner above the body counts the repeated and the new characters. |
| EchoMinChars | int | 100 | Shortest shared start that shows the banner. |

## Examples

### Prompt

```razor
@using Fx.ControlKit
@using Fx.ControlKit.AI

<div class="ai">
    <p class="ai-request"><strong>Ticket TKT-1042</strong> Albus Door · Router keeps restarting · every evening since Monday · wants a technician visit on Saturday</p>
    <AIPromptControl @bind-Prompt="_prompt" Suggestions="_suggestions" Commands="_commands" Generate="StubGenerateAsync"
                     Rows="3" AriaLabel="Ask about TKT-1042" Placeholder="Ask about this ticket…" ApplyLabel="Use in draft"
                     Apply="r => _draft = r.Output" Generated="r => _responses++" />
    <p class="ai-note">Responses so far: @_responses</p>
    <div class="ai-label">Draft for ticket TKT-1042</div>
    <TextBoxControl @bind-Value="_draft" Multiline="true" Rows="5" Width="100%" aria-label="Draft for ticket TKT-1042"
                    Placeholder="Use in draft puts the response here; edit it as you like." />
</div>
```

```csharp
// Prompt
private string _prompt = "Draft a reply with three steps to try";
private string _draft = "";
private int _responses;
private readonly string[] _suggestions =
{
    "Draft a reply with three steps to try",
    "Summarize this ticket for the technician",
    "Write a polite reply declining the Saturday visit",
};
private readonly AIPromptCommand[] _commands =
{
    new("shorten", "Shorten", "Reduce the answer to one sentence."),
    new("expand", "Expand", "Add one practical detail."),
    new("friendlier", "Friendlier tone", "Use a warmer, more personal tone."),
};

// Stub provider: no model is called. An application passes its own provider to Generate.
private static readonly string[] Steps =
{
    "Step 1: check that the power cable clicks firmly into the back of the router.",
    "Step 2: plug it straight into a wall outlet, not an extension cord.",
    "Step 3: leave space around it, because a router that overheats restarts itself.",
    "Tip: write down the time of the next restart, so we can check it against the line log.",
};
private static readonly string[] Summary =
{
    "Albus Door's router has restarted every evening since Monday.",
    "The ticket came in by phone to the Hardware queue, and the customer wants a technician visit on Saturday.",
    "Open question: does the power light go out during a restart? The call notes do not say.",
    "Line log: no outage in the customer's area this week.",
};
private static readonly string[] Decline =
{
    "We are sorry, but we cannot send a technician this Saturday.",
    "Every visit slot that day is taken.",
    "We can offer next Monday between 8 AM and noon, or a call with a technician today.",
    "If you reply by Friday, we will hold the Monday slot for you.",
};
private static async Task<string> StubGenerateAsync(AIPromptRequest request, CancellationToken token)
{
    await Task.Delay(1200, token);   // Cancel stops the wait
    var prompt = request.Prompt.ToLowerInvariant();
    var lines = prompt.Contains("steps") ? Steps
        : prompt.Contains("summar") ? Summary
        : prompt.Contains("declin") ? Decline
        : null;
    if (lines is null)
        return $"(Stub) No canned answer for \"{request.Prompt}\". Try a suggestion; an application would send the prompt to its own provider.";
    var body = string.Join("\n", lines[..3]);
    return request.Command?.Key switch
    {
        "shorten" => lines[0],
        "expand" => body + "\n" + lines[3],
        "friendlier" => lines == Summary
            ? "Thanks for picking this one up!\n" + body
            : "Hello, and thank you for bearing with us!\n" + body + "\nWe will stay on this until your connection is steady.",
        _ => body,
    };
}
```

### Host

```razor
@using Fx.ControlKit
@using Fx.ControlKit.AI

<div class="demo-row">
    <ButtonControl CssClass="btn-primary btn-sm" Disabled="_solved" OnClick="() => _ai!.GenerateAsync()">Write the refund note</ButtonControl>
    <ButtonControl CssClass="btn-sm" Disabled="_solved" OnClick="() => _ai!.GenerateAsync(_hostCommands[0])">Shorten it</ButtonControl>
    <ButtonControl CssClass="btn-sm" OnClick="() => _ai!.CancelAsync()">Stop</ButtonControl>
    <SwitchControl @bind-Checked="_billingDown" Label="Billing system is down" />
    <SwitchControl @bind-Checked="_solved" Label="Ticket solved" />
</div>
<div class="ai">
    <AIPromptControl @ref="_ai" @bind-Prompt="_hostPrompt" Commands="_hostCommands" Generate="RefundNoteAsync" MaxHistory="3" Rows="2" AriaLabel="Refund note for TKT-1043"
                     Enabled="@(!_solved)" ApplyLabel="Add to the ticket" Apply="r => _refundNote = r.Output">
        <FooterContent><p class="ai-note">Keeps the last three responses. The answers are canned, so no model is called.</p></FooterContent>
    </AIPromptControl>
</div>
<p class="ai-note" role="status">Note on Hermione Ranger's ticket TKT-1043: @(_refundNote ?? "none yet")</p>
```

```csharp
// Driving the prompt from the page: the buttons call the control's methods through @ref
private AIPromptControl? _ai;
private string _hostPrompt = "Write a refund note for the duplicate charge";
private bool _billingDown, _solved;
private string? _refundNote;
private readonly AIPromptCommand[] _hostCommands =
{
    new("shorten", "Shorten", "Reduce the answer to one sentence."),
};
// Slow enough to stop; throws while the billing system is down, which the control shows as an error.
private async Task<string> RefundNoteAsync(AIPromptRequest request, CancellationToken token)
{
    await Task.Delay(2500, token);
    if (_billingDown) throw new InvalidOperationException("The billing system did not answer. Try again in a minute.");
    return request.Command?.Key == "shorten"
        ? "Charged $59 twice on October 3; the duplicate is refunded within five business days."
        : "The October bill of $59 was charged to the same card twice on October 3.\nThe duplicate charge of $59 is refunded and reaches the card within five business days.";
}
```

